_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q8400
Pwl.Locker.change_password!
train
def change_password!(new_master_password) self.class.password_policy.validate!(new_master_password) @backend.transaction{ # Decrypt each key and value with the old master password and encrypt them with the new master password copy = {} @backend[:user].each{|k,v| # No need to (de)serialize - the value comes in as JSON and goes out as JSON new_key = Encryptor.encrypt(decrypt(k), :key => new_master_password) new_val = Encryptor.encrypt(decrypt(v), :key => new_master_password) copy[new_key] = new_val } # re-write user branch with newly encrypted keys and values @backend[:user] = copy # from now on, use the new master password as long as the object lives @master_password = new_master_password timestamp!(:last_modified) @backend[:system][:salt] = encrypt(Random.rand.to_s) } end
ruby
{ "resource": "" }
q8401
ActiveHarmony.Synchronizer.pull_object
train
def pull_object(id) local_object = @factory.with_remote_id(id) if local_object # FIXME What if there's no local object and we still want to set some # contexts? @service.set_contexts(local_object.contexts) else local_object = @factory.new end local_object.before_pull(self) if local_object.respond_to?(:before_pull) object_hash = @service.show(object_name, id) @service.clear_contexts local_object._remote_id = object_hash.delete('id') fields = configuration.synchronizable_for_pull fields.each do |key| value = object_hash[key.to_s] local_object.send("#{key}=", value) end local_object.after_pull(self) if local_object.respond_to?(:after_pull) local_object.save end
ruby
{ "resource": "" }
q8402
ActiveHarmony.Synchronizer.push_object
train
def push_object(local_object) object_name = @factory.object_name.to_sym local_object.before_push(self) if local_object.respond_to?(:before_push) changes = {} fields = configuration.synchronizable_for_push fields.each do |atr| value = local_object.send(atr) changes[atr.to_s] = value end @service.set_contexts(local_object.contexts) if local_object._remote_id @service.update(object_name, local_object._remote_id, changes) else result = @service.create(object_name, changes) if result local_object._remote_id = result['id'] fields = configuration.synchronizable_for_pull fields.each do |atr| local_object.write_attribute(atr, result[atr.to_s]) end local_object.save end end local_object.after_push(self) if local_object.respond_to?(:after_push) @service.clear_contexts end
ruby
{ "resource": "" }
q8403
ActiveHarmony.Synchronizer.pull_collection
train
def pull_collection @service.set_contexts(@contexts) collection = @service.list(object_name) @service.clear_contexts collection.each_with_index do |remote_object_hash, index| remote_id = remote_object_hash.delete("id") local_object = @factory.with_remote_id(remote_id) unless local_object local_object = @factory.new local_object.update_remote_id(remote_id) end local_object.before_pull(self) if local_object.respond_to?(:before_pull) local_object._collection_order = index fields = configuration.synchronizable_for_pull fields.each do |field| value = remote_object_hash[field.to_s] local_object.send("#{field}=", value) end local_object.after_pull(self) if local_object.respond_to?(:after_pull) local_object.save end collection.count end
ruby
{ "resource": "" }
q8404
Sem4r.AdGroup.xml
train
def xml(t) t.campaignId campaign.id t.name name t.status "ENABLED" @bids.to_xml(t) if @bids end
ruby
{ "resource": "" }
q8405
Sem4r.AdGroup.keyword
train
def keyword(text = nil, match = nil, &block) biddable_criterion = BiddableAdGroupCriterion.new(self) criterion = CriterionKeyword.new(self, text, match, &block) biddable_criterion.criterion = criterion @criterions ||= [] @criterions.push( biddable_criterion ) biddable_criterion end
ruby
{ "resource": "" }
q8406
Sem4r.AdGroup.ad_param
train
def ad_param(criterion, index = nil, text = nil, &block) ad_param = AdParam.new(self, criterion, index, text, &block) ad_param.save unless inside_initialize? or criterion.inside_initialize? @ad_params ||= [] @ad_params.push( ad_param ) ad_param end
ruby
{ "resource": "" }
q8407
Nokogiri::Decorators::XBEL.Folder.add_bookmark
train
def add_bookmark(title, href, attributes = {}, &block) attributes = attributes.merge :title => title, :href => href add_child build(:bookmark, attributes, &block) end
ruby
{ "resource": "" }
q8408
Nokogiri::Decorators::XBEL.Folder.add_folder
train
def add_folder(title, attributes = {}, &block) attributes = attributes.merge :title => title add_child build(:folder, attributes, &block) end
ruby
{ "resource": "" }
q8409
Nokogiri::Decorators::XBEL.Folder.add_alias
train
def add_alias(ref) node = Nokogiri::XML::Node.new 'alias', document node.ref = (Entry === ref) ? ref.id : ref.to_s add_child node end
ruby
{ "resource": "" }
q8410
Specfac.CLI.generate
train
def generate(*args) init_vars(options) controller = args.shift actions = args if controller sanitize(controller, actions, options) else puts "Please provide a controller name." exit end end
ruby
{ "resource": "" }
q8411
Rails3::Assist::Artifact::CRUD.Create.new_artifact_content
train
def new_artifact_content name, options = {}, &block type = get_type(options) content = extract_content type, options, &block %Q{class #{marker(name, type)} #{content} end} end
ruby
{ "resource": "" }
q8412
QLab.Reply.json
train
def json @json ||= begin JSON.parse(osc_message.to_a.first) rescue => ex puts ex.message {} end end
ruby
{ "resource": "" }
q8413
MIPPeR.GLPKModel.glpk_type
train
def glpk_type(type) case type when :integer GLPK::GLP_IV when :binary GLPK::GLP_BV when :continuous GLPK::GLP_CV else fail type end end
ruby
{ "resource": "" }
q8414
Disqussion.Applications.listUsage
train
def listUsage(*args) options = args.last.is_a?(Hash) ? args.pop : {} get('applications/listUsage', options) end
ruby
{ "resource": "" }
q8415
Smile.Smug.auth
train
def auth( email, pass ) json = secure_web_method_call( { :method => 'smugmug.login.withPassword', :EmailAddress => email, :Password => pass } ) self.session.id = json["login"]["session"]["id"] json end
ruby
{ "resource": "" }
q8416
HS.Course.find_chapter
train
def find_chapter(slug) chapters.find { |c| c.slug.to_s == slug.to_s } end
ruby
{ "resource": "" }
q8417
SDL4R.Parser.parse
train
def parse tags = [] while tokens = @tokenizer.read_line_tokens() if tokens.last.type == :START_BLOCK # tag with a block tag = construct_tag(tokens[0...-1]) add_children(tag) tags << tag elsif tokens.first.type == :END_BLOCK # we found an block end token that should have been consumed by # add_children() normally parse_error( "No opening block ({) for close block (}).", tokens.first.line, tokens.first.position) else # tag without block tags << construct_tag(tokens) end end @tokenizer.close() return tags end
ruby
{ "resource": "" }
q8418
SDL4R.Parser.add_children
train
def add_children(parent) while tokens = @tokenizer.read_line_tokens() if tokens.first.type == :END_BLOCK return elsif tokens.last.type == :START_BLOCK # found a child with a block tag = construct_tag(tokens[0...-1]); add_children(tag) parent.add_child(tag) else parent.add_child(construct_tag(tokens)) end end parse_error("No close block (}).", @tokenizer.line_no, UNKNOWN_POSITION) end
ruby
{ "resource": "" }
q8419
SDL4R.Parser.combine
train
def combine(date, time_span_with_zone) time_zone_offset = time_span_with_zone.time_zone_offset time_zone_offset = TimeSpanWithZone.default_time_zone_offset if time_zone_offset.nil? new_date_time( date.year, date.month, date.day, time_span_with_zone.hour, time_span_with_zone.min, time_span_with_zone.sec, time_zone_offset) end
ruby
{ "resource": "" }
q8420
SDL4R.Parser.expecting_but_got
train
def expecting_but_got(expecting, got, line, position) @tokenizer.expecting_but_got(expecting, got, line, position) end
ruby
{ "resource": "" }
q8421
Tracinho.ComplementBuilder.build
train
def build text = @word.hyphenated? ? remove_dash(@word.to_s) : add_dash(@word.to_s) Word.new(text) end
ruby
{ "resource": "" }
q8422
StronglyTyped.Model.initialize_from_hash
train
def initialize_from_hash(hsh) hsh.first.each_pair do |k, v| if self.class.members.include?(k.to_sym) self.public_send("#{k}=", v) else raise NameError, "Trying to assign non-existing member #{k}=#{v}" end end end
ruby
{ "resource": "" }
q8423
StronglyTyped.Model.initialize_from_ordered_args
train
def initialize_from_ordered_args(values) raise ArgumentError, "wrong number of arguments(#{values.size} for #{self.class.members.size})" if values.size > self.class.members.size values.each_with_index do |v, i| # instance_variable_set("@#{self.class.members[i]}", v) self.public_send("#{self.class.members[i]}=", v) end end
ruby
{ "resource": "" }
q8424
Pingback.Server.call
train
def call(env) @request = Rack::Request.new(env) xml_response = @xmlrpc_handler.process(request_body) [200, {'Content-Type' => 'text/xml'}, [xml_response]] end
ruby
{ "resource": "" }
q8425
Buzzsprout.Episode.duration=
train
def duration=(value) new_duration = value.to_s.split(":").reverse s, m = new_duration self[:duration] = (s.to_i + (m.to_i*60)) end
ruby
{ "resource": "" }
q8426
Stairs.Step.provide
train
def provide(prompt, options = {}) options.reverse_merge! required: true, default: nil required = options[:required] && !options[:default] prompt = "#{defaulted_prompt(prompt, options[:default])}: " if Stairs.configuration.use_defaults && options[:default] options[:default] else Stairs::Util::CLI.collect(prompt.blue, required: required) || options[:default] end end
ruby
{ "resource": "" }
q8427
Stairs.Step.env
train
def env(name, value) ENV[name] = value if value Stairs.configuration.env_adapter.set name, value else Stairs.configuration.env_adapter.unset name end end
ruby
{ "resource": "" }
q8428
DirCat.CatOnYaml.from_dir
train
def from_dir(dirname) unless File.directory?(dirname) raise "'#{dirname}' is not a directory or doesn't exists" end @dirname = File.expand_path dirname @ctime = DateTime.now _load_from_dir self end
ruby
{ "resource": "" }
q8429
DirCat.CatOnYaml.from_file
train
def from_file(filename) unless File.exist?(filename) raise DirCatException.new, "'#{filename}' not exists" end dircat_ser = File.open(filename) { |f| YAML::load(f) } @dirname = dircat_ser.dirname @ctime = dircat_ser.ctime dircat_ser.entries.each do |entry_ser| add_entry(Entry.from_ser(entry_ser)) end self end
ruby
{ "resource": "" }
q8430
DirCat.CatOnYaml.save_to
train
def save_to(file) if file.kind_of?(String) begin File.open(file, "w") do |f| f.puts to_ser.to_yaml end rescue Errno::ENOENT raise DirCatException.new, "DirCat: cannot write into '#{file}'", caller end else file.puts to_ser.to_yaml end end
ruby
{ "resource": "" }
q8431
DirCat.CatOnYaml.report
train
def report dups = duplicates s = "Base dir: #{@dirname}\n" s += "Nr. file: #{size}" if dups.size > 0 s+= " (duplicates #{dups.size})" end s += "\nBytes: #{bytes.with_separator}" s end
ruby
{ "resource": "" }
q8432
DirCat.CatOnYaml.script_dup
train
def script_dup r = "require 'fileutils'\n" duplicates.each do |entries| flg_first = true r += "\n" entries.each do |entry| src = File.join(@dirname, entry.path, entry.name) if flg_first flg_first = false r += "# FileUtils.mv( \"#{src}\", \"#{Dir.tmpdir}\" )\n" else r += "FileUtils.mv( \"#{src}\", \"#{Dir.tmpdir}\" )\n" end end end r end
ruby
{ "resource": "" }
q8433
Reaction.Registry.add
train
def add(channel, client) @lock.synchronize do _remove(client) if @clients.include? client and @clients[client] != channel debug { "Adding #{client} to #{channel}." } @clients[client] = channel @channels[channel] = @channels[channel] ? @channels[channel] + 1 : 1 end end
ruby
{ "resource": "" }
q8434
Reaction.Registry._remove
train
def _remove(client) return unless @clients.include? client channel = @clients.delete(client) debug { "Removing #{client} from #{channel}." } @channels[channel] -= 1 @channels.delete(channel) if @channels[channel].zero? end
ruby
{ "resource": "" }
q8435
Idlc.Helpers.system_command
train
def system_command(*command_args) cmd = Mixlib::ShellOut.new(*command_args) cmd.run_command cmd end
ruby
{ "resource": "" }
q8436
RenoteDac.ServiceQueueWorker.work
train
def work(message) # invoke service object to save message to database message = JSON.parse(message) RenoteDac::Mailer.enqueue( message['postmark_data']['template'], message['postmark_data']['address'], message['postmark_data']['params'], message['postmark_data']['attachments'] ) # let queue know message was received ack! end
ruby
{ "resource": "" }
q8437
Dboard.Collector.update_source
train
def update_source(source, instance) begin data = instance.fetch publish_data(source, data) ensure @after_update_callback.call end rescue Exception => ex puts "Failed to update #{source}: #{ex.message}" puts ex.backtrace @error_callback.call(ex) end
ruby
{ "resource": "" }
q8438
StorageRoom.Proxy.method_missing
train
def method_missing(method_name, *args, &block) if @object.loaded? || METHODS_WITHOUT_RELOAD.include?(method_name) # no need to reload else StorageRoom.log("Reloading #{@object['url']} due to #{method_name}") @object.reload(@object['url'], @parameters) end @object.send(method_name, *args, &block) end
ruby
{ "resource": "" }
q8439
GovukNavigationHelpers.GroupedRelatedLinks.tagged_to_same_mainstream_browse_page
train
def tagged_to_same_mainstream_browse_page return [] unless content_item.parent @tagged_to_same_mainstream_browse_page ||= content_item.related_links.select do |related_item| related_item.mainstream_browse_pages.map(&:content_id).include?(content_item.parent.content_id) end end
ruby
{ "resource": "" }
q8440
GovukNavigationHelpers.GroupedRelatedLinks.parents_tagged_to_same_mainstream_browse_page
train
def parents_tagged_to_same_mainstream_browse_page return [] unless content_item.parent && content_item.parent.parent common_parent_content_ids = tagged_to_same_mainstream_browse_page.map(&:content_id) @parents_tagged_to_same_mainstream_browse_page ||= content_item.related_links.select do |related_item| next if common_parent_content_ids.include?(related_item.content_id) related_item.mainstream_browse_pages.map(&:parent).map(&:content_id).include?(content_item.parent.parent.content_id) end end
ruby
{ "resource": "" }
q8441
GovukNavigationHelpers.GroupedRelatedLinks.tagged_to_different_mainstream_browse_pages
train
def tagged_to_different_mainstream_browse_pages all_content_ids = (tagged_to_same_mainstream_browse_page + parents_tagged_to_same_mainstream_browse_page).map(&:content_id) @tagged_to_different_mainstream_browse_pages ||= content_item.related_links.reject do |related_item| all_content_ids.include?(related_item.content_id) end end
ruby
{ "resource": "" }
q8442
Yokunai.Template.render
train
def render(template, context = {}) return nil unless exist?(template) path = File.join(@template_path, template + ".erb") layout_context = context.merge(partial: ERB.new(File.read(path)).result(Yokunai::RenderContext.new(context).get_binding)) ERB.new(@raw_layout).result(Yokunai::RenderContext.new(layout_context).get_binding) end
ruby
{ "resource": "" }
q8443
Nagios.Alerter.connection_params
train
def connection_params(host, port) params = {} if !host.nil? params[:host] = host elsif !Nagios::Connection.instance.host.nil? params[:host] = Nagios::Connection.instance.host else raise ArgumentError, "You must provide a Nagios host or use Nagios::Connection" end if !port.nil? params[:port] = port elsif !Nagios::Connection.instance.port.nil? params[:port] = Nagios::Connection.instance.port else raise ArgumentError, "You must provide a Nagios port or use Nagios::Connection" end return params end
ruby
{ "resource": "" }
q8444
Buildr.RepositoryArray.concat
train
def concat(urls) if !urls.nil? converted = urls.map { |url| convert_remote_url( url ) } super(converted) else super(nil) end end
ruby
{ "resource": "" }
q8445
Buildr.RepositoryArray.replace
train
def replace( other_array ) if !other_array.nil? converted = other_array.map { |url| convert_remote_url( url ) } super( converted ) else super( nil ) end end
ruby
{ "resource": "" }
q8446
LinkShrink.Request.request
train
def request(new_url, shrinker) shrinker.url = new_url Typhoeus::Request.new( shrinker.api_url, method: shrinker.http_method, body: shrinker.body_parameters(shrinker.url), headers: { 'Content-Type' => shrinker.content_type } ).run end
ruby
{ "resource": "" }
q8447
Implements.Interface.implementation
train
def implementation(*selectors) selectors << :auto if selectors.empty? Implementation::Registry::Finder.new(@implementations, selectors) end
ruby
{ "resource": "" }
q8448
SiteseekerNormalizer.Parse.clean_up
train
def clean_up @doc.css(".ess-separator").remove @doc.css("@title").remove @doc.css("@onclick").remove @doc.css("@tabindex").remove @doc.css(".ess-label-hits").remove @doc.css(".ess-clear").remove end
ruby
{ "resource": "" }
q8449
Confuse.KeySplitter.possible_namespaces
train
def possible_namespaces namespaces = [] key = @key.to_s while (index = key.rindex('_')) key = key[0, index] namespaces << key.to_sym end namespaces end
ruby
{ "resource": "" }
q8450
Confuse.KeySplitter.rest_of_key
train
def rest_of_key(namespace) return nil if @key == namespace key = @key.to_s index = key.index(namespace.to_s) && (namespace.to_s.length + 1) key[index, key.length].to_sym if index end
ruby
{ "resource": "" }
q8451
Mixture.Attribute.update
train
def update(value) @list.callbacks[:update].inject(value) { |a, e| e.call(self, a) } end
ruby
{ "resource": "" }
q8452
Ripl.ShellCommands.loop_eval
train
def loop_eval(input) if (@buffer.nil? && input =~ PATTERN) command = input[1..-1] name, arguments = ShellCommands.parse(command) unless BLACKLIST.include?(name) if BUILTIN.include?(name) arguments ||= [] return ShellCommands.send(name,*arguments) elsif EXECUTABLES[name] return ShellCommands.exec(name,*arguments) end end end super(input) end
ruby
{ "resource": "" }
q8453
Releaselog.Changelog.section
train
def section(section_changes, header, entry_style, header_style = nil) return "" unless section_changes.size > 0 str = "" unless header.empty? if header_style str << header_style.call(header) else str << header end end section_changes.each_with_index do |e, i| str << entry_style.call(e, i) end str end
ruby
{ "resource": "" }
q8454
Releaselog.Changelog.to_slack
train
def to_slack str = "" str << tag_info { |t| t } str << commit_info { |ci| ci.empty? ? "" : "(_#{ci}_)\n" } str << sections( changes, -> (header) { "*#{header.capitalize}*\n" }, -> (field, _index) { "\t- #{field}\n" } ) str end
ruby
{ "resource": "" }
q8455
Bixby.ThreadPool.grow
train
def grow @lock.synchronize do prune logger.debug { "jobs: #{num_jobs}; busy: #{num_working}; idle: #{num_idle}" } if @size == 0 || (@size < @max_size && num_jobs > 0 && num_jobs > num_idle) then space = @max_size-@size jobs = num_jobs-num_idle needed = space < jobs ? space : jobs needed = 1 if needed <= 0 expand(needed) else logger.debug "NOT growing the pool!" end end nil end
ruby
{ "resource": "" }
q8456
ZTK.Config.method_missing
train
def method_missing(method_symbol, *method_args) if method_args.length > 0 _set(method_symbol, method_args.first) end _get(method_symbol) end
ruby
{ "resource": "" }
q8457
Taxonifi::Export.Base.write_file
train
def write_file(filename = 'foo', string = nil) raise ExportError, 'Nothing to export for #{filename}.' if string.nil? || string == "" f = File.new( File.expand_path(File.join(export_path, filename)), 'w+') f.puts string f.close end
ruby
{ "resource": "" }
q8458
JunoReport.Pdf.new_page
train
def new_page @pdf.start_new_page set_pos_y print_section :page unless @sections[:page].nil? set_pos_y (@sections[:body][:settings][:posY] || 0) @current_groups.each do |field, value| print_section field.to_sym, @record, true end draw_columns end
ruby
{ "resource": "" }
q8459
JunoReport.Pdf.symbolize!
train
def symbolize! hash hash.symbolize_keys! hash.values.select{|v| v.is_a? Hash}.each{|h| symbolize!(h)} end
ruby
{ "resource": "" }
q8460
JunoReport.Pdf.get_sections
train
def get_sections symbolize! @rules raise "[body] section on YAML file is needed to generate the report." if @rules[:body].nil? @sections = {:page => @rules[:page], :body => @rules[:body], :defaults => @rules[:defaults], :groups => {}} @sections[:body][:settings][:groups].each { |group| @sections[:groups][group.to_sym] = @rules[group.to_sym] } if has_groups? end
ruby
{ "resource": "" }
q8461
JunoReport.Pdf.initialize_footer_values
train
def initialize_footer_values @sections[:body][:settings][:groups].each do |group| current_footer = {} @sections[:groups][group.to_sym][:footer].each { |field, settings| current_footer[field] = nil } unless @sections[:groups][group.to_sym][:footer].nil? @footers[group.to_sym] = current_footer unless current_footer.empty? end if has_groups? raise "The report must have at least a footer on body section" if @sections[:body][:footer].nil? current_footer = {} @sections[:body][:footer].each { |field, settings| current_footer[field] = nil } @footers[:body] = current_footer unless current_footer.empty? end
ruby
{ "resource": "" }
q8462
JunoReport.Pdf.draw_footer
train
def draw_footer footers_to_print, source footers_to_print.reverse_each do |group| draw_line(@posY + @sections[:body][:settings][:height]/2) source[group][:footer].each do |field, settings| settings = [settings[0], @posY, (@defaults.merge (settings[1] || { }).symbolize_keys!)] settings[2][:style] = settings[2][:style].to_sym set_options settings[2] draw_text @footers[group][field], settings end draw_line(@posY - @sections[:body][:settings][:height]/4) set_pos_y @sections[:body][:settings][:height] reset_footer group end end
ruby
{ "resource": "" }
q8463
Edoors.Spin.release_p
train
def release_p p # hope there is no circular loop while p2=p.merged_shift release_p p2 end p.reset! ( @pool[p.class] ||= [] ) << p end
ruby
{ "resource": "" }
q8464
Edoors.Spin.require_p
train
def require_p p_kls l = @pool[p_kls] return p_kls.new if l.nil? p = l.pop return p_kls.new if p.nil? p end
ruby
{ "resource": "" }
q8465
Edoors.Spin.process_sys_p
train
def process_sys_p p if p.action==Edoors::SYS_ACT_HIBERNATE stop! hibernate! p[FIELD_HIBERNATE_PATH] else super p end end
ruby
{ "resource": "" }
q8466
Edoors.Spin.spin!
train
def spin! start! @run = true @hibernation = false while @run and (@sys_fifo.length>0 or @app_fifo.length>0) while @run and @sys_fifo.length>0 p = @sys_fifo.shift p.dst.process_sys_p p end while @run and @app_fifo.length>0 p = @app_fifo.shift p.dst.process_p p break end end stop! end
ruby
{ "resource": "" }
q8467
Edoors.Spin.hibernate!
train
def hibernate! path=nil @hibernation = true File.open(path||@hibernate_path,'w') do |f| f << JSON.pretty_generate(self) end end
ruby
{ "resource": "" }
q8468
DwCAContentAnalyzer.Column.collapse
train
def collapse(types) return types.first if types.size == 1 return nil if types.empty? return String if string?(types) return Float if float?(types) String end
ruby
{ "resource": "" }
q8469
SiteAnalyzer.Page.remote_a
train
def remote_a return unless @page_a_tags remote_a = [] @page_a_tags.uniq.each do |link| uri = URI(link[0].to_ascii) if uri && @site_domain remote_a << link[0] unless uri.host == @site_domain end end remote_a end
ruby
{ "resource": "" }
q8470
SiteAnalyzer.Page.fill_data_field!
train
def fill_data_field! @all_titles = titles @meta_data = collect_metadates @title_h1_h2 = all_titles_h1_h2 @page_text_size = text_size @page_a_tags = all_a_tags @meta_desc_content = all_meta_description_content @h2_text = h2 @hlu = bad_url @title_good = title_good? @title_and_h1_good = title_and_h1_good? @meta_description_good = metadescription_good? @meta_keywords = keywords_good? @code_less = code_less? @meta_title_duplicates = metadates_good? @have_h2 = h2? end
ruby
{ "resource": "" }
q8471
SiteAnalyzer.Page.get_page
train
def get_page(url) timeout(30) do page = open(url) @site_domain = page.base_uri.host @page_path = page.base_uri.request_uri @page = Nokogiri::HTML(page) end rescue Timeout::Error, EOFError, OpenURI::HTTPError, Errno::ENOENT, TypeError return nil end
ruby
{ "resource": "" }
q8472
SiteAnalyzer.Page.title_and_h1_good?
train
def title_and_h1_good? return unless @page arr = [] @page.css('h1').each { |node| arr << node.text } @page.css('title').size == 1 && arr.uniq.size == arr.size end
ruby
{ "resource": "" }
q8473
SiteAnalyzer.Page.metadescription_good?
train
def metadescription_good? return unless @page tags = @page.css("meta[name='description']") return false if tags.size == 0 tags.each do |t| unless t['value'].nil? return false if t['content'].size == 0 || t['content'].size > 200 end end true end
ruby
{ "resource": "" }
q8474
SiteAnalyzer.Page.code_less?
train
def code_less? return unless @page sum = 0 page_text = @page.text.size @page.css('script').each do |tag| sum += tag.text.size end sum < page_text / 2 end
ruby
{ "resource": "" }
q8475
SiteAnalyzer.Page.metadates_good?
train
def metadates_good? return unless @page return false if @all_titles.size > 1 || @meta_data.empty? node_names = [] @meta_data.each { |node| node_names << node['name'] } node_names.compact! node_names.uniq.size == node_names.size unless node_names.nil? || node_names.size < 1 end
ruby
{ "resource": "" }
q8476
SiteAnalyzer.Page.all_titles_h1_h2
train
def all_titles_h1_h2 return unless @page out = [] out << @page.css('title').text << { @page_url => @page.css('h1').text } out << { @page_url => @page.css('h2').text } out end
ruby
{ "resource": "" }
q8477
SiteAnalyzer.Page.all_a_tags
train
def all_a_tags return unless @page tags = [] @page.css('a').each do |node| tags << [node['href'], node['target'], node['rel']] end tags.compact end
ruby
{ "resource": "" }
q8478
Smile.Common.default_params
train
def default_params @params ||= { :api_key => session.api_key } @params.merge!( :session_id => session.id ) if( session.id ) @params = Smile::ParamConverter.clean_hash_keys( @params ) end
ruby
{ "resource": "" }
q8479
Smile.Common.base_web_method_call
train
def base_web_method_call( web_options, options ={}, url ) options = Smile::ParamConverter.clean_hash_keys( options ) web_options = Smile::ParamConverter.clean_hash_keys( web_options ) params = default_params.merge( web_options ) params.merge!( options ) if( options ) logger.info( params.inspect ) json = RestClient.post( url, params ).body upper_hash_to_lower_hash( Smile::Json.parse( json ) ) end
ruby
{ "resource": "" }
q8480
Smile.Common.upper_hash_to_lower_hash
train
def upper_hash_to_lower_hash( upper ) case upper when Hash upper.inject({}) do |lower,array| key, value = array lower[key.downcase] = upper_hash_to_lower_hash( value ) lower end else upper end end
ruby
{ "resource": "" }
q8481
CanCanNamespace.Rule.relevant?
train
def relevant?(action, subject, context = nil) subject = subject.values.first if subject.class == Hash @match_all || (matches_action?(action) && matches_subject?(subject) && matches_context(context)) end
ruby
{ "resource": "" }
q8482
JenkinsJunitBuilder.Suite.build_report
train
def build_report # build cases builder = Nokogiri::XML::Builder.new do |xml| xml.testsuites { testsuite = xml.testsuite { @cases.each do |tc| testcase = xml.testcase { if tc.result_has_message? result_type = xml.send(tc.result) result_type[:message] = tc.message if tc.message.present? end if tc.system_out.size > 0 xml.send('system-out') { xml.text tc.system_out.to_s } end if tc.system_err.size > 0 xml.send('system-err') { xml.text tc.system_err.to_s } end } testcase[:name] = tc.name if tc.name.present? testcase[:time] = tc.time if tc.time.present? testcase[:classname] = package if package.present? if tc.classname.present? if testcase[:classname].present? testcase[:classname] = "#{testcase[:classname]}.#{tc.classname}" else testcase[:classname] = tc.classname end end end } testsuite[:name] = name if name.present? testsuite[:package] = package if package.present? } end builder.parent.root.to_xml end
ruby
{ "resource": "" }
q8483
JenkinsJunitBuilder.Suite.write_report_file
train
def write_report_file raise FileNotFoundException.new 'There is no report file path specified' if report_path.blank? report = build_report if append_report.present? && File.exist?(report_path) f = File.open(report_path) existing_xml = Nokogiri::XML(f) f.close report = existing_xml.root << Nokogiri::XML(report).at('testsuite') # formatting report = format_xml report.to_xml end File.write report_path, report report end
ruby
{ "resource": "" }
q8484
Checkdin.Client.return_error_or_body
train
def return_error_or_body(response) if response.status / 100 == 2 response.body else raise Checkdin::APIError.new(response.status, response.body) end end
ruby
{ "resource": "" }
q8485
MIPPeR.CbcModel.set_variable_bounds
train
def set_variable_bounds(var_index, lb, ub, force = false) # This is a bit of a hack so that we don't try to set # the variable bounds before they get added to the model return unless force Cbc.Cbc_setColLower @ptr, var_index, lb Cbc.Cbc_setColUpper @ptr, var_index, ub end
ruby
{ "resource": "" }
q8486
MIPPeR.CbcModel.new_model
train
def new_model ptr = FFI::AutoPointer.new Cbc.Cbc_newModel, Cbc.method(:Cbc_deleteModel) # Older versions of COIN-OR do not support setting the log level via # the C interface in which case setParameter will not be defined Cbc.Cbc_setParameter ptr, 'logLevel', '0' \ if Cbc.respond_to?(:Cbc_setParameter) ptr end
ruby
{ "resource": "" }
q8487
MIPPeR.CbcModel.build_constraint_matrix
train
def build_constraint_matrix(constrs) store_constraint_indexes constrs # Construct a matrix of non-zero values in CSC format start = [] index = [] value = [] col_start = 0 @variables.each do |var| # Mark the start of this column start << col_start var.constraints.each do |constr| col_start += 1 index << constr.index value << constr.expression.terms[var] end end start << col_start [start, index, value] end
ruby
{ "resource": "" }
q8488
MIPPeR.CbcModel.store_model
train
def store_model(constrs, vars) # Store all constraints constrs.each do |constr| store_constraint constr @constraints << constr end # We store variables now since they didn't exist earlier vars.each_with_index do |var, i| var.index = i var.model = self store_variable var end end
ruby
{ "resource": "" }
q8489
MIPPeR.CbcModel.store_constraint_bounds
train
def store_constraint_bounds(index, sense, rhs) case sense when :== lb = ub = rhs when :>= lb = rhs ub = Float::INFINITY when :<= lb = -Float::INFINITY ub = rhs end Cbc.Cbc_setRowLower @ptr, index, lb Cbc.Cbc_setRowUpper @ptr, index, ub end
ruby
{ "resource": "" }
q8490
MIPPeR.CbcModel.store_variable
train
def store_variable(var) # Force the correct bounds since we can't explicitly specify binary if var.type == :binary var.instance_variable_set(:@lower_bound, 0) var.instance_variable_set(:@upper_bound, 1) end set_variable_bounds var.index, var.lower_bound, var.upper_bound, true Cbc.Cbc_setObjCoeff @ptr, var.index, var.coefficient Cbc.Cbc_setColName(@ptr, var.index, var.name) unless var.name.nil? set_variable_type var.index, var.type end
ruby
{ "resource": "" }
q8491
Ecm.CalendarHelper.month_calendar
train
def month_calendar(date = Time.zone.now.to_date, elements = [], options = {}) options.reverse_merge! :date_method => :start_at, :display_method => :to_s, :link_elements => true, :start_day => :sunday, start_date_method: nil, end_date_method: nil display_method = options.delete(:display_method) link_elements = options.delete(:link_elements) start_date_method = options.delete(:start_date_method) end_date_method = options.delete(:end_date_method) # calculate beginning and end of month beginning_of_month = date.beginning_of_month.to_date end_of_month = date.end_of_month.to_date # Get localized day names localized_day_names = I18n.t('date.abbr_day_names').dup # Shift day names to suite start day english_day_names = [:sunday, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday] # Raise an exception if the passed start day is not an english day name raise ":start_day option for month_calendar must be in: #{english_day_names.join(', ')}, but you passed: #{options[:start_day].to_s} (class: #{options[:start_day].class.to_s})" unless english_day_names.include?(options[:start_day]) # Get the offset of start day offset = english_day_names.index(options[:start_day]) last_day_of_week = Time.zone.now.end_of_week.wday # Change calendar heading if offset is not 0 (offset 0 means sunday is the first day of the week) offset.times do localized_day_names.push(localized_day_names.shift) end days_by_week = {} first_day = beginning_of_month.beginning_of_week last_day = end_of_month.end_of_week days = (first_day..last_day).each_with_object({}).with_index do |(day, memo), index| memo[day.to_date] = elements.find_all do |e| if start_date_method.present? && end_date_method.present? day.to_date.between?(e.send(start_date_method), e.send(end_date_method)) else e.send(options[:date_method]).to_date == day.to_date end end || {} end days_by_week = days.each_with_object({}) { |(k, v), m| (m[k.cweek] ||= {})[k] = v } render partial: 'ecm/calendar_helper/month_calendar', locals: { localized_day_names: localized_day_names, days_by_week: days_by_week, display_method: display_method, link_elements: link_elements } end
ruby
{ "resource": "" }
q8492
Weechat.Buffer.command
train
def command(*parts) parts[0][0,0] = '/' unless parts[0][0..0] == '/' line = parts.join(" ") Weechat.exec(line, self) line end
ruby
{ "resource": "" }
q8493
Weechat.Buffer.send
train
def send(*text) text[0][0,0] = '/' if text[0][0..0] == '/' line = text.join(" ") Weechat.exec(line) line end
ruby
{ "resource": "" }
q8494
Weechat.Buffer.lines
train
def lines(strip_colors = false) lines = [] Weechat::Infolist.parse("buffer_lines", @ptr).each do |line| line = Weechat::Line.from_hash(line) if strip_colors line.prefix.strip_colors! line.message.strip_colors! end lines << line end lines end
ruby
{ "resource": "" }
q8495
Weechat.Buffer.bind_keys
train
def bind_keys(*args) keys = args[0..-2] command = args[-1] keychain = keys.join("-") if command.is_a? Command command = command.command end set("key_bind_#{keychain}", command) @keybinds[keys] = command keychain end
ruby
{ "resource": "" }
q8496
GoogleAPI.API.request
train
def request(method, url = nil, options = {}) options[:headers] = {'Content-Type' => 'application/json'}.merge(options[:headers] || {}) options[:body] = options[:body].to_json if options[:body].is_a?(Hash) # Adopt Google's API erorr handling recommendation here: # https://developers.google.com/drive/handle-errors#implementing_exponential_backoff # # In essence, we try 5 times to perform the request. With each subsequent request, # we wait 2^n seconds plus a random number of milliseconds (no greater than 1 second) # until either we receive a successful response, or we run out of attempts. # If the Retry-After header is in the error response, we use whichever happens to be # greater, our calculated wait time, or the value in the Retry-After header. # # If development_mode is set to true, we only run the request once. This speeds up # development for those using this gem. attempt = 0 max_attempts = GoogleAPI.development_mode ? 1 : 5 while attempt < max_attempts response = access_token.send(method.to_sym, url, options) seconds_to_wait = [((2 ** attempt) + rand), response.headers['Retry-After'].to_i].max attempt += 1 break if response.status < 400 || attempt == max_attempts GoogleAPI.logger.error "Request attempt ##{attempt} to #{url} failed for. Trying again in #{seconds_to_wait} seconds..." sleep seconds_to_wait end response.parsed || response end
ruby
{ "resource": "" }
q8497
GoogleAPI.API.upload
train
def upload(api_method, url, options = {}) mime_type = ::MIME::Types.type_for(options[:media]).first.to_s file = File.read(options.delete(:media)) options[:body][:mimeType] = mime_type options[:headers] = (options[:headers] || {}).merge({'X-Upload-Content-Type' => mime_type}) response = request(api_method, url, options) options[:body] = file options[:headers].delete('X-Upload-Content-Type') options[:headers].merge!({'Content-Type' => mime_type, 'Content-Length' => file.bytesize.to_s}) request(:put, response.headers['Location'], options) end
ruby
{ "resource": "" }
q8498
GoogleAPI.API.build_url
train
def build_url(api_method, options = {}) if api_method['mediaUpload'] && options[:media] # we need to do [1..-1] to remove the prepended slash url = GoogleAPI.discovered_apis[api]['rootUrl'] + api_method['mediaUpload']['protocols']['resumable']['path'][1..-1] else url = GoogleAPI.discovered_apis[api]['baseUrl'] + api_method['path'] query_params = [] api_method['parameters'].each_with_index do |(param, settings), index| param = param.to_sym case settings['location'] when 'path' raise ArgumentError, ":#{param} was not passed" if settings['required'] && !options[param] url.sub!("{#{param}}", options.delete(param).to_s) when 'query' query_params << "#{param}=#{options.delete(param)}" if options[param] end end if api_method['parameters'] url += "?#{query_params.join('&')}" if query_params.length > 0 end [url, options] end
ruby
{ "resource": "" }
q8499
I18nLanguageSelect.InstanceTag.language_code_select
train
def language_code_select(priority_languages, options, html_options) selected = object.send(@method_name) if object.respond_to?(@method_name) languages = "" if options.present? and options[:include_blank] option = options[:include_blank] == true ? "" : options[:include_blank] languages += "<option>#{option}</option>\n" end if priority_languages languages += options_for_select(priority_languages, selected) languages += "<option value=\"\" disabled=\"disabled\">-------------</option>\n" end languages = languages + options_for_select(language_translations, selected) html_options = html_options.stringify_keys add_default_name_and_id(html_options) content_tag(:select, languages.html_safe, html_options) end
ruby
{ "resource": "" }