_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 ...
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.be...
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) cha...
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) unl...
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 e...
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 # ...
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) ...
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, ...
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...
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 ...
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_ent...
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 ...
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}\", \"...
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']['attach...
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(me...
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_it...
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?(r...
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...
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::Conn...
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) ...
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_...
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 <...
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 ...
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]....
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? @footer...
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] || { ...
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 ...
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? ...
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( par...
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 ...
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 ...
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...
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.c...
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 ...
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 ...
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 ...
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_e...
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 e...
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.goog...
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}) re...
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 = Goog...
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] language...
ruby
{ "resource": "" }