_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q5400
GuessHtmlEncoding.HTMLScanner.charset_from_meta_content
train
def charset_from_meta_content(string) charset_match = string.match(/charset\s*\=\s*(.+)/i) if charset_match charset_value = charset_match[1] charset_value[/\A\"(.*)\"/, 1] || charset_value[/\A\'(.*)\'/, 1] || charset_value[/(.*)[\s;]/, 1] || charset_value[/(.*)/, 1] else nil end end
ruby
{ "resource": "" }
q5401
GuessHtmlEncoding.HTMLScanner.attribute_value
train
def attribute_value(string) attribute_value = '' position = 0 length = string.length while position < length # x09 (ASCII TAB), 0x0A (ASCII LF), 0x0C (ASCII FF), 0x0D (ASCII CR), or 0x20 (ASCII space) then advance position to the next byte, then, repeat this step. if string[position] =~ /[\u{09}\u{0A}\u{0C}\u{0D}\u{20}]/ position += 1 elsif string[position] =~ /['"]/ attribute_value, position = quoted_value(string[position, length]) break elsif string[position] == '>' position += 1 break else attribute_value, position = unquoted_value(string[position, length]) break end end [attribute_value, position] end
ruby
{ "resource": "" }
q5402
OQGraph.Node.create_edge_to_and_from
train
def create_edge_to_and_from(other, weight = 1.0) self.class.edge_class.create!(:from_id => id, :to_id => other.id, :weight => weight) self.class.edge_class.create!(:from_id => other.id, :to_id => id, :weight => weight) end
ruby
{ "resource": "" }
q5403
OQGraph.Node.path_weight_to
train
def path_weight_to(other) shortest_path_to(other,:method => :djikstra).map{|edge| edge.weight.to_f}.sum end
ruby
{ "resource": "" }
q5404
GuiGeo.Rectangle.bound
train
def bound(val) case val when Rectangle then r = val.clone r.size = r.size.min(size) r.loc = r.loc.bound(loc, loc + size - val.size) r when Point then (val-loc).bound(point, size) + loc else raise ArgumentError.new("wrong type: (#{val.class}) - Rectangle or Point expected") end end
ruby
{ "resource": "" }
q5405
GuiGeo.Rectangle.disjoint
train
def disjoint(b) return self if !b || contains(b) return b if b.contains(self) return self,b unless overlaps?(b) tl_contained = contains?(b.tl) ? 1 : 0 tr_contained = contains?(b.tr) ? 1 : 0 bl_contained = contains?(b.bl) ? 1 : 0 br_contained = contains?(b.br) ? 1 : 0 sum = tl_contained + tr_contained + bl_contained + br_contained case sum when 0 # rectangles form a plus "+" if b.y < self.y r1,r2 = b,self else r1,r2 = self,b end tl1 = r1.tl br1 = point(r1.right, r2.top) tl2 = point(r1.left, r2.bottom) br2 = r1.br [ r2, rect(tl1,br1-tl1), rect(tl2,br2-tl2), ] when 1 when 2 else raise "internal error in disjoint - cases 3 and 4 should be taken care of by the return-tests at the top of the method" end end
ruby
{ "resource": "" }
q5406
PogoPlug.Client.version
train
def version response = get('/getVersion', {}, false) ApiVersion.new(response.body['version'], response.body['builddate']) end
ruby
{ "resource": "" }
q5407
PogoPlug.Client.devices
train
def devices response = get('/listDevices') devices = [] response.body['devices'].each do |d| devices << Device.from_json(d, @token, @logger) end devices end
ruby
{ "resource": "" }
q5408
PogoPlug.Client.services
train
def services(device_id=nil, shared=false) params = { shared: shared } params[:deviceid] = device_id unless device_id.nil? response = get('/listServices', params) services = [] response.body['services'].each do |s| services << Service.from_json(s, @token, @logger) end services end
ruby
{ "resource": "" }
q5409
Serif.FileDigest.render
train
def render(context) return "" unless ENV["ENV"] == "production" full_path = File.join(context["site"]["__directory"], @path.strip) return @prefix + DIGEST_CACHE[full_path] if DIGEST_CACHE[full_path] digest = Digest::MD5.hexdigest(File.read(full_path)) DIGEST_CACHE[full_path] = digest @prefix + digest end
ruby
{ "resource": "" }
q5410
Substation.Dispatcher.call
train
def call(name, input) fetch(name).call(Request.new(name, env, input)) end
ruby
{ "resource": "" }
q5411
QnAMaker.Client.create_kb
train
def create_kb(name, qna_pairs = [], urls = []) response = @http.post( "#{BASE_URL}/create", json: { name: name, qnaPairs: qna_pairs.map { |pair| { question: pair[0], answer: pair[1] } }, urls: urls } ) case response.code when 201 QnAMaker::Client.new( response.parse['kbId'], @subscription_key, response.parse['dataExtractionResults'] ) when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error']['message'] else raise UnknownError, "Oh no! (#{response.code})" end end
ruby
{ "resource": "" }
q5412
MongoDoc.Index.index
train
def index(*args) options_and_fields = args.extract_options! if args.any? collection.create_index(args.first, options_and_fields) else fields = options_and_fields.except(*OPTIONS) options = options_and_fields.slice(*OPTIONS) collection.create_index(to_mongo_direction(fields), options) end end
ruby
{ "resource": "" }
q5413
Rubikon.ProgressBar.+
train
def +(value = 1) return if (value <= 0) || (@value == @maximum) @value += value old_progress = @progress add_progress = ((@value - @progress / @factor) * @factor).round @progress += add_progress if @progress > @size @progress = @size add_progress = @size - old_progress end if add_progress > 0 @ostream << @progress_char * add_progress @ostream.flush @ostream.putc 10 if @progress == @size end self end
ruby
{ "resource": "" }
q5414
Borrower.PublicAPI.put
train
def put content, destination, on_conflict=:overwrite if on_conflict != :overwrite && Content::Item.new( destination ).exists? case on_conflict when :skip then return when :prompt then input = Util.get_input "a file already exists at #{destination}\noverwrite? (y|n): " return unless input.downcase == "y" when :raise_error then raise "File already exists at #{destination}" end end Content.put content, destination end
ruby
{ "resource": "" }
q5415
Ciphers.Caesar.encipher
train
def encipher(message,shift) assert_valid_shift!(shift) real_shift = convert_shift(shift) message.split("").map do|char| mod = (char =~ /[a-z]/) ? 123 : 91 offset = (char =~ /[a-z]/) ? 97 : 65 (char =~ /[^a-zA-Z]/) ? char : CryptBuffer(char).add(real_shift, mod: mod, offset: offset).str end.join end
ruby
{ "resource": "" }
q5416
PogoPlug.ServiceClient.create_entity
train
def create_entity(file, io = nil, properties = {}) params = { deviceid: @device_id, serviceid: @service_id, filename: file.name, type: file.type }.merge(properties) params[:parentid] = file.parent_id unless file.parent_id.nil? if params[:properties] params[:properties] = params[:properties].to_json end file_handle = unless file.id response = get('/createFile', params) File.from_json(response.body['file']) else file end if io HttpHelper.send_file(files_url, @token, @device_id, @service_id, file_handle, io, @logger) file_handle.size = io.size end file_handle end
ruby
{ "resource": "" }
q5417
Assemblotron.AssemblerManager.load_assemblers
train
def load_assemblers Biopsy::Settings.instance.target_dir.each do |dir| Dir.chdir dir do Dir['*.yml'].each do |file| name = File.basename(file, '.yml') target = Assembler.new target.load_by_name name unless System.match? target.bindeps[:url] logger.info "Assembler #{target.name} is not available" + " for this operating system" next end bin_paths = target.bindeps[:binaries].map do |bin| Which.which bin end missing_bin = bin_paths.any? { |path| path.empty? } if missing_bin logger.debug "Assembler #{target.name} was not installed" missing = bin_paths .select{ |path| path.empty? } .map.with_index{ |path, i| target.bindeps[:binaries][i] } logger.debug "(missing binaries: #{missing.join(', ')})" @assemblers_uninst << target else @assemblers << target end end end end end
ruby
{ "resource": "" }
q5418
Assemblotron.AssemblerManager.assembler_names
train
def assembler_names a = [] @assemblers.each do |t| a << t.name a << t.shortname if t.shortname end a end
ruby
{ "resource": "" }
q5419
Assemblotron.AssemblerManager.list_assemblers
train
def list_assemblers str = "" if @assemblers.empty? str << "\nNo assemblers are currently installed! Please install some.\n" else str << <<-EOS Installed assemblers are listed below. Shortnames are shown in brackets if available. Assemblers installed: EOS @assemblers.each do |a| p = " - #{a.name}" p += " (#{a.shortname})" if a.respond_to? :shortname str << p + "\n" end end if @assemblers_uninst.empty? str << "\nAll available assemblers are already installed!\n" else str << <<-EOS Assemblers that are available to be installed are listed below. To install one, use: atron --install-assemblers <name OR shortname> Assemblers installable: EOS @assemblers_uninst.each do |a| p = " - #{a.name}" p += " (#{a.shortname})" if a.respond_to? :shortname str << p + "\n" end end str + "\n" end
ruby
{ "resource": "" }
q5420
Assemblotron.AssemblerManager.get_assembler
train
def get_assembler assembler ret = @assemblers.find do |a| a.name == assembler || a.shortname == assembler end raise "couldn't find assembler #{assembler}" if ret.nil? ret end
ruby
{ "resource": "" }
q5421
Assemblotron.AssemblerManager.run_all_assemblers
train
def run_all_assemblers options res = {} subset = false unless options[:assemblers] == 'all' subset = options[:assemblers].split(',') missing = [] subset.each do |choice| missing < choice unless @assemblers.any do |a| a.name == choice || a.shortname == choice end end unless missing.empty? log.error "The specified assemblers (#{missing.join(', ')}) were not valid choices" log.error "Please choose from the options in --list-assembler" exit(1) end end unless options[:skip_final] if (File.exist? 'final_assemblies') logger.warn("Directory final_assemblies already exists. Some results may be overwritten.") end FileUtils.mkdir_p('final_assemblies') final_dir = File.expand_path 'final_assemblies' end results_filepath = Time.now.to_s.gsub(/ /, '_') + '.json' @assemblers.each do |assembler| logger.info "Starting optimisation for #{assembler.name}" this_res = run_assembler assembler logger.info "Optimisation of #{assembler.name} finished" # run the final assembly unless options[:skip_final] this_final_dir = File.join(final_dir, assembler.name.downcase) Dir.chdir this_final_dir do logger.info "Running full assembly for #{assembler.name}" + " with optimal parameters" # use the full read set this_res[:left] = options[:left] this_res[:right] = options[:right] this_res[:threads] = options[:threads] final = final_assembly assembler, res this_res[:final] = final end res[assembler.name] = this_res end File.open(results_filepath, 'w') do |out| out.write JSON.pretty_generate(res) end logger.info "Result file updated: #{results_filepath}" end logger.info "All assemblers optimised" res end
ruby
{ "resource": "" }
q5422
Assemblotron.AssemblerManager.run_assembler
train
def run_assembler assembler # run the optimisation opts = @options.clone opts[:left] = opts[:left_subset] opts[:right] = opts[:right_subset] if @options[:optimiser] == 'sweep' logger.info("Using full parameter sweep optimiser") algorithm = Biopsy::ParameterSweeper.new(assembler.parameters) elsif @options[:optimiser] == 'tabu' logger.info("Using tabu search optimiser") algorithm = Biopsy::TabuSearch.new(assembler.parameters) else logger.error("Optimiser '#{@options[:optimiser]}' is not a valid optiion") logger.error("Please check the options using --help") exit(1) end exp = Biopsy::Experiment.new(assembler, options: opts, threads: @options[:threads], timelimit: @options[:timelimit], algorithm: algorithm, verbosity: :loud) exp.run end
ruby
{ "resource": "" }
q5423
Chatrix.Rooms.[]
train
def [](id) return @rooms[id] if id.start_with? '!' if id.start_with? '#' res = @rooms.find { |_, r| r.canonical_alias == id } return res.last if res.respond_to? :last end res = @rooms.find { |_, r| r.name == id } res.last if res.respond_to? :last end
ruby
{ "resource": "" }
q5424
Chatrix.Rooms.process_events
train
def process_events(events) process_join events['join'] if events.key? 'join' process_invite events['invite'] if events.key? 'invite' process_leave events['leave'] if events.key? 'leave' end
ruby
{ "resource": "" }
q5425
Chatrix.Rooms.get_room
train
def get_room(id) return @rooms[id] if @rooms.key? id room = Room.new id, @users, @matrix @rooms[id] = room broadcast(:added, room) room end
ruby
{ "resource": "" }
q5426
Chatrix.Rooms.process_join
train
def process_join(events) events.each do |room, data| get_room(room).process_join data end end
ruby
{ "resource": "" }
q5427
Chatrix.Rooms.process_invite
train
def process_invite(events) events.each do |room, data| get_room(room).process_invite data end end
ruby
{ "resource": "" }
q5428
Chatrix.Rooms.process_leave
train
def process_leave(events) events.each do |room, data| get_room(room).process_leave data end end
ruby
{ "resource": "" }
q5429
ResourcesController.Helper.method_missing
train
def method_missing(method, *args, &block) if controller.resource_named_route_helper_method?(method) self.class.send(:delegate, method, :to => :controller) controller.send(method, *args) else super(method, *args, &block) end end
ruby
{ "resource": "" }
q5430
LatoCore.Widgets::Index::Cell.generate_table_head
train
def generate_table_head labels = [] if @args[:head] && @args[:head].length > 0 # manage case with custom head labels = [] if @args[:actions_on_start] && @show_row_actions labels.push(LANGUAGES[:lato_core][:mixed][:actions]) end @args[:head].each do |head| if head.is_a?(Hash) sort_value = @args[:records].is_a?(Hash) ? @args[:records][:sort] : '' sort_dir_value = @args[:records].is_a?(Hash) ? @args[:records][:sort_dir] : 'ASC' active_class = sort_value == head[:sort] ? "attr-active attr-sort-#{sort_dir_value}" : '' active_sort = sort_value == head[:sort] ? (sort_dir_value == 'ASC' ? 'DESC' : 'ASC') : sort_dir_value search_value = @args[:records].is_a?(Hash) ? @args[:records][:search] : '' url = core__add_param_to_url(@args[:index_url], 'widget_index[search]', search_value) url = core__add_param_to_url(url, 'widget_index[sort]', head[:sort]) url = core__add_param_to_url(url, 'widget_index[sort_dir]', active_sort) string = "<a href='#{url}' class='#{active_class}'>#{head[:label]}</a>" labels.push(string) else labels.push(head) end end if !@args[:actions_on_start] && @show_row_actions labels.push(LANGUAGES[:lato_core][:mixed][:actions]) end elsif @records&.length > 0 # manage case without custom head labels = [] if @args[:actions_on_start] && @show_row_actions labels.push(LANGUAGES[:lato_core][:mixed][:actions]) end labels = labels + @records.first.attributes.keys.map {|s| s.gsub('_', ' ')} labels = labels.map(&:capitalize) if !@args[:actions_on_start] && @show_row_actions labels.push(LANGUAGES[:lato_core][:mixed][:actions]) end end return LatoCore::Elements::Table::Head::Cell.new(labels: labels) end
ruby
{ "resource": "" }
q5431
LatoCore.Widgets::Index::Cell.generate_table_rows
train
def generate_table_rows table_rows = [] if @args[:columns] && @args[:columns].length > 0 # manage case with custom columns table_rows = generate_table_rows_from_columns_functions(@args[:columns]) elsif @records && @records.length > 0 # manage case without custom columns table_rows = generate_table_rows_from_columns_functions(@records.first.attributes.keys) end return table_rows end
ruby
{ "resource": "" }
q5432
LatoCore.Widgets::Index::Cell.generate_table_rows_from_columns_functions
train
def generate_table_rows_from_columns_functions columns_functions table_rows = [] @records.each do |record| labels = [] # add actions to row columns if @args[:actions_on_start] && @show_row_actions labels.push(generate_actions_bottongroup_for_record(record)) end # add function result to row columns columns_functions.each do |column_function| labels.push(record.send(column_function)) end # add actions to row columns if !@args[:actions_on_start] && @show_row_actions labels.push(generate_actions_bottongroup_for_record(record)) end # puts rows on table rows table_rows.push(LatoCore::Elements::Table::Row::Cell.new(labels: labels)) end return table_rows end
ruby
{ "resource": "" }
q5433
LatoCore.Widgets::Index::Cell.generate_actions_bottongroup_for_record
train
def generate_actions_bottongroup_for_record record action_buttons = [] action_buttons.push(generate_show_button(record.id)) if @args[:actions][:show] action_buttons.push(generate_edit_button(record.id)) if @args[:actions][:edit] action_buttons.push(generate_delete_button(record.id)) if @args[:actions][:delete] return LatoCore::Elements::Buttongroup::Cell.new(buttons: action_buttons) end
ruby
{ "resource": "" }
q5434
LatoCore.Widgets::Index::Cell.generate_delete_button
train
def generate_delete_button record_id return unless @args[:index_url] url = @args[:index_url].end_with?('/') ? "#{@args[:index_url].gsub(/\?.*/, '')}#{record_id}" : "#{@args[:index_url].gsub(/\?.*/, '')}/#{record_id}" return LatoCore::Elements::Button::Cell.new(label: LANGUAGES[:lato_core][:mixed][:delete], url: url, method: 'delete', icon: 'trash', style: 'danger', confirmation: { message: LANGUAGES[:lato_core][:mixed][:default_delete_message], positive_response: LANGUAGES[:lato_core][:mixed][:default_delete_positive_response], negative_response: LANGUAGES[:lato_core][:mixed][:default_delete_negative_response] }) end
ruby
{ "resource": "" }
q5435
LatoCore.Widgets::Index::Cell.generate_new_button
train
def generate_new_button return unless @args[:index_url] url = "#{@args[:index_url].gsub(/\?.*/, '')}/new" return LatoCore::Elements::Button::Cell.new(label: LANGUAGES[:lato_core][:mixed][:new], url: url, icon: 'plus') end
ruby
{ "resource": "" }
q5436
LatoCore.Widgets::Index::Cell.generate_search_input
train
def generate_search_input search_placeholder = '' if @args[:records].is_a?(Hash) search_placeholder = @args[:records][:search_key].is_a?(Array) ? @args[:records][:search_key].to_sentence : @args[:records][:search_key].humanize end search_value = @args[:records].is_a?(Hash) ? @args[:records][:search] : '' return LatoCore::Inputs::Text::Cell.new(name: 'widget_index[search]', value: search_value, placeholder: search_placeholder) end
ruby
{ "resource": "" }
q5437
LatoCore.Widgets::Index::Cell.generate_search_submit
train
def generate_search_submit return LatoCore::Elements::Button::Cell.new(label: ' ', icon: 'search', type: 'submit', icon_align: 'right') end
ruby
{ "resource": "" }
q5438
ConfigCurator.ConfigFile.install_file
train
def install_file FileUtils.mkdir_p File.dirname(destination_path) FileUtils.copy source_path, destination_path, preserve: true end
ruby
{ "resource": "" }
q5439
Algebra.Polynomial.need_paren_in_coeff?
train
def need_paren_in_coeff? if constant? c = @coeff[0] if c.respond_to?(:need_paren_in_coeff?) c.need_paren_in_coeff? elsif c.is_a?(Numeric) false else true end elsif !monomial? true else false end end
ruby
{ "resource": "" }
q5440
ExpressPigeon.Messages.reports
train
def reports(from_id, start_date = nil, end_date = nil) params = [] if from_id params << "from_id=#{from_id}" end if start_date and not end_date raise 'must include both start_date and end_date' end if end_date and not start_date raise 'must include both start_date and end_date' end if start_date and end_date params << "start_date=#{start_date.strftime('%FT%T.%L%z')}" params << "end_date=#{end_date.strftime('%FT%T.%L%z')}" end query = "#{@endpoint}?" if params.size > 0 query << params.join('&') end get query end
ruby
{ "resource": "" }
q5441
QnAMaker.Client.train_kb
train
def train_kb(feedback_records = []) feedback_records = feedback_records.map do |record| { userId: record[0], userQuestion: record[1], kbQuestion: record[2], kbAnswer: record[3] } end response = @http.patch( "#{BASE_URL}/#{@knowledgebase_id}/train", json: { feedbackRecords: feedback_records } ) case response.code when 204 nil when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error']['message'] when 403 raise ForbiddenError, response.parse['error']['message'] when 404 raise NotFoundError, response.parse['error']['message'] when 408 raise OperationTimeOutError, response.parse['error']['message'] when 429 raise RateLimitExceededError, response.parse['error']['message'] else raise UnknownError, "Oh no! (#{response.code})" end end
ruby
{ "resource": "" }
q5442
TSparser.AribTime.convert_mjd_to_date
train
def convert_mjd_to_date(mjd) y_ = ((mjd - 15078.2) / 365.25).to_i m_ = ((mjd - 14956.1 - (y_ * 365.25).to_i) / 30.6001).to_i d = mjd - 14956 - (y_ * 365.25).to_i - (m_ * 30.6001).to_i k = (m_ == 14 || m_ == 15) ? 1 : 0 y = y_ + k m = m_ - 1 - k * 12 return Date.new(1900 + y, m, d) end
ruby
{ "resource": "" }
q5443
Substation.Chain.call
train
def call(request) reduce(request) { |result, processor| begin response = processor.call(result) return response unless processor.success?(response) processor.result(response) rescue => exception return on_exception(request, result.data, exception) end } end
ruby
{ "resource": "" }
q5444
Substation.Chain.on_exception
train
def on_exception(state, data, exception) response = self.class.exception_response(state, data, exception) exception_chain.call(response) end
ruby
{ "resource": "" }
q5445
EISCP.Receiver.update_state
train
def update_state Thread.new do Dictionary.commands.each do |zone, commands| Dictionary.commands[zone].each do |command, info| info[:values].each do |value, _| if value == 'QSTN' send(Parser.parse(command + "QSTN")) # If we send any faster we risk making the stereo drop replies. # A dropped reply is not necessarily indicative of the # receiver's failure to receive the command and change state # accordingly. In this case, we're only making queries, so we do # want to capture every reply. sleep DEFAULT_TIMEOUT end end end end end end
ruby
{ "resource": "" }
q5446
SweetNotifications.ControllerRuntime.controller_runtime
train
def controller_runtime(name, log_subscriber) runtime_attr = "#{name.to_s.underscore}_runtime".to_sym Module.new do extend ActiveSupport::Concern attr_internal runtime_attr protected define_method :process_action do |action, *args| log_subscriber.reset_runtime super(action, *args) end define_method :cleanup_view_runtime do |&block| runtime_before_render = log_subscriber.reset_runtime send("#{runtime_attr}=", (send(runtime_attr) || 0) + runtime_before_render) runtime = super(&block) runtime_after_render = log_subscriber.reset_runtime send("#{runtime_attr}=", send(runtime_attr) + runtime_after_render) runtime - runtime_after_render end define_method :append_info_to_payload do |payload| super(payload) runtime = (send(runtime_attr) || 0) + log_subscriber.reset_runtime payload[runtime_attr] = runtime end const_set(:ClassMethods, Module.new do define_method :log_process_action do |payload| messages = super(payload) runtime = payload[runtime_attr] if runtime && runtime != 0 messages << format("#{name}: %.1fms", runtime.to_f) end messages end end) end end
ruby
{ "resource": "" }
q5447
LatoCore.Interface::Apihelpers.core__send_request_success
train
def core__send_request_success(payload) response = { result: true, error_message: nil } response[:payload] = payload if payload render json: response end
ruby
{ "resource": "" }
q5448
LatoCore.Interface::Apihelpers.core__send_request_fail
train
def core__send_request_fail(error, payload: nil) response = { result: false, error_message: error } response[:payload] = payload if payload render json: response end
ruby
{ "resource": "" }
q5449
Siba.SibaFile.shell_ok?
train
def shell_ok?(command) # Using Open3 instead of `` or system("cmd") in order to hide stderr output sout, status = Open3.capture2e command return status.to_i == 0 rescue return false end
ruby
{ "resource": "" }
q5450
Disclaimer.Document.modify_via_segment_holder_acts_as_list_method
train
def modify_via_segment_holder_acts_as_list_method(method, segment) segment_holder = segment_holder_for(segment) raise segment_not_associated_message(method, segment) unless segment_holder segment_holder.send(method) end
ruby
{ "resource": "" }
q5451
MongoDoc.Document.update
train
def update(attrs, safe = false) self.attributes = attrs if new_record? _root.send(:_save, safe) if _root _save(safe) else _update_attributes(converted_attributes(attrs), safe) end end
ruby
{ "resource": "" }
q5452
QnAMaker.Client.download_kb
train
def download_kb response = @http.get( "#{BASE_URL}/#{@knowledgebase_id}" ) case response.code when 200 response.parse when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error']['message'] when 403 raise ForbiddenError, response.parse['error']['message'].join(' ') when 404 raise NotFoundError, response.parse['error']['message'].join(' ') else raise UnknownError, "Oh no! (#{response.code})" end end
ruby
{ "resource": "" }
q5453
Bcome::Orchestration.InteractiveTerraform.form_var_string
train
def form_var_string terraform_vars = terraform_metadata ec2_credentials = @node.network_driver.raw_fog_credentials cleaned_data = terraform_vars.select{|k,v| !v.is_a?(Hash) && !v.is_a?(Array) } # we can't yet handle nested terraform metadata on the command line so no arrays or hashes all_vars = cleaned_data.merge({ :access_key => ec2_credentials["aws_access_key_id"], :secret_key => ec2_credentials["aws_secret_access_key"] }) all_vars.collect{|key, value| "-var #{key}=\"#{value}\""}.join("\s") end
ruby
{ "resource": "" }
q5454
Polisher.GemFiles.has_file_satisfied_by?
train
def has_file_satisfied_by?(spec_file) file_paths.any? { |gem_file| RPM::Spec.file_satisfies?(spec_file, gem_file) } end
ruby
{ "resource": "" }
q5455
Polisher.GemFiles.unpack
train
def unpack(&bl) dir = nil pkg = ::Gem::Installer.new gem_path, :unpack => true if bl Dir.mktmpdir do |tmpdir| pkg.unpack tmpdir bl.call tmpdir end else dir = Dir.mktmpdir pkg.unpack dir end dir end
ruby
{ "resource": "" }
q5456
Polisher.GemFiles.each_file
train
def each_file(&bl) unpack do |dir| Pathname.new(dir).find do |path| next if path.to_s == dir.to_s pathstr = path.to_s.gsub("#{dir}/", '') bl.call pathstr unless pathstr.blank? end end end
ruby
{ "resource": "" }
q5457
ConfigCurator.Component.install_component
train
def install_component if (backend != :stdlib && command?('rsync')) || backend == :rsync FileUtils.mkdir_p destination_path cmd = [command?('rsync'), '-rtc', '--del', '--links', "#{source_path}/", destination_path] logger.debug { "Running command: #{cmd.join ' '}" } system(*cmd) else FileUtils.remove_entry_secure destination_path if Dir.exist? destination_path FileUtils.mkdir_p destination_path FileUtils.cp_r "#{source_path}/.", destination_path, preserve: true end end
ruby
{ "resource": "" }
q5458
ConfigCurator.Component.set_mode
train
def set_mode chmod = command? 'chmod' find = command? 'find' return unless chmod && find {fmode: 'f', dmode: 'd'}.each do |k, v| next if send(k).nil? cmd = [find, destination_path, '-type', v, '-exec'] cmd.concat [chmod, send(k).to_s(8), '{}', '+'] logger.debug { "Running command: #{cmd.join ' '}" } system(*cmd) end end
ruby
{ "resource": "" }
q5459
ConfigCurator.Component.set_owner
train
def set_owner return unless owner || group chown = command? 'chown' return unless chown cmd = [chown, '-R', "#{owner}:#{group}", destination_path] logger.debug { "Running command: #{cmd.join ' '}" } system(*cmd) end
ruby
{ "resource": "" }
q5460
Pokerstats.HandStatistics.calculate_player_position
train
def calculate_player_position screen_name @cached_player_position = {} @player_hashes.sort!{|a,b| button_relative_seat(a) <=> button_relative_seat(b)} @player_hashes = [@player_hashes.pop] + @player_hashes unless @player_hashes.first[:seat] == @button_player_index @player_hashes.each_with_index{|player, index| player[:position] = index, @cached_player_position[player[:screen_name]] = index} @cached_player_position[screen_name] end
ruby
{ "resource": "" }
q5461
Pokerstats.HandStatistics.betting_order?
train
def betting_order?(screen_name_first, screen_name_second) if button?(screen_name_first) false elsif button?(screen_name_second) true else position(screen_name_first) < position(screen_name_second) end end
ruby
{ "resource": "" }
q5462
Paginator.Pager.page
train
def page(number) number = (n = number.to_i) > 0 ? n : 1 Page.new(self, number, lambda { offset = (number - 1) * @per_page args = [offset] args << @per_page if @select.arity == 2 @select.call(*args) }) end
ruby
{ "resource": "" }
q5463
Auth.Mailgun.add_webhook_identifier_to_email
train
def add_webhook_identifier_to_email(email) email.message.mailgun_variables = {} email.message.mailgun_variables["webhook_identifier"] = BSON::ObjectId.new.to_s email end
ruby
{ "resource": "" }
q5464
DeploYML.Shell.ruby
train
def ruby(program,*arguments) command = [program, *arguments] # assume that `.rb` scripts do not have a `#!/usr/bin/env ruby` command.unshift('ruby') if program[-3,3] == '.rb' # if the environment uses bundler, run all ruby commands via `bundle exec` if (@environment && @environment.bundler) command.unshift('bundle','exec') end run(*command) end
ruby
{ "resource": "" }
q5465
DeploYML.Shell.shellescape
train
def shellescape(str) # An empty argument will be skipped, so return empty quotes. return "''" if str.empty? str = str.dup # Process as a single byte sequence because not all shell # implementations are multibyte aware. str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/n, "\\\\\\1") # A LF cannot be escaped with a backslash because a backslash + LF # combo is regarded as line continuation and simply ignored. str.gsub!(/\n/, "'\n'") return str end
ruby
{ "resource": "" }
q5466
DeploYML.Shell.rake_task
train
def rake_task(name,*arguments) name = name.to_s unless arguments.empty? name += ('[' + arguments.join(',') + ']') end return name end
ruby
{ "resource": "" }
q5467
TSparser.Binary.read_byte_as_integer
train
def read_byte_as_integer(bytelen) unless bit_pointer % 8 == 0 raise BinaryException.new("Bit pointer must be pointing start of byte. " + "But now pointing #{bit_pointer}.") end if self.length - bit_pointer/8 < bytelen raise BinaryException.new("Rest of self length(#{self.length - bit_pointer/8}byte) " + "is shorter than specified byte length(#{bytelen}byte).") end response = 0 bytelen.times do |i| response = response << 8 response += to_i(bit_pointer/8 + i) end bit_pointer_inc(bytelen * 8) return response end
ruby
{ "resource": "" }
q5468
TSparser.Binary.read_one_bit
train
def read_one_bit unless self.length * 8 - bit_pointer > 0 raise BinaryException.new("Readable buffer doesn't exist" + "(#{self.length * 8 - bit_pointer}bit exists).") end response = to_i(bit_pointer/8)[7 - bit_pointer%8] bit_pointer_inc(1) return response end
ruby
{ "resource": "" }
q5469
TSparser.Binary.read_bit_as_binary
train
def read_bit_as_binary(bitlen) unless bit_pointer % 8 == 0 raise BinaryException.new("Bit pointer must be pointing start of byte. " + "But now pointing #{bit_pointer}.") end unless bitlen % 8 == 0 raise BinaryException.new("Arg must be integer of multiple of 8. " + "But you specified #{bitlen}.") end if self.length - bit_pointer/8 < bitlen/8 raise BinaryException.new("Rest of self length(#{self.length - bit_pointer/8}byte)" + " is shorter than specified byte length(#{bitlen/8}byte).") end response = self[bit_pointer/8, bitlen/8] bit_pointer_inc(bitlen) return response end
ruby
{ "resource": "" }
q5470
Bcome::Registry::Command.External.execute
train
def execute(node, arguments) full_command = construct_full_command(node, arguments) begin puts "\n(external) > #{full_command}".bc_blue + "\n\n" system(full_command) rescue Interrupt puts "\nExiting gracefully from interrupt\n".warning end end
ruby
{ "resource": "" }
q5471
Opto.Group.option
train
def option(option_name) if option_name.to_s.include?('.') parts = option_name.to_s.split('.') var_name = parts.pop group = parts.inject(self) do |base, part| grp = base.option(part).value if grp.nil? raise NameError, "No such group: #{base.name}.#{part}" elsif grp.kind_of?(Opto::Group) grp else raise TypeError, "Is not a group: #{base.name}.#{part}" end end else group = self var_name = option_name end group.options.find { |opt| opt.name == var_name } end
ruby
{ "resource": "" }
q5472
GovKit::ActsAsNoteworthy.ActMethods.acts_as_noteworthy
train
def acts_as_noteworthy(options={}) class_inheritable_accessor :options self.options = options unless included_modules.include? InstanceMethods instance_eval do has_many :mentions, :as => :owner, :order => 'date desc' with_options :as => :owner, :class_name => "Mention" do |c| c.has_many :google_news_mentions, :conditions => {:search_source => "Google News"}, :order => 'date desc' c.has_many :google_blog_mentions, :conditions => {:search_source => "Google Blogs"}, :order => 'date desc' # c.has_many :technorati_mentions, :conditions => {:search_source => "Technorati"}, :order => 'date desc' c.has_many :bing_mentions, :conditions => {:search_source => "Bing"}, :order => 'date desc' end end extend ClassMethods include InstanceMethods end end
ruby
{ "resource": "" }
q5473
GovKit::ActsAsNoteworthy.InstanceMethods.raw_mentions
train
def raw_mentions opts = self.options.clone attributes = opts.delete(:with) if opts[:geo] opts[:geo] = self.instance_eval("#{opts[:geo]}") end query = [] attributes.each do |attr| query << self.instance_eval("#{attr}") end { :google_news => GovKit::SearchEngines::GoogleNews.search(query, opts), :google_blogs => GovKit::SearchEngines::GoogleBlog.search(query, opts), # :technorati => GovKit::SearchEngines::Technorati.search(query), :bing => GovKit::SearchEngines::Bing.search(query, opts) } end
ruby
{ "resource": "" }
q5474
QnAMaker.Client.publish_kb
train
def publish_kb response = @http.put( "#{BASE_URL}/#{@knowledgebase_id}" ) case response.code when 204 nil when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error']['message'] when 403 raise ForbiddenError, response.parse['error']['message'] when 404 raise NotFoundError, response.parse['error']['message'] when 409 raise ConflictError, response.parse['error']['message'] else raise UnknownError, "Oh no! (#{response.code})" end end
ruby
{ "resource": "" }
q5475
Push0r.ApnsPushMessage.simple
train
def simple(alert_text = nil, sound = nil, badge = nil, category = nil) new_payload = {aps: {}} if alert_text new_payload[:aps][:alert] = alert_text end if sound new_payload[:aps][:sound] = sound end if badge new_payload[:aps][:badge] = badge end if category new_payload[:aps][:category] = category end @payload.merge!(new_payload) return self end
ruby
{ "resource": "" }
q5476
LatoCore.Interface::Cells.core__widgets_index
train
def core__widgets_index(records, search: nil, pagination: 50) response = { records: records, total: records.length, per_page: pagination, search: '', search_key: search, sort: '', sort_dir: 'ASC', pagination: 1, } # manage search if search && params[:widget_index] && params[:widget_index][:search] && !params[:widget_index][:search].blank? search_array = search.is_a?(Array) ? search : [search] query1 = '' query2 = [] search_array.each do |s| query1 += "#{s} like ? OR " query2.push("%#{params[:widget_index][:search]}%") end query1 = query1[0...-4] query = [query1] + query2 response[:records] = response[:records].where(query) response[:total] = response[:records].length response[:search] = params[:widget_index][:search] end # manage sort if params[:widget_index] && !params[:widget_index][:sort].blank? && !params[:widget_index][:sort_dir].blank? response[:sort] = params[:widget_index][:sort] response[:sort_dir] = params[:widget_index][:sort_dir] response[:records] = response[:records].order("#{params[:widget_index][:sort]} #{params[:widget_index][:sort_dir]}") end # manage pagination if pagination if params[:widget_index] && params[:widget_index][:pagination] response[:pagination] = params[:widget_index][:pagination].to_i end response[:records] = core__paginate_array(response[:records], pagination, response[:pagination]) end # return response response end
ruby
{ "resource": "" }
q5477
Configurable.ClassMethods.remove_config
train
def remove_config(key, options={}) unless config_registry.has_key?(key) raise NameError.new("#{key.inspect} is not a config on #{self}") end options = { :reader => true, :writer => true }.merge(options) config = config_registry.delete(key) reset_configs remove_method(config.reader) if options[:reader] remove_method(config.writer) if options[:writer] config end
ruby
{ "resource": "" }
q5478
Configurable.ClassMethods.undef_config
train
def undef_config(key, options={}) unless configs.has_key?(key) raise NameError.new("#{key.inspect} is not a config on #{self}") end options = { :reader => true, :writer => true }.merge(options) config = configs[key] config_registry[key] = nil reset_configs undef_method(config.reader) if options[:reader] undef_method(config.writer) if options[:writer] config end
ruby
{ "resource": "" }
q5479
Configurable.ClassMethods.remove_config_type
train
def remove_config_type(name) unless config_type_registry.has_key?(name) raise NameError.new("#{name.inspect} is not a config_type on #{self}") end config_type = config_type_registry.delete(name) reset_config_types config_type end
ruby
{ "resource": "" }
q5480
Configurable.ClassMethods.undef_config_type
train
def undef_config_type(name) unless config_types.has_key?(name) raise NameError.new("#{name.inspect} is not a config_type on #{self}") end config_type = config_type_registry[name] config_type_registry[name] = nil reset_config_types config_type end
ruby
{ "resource": "" }
q5481
Configurable.ClassMethods.check_infinite_nest
train
def check_infinite_nest(klass) # :nodoc: raise "infinite nest detected" if klass == self klass.configs.each_value do |config| if config.type.kind_of?(NestType) check_infinite_nest(config.type.configurable.class) end end end
ruby
{ "resource": "" }
q5482
SweetNotifications.LogSubscriber.message
train
def message(event, label, body) @odd = !@odd label_color = @odd ? odd_color : even_color format( ' %s (%.2fms) %s', color(label, label_color, true), event.duration, color(body, nil, !@odd) ) end
ruby
{ "resource": "" }
q5483
DeploYML.RemoteShell.join
train
def join commands = [] @history.each do |command| program = command[0] arguments = command[1..-1].map { |word| shellescape(word.to_s) } commands << [program, *arguments].join(' ') end return commands.join(' && ') end
ruby
{ "resource": "" }
q5484
DeploYML.RemoteShell.ssh_uri
train
def ssh_uri unless @uri.host raise(InvalidConfig,"URI does not have a host: #{@uri}",caller) end new_uri = @uri.host new_uri = "#{@uri.user}@#{new_uri}" if @uri.user return new_uri end
ruby
{ "resource": "" }
q5485
DeploYML.RemoteShell.ssh
train
def ssh(*arguments) options = [] # Add the -p option if an alternate destination port is given if @uri.port options += ['-p', @uri.port.to_s] end # append the SSH URI options << ssh_uri # append the additional arguments arguments.each { |arg| options << arg.to_s } return system('ssh',*options) end
ruby
{ "resource": "" }
q5486
ConfHelpers.ClassMethods.conf_attr
train
def conf_attr(name, opts = {}) @conf_attrs ||= [] @conf_attrs << name default = opts[:default] accumulate = opts[:accumulate] send(:define_singleton_method, name) do |*args| nvar = "@#{name}".intern current = instance_variable_get(nvar) envk = "POLISHER_#{name.to_s.upcase}" if accumulate instance_variable_set(nvar, []) unless current current = instance_variable_get(nvar) current << default current << ENV[envk] current += args current.uniq! current.compact! current.flatten! instance_variable_set(nvar, current) else instance_variable_set(nvar, default) unless current instance_variable_set(nvar, ENV[envk]) if ENV.key?(envk) instance_variable_set(nvar, args.first) unless args.empty? end instance_variable_get(nvar) end send(:define_method, name) do self.class.send(name) end end
ruby
{ "resource": "" }
q5487
AridCache.Helpers.lookup
train
def lookup(object, key, opts, &block) if !block.nil? define(object, key, opts, &block) elsif key =~ /(.*)_count$/ if AridCache.store.has?(object, $1) method_for_cached(object, $1, :fetch_count, key) elsif object.respond_to?(key) define(object, key, opts, :fetch_count) elsif object.respond_to?($1) define(object, $1, opts, :fetch_count, key) else raise ArgumentError.new("#{object} doesn't respond to #{key.inspect} or #{$1.inspect}. Cannot dynamically create query to get the count, please call with a block.") end elsif AridCache.store.has?(object, key) method_for_cached(object, key, :fetch) elsif object.respond_to?(key) define(object, key, opts, &block) else raise ArgumentError.new("#{object} doesn't respond to #{key.inspect}! Cannot dynamically create query, please call with a block.") end object.send("cached_#{key}", opts) end
ruby
{ "resource": "" }
q5488
AridCache.Helpers.define
train
def define(object, key, opts, fetch_method=:fetch, method_name=nil, &block) # FIXME: Pass default options to store.add # Pass nil in for now until we get the cache_ calls working. # This means that the first time you define a dynamic cache # (by passing in a block), the options you used are not # stored in the blueprint and applied to each subsequent call. # # Otherwise we have a situation where a :limit passed in to the # first call persists when no options are passed in on subsequent calls, # but if a different :limit is passed in that limit is applied. # # I think in this scenario one would expect no limit to be applied # if no options are passed in. # # When the cache_ methods are supported, those options should be # remembered and applied to the collection however. blueprint = AridCache.store.add_object_cache_configuration(object, key, nil, block) method_for_cached(object, key, fetch_method, method_name) blueprint end
ruby
{ "resource": "" }
q5489
AridCache.Helpers.class_name
train
def class_name(object, *modifiers) name = object.is_a?(Class) ? object.name : object.class.name name = 'AnonymousClass' if name.nil? while modifier = modifiers.shift case modifier when :downcase name = name.downcase when :pluralize name = AridCache::Inflector.pluralize(name) else raise ArgumentError.new("Unsupported modifier #{modifier.inspect}") end end name end
ruby
{ "resource": "" }
q5490
Trust.Permissions.authorized?
train
def authorized? trace 'authorized?', 0, "@user: #{@user.inspect}, @action: #{@action.inspect}, @klass: #{@klass.inspect}, @subject: #{@subject.inspect}, @parent: #{@parent.inspect}" if params_handler = (user && (permission_by_role || permission_by_member_role)) params_handler = params_handler_default(params_handler) end params_handler end
ruby
{ "resource": "" }
q5491
Trust.Permissions.permission_by_member_role
train
def permission_by_member_role m = members_role trace 'authorize_by_member_role?', 0, "#{user.try(:name)}:#{m}" p = member_permissions[m] trace 'authorize_by_role?', 1, "permissions: #{p.inspect}" p && authorization(p) end
ruby
{ "resource": "" }
q5492
Polisher.GemState.state
train
def state(args = {}) return :available if koji_state(args) == :available state = distgit_state(args) return :needs_repo if state == :missing_repo return :needs_branch if state == :missing_branch return :needs_spec if state == :missing_spec return :needs_build if state == :available return :needs_update end
ruby
{ "resource": "" }
q5493
Verku.SourceList.entries
train
def entries Dir.entries(source).sort.each_with_object([]) do |entry, buffer| buffer << source.join(entry) if valid_entry?(entry) end end
ruby
{ "resource": "" }
q5494
Verku.SourceList.valid_directory?
train
def valid_directory?(entry) File.directory?(source.join(entry)) && !IGNORE_DIR.include?(File.basename(entry)) end
ruby
{ "resource": "" }
q5495
Verku.SourceList.valid_file?
train
def valid_file?(entry) ext = File.extname(entry).gsub(/\./, "").downcase File.file?(source.join(entry)) && EXTENSIONS.include?(ext) && entry !~ IGNORE_FILES end
ruby
{ "resource": "" }
q5496
HungryForm.Form.validate
train
def validate is_valid = true pages.each do |page| # Loop through pages to get all errors is_valid = false if page.invalid? end is_valid end
ruby
{ "resource": "" }
q5497
HungryForm.Form.values
train
def values active_elements = elements.select do |_, el| el.is_a? Elements::Base::ActiveElement end active_elements.each_with_object({}) do |(name, el), o| o[name.to_sym] = el.value end end
ruby
{ "resource": "" }
q5498
ConfigCurator.CLI.install
train
def install(manifest = 'manifest.yml') unless File.exist? manifest logger.fatal { "Manifest file '#{manifest}' does not exist." } return false end collection.load_manifest manifest result = options[:dryrun] ? collection.install? : collection.install msg = install_message(result, options[:dryrun]) result ? logger.info(msg) : logger.error(msg) result end
ruby
{ "resource": "" }
q5499
Attached.ClassMethods.number_to_size
train
def number_to_size(number, options = {}) return if number == 0.0 / 1.0 return if number == 1.0 / 0.0 singular = options[:singular] || 1 base = options[:base] || 1024 units = options[:units] || ["byte", "kilobyte", "megabyte", "gigabyte", "terabyte", "petabyte"] exponent = (Math.log(number) / Math.log(base)).floor number /= base ** exponent unit = units[exponent] number == singular ? unit.gsub!(/s$/, '') : unit.gsub!(/$/, 's') "#{number} #{unit}" end
ruby
{ "resource": "" }