_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q9900
Dio.Injector.register
train
def register(key, object = nil) assert_register_args_valid(object, block_given?) @container.register(key) do |*args| object = yield(*args) if block_given? injectable?(object) ? inject(object) : object end self end
ruby
{ "resource": "" }
q9901
Dio.Injector.inject
train
def inject(target) unless injectable?(target) raise ArgumentError, 'The given object does not include Dio module' end loader = @loader_factory.create(@container, target) target.__dio_inject__(loader) target end
ruby
{ "resource": "" }
q9902
Dio.Injector.create
train
def create(clazz, *args) raise ArgumentError, "#{clazz} is not a class" unless clazz.is_a?(Class) inject(clazz.new(*args)) end
ruby
{ "resource": "" }
q9903
BitmaskAttributesHelpers.ClassMethods.bitmask_scopes
train
def bitmask_scopes(bitmask) send("values_for_#{bitmask}").each do |value| scope value, send("with_#{bitmask}", value) scope "not_#{value}", send("without_#{bitmask}", value) end end
ruby
{ "resource": "" }
q9904
BitmaskAttributesHelpers.ClassMethods.bitmask_virtual_attributes
train
def bitmask_virtual_attributes(bitmask) send("values_for_#{bitmask}").each do |value| define_method("#{value}") { send("#{bitmask}?", value) } define_method("#{value}=") { |arg| send("#{bitmask}=", arg.blank? || arg == "0" ? send("#{bitmask}") - [value] : send("#{bitmask}") << value) } end end
ruby
{ "resource": "" }
q9905
AwesomePrintLite.Formatter.awesome_hash
train
def awesome_hash(h) return "{}" if h == {} keys = @options[:sort_keys] ? h.keys.sort { |a, b| a.to_s <=> b.to_s } : h.keys data = keys.map do |key| plain_single_line do [ @inspector.awesome(key), h[key] ] end end width = data.map { |key, | key.size }.max || 0 width += @indentation if @options[:indent] > 0 data = data.map do |key, value| indented do align(key, width) + colorize(" => ", :hash) + @inspector.awesome(value) end end data = limited(data, width, :hash => true) if should_be_limited? if @options[:multiline] "{\n" + data.join(",\n") + "\n#{outdent}}" else "{ #{data.join(', ')} }" end end
ruby
{ "resource": "" }
q9906
OrchestrateIo.Client.request
train
def request(http_method, uri, options={}) response = self.class.__send__(http_method, uri, options.merge(basic_auth)) # Add some logger.debug here ... response end
ruby
{ "resource": "" }
q9907
Sloe.Ixia.run_setup
train
def run_setup setup_tcl = File.open("/var/tmp/setup-#{@buildtime}", 'w') setup_tcl.write setup setup_tcl.close system "#@ixia_exe /var/tmp/setup-#{@buildtime}" File.delete setup_tcl end
ruby
{ "resource": "" }
q9908
Sloe.Ixia.clear_stats
train
def clear_stats clear_tcl = File.open("/var/tmp/clear-#{@buildtime}", 'w') clear_tcl.write clear_traffic_stats clear_tcl.close system "#{@ixia_exe} /var/tmp/clear-#{@buildtime}" File.delete clear_tcl end
ruby
{ "resource": "" }
q9909
Sloe.Ixia.run_stats_gather
train
def run_stats_gather stats_tcl = File.open("/var/tmp/stats-#{@buildtime}", 'w') stats_tcl.write finish stats_tcl.close system "#@ixia_exe /var/tmp/stats-#{@buildtime}" File.delete stats_tcl ftp = Net::FTP.new(@host) ftp.login file = "#{@csv_file}.csv" Dir.chdir "#{$log_path}/ixia" do ftp.get "Reports/#{file}" end ftp.delete "Reports/#{file}" ftp.delete "Reports/#{file}.columns" ftp.close CSV.read("#{$log_path}/ixia/#{file}", headers: true) end
ruby
{ "resource": "" }
q9910
Sloe.Ixia.run_protocols
train
def run_protocols run_proto = File.open("/var/tmp/run-proto-#{@buildtime}", 'w') tcl = connect tcl << load_config tcl << start_protocols tcl << disconnect run_proto.write tcl run_proto.close system "#{@ixia_exe} /var/tmp/run-proto-#{@buildtime}" File.delete run_proto end
ruby
{ "resource": "" }
q9911
Danger.DangerIosVersionChange.assert_version_changed
train
def assert_version_changed(info_plist_file_path) unless File.file?(info_plist_file_path) fail "Info.plist at path " + info_plist_file_path + " does not exist." return # rubocop:disable UnreachableCode end unless git.diff_for_file(info_plist_file_path) # No diff found for Info.plist file. fail "You did not edit your Info.plist file at all. Therefore, you did not change the iOS version." return # rubocop:disable UnreachableCode end git_diff_string = git.diff_for_file(info_plist_file_path).patch assert_version_changed_diff(git_diff_string) end
ruby
{ "resource": "" }
q9912
Announcer.Event._evaluate_params
train
def _evaluate_params(params) unless params.is_a?(Hash) raise ArgumentError, 'event parameters must be a hash' end params = params.dup @instance = params.delete(:instance) @params = _sanitize_params(params) end
ruby
{ "resource": "" }
q9913
Announcer.Event._sanitize_params
train
def _sanitize_params(params) Hash[params.map { |key, value| [key.to_sym, _sanitize_value(key, value)] }].freeze end
ruby
{ "resource": "" }
q9914
Announcer.Event._sanitize_array
train
def _sanitize_array(key, array) array.map { |value| _sanitize_value(key, value) }.freeze end
ruby
{ "resource": "" }
q9915
Announcer.Event._sanitize_value
train
def _sanitize_value(key, value) case value when String value.dup.freeze when Symbol, Integer, Float, NilClass, TrueClass, FalseClass value when Array _sanitize_array(key, value) when Hash _sanitize_params(value) else raise Errors::UnsafeValueError.new(key, value) end end
ruby
{ "resource": "" }
q9916
HashThatTree.HashIt.validate
train
def validate @folders.each do |item| if(item==nil) || (item=="") || !Dir.exists?(item) puts "a valid folder path is required as argument #{item}" exit end end end
ruby
{ "resource": "" }
q9917
MPQ.SC2ReplayFile.attributes
train
def attributes return @attributes if defined? @attributes data = read_file "replay.attributes.events" data.slice! 0, (game_version[:build] < 17326 ? 4 : 5) @attributes = [] data.slice!(0, 4).unpack("V")[0].times do @attributes << Attribute.read(data.slice!(0, 13)) end @attributes end
ruby
{ "resource": "" }
q9918
MPQ.SC2ReplayFile.parse_global_attributes
train
def parse_global_attributes attributes.each do |attr| case attr.id.to_i when 0x07d1 @game_type = attr.sval @game_type = @game_type == 'Cust' ? :custom : @game_type[1, 3].to_sym when 0x0bb8 @game_speed = ATTRIBUTES[:game_speed][attr.sval] when 0x0bc1 @category = ATTRIBUTES[:category][attr.sval] end end end
ruby
{ "resource": "" }
q9919
ActionPusher.Base.push
train
def push(opts) tokens = [opts[:tokens] || opts[:token] || opts[:to]].flatten message = opts[:message] || '' data = opts[:data] || {} badge_count = opts[:badge_count] || 0 return self if message.blank? @_notifications = Array.new.tap do |notifications| tokens.each do |token| notifications << Houston::Notification.new(device: token).tap do |notification| notification.alert = message notification.badge = badge_count notification.custom_data = data end end end self end
ruby
{ "resource": "" }
q9920
ActionPusher.Base.deliver
train
def deliver return self if @_push_was_called @_push_was_called = true apn = APNCertificate.instance @_notifications.each do |notification| apn.push(notification) end end
ruby
{ "resource": "" }
q9921
Apexgen.ObjectFactory.generate
train
def generate create_header unless @fields.empty? @fields.each { |field| create_field(field) } end create_footer @dtd << Ox.dump(@doc).strip end
ruby
{ "resource": "" }
q9922
Apexgen.ObjectFactory.make_node
train
def make_node(name, value=nil, attributes={}) node = Ox::Element.new(name) node << value unless value.nil? attributes.each { |att, val| node[att] = val } unless attributes.empty? node end
ruby
{ "resource": "" }
q9923
Apexgen.ObjectFactory.make_nodes
train
def make_nodes(nodes, parent_node) nodes.each do |name, value| if value.kind_of?(Hash) node = Ox::Element.new(name.to_s) make_nodes(value, node) else node = make_node(name.to_s, value) end parent_node << node parent_node end end
ruby
{ "resource": "" }
q9924
Apexgen.ObjectFactory.create_header
train
def create_header nodes = { deploymentStatus: 'Deployed', description: "A custom object named #{@name}", enableActivities: 'true', enableFeeds: 'false', enableHistory: 'true', enableReports: 'true' } make_nodes(nodes, @doc_root) end
ruby
{ "resource": "" }
q9925
AngularRailsSeo.ViewHelpers.seo_data
train
def seo_data if @seo_data.nil? Rails.configuration.seo.each do |key, value| regex = Regexp.new(value["regex"]).match(request.path) unless regex.nil? data = Rails.configuration.seo[key] fallback = data["parent"].blank? ? seo_default : seo_default.merge(Rails.configuration.seo[data["parent"]]) unless data["model"].blank? response = seo_dynamic(data["model"], regex[1..(regex.size - 1)]) data = response.nil? ? {} : response end @seo_data = fallback.merge(data) end end end @seo_data ||= seo_default end
ruby
{ "resource": "" }
q9926
ViewFu.TagHelper.add_class
train
def add_class(css_class, options = {}) return {} unless css_class attributes = {:class => css_class} if options.has_key?(:unless) return options[:unless] ? {} : attributes end if options.has_key?(:if) return options[:if] ? attributes : {} end attributes end
ruby
{ "resource": "" }
q9927
ViewFu.TagHelper.delete_link
train
def delete_link(*args) options = {:method => :delete, :confirm => "Are you sure you want to delete this?"}.merge(extract_options_from_args!(args)||{}) args << options link_to(*args) end
ruby
{ "resource": "" }
q9928
TableTransform.Table.metadata
train
def metadata warn 'metadata is deprecated. Use column_properties[] instead' @column_properties.inject({}){|res, (k, v)| res.merge!({k => v.to_h})} end
ruby
{ "resource": "" }
q9929
TableTransform.Table.+
train
def +(table) t2 = table.to_a t2_header = t2.shift raise 'Tables cannot be added due to header mismatch' unless @column_properties.keys == t2_header raise 'Tables cannot be added due to column properties mismatch' unless column_properties_eql? table.column_properties raise 'Tables cannot be added due to table properties mismatch' unless @table_properties.to_h == table.table_properties.to_h TableTransform::Table.new(self.to_a + t2) end
ruby
{ "resource": "" }
q9930
TableTransform.Table.add_column
train
def add_column(name, column_properties = {}) validate_column_absence(name) create_column_properties(name, column_properties) @data_rows.each{|x| x << (yield Row.new(@column_indexes, x)) } @column_indexes[name] = @column_indexes.size self # enable chaining end
ruby
{ "resource": "" }
q9931
Clyp.Client.upload
train
def upload track if track.playlist_id and track.playlist_token response = JSON.parse(RestClient.post(UPLOAD_BASE, audioFile: track.file, title: track.title, playlistId: track.playlist_id, playlistUploadToken: track.playlist_token, order: track.order, description: track.description, longitude: track.longitude, latitude: track.latitude)) else response = JSON.parse(RestClient.post(UPLOAD_BASE, audioFile: track.file, title: track.title, order: track.order, description: track.description, longitude: track.longitude, latitude: track.latitude)) end TrackUser.new(response) end
ruby
{ "resource": "" }
q9932
Clyp.Client.get
train
def get (id:) response = Faraday.get("#{API_BASE}/#{id}") attributes = JSON.parse(response.body) Track.new(attributes) end
ruby
{ "resource": "" }
q9933
Clyp.Client.soundwave
train
def soundwave (id:) response = Faraday.get("#{API_BASE}/#{id}/soundwave") attributes = JSON.parse(response.body) Soundwave.new(attributes) end
ruby
{ "resource": "" }
q9934
Clyp.Client.category_list
train
def category_list response = Faraday.get("#{API_BASE}/categorylist") attributes = JSON.parse(response.body) result = Array.new attributes.each do |attrs| result << ListItem.new(attrs) end result end
ruby
{ "resource": "" }
q9935
Clyp.Client.search
train
def search term response = Faraday.get("#{API_BASE}/categorylist/#{term}") attributes = JSON.parse(response.body) assemble_tracks attributes end
ruby
{ "resource": "" }
q9936
Clyp.Client.featured
train
def featured (count: 10) response = Faraday.get("#{API_BASE}/featuredlist/featured?count=#{count}") attributes = JSON.parse(response.body) assemble_tracks attributes end
ruby
{ "resource": "" }
q9937
MIPPeR.GurobiModel.gurobi_status
train
def gurobi_status intptr = FFI::MemoryPointer.new :pointer ret = Gurobi.GRBgetintattr @ptr, Gurobi::GRB_INT_ATTR_STATUS, intptr fail if ret != 0 case intptr.read_int when Gurobi::GRB_OPTIMAL :optimized when Gurobi::GRB_INFEASIBLE, Gurobi::GRB_INF_OR_UNBD, Gurobi::GRB_UNBOUNDED :invalid else :unknown end end
ruby
{ "resource": "" }
q9938
MIPPeR.GurobiModel.gurobi_objective
train
def gurobi_objective dblptr = FFI::MemoryPointer.new :pointer ret = Gurobi.GRBgetdblattr @ptr, Gurobi::GRB_DBL_ATTR_OBJVAL, dblptr fail if ret != 0 dblptr.read_double end
ruby
{ "resource": "" }
q9939
MIPPeR.GurobiModel.add_variable
train
def add_variable(var) ret = Gurobi.GRBaddvar @ptr, 0, nil, nil, var.coefficient, var.lower_bound, var.upper_bound, gurobi_type(var.type), var.name fail if ret != 0 store_variable var end
ruby
{ "resource": "" }
q9940
MIPPeR.GurobiModel.add_constraint
train
def add_constraint(constr) terms = constr.expression.terms indexes_buffer = build_pointer_array(terms.each_key.map do |var| var.index end, :int) values_buffer = build_pointer_array terms.values, :double ret = Gurobi.GRBaddconstr @ptr, terms.length, indexes_buffer, values_buffer, gurobi_sense(constr.sense), constr.rhs, constr.name fail if ret != 0 constr.model = self constr.index = @constraints.length constr.freeze @constraints << constr end
ruby
{ "resource": "" }
q9941
MIPPeR.GurobiModel.build_constraint_matrix
train
def build_constraint_matrix(constrs) cbeg = [] cind = [] cval = [] constrs.each.map do |constr| cbeg << cind.length constr.expression.terms.each do |var, coeff| cind << var.index cval << coeff end end [cbeg, cind, cval] end
ruby
{ "resource": "" }
q9942
MIPPeR.GurobiModel.array_to_pointers_to_names
train
def array_to_pointers_to_names(arr) arr.map do |obj| obj.name.nil? ? nil : FFI::MemoryPointer.from_string(obj.name) end end
ruby
{ "resource": "" }
q9943
LatoBlog.Post::SerializerHelpers.serialize
train
def serialize serialized = {} # set basic info serialized[:id] = id serialized[:title] = title serialized[:subtitle] = subtitle serialized[:excerpt] = excerpt serialized[:content] = content serialized[:seo_description] = seo_description serialized[:meta_language] = meta_language serialized[:meta_permalink] = meta_permalink serialized[:meta_status] = meta_status # add fields informations serialized[:fields] = serialize_fields # add categories informations serialized[:categories] = serialize_categories # add tags informations serialized[:tags] = serialize_tags # add post parent informations serialized[:other_informations] = serialize_other_informations # return serialized post serialized end
ruby
{ "resource": "" }
q9944
LatoBlog.Post::SerializerHelpers.serialize_fields
train
def serialize_fields serialized = {} post_fields.visibles.roots.order('position ASC').each do |post_field| serialized[post_field.key] = post_field.serialize_base end serialized end
ruby
{ "resource": "" }
q9945
LatoBlog.Post::SerializerHelpers.serialize_categories
train
def serialize_categories serialized = {} categories.each do |category| serialized[category.id] = category.serialize_base end serialized end
ruby
{ "resource": "" }
q9946
LatoBlog.Post::SerializerHelpers.serialize_tags
train
def serialize_tags serialized = {} tags.each do |tag| serialized[tag.id] = tag.serialize_base end serialized end
ruby
{ "resource": "" }
q9947
LatoBlog.Post::SerializerHelpers.serialize_other_informations
train
def serialize_other_informations serialized = {} # set pubblication datetime serialized[:publication_datetime] = post_parent.publication_datetime # set translations links serialized[:translations] = {} post_parent.posts.published.each do |post| next if post.id == id serialized[:translations][post.meta_language] = post.serialize_base end # return serialzed informations serialized end
ruby
{ "resource": "" }
q9948
Rscratch.Exception.set_attributes_for
train
def set_attributes_for _exception, _controller, _action, _env self.exception = _exception.class self.message = _exception.message self.controller = _controller self.action = _action self.app_environment = _env end
ruby
{ "resource": "" }
q9949
FifteenPuzzle.GameMatrix.moved_matrix_with_parent
train
def moved_matrix_with_parent( i, j, new_i, new_j, open_list, closed_list ) return nil if !index_exist?( new_i, new_j ) swapped_matrix = swap( i, j, new_i, new_j ) new_depth = @depth + 1 swapped_matrix = GameMatrix.new( swapped_matrix, self, new_depth ) return nil if closed_list.include?( swapped_matrix ) swapped_matrix.calculate_cost open_list_matrix = open_list.find{ |e| e == swapped_matrix } if open_list_matrix && open_list_matrix.cost < swapped_matrix.cost return open_list_matrix elsif open_list_matrix open_list_matrix.parent = self open_list_matrix.depth = new_depth return open_list_matrix else return swapped_matrix end end
ruby
{ "resource": "" }
q9950
FifteenPuzzle.GameMatrix.neighbors
train
def neighbors( open_list=[], closed_list=[] ) i,j = free_cell up = moved_matrix_with_parent(i, j, i-1, j, open_list, closed_list) down = moved_matrix_with_parent(i, j, i+1, j, open_list, closed_list) left = moved_matrix_with_parent(i, j, i, j-1, open_list, closed_list) right = moved_matrix_with_parent(i, j, i, j+1, open_list, closed_list) moved = [] moved << up if !up.nil? moved << down if !down.nil? moved << left if !left.nil? moved << right if !right.nil? return moved end
ruby
{ "resource": "" }
q9951
MPQ.Archive.read_table
train
def read_table table table_offset = @archive_header.send "#{table}_table_offset" @io.seek @user_header.archive_header_offset + table_offset table_entries = @archive_header.send "#{table}_table_entries" data = @io.read table_entries * 16 key = Hashing::hash_for :table, "(#{table} table)" data = Hashing::decrypt data, key klass = table == :hash ? HashTableEntry : BlockTableEntry (0...table_entries).map do |i| klass.read(data[i * 16, 16]) end end
ruby
{ "resource": "" }
q9952
MPQ.Archive.read_file
train
def read_file filename # The first block location is stored in the hash table. hash_a = Hashing::hash_for :hash_a, filename hash_b = Hashing::hash_for :hash_b, filename hash_entry = @hash_table.find do |h| [h.hash_a, h.hash_b] == [hash_a, hash_b] end unless hash_entry return nil end block_entry = @block_table[hash_entry.block_index] unless block_entry.file? return nil end @io.seek @user_header.archive_header_offset + block_entry.block_offset file_data = @io.read block_entry.archived_size # Blocks can be encrypted. Decryption isn't currently implemented as none # of the blocks in a StarCraft 2 replay are encrypted. if block_entry.encrypted? return nil end # Files can consist of one or many blocks. In either case, each block # (or *sector*) is read and individually decompressed if needed, then # stitched together for the final result. if block_entry.single_unit? if block_entry.compressed? if file_data.bytes.next == 16 file_data = Bzip2.uncompress file_data[1, file_data.length] end end return file_data end sector_size = 512 << @archive_header.sector_size_shift sectors = block_entry.size / sector_size + 1 if block_entry.has_checksums sectors += 1 end positions = file_data[0, 4 * (sectors + 1)].unpack "V#{sectors + 1}" sectors = [] positions.each_with_index do |pos, i| break if i + 1 == positions.length sector = file_data[pos, positions[i + 1] - pos] if block_entry.compressed? if block_entry.size > block_entry.archived_size if sector.bytes.next == 16 sector = Bzip2.uncompress sector end end end sectors << sector end sectors.join '' end
ruby
{ "resource": "" }
q9953
DCPU16.Assembler.assemble
train
def assemble location = 0 @labels = {} @body = [] lines.each do |line| # Set label location @labels[line.label] = location if line.label # Skip when no op next if line.op.empty? op = Instruction.create(line.op, line.args, location) @body << op location += op.size end # Apply labels begin @body.each { |op| op.apply_labels(@labels) } rescue Exception => e puts @labels.inspect raise e end end
ruby
{ "resource": "" }
q9954
Rscratch.ExceptionLog.set_attributes_for
train
def set_attributes_for exc, request self.backtrace = exc.backtrace.join("\n"), self.request_url = request.original_url, self.request_method = request.request_method, self.parameters = request.filtered_parameters, self.user_agent = request.user_agent, self.client_ip = request.remote_ip, self.status = "new", self.description = exc.inspect end
ruby
{ "resource": "" }
q9955
Cathode.CreateRequest.default_action_block
train
def default_action_block proc do begin create_params = instance_eval(&@strong_params) if resource.singular create_params["#{parent_resource_name}_id"] = parent_resource_id end body model.create(create_params) rescue ActionController::ParameterMissing => error body error.message status :bad_request end end end
ruby
{ "resource": "" }
q9956
Kat.App.running
train
def running puts set_window_width searching = true [ -> { @kat.search @page searching = false }, -> { i = 0 while searching print "\rSearching...".yellow + '\\|/-'[i % 4] i += 1 sleep 0.1 end } ].map { |w| Thread.new { w.call } }.each(&:join) puts((res = format_results)) if res.size > 1 case (answer = prompt) when 'i' then @show_info = !@show_info when 'n' then @page += 1 if next? when 'p' then @page -= 1 if prev? when 'q' then return false else if (1..@kat.results[@page].size).include?((answer = answer.to_i)) print "\nDownloading".yellow << ": #{ @kat.results[@page][answer - 1][:title] }... " puts download @kat.results[@page][answer - 1] end end true else false end end
ruby
{ "resource": "" }
q9957
Kat.App.format_lists
train
def format_lists(lists) lists.inject([nil]) do |buf, (_, val)| opts = Kat::Search.send(val[:select]) buf << val[:select].to_s.capitalize buf << nil unless opts.values.first.is_a? Array width = opts.keys.sort { |a, b| b.size <=> a.size }.first.size opts.each do |k, v| buf += if v.is_a? Array [nil, "%#{ width }s => #{ v.shift }" % k] + v.map { |e| ' ' * (width + 4) + e } else ["%-#{ width }s => #{ v }" % k] end end buf << nil end end
ruby
{ "resource": "" }
q9958
Kat.App.format_results
train
def format_results main_width = @window_width - (!hide_info? || @show_info ? 42 : 4) buf = [] if @kat.error return ["\rConnection failed".red] elsif !@kat.results[@page] return ["\rNo results ".red] end buf << "\r#{ @kat.message[:message] }\n".red if @kat.message buf << ("\r%-#{ main_width + 5 }s#{ ' Size Age Seeds Leeches' if !hide_info? || @show_info }" % ["Page #{ page + 1 } of #{ @kat.pages }", nil]).yellow @kat.results[@page].each_with_index do |t, i| age = t[:age].split "\xC2\xA0" age = '%3d %-6s' % age # Filter out the crap that invariably infests torrent names title = t[:title].codepoints.map { |c| c > 31 && c < 127 ? c.chr : '?' }.join[0...main_width] buf << ("%2d. %-#{ main_width }s#{ ' %10s %10s %7d %7d' if !hide_info? or @show_info }" % [i + 1, title, t[:size], age, t[:seeds], t[:leeches]]).tap { |s| s.red! if t[:seeds] == 0 } end buf << nil end
ruby
{ "resource": "" }
q9959
Kat.App.prompt
train
def prompt n = @kat.results[@page].size @h.ask("1#{ "-#{n}" if n > 1}".cyan(true) << ' to download' << "#{ ', ' << '(n)'.cyan(true) << 'ext' if next? }" << "#{ ', ' << '(p)'.cyan(true) << 'rev' if prev? }" << "#{ ", #{ @show_info ? 'hide' : 'show' } " << '(i)'.cyan(true) << 'nfo' if hide_info? }" << ', ' << '(q)'.cyan(true) << 'uit: ') do |q| q.responses[:not_valid] = 'Invalid option.' q.validate = validation_regex end rescue RegexpError puts((@kat.pages > 0 ? "Error reading the page\n" : "Could not connect to the site\n").red) return 'q' end
ruby
{ "resource": "" }
q9960
Anvil.Cli.run
train
def run(argv) load_tasks return build_task(argv).run unless argv.empty? print_help_header print_help_body end
ruby
{ "resource": "" }
q9961
Anvil.Cli.build_task
train
def build_task(argv) arguments = argv.dup task_name = arguments.shift klazz = Task.from_name(task_name) klazz.new(*klazz.parse_options!(arguments)) rescue NameError task_not_found(task_name) exit false rescue ArgumentError bad_arguments(task_name) exit false end
ruby
{ "resource": "" }
q9962
SynCache.Cache.flush
train
def flush(base = nil) debug { 'flush ' << base.to_s } @sync.synchronize do if @flush_delay next_flush = @last_flush + @flush_delay if next_flush > Time.now flush_at(next_flush, base) else flush_now(base) @last_flush = Time.now end else flush_now(base) end end end
ruby
{ "resource": "" }
q9963
SynCache.Cache.[]=
train
def []=(key, value) debug { '[]= ' << key.to_s } entry = get_locked_entry(key) begin return entry.value = value ensure entry.sync.unlock end end
ruby
{ "resource": "" }
q9964
SynCache.Cache.debug
train
def debug return unless @debug message = Thread.current.to_s + ' ' + yield if defined?(Syslog) and Syslog.opened? Syslog.debug(message) else STDERR << 'syncache: ' + message + "\n" STDERR.flush end end
ruby
{ "resource": "" }
q9965
AbortIf.Assert.assert_keys
train
def assert_keys coll, *keys check_responds_to coll, :[] check_not_empty keys assert keys.all? { |key| coll[key] }, "Expected coll to include all keys" end
ruby
{ "resource": "" }
q9966
AbortIf.Assert.assert_length
train
def assert_length coll, len check_responds_to coll, :length assert coll.length == len, "Expected coll to have %d items", len end
ruby
{ "resource": "" }
q9967
Ejs.Compiler.js_source
train
def js_source(source_path, namespace = nil, output_as_array = false) template_name = File.basename(source_path, ".ejs") template_name = "#{namespace}.#{template_name}" if namespace js_source_from_string(template_name, File.read(source_path), output_as_array) end
ruby
{ "resource": "" }
q9968
Ejs.Compiler.js_source_from_string
train
def js_source_from_string(template_name, content, output_as_array = false) buffer = [] parsed = @parser.parse(content) if parsed.nil? raise ParseError.new(@parser.failure_reason, @parser.failure_line, @parser.failure_column) end template_namespace(buffer, template_name) template_header(buffer, template_name) parsed.elements.each do |element| push_content(buffer, element) end template_footer(buffer) output_as_array ? buffer : buffer.join("\n") end
ruby
{ "resource": "" }
q9969
RDFResource.Resource.provenance
train
def provenance s = [rdf_uri, RDF::PROV.SoftwareAgent, @@agent] rdf.insert(s) s = [rdf_uri, RDF::PROV.generatedAtTime, rdf_now] rdf.insert(s) end
ruby
{ "resource": "" }
q9970
RDFResource.Resource.rdf_find_object
train
def rdf_find_object(id) return nil unless rdf_valid? rdf.each_statement do |s| if s.subject == @iri.to_s return s.object if s.object.to_s =~ Regexp.new(id, Regexp::IGNORECASE) end end nil end
ruby
{ "resource": "" }
q9971
RDFResource.Resource.rdf_find_subject
train
def rdf_find_subject(id) return nil unless rdf_valid? rdf.each_subject do |s| return s if s.to_s =~ Regexp.new(id, Regexp::IGNORECASE) end nil end
ruby
{ "resource": "" }
q9972
Merritt.Manifest.write_to
train
def write_to(io) write_sc(io, conformance) write_sc(io, 'profile', profile) prefixes.each { |prefix, url| write_sc(io, 'prefix', "#{prefix}:", url) } write_sc(io, 'fields', *fields) entries.each { |entry| io.puts(entry_line(entry)) } write_sc(io, 'eof') end
ruby
{ "resource": "" }
q9973
Merritt.Manifest.write_sc
train
def write_sc(io, comment, *columns) io << '#%' << comment io << COLSEP << columns.join(COLSEP) unless columns.empty? io << "\n" end
ruby
{ "resource": "" }
q9974
Uninhibited.Feature.Scenario
train
def Scenario(*args, &example_group_block) args << {} unless args.last.is_a?(Hash) args.last.update(:scenario => true) describe("Scenario:", *args, &example_group_block) end
ruby
{ "resource": "" }
q9975
Uninhibited.Feature.skip_examples_after
train
def skip_examples_after(example, example_group = self) examples = example_group.descendant_filtered_examples.flatten examples[examples.index(example)..-1].each do |e| e.metadata[:pending] = true e.metadata[:skipped] = true end end
ruby
{ "resource": "" }
q9976
Uninhibited.Feature.handle_exception
train
def handle_exception(example) if example.instance_variable_get(:@exception) if metadata[:background] skip_examples_after(example, ancestors[1]) else skip_examples_after(example) end end end
ruby
{ "resource": "" }
q9977
Colonel.Builder.update_job
train
def update_job(opts={}) index = get_job_index(opts[:id]) job = find_job(opts[:id]) @jobs[index] = job.update(opts) end
ruby
{ "resource": "" }
q9978
Colonel.Builder.add_job
train
def add_job(opts={}) @jobs << Job.new( Parser::Schedule.new(opts[:schedule]), Parser::Command.new(opts[:command])) end
ruby
{ "resource": "" }
q9979
Aker::Rack.Setup.call
train
def call(env) env['aker.configuration'] = @configuration env['aker.authority'] = @configuration.composite_authority env['aker.interactive'] = interactive?(env) @app.call(env) end
ruby
{ "resource": "" }
q9980
CanvasInteractor.CanvasApi.hash_csv
train
def hash_csv(csv_string) require 'csv' csv = CSV.parse(csv_string) headers = csv.shift output = [] csv.each do |row| hash = {} headers.each do |header| hash[header] = row.shift.to_s end output << hash end return output end
ruby
{ "resource": "" }
q9981
Analects.Source.retrieve_save
train
def retrieve_save(data) File.open(location, 'w') do |f| f << (data.respond_to?(:read) ? data.read : data) end end
ruby
{ "resource": "" }
q9982
Breeze.Server.wait_until_host_is_available
train
def wait_until_host_is_available(host, get_ip=false) resolved_host = Resolv.getaddresses(host).first if resolved_host.nil? print("Waiting for #{host} to resolve") wait_until('ready!') { resolved_host = Resolv.getaddresses(host).first } end host = resolved_host if get_ip unless remote_is_available?(host) print("Waiting for #{host} to accept connections") wait_until('ready!') { remote_is_available?(host) } end return host end
ruby
{ "resource": "" }
q9983
Bitsa.ContactsCache.search
train
def search(qry) rg = Regexp.new(qry || '', Regexp::IGNORECASE) # Flatten to an array with [email1, name1, email2, name2] etc. results = @addresses.values.flatten.each_slice(2).find_all do |e, n| e.match(rg) || n.match(rg) end # Sort by case-insensitive email address results.sort { |a, b| a[0].downcase <=> b[0].downcase } end
ruby
{ "resource": "" }
q9984
Bitsa.ContactsCache.update
train
def update(id, name, addresses) @cache_last_modified = DateTime.now.to_s @addresses[id] = addresses.map { |a| [a, name] } end
ruby
{ "resource": "" }
q9985
ActionDispatch::Routing.Mapper.mount_rails_info
train
def mount_rails_info match '/rails/info' => 'rails_info/properties#index', via: :get, via: :get, as: 'rails_info' match '/rails/info/properties' => 'rails_info/properties#index', via: :get, via: :get, as: 'rails_info_properties' match '/rails/info/routes' => 'rails_info/routes#index', via: :get, as: 'rails_info_routes' match '/rails/info/model' => 'rails_info/model#index', via: :get, as: 'rails_info_model' match '/rails/info/data' => 'rails_info/data#index', via: :get, as: 'rails_info_data', via: :get, as: 'rails_info_data' post '/rails/info/data/update_multiple' => 'rails_info/data#update_multiple', via: :post, as: 'rails_update_multiple_rails_info_data' match '/rails/info/logs/server' => 'rails_info/logs/server#new', via: :get, as: 'new_rails_info_server_log' put '/rails/info/logs/server' => 'rails_info/logs/server#update', via: :put, as: 'rails_info_server_log' get '/rails/info/logs/server/big' => 'rails_info/logs/server#big' match '/rails/info/logs/test/rspec' => 'rails_info/logs/test/rspec#new', via: :get, as: 'new_rails_info_rspec_log' put '/rails/info/logs/test/rspec' => 'rails_info/logs/test/rspec#update', via: :put, as: 'rails_info_rspec_log' match '/rails/info/stack_traces/new' => 'rails_info/stack_traces#new', via: :get, as: 'new_rails_info_stack_trace' post '/rails/info/stack_traces' => 'rails_info/stack_traces#create', via: :post, as: 'rails_info_stack_trace' namespace 'rails_info', path: 'rails/info' do namespace 'system' do resources :directories, only: :index end namespace 'version_control' do resources :filters, only: [:new, :create] resources :diffs, only: :new end end end
ruby
{ "resource": "" }
q9986
MatchyMatchy.Matchbook.build_candidates
train
def build_candidates(candidates) candidates.to_a.map do |object, preferences| candidate(object).tap do |c| c.prefer(*preferences.map { |t| target(t) }) end end end
ruby
{ "resource": "" }
q9987
NoSequel.Configuration.sequel_url
train
def sequel_url return '' unless db_type # Start our connection string connect_string = db_type + '://' # Add user:password if supplied unless db_user.nil? connect_string += db_user # Add either a @ or / depending on if a host was provided too connect_string += db_host ? '@' : '/' # Add host:port if supplied connect_string += db_host + '/' if db_host end connect_string + db_name end
ruby
{ "resource": "" }
q9988
RubyEdit.Find.execute
train
def execute(output: $stdout, errors: $stderr) if empty_name? output.puts 'No name given' return false end result = run "find #{@path} #{type} -name '#{@name}'" do |_out, err| errors << err if err end # The following line makes the output into something readable # # Before the output would have looked like this: ## ./lib/my_file.rb ## ./lib/folder/my_file.rb # # Whereas it will now look like this: ## ./lib/my_file.rbi NEW_NAME=> ./lib/my_file.rb ## ./lib/folder/my_file.rb NEW_NAME=> ./lib/folder/my_file.rb # # Making it more obvious that the original path is on the left # and the path to edit is on the right @result = result.out.split("\n").map { |path| "#{path} NEW_NAME=> #{path}" }.join("\n") rescue TTY::Command::ExitError => error output.puts error end
ruby
{ "resource": "" }
q9989
Denglu.Comment.list
train
def list(comment_id=0, max=50) req_method = :GET req_uri = '/api/v4/get_comment_list' req_options = { :commentid => comment_id, :count => max } response = request_api(req_method, req_uri, req_options) normalize_comments JSON.parse(response) end
ruby
{ "resource": "" }
q9990
Denglu.Comment.total
train
def total(resource=nil) req_method = :GET req_uri = '/api/v4/get_comment_count' req_options = {} case when resource.is_a?(Integer) req_options[:postid] = resource when resource.is_a?(String) req_options[:url] = resource end response = request_api(req_method, req_uri, req_options) response = JSON.parse(response) unless resource.nil? response = response[0] end response end
ruby
{ "resource": "" }
q9991
LatoBlog.Back::PostsController.index
train
def index core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:posts]) # find correct status to show @posts_status = 'published' @posts_status = 'drafted' if params[:status] && params[:status] === 'drafted' @posts_status = 'deleted' if params[:status] && params[:status] === 'deleted' # find informations data @posts_informations = { published_length: LatoBlog::Post.published.where(meta_language: cookies[:lato_blog__current_language]).length, drafted_length: LatoBlog::Post.drafted.where(meta_language: cookies[:lato_blog__current_language]).length, deleted_length: LatoBlog::Post.deleted.where(meta_language: cookies[:lato_blog__current_language]).length } # find posts to show @posts = LatoBlog::Post.where(meta_status: @posts_status, meta_language: cookies[:lato_blog__current_language]).joins(:post_parent).order('lato_blog_post_parents.publication_datetime DESC') @widget_index_posts = core__widgets_index(@posts, search: 'title', pagination: 10) end
ruby
{ "resource": "" }
q9992
LatoBlog.Back::PostsController.new
train
def new core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:posts_new]) @post = LatoBlog::Post.new set_current_language params[:language] if params[:language] if params[:parent] @post_parent = LatoBlog::PostParent.find_by(id: params[:parent]) end fetch_external_objects end
ruby
{ "resource": "" }
q9993
LatoBlog.Back::PostsController.create
train
def create @post = LatoBlog::Post.new(new_post_params) unless @post.save flash[:danger] = @post.errors.full_messages.to_sentence redirect_to lato_blog.new_post_path return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:post_create_success] redirect_to lato_blog.post_path(@post.id) end
ruby
{ "resource": "" }
q9994
LatoBlog.Back::PostsController.edit
train
def edit core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:posts_edit]) @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence if @post.meta_language != cookies[:lato_blog__current_language] set_current_language @post.meta_language end fetch_external_objects end
ruby
{ "resource": "" }
q9995
LatoBlog.Back::PostsController.update
train
def update @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence # update for autosaving autosaving = params[:autosave] && params[:autosave] == 'true' if autosaving @post.update(edit_post_params) update_fields render status: 200, json: {} # render something positive :) return end # check post data update unless @post.update(edit_post_params) flash[:danger] = @post.errors.full_messages.to_sentence redirect_to lato_blog.edit_post_path(@post.id) return end # update single fields unless update_fields flash[:warning] = LANGUAGES[:lato_blog][:flashes][:post_update_fields_warning] redirect_to lato_blog.edit_post_path(@post.id) return end # render positive response flash[:success] = LANGUAGES[:lato_blog][:flashes][:post_update_success] redirect_to lato_blog.post_path(@post.id) end
ruby
{ "resource": "" }
q9996
LatoBlog.Back::PostsController.update_status
train
def update_status @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence @post.update(meta_status: params[:status]) end
ruby
{ "resource": "" }
q9997
LatoBlog.Back::PostsController.update_categories
train
def update_categories @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence params[:categories].each do |category_id, value| category = LatoBlog::Category.find_by(id: category_id) next if !category || category.meta_language != @post.meta_language category_post = LatoBlog::CategoryPost.find_by(lato_blog_post_id: @post.id, lato_blog_category_id: category.id) if value == 'true' LatoBlog::CategoryPost.create(lato_blog_post_id: @post.id, lato_blog_category_id: category.id) unless category_post else category_post.destroy if category_post end end end
ruby
{ "resource": "" }
q9998
LatoBlog.Back::PostsController.update_tags
train
def update_tags @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence params_tags = params[:tags].map(&:to_i) tag_posts = LatoBlog::TagPost.where(lato_blog_post_id: @post.id) params_tags.each do |tag_id| tag = LatoBlog::Tag.find_by(id: tag_id) next if !tag || tag.meta_language != @post.meta_language tag_post = tag_posts.find_by(lato_blog_tag_id: tag.id) LatoBlog::TagPost.create(lato_blog_post_id: @post.id, lato_blog_tag_id: tag.id) unless tag_post end tag_ids = tag_posts.pluck(:lato_blog_tag_id) tag_ids.each do |tag_id| next if params_tags.include?(tag_id) tag_post = tag_posts.find_by(lato_blog_tag_id: tag_id) tag_post.destroy if tag_post end end
ruby
{ "resource": "" }
q9999
LatoBlog.Back::PostsController.update_seo_description
train
def update_seo_description @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence @post.update(seo_description: params[:seo_description]) end
ruby
{ "resource": "" }