_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q4800
GeoWorks.ImageFileBehavior.image_work
train
def image_work parents.select do |parent| parent.class.included_modules.include?(::GeoWorks::ImageWorkBehavior) end.to_a end
ruby
{ "resource": "" }
q4801
RailsPaginate::Pagers.Slider.visible_pages
train
def visible_pages visible = [] last_inserted = 0 splited = false (1..pages).each do |page| # insert if visible? page visible << page last_inserted = page splited = false else # need splitter if not splited and outer > 0 and last_inserted < page visible << nil splited = true end end end visible end
ruby
{ "resource": "" }
q4802
RailsPaginate::Pagers.Slider.visible?
train
def visible?(page) # outer if outer > 0 return true if outer >= page return true if (pages - outer) < page end # current page return true if current_page == page # inner return true if inner_range.include? page false end
ruby
{ "resource": "" }
q4803
Mongoid::Globalize.ClassMethods.required_attributes
train
def required_attributes validators.map{ |v| v.attributes if v.is_a?(Mongoid::Validations::PresenceValidator) }.flatten.compact end
ruby
{ "resource": "" }
q4804
Mongoid::Globalize.Methods.translated_attributes
train
def translated_attributes @translated_attributes ||= translated_attribute_names.inject({}) do |attrs, name| attrs.merge(name.to_s => translation.send(name)) end end
ruby
{ "resource": "" }
q4805
Mongoid::Globalize.Methods.translation_for
train
def translation_for(locale) @translation_caches ||= {} # Need to temporary switch of merging, because #translations uses # #attributes method too, to avoid stack level too deep error. @stop_merging_translated_attributes = true unless @translation_caches[locale] _translation = translations.find_by_locale(locale) _translation ||= translations.build(:locale => locale) @translation_caches[locale] = _translation end @stop_merging_translated_attributes = false @translation_caches[locale] end
ruby
{ "resource": "" }
q4806
Mongoid::Globalize.Methods.used_locales
train
def used_locales locales = globalize.stash.keys.concat(globalize.stash.keys).concat(translations.translated_locales) locales.uniq! locales end
ruby
{ "resource": "" }
q4807
Mongoid::Globalize.Methods.prepare_translations!
train
def prepare_translations! @stop_merging_translated_attributes = true translated_attribute_names.each do |name| @attributes.delete name.to_s @changed_attributes.delete name.to_s if @changed_attributes end globalize.prepare_translations! end
ruby
{ "resource": "" }
q4808
IcalImporter.SingleEventBuilder.build
train
def build # handle recuring events @local_event.tap do |le| if @event.rrule.present? @rrule = @event.rrule.first # only support recurrence on one schedule # set out new event's basic rucurring properties le.attributes = recurrence_attributes set_date_exclusion frequency_set else # make sure we remove this if it changed le.attributes = non_recurrence_attributes end end end
ruby
{ "resource": "" }
q4809
Jsonism.Definer.define_methods_into
train
def define_methods_into(client) links.each do |link| @client.define_singleton_method(link.method_signature) do |params = {}, headers = {}| Request.call(client: client, headers: headers, link: link, params: params) end end end
ruby
{ "resource": "" }
q4810
GeoWorks.BoundingBoxHelper.bbox
train
def bbox(property) markup = '' markup << %(<div id='bbox'></div>) markup << bbox_display_inputs markup << bbox_script_tag(property) markup.html_safe end
ruby
{ "resource": "" }
q4811
Grantinee.CLI.process_database_param
train
def process_database_param unless @options[:config] || Grantinee.configuration.configured? Grantinee::Engine.detect_active_record_connection! unless Grantinee.configuration.configured? raise "No configuration file found. Please use the -c option"\ " to pass a configuration file." end end require options[:config] rescue StandardError, LoadError => error puts error exit end
ruby
{ "resource": "" }
q4812
Grantinee.CLI.process_verbosity_param
train
def process_verbosity_param return unless @options[:verbose] log_levels = %w[debug info warn error fatal unknown] @logger.level = log_levels.index(@options[:verbose]) end
ruby
{ "resource": "" }
q4813
Danger.DangerShellcheck.report
train
def report(file_path) raise 'ShellCheck summary file not found' unless File.file?(file_path) shellcheck_summary = JSON.parse(File.read(file_path), symbolize_names: true) run_summary(shellcheck_summary) end
ruby
{ "resource": "" }
q4814
Danger.DangerShellcheck.parse_files
train
def parse_files(shellcheck_summary) shellcheck_summary.each do |element| file = element[:file] @files.add(file) level = element[:level] message = format_violation(file, element) if level == 'error' @error_count += 1 fail(message, sticky: false) else if level == 'warning' @warning_count += 1 elsif level == 'info' @info_count += 1 else @style_count += 1 end warn(message, sticky: false) end end end
ruby
{ "resource": "" }
q4815
Features.SessionHelpers.sign_up_with
train
def sign_up_with(email, password) Capybara.exact = true visit new_user_registration_path fill_in 'Email', with: email fill_in 'Password', with: password fill_in 'Password confirmation', with: password click_button 'Sign up' end
ruby
{ "resource": "" }
q4816
Features.SessionHelpers.sign_in
train
def sign_in(who = :user) user = if who.instance_of?(User) who else FactoryGirl.build(:user).tap(&:save!) end visit new_user_session_path fill_in 'Email', with: user.email fill_in 'Password', with: user.password click_button 'Log in' expect(page).not_to have_text 'Invalid email or password.' end
ruby
{ "resource": "" }
q4817
CouchRest.Database.clear_extended_doc_fresh_cache
train
def clear_extended_doc_fresh_cache ::CouchRest::ExtendedDocument.subclasses.each{|klass| klass.req_design_doc_refresh if klass.respond_to?(:req_design_doc_refresh)} end
ruby
{ "resource": "" }
q4818
ODT2HTML.AnalyzeContent.register_style
train
def register_style( element ) # get namespace prefix for this element style_name = element.attribute("#{element.prefix}:style-name"); if (style_name != nil) then style_name = style_name.value.tr_s('.','_') if (@style_info[style_name] != nil) then @style_info[style_name].block_used = true end end return style_name end
ruby
{ "resource": "" }
q4819
Luis.Result.entities_of_type
train
def entities_of_type(type) @entities.select { |entity| entity['type'] == type }.map { |entity| Entity.new entity } end
ruby
{ "resource": "" }
q4820
AdbSdkLib.Common.convert_map_to_hash
train
def convert_map_to_hash(object, &block) hash = Hash.new i = object.entrySet.iterator if block_given? while i.hasNext entry = i.next yield hash, entry.getKey, entry.getValue end else while i.hasNext entry = i.next hash[entry.getKey] = entry.getValue end end hash end
ruby
{ "resource": "" }
q4821
CodeModels.Parser.parse_file
train
def parse_file(path,file_encoding=nil) file_encoding = @internal_encoding unless file_encoding code = IO.read(path,{ :encoding => file_encoding, :mode => 'rb'}) code = code.encode(@internal_encoding) artifact = FileArtifact.new(path,code) parse_artifact(artifact) end
ruby
{ "resource": "" }
q4822
CodeModels.Parser.parse_string
train
def parse_string(code) code = code.encode(@internal_encoding) artifact = StringArtifact.new(code) parse_artifact(artifact) end
ruby
{ "resource": "" }
q4823
AdbSdkLib.Adb.devices
train
def devices devices = @adb.devices.map { |d| serial = d.serial_number (@devices.has_key?(serial) && same_jobject?(@devices[serial].jobject, d)) \ ? @devices[serial] : Device.new(d) } @devices = DeviceList.new(devices) return @devices end
ruby
{ "resource": "" }
q4824
VaultedBilling.CreditCard.attributes
train
def attributes { :vault_id => vault_id, :currency => currency, :card_number => card_number, :cvv_number => cvv_number, :expires_on => expires_on, :first_name => first_name, :last_name => last_name, :street_address => street_address, :locality => locality, :region => region, :postal_code => postal_code, :country => country, :phone => phone } end
ruby
{ "resource": "" }
q4825
RailsPaginate::Helpers.Array.paginate
train
def paginate(*args) options = args.extract_options! per_page = options.delete(:per_page) page = options.delete(:page) || 1 ::RailsPaginate::Collection.new(self, args.first || page, per_page) end
ruby
{ "resource": "" }
q4826
GoogleCheckout.Command.post
train
def post # Create HTTP(S) POST command and set up Basic Authentication. uri = URI.parse(url) request = Net::HTTP::Post.new(uri.path) request.basic_auth(@merchant_id, @merchant_key) # Set up the HTTP connection object and the SSL layer. https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true https.cert_store = self.class.x509_store https.verify_mode = OpenSSL::SSL::VERIFY_PEER https.verify_depth = 5 # Send the request to Google. response = https.request(request, self.to_xml) # NOTE Because Notification.parse() is used, the content of objects # will be correctly parsed no matter what the HTTP response code # is from the server. case response when Net::HTTPSuccess, Net::HTTPClientError notification = Notification.parse(response.body) if notification.error? raise APIError, "#{notification.message} [in #{GoogleCheckout.production? ? 'production' : 'sandbox' }]" end return notification when Net::HTTPRedirection, Net::HTTPServerError, Net::HTTPInformation raise "Unexpected response code (#{response.class}): #{response.code} - #{response.message}" else raise "Unknown response code: #{response.code} - #{response.message}" end end
ruby
{ "resource": "" }
q4827
GoogleCheckout.SendBuyerMessage.to_xml
train
def to_xml # :nodoc: xml = Builder::XmlMarkup.new xml.instruct! @xml = xml.tag!('send-buyer-message', { :xmlns => "http://checkout.google.com/schema/2", "google-order-number" => @google_order_number }) do xml.tag!("message", @message) xml.tag!("send-email", true) end @xml end
ruby
{ "resource": "" }
q4828
Rtasklib.Taskrc.hash_to_model
train
def hash_to_model taskrc_hash taskrc_hash.each do |attr, value| add_model_attr(attr, value) set_model_attr_value(attr, value) end config end
ruby
{ "resource": "" }
q4829
Rtasklib.Taskrc.mappable_to_model
train
def mappable_to_model rc_file rc_file.map! { |l| line_to_tuple(l) }.compact! taskrc = Hash[rc_file] hash_to_model(taskrc) end
ruby
{ "resource": "" }
q4830
Rtasklib.Taskrc.part_of_model_to_rc
train
def part_of_model_to_rc *attrs attrs.map do |attr| value = get_model_attr_value attr hash_attr = get_rc_attr_from_hash attr.to_s attr = "rc.#{hash_attr}=#{value}" end end
ruby
{ "resource": "" }
q4831
Rtasklib.Taskrc.path_exist?
train
def path_exist? path if path.is_a? Pathname return path.exist? elsif path.is_a? String return Pathname.new(path).exist? else return false end end
ruby
{ "resource": "" }
q4832
Jim.Index.find_all
train
def find_all(name, version = nil) matched = [] find(name, version) {|p| matched << p } matched end
ruby
{ "resource": "" }
q4833
HoneyFormat.Header.to_csv
train
def to_csv(columns: nil) attributes = if columns self.columns & columns.map(&:to_sym) else self.columns end ::CSV.generate_line(attributes) end
ruby
{ "resource": "" }
q4834
HoneyFormat.Header.build_columns
train
def build_columns(header) columns = header.each_with_index.map do |header_column, index| convert_column(header_column, index).tap do |column| maybe_raise_missing_column!(column) end end @deduplicator.call(columns) end
ruby
{ "resource": "" }
q4835
HoneyFormat.Header.convert_column
train
def convert_column(column, index) value = if converter_arity == 1 @converter.call(column) else @converter.call(column, index) end value.to_sym end
ruby
{ "resource": "" }
q4836
Mascot.DAT.goto
train
def goto(key) if @idx.has_key?(key.to_sym) @dat_file.pos = @idx[key.to_sym] else raise Exception.new "Invalid DAT section \"#{key}\"" end end
ruby
{ "resource": "" }
q4837
Mascot.DAT.read_section
train
def read_section(key) self.goto(key.to_sym) # read past the initial boundary marker tmp = @dat_file.readline @dat_file.each do |l| break if l =~ @boundary tmp << l end tmp end
ruby
{ "resource": "" }
q4838
Usmu.Configuration.excluded?
train
def excluded?(filename) exclude.each do |f| f += '**/*' if f.end_with? '/' return true if File.fnmatch(f, filename, File::FNM_EXTGLOB | File::FNM_PATHNAME) end false end
ruby
{ "resource": "" }
q4839
Pagination.Template.render
train
def render if engine.respond_to?(:render) engine.render(Object.new, :items => items) else engine.result(binding) end end
ruby
{ "resource": "" }
q4840
Snow.ArraySupport.map!
train
def map!(&block) return to_enum(:map!) unless block_given? (0 ... self.length).each { |index| store(index, yield(fetch(index))) } self end
ruby
{ "resource": "" }
q4841
PaynetEasy::PaynetEasyApi::Query.QueryFactory.query
train
def query(api_query_name) query_class = "#{api_query_name.camelize}Query" query_file = "query/#{api_query_name.gsub('-', '_')}_query" require query_file PaynetEasy::PaynetEasyApi::Query.const_get(query_class).new(api_query_name) end
ruby
{ "resource": "" }
q4842
JumpStart.Base.start
train
def start puts "\n******************************************************************************************************************************************\n\n" puts " JumpStarting....\n".purple check_setup execute_install_command run_scripts_from_yaml(:run_after_install_command) parse_template_dir create_dirs populate_files_from_whole_templates populate_files_from_append_templates populate_files_from_line_templates remove_unwanted_files run_scripts_from_yaml(:run_after_jumpstart) check_for_strings_to_replace run_scripts_from_yaml(:run_after_string_replace) check_local_nginx_configuration exit_with_success end
ruby
{ "resource": "" }
q4843
JumpStart.Base.check_install_path
train
def check_install_path @install_path = JumpStart::LAUNCH_PATH if @install_path.nil? || @install_path.empty? if File.directory?(FileUtils.join_paths(@install_path, @project_name)) puts "\nThe directory #{FileUtils.join_paths(@install_path, @project_name).red} already exists.\nAs this is the location you have specified for creating your new project jumpstart will now exit to avoid overwriting anything." exit_normal end return true end
ruby
{ "resource": "" }
q4844
JumpStart.Base.create_template
train
def create_template if File.directory?(FileUtils.join_paths(JumpStart.templates_path, @template_name)) puts "\nThe directory #{FileUtils.join_paths(JumpStart.templates_path, @template_name).red} already exists. The template will not be created." exit_normal else FileUtils.mkdir_p(FileUtils.join_paths(JumpStart.templates_path, @template_name, "/jumpstart_config")) yaml = IO.read(FileUtils.join_paths(ROOT_PATH, "/source_templates/template_config.yml")) File.open(FileUtils.join_paths(JumpStart.templates_path, @template_name, "/jumpstart_config", "#{@template_name}.yml"), 'w') do |file| file.puts yaml end puts "The template #{@template_name.green} has been generated.\n" end end
ruby
{ "resource": "" }
q4845
JumpStart.Base.jumpstart_menu
train
def jumpstart_menu puts "\n\n******************************************************************************************************************************************\n\n" puts " JUMPSTART MENU\n".purple puts " Here are your options:\n\n" puts " 1".yellow + " Create a new project from an existing template.\n" puts " 2".yellow + " Create a new template.\n" puts " 3".yellow + " Set the default template.\n" puts " 4".yellow + " Set the templates directory.\n\n" puts " x".yellow + " Exit jumpstart.\n\n" puts "******************************************************************************************************************************************\n\n" jumpstart_menu_options end
ruby
{ "resource": "" }
q4846
JumpStart.Base.jumpstart_menu_options
train
def jumpstart_menu_options input = gets.chomp.strip.downcase case when input == "1" new_project_from_template_menu when input == "2" new_template_menu when input == "3" set_default_template_menu when input == "4" templates_dir_menu when input == "x" exit_normal else puts "That command hasn't been understood. Try again!".red jumpstart_menu_options end end
ruby
{ "resource": "" }
q4847
JumpStart.Base.new_project_from_template_menu
train
def new_project_from_template_menu puts "\n\n******************************************************************************************************************************************\n\n" puts " CREATE A NEW JUMPSTART PROJECT FROM AN EXISTING TEMPLATE\n\n".purple puts " Type a number for the template that you want.\n\n" display_existing_templates puts "\n b".yellow + " Back to main menu." puts "\n x".yellow + " Exit jumpstart.\n\n" puts "******************************************************************************************************************************************\n\n" new_project_from_template_options end
ruby
{ "resource": "" }
q4848
JumpStart.Base.new_project_from_template_options
train
def new_project_from_template_options input = gets.chomp.strip.downcase case when input.to_i <= JumpStart.existing_templates.count && input.to_i > 0 @template_name = JumpStart.existing_templates[(input.to_i - 1)] check_project_name project = JumpStart::Base.new([@project_name, @template_name]) project.check_setup project.start when input == "b" jumpstart_menu when input == "x" exit_normal else puts "That command hasn't been understood. Try again!".red new_project_from_template_options end end
ruby
{ "resource": "" }
q4849
JumpStart.Base.new_template_menu
train
def new_template_menu puts "\n\n******************************************************************************************************************************************\n\n" puts " CREATE A NEW JUMPSTART TEMPLATE\n".purple puts " Existing templates:\n" display_existing_templates puts "\n b".yellow + " Back to main menu." puts "\n x".yellow + " Exit jumpstart.\n" new_template_options end
ruby
{ "resource": "" }
q4850
JumpStart.Base.new_template_options
train
def new_template_options puts "\n Enter a unique name to create a new template, or enter an existing templates name (or number) to duplicate it.".yellow input = gets.chomp.strip case when input.downcase == "b" jumpstart_menu when input.downcase == "x" exit_normal when JumpStart.existing_templates.include?(input) puts "\n You have chosen to duplicate the " + input.green + " template." + "\n Please enter a name for the duplicate.".yellow duplicate_template(input) when input.to_i != 0 && input.to_i <= JumpStart.existing_templates.count puts "\n You have chosen to duplicate the " + JumpStart.existing_templates[(input.to_i - 1)].green + " template." + "\n Please enter a name for the duplicate.".yellow duplicate_template(JumpStart.existing_templates[(input.to_i - 1)]) when input.length < 3 puts "\n The template name ".red + input.red_bold + " is too short. Please enter a name that is at least 3 characters long.".red new_template_options when input.match(/^\W|\W$/) puts "\n The template name ".red + input.red_bold + " begins or ends with an invalid character. Please enter a name that begins with a letter or a number.".red new_template_options else FileUtils.mkdir_p(FileUtils.join_paths(JumpStart.templates_path, input, "jumpstart_config")) FileUtils.cp(FileUtils.join_paths(ROOT_PATH, "source_templates/template_config.yml"), FileUtils.join_paths(JumpStart.templates_path, input, "jumpstart_config", "#{input}.yml")) puts "\n The template ".green + input.green_bold + " has been created in your default jumpstart template directory ".green + JumpStart.templates_path.green_bold + " ready for editing.".green jumpstart_menu end end
ruby
{ "resource": "" }
q4851
JumpStart.Base.set_default_template_menu
train
def set_default_template_menu puts "\n\n******************************************************************************************************************************************\n\n" puts " SELECT A DEFAULT JUMPSTART TEMPLATE\n".purple display_existing_templates puts "\n b".yellow + " Back to main menu.\n\n" puts " x".yellow + " Exit jumpstart.\n\n" puts "******************************************************************************************************************************************\n\n" set_default_template_options end
ruby
{ "resource": "" }
q4852
JumpStart.Base.set_default_template_options
train
def set_default_template_options input = gets.chomp.strip case when input.to_i <= JumpStart.existing_templates.count && input.to_i > 0 JumpStart.default_template_name = JumpStart.existing_templates[(input.to_i - 1)] JumpStart.dump_jumpstart_setup_yaml puts " The default jumpstart template has been set to: ".green + JumpStart.default_template_name.green_bold jumpstart_menu when input.downcase == "b" jumpstart_menu when input.downcase == "x" exit_normal else puts "That command hasn't been understood. Try again!".red set_default_template_options end end
ruby
{ "resource": "" }
q4853
JumpStart.Base.templates_dir_menu
train
def templates_dir_menu puts "\n\n******************************************************************************************************************************************\n\n" puts " JUMPSTART TEMPLATES DIRECTORY OPTIONS\n".purple puts " The JumpStart template directory is currently: " + JumpStart.templates_path.green puts "\n 1".yellow + " Change the templates directory.\n" puts " 2".yellow + " Reset the templates directory to default.\n\n" puts " b".yellow + " Back to main menu.\n\n" puts " x".yellow + " Exit jumpstart.\n\n" puts "******************************************************************************************************************************************\n\n" templates_dir_options end
ruby
{ "resource": "" }
q4854
JumpStart.Base.templates_dir_options
train
def templates_dir_options input = gets.chomp.strip.downcase case when input == "1" puts " Please enter the absolute path for the directory that you would like to contain your jumpstart templates.".yellow puts " e.g. /Users/your_name/projects/jumpstart_templates\n\n" set_templates_dir when input == "2" reset_templates_dir_to_default_check when input == "b" jumpstart_menu when input == "x" exit_normal else puts " That command hasn't been understood. Try again!".red templates_dir_options end end
ruby
{ "resource": "" }
q4855
JumpStart.Base.set_templates_dir
train
def set_templates_dir input = gets.chomp.strip root_path = input.sub(/\/\w*\/*$/, '') case when input.downcase == "b" jumpstart_menu when input.downcase == "x" exit_normal when File.directory?(input) puts "\n A directory of that name already exists, would you like to set it as your template directory anyway? (Nothing will be copied or removed.)".yellow puts " Yes (" + "y".yellow + ") or No (" + "n".yellow + ")?" set_templates_dir_to_existing_dir(input) when File.directory?(root_path) begin Dir.chdir(root_path) Dir.mkdir(input) files_and_dirs = FileUtils.sort_contained_files_and_dirs(JumpStart.templates_path) puts "\nCopying existing templates to #{input}" files_and_dirs[:dirs].each {|x| FileUtils.mkdir_p(FileUtils.join_paths(input, x))} files_and_dirs[:files].each {|x| FileUtils.cp(FileUtils.join_paths(JumpStart.templates_path, x), FileUtils.join_paths(input, x)) } JumpStart.templates_path = input.to_s JumpStart.dump_jumpstart_setup_yaml puts "\n Transfer complete!".green puts "\n The directory " + input.green + " has been set as the JumpStart templates directory." jumpstart_menu rescue puts " It looks like you do not have the correct permissions to create a directory in #{root_path.red}" end else puts " Couldn't find a directory of that name. Try again.".red set_templates_dir end end
ruby
{ "resource": "" }
q4856
JumpStart.Base.set_templates_dir_to_existing_dir
train
def set_templates_dir_to_existing_dir(dir) input = gets.chomp.strip.downcase case when input == "b" jumpstart_menu when input == "x" exit_normal when input == "y" || input == "yes" JumpStart.templates_path = dir JumpStart.dump_jumpstart_setup_yaml puts "\n The directory ".green + dir.green_bold + " has been set as the JumpStart templates directory.".green jumpstart_menu when input == "n" || input == "no" puts "\n The JumpStart templates directory has not been altered".yellow jumpstart_menu else puts "\n The command has not been understood, try again!".red set_templates_dir_to_existing_dir(dir) end end
ruby
{ "resource": "" }
q4857
JumpStart.Base.parse_template_dir
train
def parse_template_dir @dir_list = [] file_list = [] @append_templates = [] @line_templates = [] @whole_templates = [] Find.find(@template_path) do |x| case when File.file?(x) && x !~ /\/jumpstart_config/ then file_list << x.sub!(@template_path, '') when File.directory?(x) && x !~ /\/jumpstart_config/ then @dir_list << x.sub!(@template_path, '') when File.file?(x) && x =~ /\/jumpstart_config\/nginx.local.conf/ then @nginx_local_template = x when File.file?(x) && x =~ /\/jumpstart_config\/nginx.remote.conf/ then @nginx_remote_template = x end end file_list.each do |file| if file =~ /_([lL]?)\._{1}\w*/ @append_templates << file elsif file =~ /_(\d+)\._{1}\w*/ @line_templates << file else @whole_templates << file end end end
ruby
{ "resource": "" }
q4858
JumpStart.Base.populate_files_from_whole_templates
train
def populate_files_from_whole_templates @whole_templates.each {|x| FileUtils.cp(FileUtils.join_paths(@template_path, x), FileUtils.join_paths(@install_path, @project_name, x)) } unless @whole_templates.nil? end
ruby
{ "resource": "" }
q4859
JumpStart.Base.remove_unwanted_files
train
def remove_unwanted_files file_array = [] root_path = FileUtils.join_paths(@install_path, @project_name) unless @config_file[:remove_files].nil? @config_file[:remove_files].each do |file| file_array << FileUtils.join_paths(root_path, file) end FileUtils.remove_files(file_array) end end
ruby
{ "resource": "" }
q4860
JumpStart.Base.run_scripts_from_yaml
train
def run_scripts_from_yaml(script_name) unless @config_file[script_name].nil? || @config_file[script_name].empty? begin Dir.chdir(FileUtils.join_paths(@install_path, @project_name)) @config_file[script_name].each do |x| puts "\nExecuting command: #{x.green}" system "#{x}" end rescue puts "\nCould not access the directory #{FileUtils.join_paths(@install_path, @project_name).red}.\nIn the interest of safety JumpStart will NOT run any YAML scripts from #{script_name.to_s.red_bold} until it can change into the new projects home directory." end end end
ruby
{ "resource": "" }
q4861
JumpStart.Base.check_for_strings_to_replace
train
def check_for_strings_to_replace if @replace_strings.nil? || @replace_strings.empty? return false else puts "\nChecking for strings to replace inside files...\n\n" @replace_strings.each do |file| if file[:target_path].nil? || file[:symbols].nil? return false else puts "Target file: #{file[:target_path].green}\n" puts "Strings to replace:\n\n" check_replace_string_pairs_for_project_name_sub(file[:symbols]) file[:symbols].each do |x,y| puts "Key: #{x.to_s.green}" puts "Value: #{y.to_s.green}\n\n" end puts "\n" path = FileUtils.join_paths(@install_path, @project_name, file[:target_path]) FileUtils.replace_strings(path, file[:symbols]) end end end end
ruby
{ "resource": "" }
q4862
JumpStart.Base.exit_with_success
train
def exit_with_success puts "\n\n Exiting JumpStart...".purple puts "\n Success! ".green + @project_name.green_bold + " has been created at: ".green + FileUtils.join_paths(@install_path, @project_name).green_bold + "\n\n".green puts "******************************************************************************************************************************************\n" JumpStart.dump_jumpstart_setup_yaml exit end
ruby
{ "resource": "" }
q4863
Elk.Number.save
train
def save attributes = { sms_url: self.sms_url, voice_start: self.voice_start_url } # If new URL, send country, otherwise not unless self.number_id attributes[:country] = self.country end response = @client.post("/Numbers/#{self.number_id}", attributes) response.code == 200 end
ruby
{ "resource": "" }
q4864
Elk.Number.deallocate!
train
def deallocate! response = @client.post("/Numbers/#{self.number_id}", { active: "no" }) self.set_paramaters(Elk::Util.parse_json(response.body)) response.code == 200 end
ruby
{ "resource": "" }
q4865
Edgarj.CommonHelper.datetime_fmt
train
def datetime_fmt(dt) if dt.blank? then '' else I18n.l(dt, format: I18n.t('edgarj.time.format')) end end
ruby
{ "resource": "" }
q4866
Edgarj.CommonHelper.get_enum
train
def get_enum(model, col) col_name = col.name if model.const_defined?(col_name.camelize, false) enum = model.const_get(col_name.camelize) enum.is_a?(Module) ? enum : nil else nil end end
ruby
{ "resource": "" }
q4867
Magma.Templater.render
train
def render(template) template.render(config.variables.deep_merge(options[:globals]), strict_variables: true).tap do if template.errors&.length&.positive? puts template.errors raise template.errors.map(&:to_s).join('; ') end end end
ruby
{ "resource": "" }
q4868
Banklink.Common.parse
train
def parse(post) @raw = post.to_s for line in @raw.split('&') key, value = *line.scan( %r{^([A-Za-z0-9_.]+)\=(.*)$} ).flatten params[key] = CGI.unescape(value) end end
ruby
{ "resource": "" }
q4869
Languages.ManagerBasicStructureData.add_conditional
train
def add_conditional(pConditional) return nil unless pConditional.is_a?(Languages::ConditionalData) pConditional.level = @currentLevel @basicStructure.push(pConditional) end
ruby
{ "resource": "" }
q4870
Languages.ManagerBasicStructureData.add_repetition
train
def add_repetition(pRepetition) return nil unless pRepetition.is_a?(Languages::RepetitionData) pRepetition.level = @currentLevel @basicStructure.push(pRepetition) end
ruby
{ "resource": "" }
q4871
Languages.ManagerBasicStructureData.add_block
train
def add_block(pBlock) return nil unless pBlock.is_a?(Languages::BlockData) pBlock.level = @currentLevel @basicStructure.push(pBlock) end
ruby
{ "resource": "" }
q4872
XmlFu.Configuration.symbol_conversion_algorithm=
train
def symbol_conversion_algorithm=(algorithm) raise(ArgumentError, "Missing symbol conversion algorithm") unless algorithm if algorithm.respond_to?(:call) @symbol_conversion_algorithm = algorithm else if algorithm == :default @symbol_conversion_algorithm = ALGORITHMS[:lower_camelcase] elsif ALGORITHMS.keys.include?(algorithm) @symbol_conversion_algorithm = ALGORITHMS[algorithm] else raise(ArgumentError, "Invalid symbol conversion algorithm") end end end
ruby
{ "resource": "" }
q4873
CricosScrape.CourseImporter.find_course_location
train
def find_course_location location_ids = [] if location_results_paginated? for page_number in 1..total_pages jump_to_page(page_number) location_ids += fetch_location_ids_from_current_page end else location_ids += fetch_location_ids_from_current_page end location_ids end
ruby
{ "resource": "" }
q4874
GithubGem.RakeTasks.define_rspec_tasks!
train
def define_rspec_tasks! require 'rspec/core/rake_task' namespace(:spec) do desc "Verify all RSpec examples for #{gemspec.name}" RSpec::Core::RakeTask.new(:basic) do |t| t.pattern = spec_pattern end desc "Verify all RSpec examples for #{gemspec.name} and output specdoc" RSpec::Core::RakeTask.new(:specdoc) do |t| t.pattern = spec_pattern t.rspec_opts = ['--format', 'documentation', '--color'] end desc "Run RCov on specs for #{gemspec.name}" RSpec::Core::RakeTask.new(:rcov) do |t| t.pattern = spec_pattern t.rcov = true t.rcov_opts = ['--exclude', '"spec/*,gems/*"', '--rails'] end end desc "Verify all RSpec examples for #{gemspec.name} and output specdoc" task(:spec => ['spec:specdoc']) end
ruby
{ "resource": "" }
q4875
GithubGem.RakeTasks.define_tasks!
train
def define_tasks! define_test_tasks! if has_tests? define_rspec_tasks! if has_specs? namespace(@task_namespace) do desc "Updates the filelist in the gemspec file" task(:manifest) { manifest_task } desc "Builds the .gem package" task(:build => :manifest) { build_task } desc "Sets the version of the gem in the gemspec" task(:set_version => [:check_version, :check_current_branch]) { version_task } task(:check_version => :fetch_origin) { check_version_task } task(:fetch_origin) { fetch_origin_task } task(:check_current_branch) { check_current_branch_task } task(:check_clean_status) { check_clean_status_task } task(:check_not_diverged => :fetch_origin) { check_not_diverged_task } checks = [:check_current_branch, :check_clean_status, :check_not_diverged, :check_version] checks.unshift('spec:basic') if has_specs? checks.unshift('test:basic') if has_tests? # checks.push << [:check_rubyforge] if gemspec.rubyforge_project desc "Perform all checks that would occur before a release" task(:release_checks => checks) release_tasks = [:release_checks, :set_version, :build, :github_release, :gemcutter_release] # release_tasks << [:rubyforge_release] if gemspec.rubyforge_project desc "Release a new version of the gem using the VERSION environment variable" task(:release => release_tasks) { release_task } namespace(:release) do desc "Release the next version of the gem, by incrementing the last version segment by 1" task(:next => [:next_version] + release_tasks) { release_task } desc "Release the next version of the gem, using a patch increment (0.0.1)" task(:patch => [:next_patch_version] + release_tasks) { release_task } desc "Release the next version of the gem, using a minor increment (0.1.0)" task(:minor => [:next_minor_version] + release_tasks) { release_task } desc "Release the next version of the gem, using a major increment (1.0.0)" task(:major => [:next_major_version] + release_tasks) { release_task } end # task(:check_rubyforge) { check_rubyforge_task } # task(:rubyforge_release) { rubyforge_release_task } task(:gemcutter_release) { gemcutter_release_task } task(:github_release => [:commit_modified_files, :tag_version]) { github_release_task } task(:tag_version) { tag_version_task } task(:commit_modified_files) { commit_modified_files_task } task(:next_version) { next_version_task } task(:next_patch_version) { next_version_task(:patch) } task(:next_minor_version) { next_version_task(:minor) } task(:next_major_version) { next_version_task(:major) } desc "Updates the gem release tasks with the latest version on Github" task(:update_tasks) { update_tasks_task } end end
ruby
{ "resource": "" }
q4876
GithubGem.RakeTasks.version_task
train
def version_task update_gemspec(:version, ENV['VERSION']) if ENV['VERSION'] update_gemspec(:date, Date.today) update_version_file(gemspec.version) update_version_constant(gemspec.version) end
ruby
{ "resource": "" }
q4877
GithubGem.RakeTasks.update_version_file
train
def update_version_file(version) if File.exists?('VERSION') File.open('VERSION', 'w') { |f| f << version.to_s } modified_files << 'VERSION' end end
ruby
{ "resource": "" }
q4878
GithubGem.RakeTasks.update_version_constant
train
def update_version_constant(version) if main_include && File.exist?(main_include) file_contents = File.read(main_include) if file_contents.sub!(/^(\s+VERSION\s*=\s*)[^\s].*$/) { $1 + version.to_s.inspect } File.open(main_include, 'w') { |f| f << file_contents } modified_files << main_include end end end
ruby
{ "resource": "" }
q4879
JsonRecord.EmbeddedDocument.attributes=
train
def attributes= (attrs) attrs.each_pair do |name, value| field = schema.fields[name.to_s] || FieldDefinition.new(name, :type => value.class) setter = "#{name}=".to_sym if respond_to?(setter) send(setter, value) else write_attribute(field, value, self) end end end
ruby
{ "resource": "" }
q4880
JsonRecord.EmbeddedDocument.[]=
train
def []= (name, value) field = schema.fields[name.to_s] || FieldDefinition.new(name, :type => value.class) write_attribute(field, value, self) end
ruby
{ "resource": "" }
q4881
ActiveRepository.Base.reload
train
def reload object = self.id.present? ? persistence_class.where(id: self.id).first_or_initialize : self serialize! object.attributes end
ruby
{ "resource": "" }
q4882
ActiveRepository.Base.serialize!
train
def serialize!(attributes) unless attributes.nil? attributes.each do |key, value| key = "id" if key == "_id" self.send("#{key}=", (value.dup rescue value)) end end self.dup end
ruby
{ "resource": "" }
q4883
ActiveRepository.Base.convert
train
def convert(attribute="id") klass = persistence_class object = klass.where(attribute.to_sym => self.send(attribute)).first object ||= persistence_class.new attributes = self.attributes.select{ |key, value| self.class.serialized_attributes.include?(key.to_s) } attributes.delete(:id) object.attributes = attributes object.save self.id = object.id object end
ruby
{ "resource": "" }
q4884
ActiveRepository.Base.set_timestamps
train
def set_timestamps if self.errors.empty? self.created_at = DateTime.now.utc if self.respond_to?(:created_at=) && self.created_at.nil? self.updated_at = DateTime.now.utc if self.respond_to?(:updated_at=) end end
ruby
{ "resource": "" }
q4885
Atom.Element.set
train
def set(ns, element_name, value="", attributes=nil) xpath = child_xpath(ns, element_name) @elem.elements.delete_all(xpath) add(ns, element_name, value, attributes) end
ruby
{ "resource": "" }
q4886
Atom.Element.add
train
def add(ns, element_name, value, attributes={}) element = REXML::Element.new(element_name) if ns.is_a?(Namespace) unless ns.prefix.nil? || ns.prefix.empty? element.name = "#{ns.prefix}:#{element_name}" element.add_namespace ns.prefix, ns.uri unless @ns == ns || @ns == ns.uri else element.add_namespace ns.uri unless @ns == ns || @ns == ns.uri end else element.add_namespace ns unless @ns == ns || @ns.to_s == ns end if value.is_a?(Element) value.elem.each_element do |e| element.add e.deep_clone end value.elem.attributes.each_attribute do |a| unless a.name =~ /^xmlns(?:\:)?/ element.add_attribute a end end #element.text = value.elem.text unless value.elem.text.nil? text = value.elem.get_text unless text.nil? element.text = REXML::Text.new(text.to_s, true, nil, true) end else if value.is_a?(REXML::Element) element.add_element value.deep_clone else element.add_text value.to_s end end element.add_attributes attributes unless attributes.nil? @elem.add_element element end
ruby
{ "resource": "" }
q4887
Atom.Element.get_object
train
def get_object(ns, element_name, ext_class) elements = getlist(ns, element_name) return nil if elements.empty? ext_class.new(:namespace => ns, :elem => elements.first) end
ruby
{ "resource": "" }
q4888
Atom.Element.get_objects
train
def get_objects(ns, element_name, ext_class) elements = getlist(ns, element_name) return [] if elements.empty? elements.collect do |e| ext_class.new(:namespace => ns, :elem => e) end end
ruby
{ "resource": "" }
q4889
Atom.Element.to_s
train
def to_s(*) doc = REXML::Document.new decl = REXML::XMLDecl.new("1.0", "utf-8") doc.add decl doc.add_element @elem doc.to_s end
ruby
{ "resource": "" }
q4890
Atom.Element.child_xpath
train
def child_xpath(ns, element_name, attributes=nil) ns_uri = ns.is_a?(Namespace) ? ns.uri : ns unless !attributes.nil? && attributes.is_a?(Hash) "child::*[local-name()='#{element_name}' and namespace-uri()='#{ns_uri}']" else attr_str = attributes.collect{|key, val| "@#{key.to_s}='#{val}'"}.join(' and ') "child::*[local-name()='#{element_name}' and namespace-uri()='#{ns_uri}' and #{attr_str}]" end end
ruby
{ "resource": "" }
q4891
Atompub.Client.get_media
train
def get_media(media_uri) get_resource(media_uri) if @rc.instance_of?(Atom::Entry) raise ResponseError, "Response is not Media Resource" end return @rc, @res.content_type end
ruby
{ "resource": "" }
q4892
Atompub.Client.create_entry
train
def create_entry(post_uri, entry, slug=nil) unless entry.kind_of?(Atom::Entry) entry = Atom::Entry.new :stream => entry end service = @service_info.get(post_uri) unless entry.categories.all?{ |c| service.allows_category?(c) } raise RequestError, "Forbidden Category" end create_resource(post_uri, entry.to_s, Atom::MediaType::ENTRY.to_s, slug) @res['Location'] end
ruby
{ "resource": "" }
q4893
Atompub.Client.create_media
train
def create_media(media_uri, file_path, content_type, slug=nil) file_path = Pathname.new(file_path) unless file_path.is_a?(Pathname) stream = file_path.open { |f| f.binmode; f.read } service = @service_info.get(media_uri) if service.nil? raise RequestError, "Service information not found. Get service document before you do create_media." end unless service.accepts_media_type?(content_type) raise RequestError, "Unsupported Media Type: #{content_type}" end create_resource(media_uri, stream, content_type, slug) @res['Location'] end
ruby
{ "resource": "" }
q4894
Atompub.Client.update_media
train
def update_media(media_uri, file_path, content_type) file_path = Pathname.new(file_path) unless file_path.is_a?(Pathname) stream = file_path.open { |f| f.binmode; f.read } update_resource(media_uri, stream, content_type) end
ruby
{ "resource": "" }
q4895
Atompub.Client.get_contents_except_resources
train
def get_contents_except_resources(uri, &block) clear uri = URI.parse(uri) @req = Net::HTTP::Get.new uri.request_uri set_common_info(@req) @http_class.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| @res = http.request(@req) case @res when Net::HTTPOK block.call(@res) if block_given? else raise RequestError, "Failed to get contents. #{@res.code}" end end end
ruby
{ "resource": "" }
q4896
ROF::Translators.OsfToRof.fetch_from_ttl
train
def fetch_from_ttl(ttl_file) graph = RDF::Turtle::Reader.open(ttl_file, prefixes: ROF::OsfPrefixList.dup) JSON::LD::API.fromRdf(graph) end
ruby
{ "resource": "" }
q4897
ROF::Translators.OsfToRof.apply_previous_archived_version_if_applicable
train
def apply_previous_archived_version_if_applicable(rels_ext) # If a previously archived pid was passed in, use it to set pav:previousVersion # If not, check SOLR for one. pid = previously_archived_pid_finder.call(archive_type, osf_project_identifier) pid = ROF::Utility.check_solr_for_previous(config, osf_project_identifier) if pid.nil? rels_ext['pav:previousVersion'] = pid if pid rels_ext end
ruby
{ "resource": "" }
q4898
ROF::Translators.OsfToRof.build_archive_record
train
def build_archive_record this_rof = {} this_rof['owner'] = project['owner'] this_rof['type'] = 'OsfArchive' this_rof['rights'] = map_rights this_rof['rels-ext'] = map_rels_ext this_rof['metadata'] = map_metadata this_rof['files'] = [source_slug + '.tar.gz'] this_rof end
ruby
{ "resource": "" }
q4899
ROF::Translators.OsfToRof.map_creator
train
def map_creator creator = [] ttl_data[0][@osf_map['hasContributor']].each do |contributor| # Looping through the primary document and the contributors ttl_data.each do |item| next unless item['@id'] == contributor['@id'] if item[@osf_map['isBibliographic']][0]['@value'] == 'true' creator.push map_user_from_ttl(item[@osf_map['hasUser']][0]['@id']) end end end creator end
ruby
{ "resource": "" }