_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q300
Epuber.Book.targets
train
def targets(*names, &block) if names.empty? UI.warning('Book#targets to get all targets is deprecated, use #all_targets instead', location: caller_locations.first) return all_targets end names.map { |name| target(name, &block) } end
ruby
{ "resource": "" }
q301
SmugMug.HTTP.request
train
def request(api, args) uri = api == :uploading ? UPLOAD_URI : API_URI args[:method] = "smugmug.#{api}" unless api == :uploading http = ::Net::HTTP.new(uri.host, uri.port, @http_proxy_host, @http_proxy_port, @http_proxy_user, @http_proxy_pass) http.set_debug_output(@config[:debug_output]) if @co...
ruby
{ "resource": "" }
q302
SmugMug.HTTP.sign_request
train
def sign_request(method, uri, form_args) # Convert non-string keys to strings so the sort works args = {} if form_args form_args.each do |key, value| next unless value and value != "" key = key.to_s unless key.is_a?(String) args[key] = value end end...
ruby
{ "resource": "" }
q303
Grooveshark.Client.get_user_by_id
train
def get_user_by_id(id) resp = request('getUserByID', userID: id)['user'] resp['user_id'].nil? ? nil : User.new(self, resp) end
ruby
{ "resource": "" }
q304
Grooveshark.Client.get_user_by_username
train
def get_user_by_username(name) resp = request('getUserByUsername', username: name)['user'] resp['user_id'].nil? ? nil : User.new(self, resp) end
ruby
{ "resource": "" }
q305
Grooveshark.Client.popular_songs
train
def popular_songs(type = 'daily') fail ArgumentError, 'Invalid type' unless %w(daily monthly).include?(type) request('popularGetSongs', type: type)['songs'].map { |s| Song.new(s) } end
ruby
{ "resource": "" }
q306
Grooveshark.Client.top_broadcasts
train
def top_broadcasts(count = 10) top_broadcasts = [] request('getTopBroadcastsCombined').each do |key, _val| broadcast_id = key.split(':')[1] top_broadcasts.push(Broadcast.new(self, broadcast_id)) count -= 1 break if count == 0 end top_broadcasts end
ruby
{ "resource": "" }
q307
Grooveshark.Client.search
train
def search(type, query) results = [] search = request('getResultsFromSearch', type: type, query: query) results = search['result'].map do |data| next Song.new data if type == 'Songs' next Playlist.new(self, data) if type == 'Playlists' data end if search.key?('result') ...
ruby
{ "resource": "" }
q308
Grooveshark.Client.get_stream_auth_by_songid
train
def get_stream_auth_by_songid(song_id) result = request('getStreamKeyFromSongIDEx', 'type' => 0, 'prefetch' => false, 'songID' => song_id, 'country' => @country, 'mobile' => false) if result ==...
ruby
{ "resource": "" }
q309
Grooveshark.Client.request
train
def request(method, params = {}, secure = false) refresh_token if @comm_token url = "#{secure ? 'https' : 'http'}://grooveshark.com/more.php?#{method}" begin data = RestClient.post(url, body(method, params).to_json, 'Content-Type' ...
ruby
{ "resource": "" }
q310
Oeffi.Configuration.provider=
train
def provider=(sym) klass = "#{sym.to_s.capitalize}Provider" begin java_import "de.schildbach.pte.#{klass}" @provider = Oeffi::const_get(klass).new rescue Exception => e raise "Unknown Provider name: #{klass}" end end
ruby
{ "resource": "" }
q311
CrmFormatter.Address.check_addr_status
train
def check_addr_status(hsh) full_addr = hsh[:full_addr] full_addr_f = hsh[:full_addr_f] status = nil if full_addr && full_addr_f status = full_addr != full_addr_f ? 'formatted' : 'unchanged' end hsh[:address_status] = status hsh end
ruby
{ "resource": "" }
q312
CrmFormatter.Address.make_full_address_original
train
def make_full_address_original(hsh) full_adr = [hsh[:street], hsh[:city], hsh[:state], hsh[:zip]].compact.join(', ') full_adr end
ruby
{ "resource": "" }
q313
MoreViewHooks.HookCollection.add
train
def add(name, options) fail ArgumentError, "A view hook '#{name}' already exists" if @hooks[name] context = options.delete(:context) hook = @hooks[name] = Hook.new(name, context, options) hook.apply! if @applied end
ruby
{ "resource": "" }
q314
BlueprintClient.HierarchyApi.add_node
train
def add_node(namespace_inc_global, body, opts = {}) data, _status_code, _headers = add_node_with_http_info(namespace_inc_global, body, opts) return data end
ruby
{ "resource": "" }
q315
BlueprintClient.HierarchyApi.delete_node
train
def delete_node(namespace, id, type, opts = {}) delete_node_with_http_info(namespace, id, type, opts) return nil end
ruby
{ "resource": "" }
q316
BlueprintClient.HierarchyApi.get_node
train
def get_node(namespace, id, type, opts = {}) data, _status_code, _headers = get_node_with_http_info(namespace, id, type, opts) return data end
ruby
{ "resource": "" }
q317
BlueprintClient.HierarchyApi.replace_node
train
def replace_node(namespace, id, body, type, opts = {}) data, _status_code, _headers = replace_node_with_http_info(namespace, id, body, type, opts) return data end
ruby
{ "resource": "" }
q318
BlueprintClient.HierarchyApi.update_node
train
def update_node(namespace, id, body, type, opts = {}) data, _status_code, _headers = update_node_with_http_info(namespace, id, body, type, opts) return data end
ruby
{ "resource": "" }
q319
Berkshelf.HgLocation.install
train
def install if cached? # Update and checkout the correct ref Dir.chdir(cache_path) do hg %|pull| end else # Ensure the cache directory is present before doing anything FileUtils.mkdir_p(cache_path) Dir.chdir(cache_path) do hg %|clone #{uri...
ruby
{ "resource": "" }
q320
Berkshelf.HgLocation.hg
train
def hg(command, error = true) unless Berkshelf.which('hg') || Berkshelf.which('hg.exe') raise HgNotInstalled.new end Berkshelf.log.debug("Running:hg #{command}") response = shell_out(%|hg #{command}|) Berkshelf.log.debug("response:hg #{response.stdout}") if response.error? ...
ruby
{ "resource": "" }
q321
Berkshelf.HgLocation.cache_path
train
def cache_path Pathname.new(Berkshelf.berkshelf_path) .join('.cache', 'hg', Digest::SHA1.hexdigest(uri)) end
ruby
{ "resource": "" }
q322
Cadenero::V1.Account::SessionsController.create
train
def create if env['warden'].authenticate(:password, :scope => :user) #return the user JSON on success render json: current_user, status: :created else #return error mesage in a JSON on error render json: {errors: {user:["Invalid email or password"]}}, status: :unprocessable_e...
ruby
{ "resource": "" }
q323
Cadenero::V1.Account::SessionsController.delete
train
def delete user = Cadenero::User.find_by_id(params[:id]) if user_signed_in? env['warden'].logout(:user) render json: {message: "Successful logout"}, status: :ok else render json: {message: "Unsuccessful logout user with id"}, status: :forbidden end end
ruby
{ "resource": "" }
q324
Bunto.BuntoSitemap.file_exists?
train
def file_exists?(file_path) if @site.respond_to?(:in_source_dir) File.exist? @site.in_source_dir(file_path) else File.exist? Bunto.sanitized_path(@site.source, file_path) end end
ruby
{ "resource": "" }
q325
RiddlerAdmin.StepsController.internal_preview
train
def internal_preview @preview_context = ::RiddlerAdmin::PreviewContext.find_by_id params["pctx_id"] if @preview_context.nil? render(status: 400, json: {message: "Invalid pctx_id"}) and return end @use_case = ::Riddler::UseCases::AdminPreviewStep.new @step.definition_hash, previe...
ruby
{ "resource": "" }
q326
GeneValidatorApp.Config.write_config_file
train
def write_config_file return unless config_file File.open(config_file, 'w') do |f| f.puts(data.delete_if { |_, v| v.nil? }.to_yaml) end end
ruby
{ "resource": "" }
q327
GeneValidatorApp.Config.symbolise
train
def symbolise(data) return {} unless data # Symbolize keys. Hash[data.map { |k, v| [k.to_sym, v] }] end
ruby
{ "resource": "" }
q328
GeneValidatorApp.Config.defaults
train
def defaults { num_threads: 1, mafft_threads: 1, port: 5678, ssl: false, host: '0.0.0.0', serve_public_dir: File.join(Dir.home, '.genevalidatorapp/'), max_characters: 'undefined' } end
ruby
{ "resource": "" }
q329
RippleRest.Account.trustlines
train
def trustlines data = RippleRest .get("v1/accounts/#{@address}/trustlines")["trustlines"] .map(&Trustline.method(:new)) obj = Trustlines.new data obj.account = self obj end
ruby
{ "resource": "" }
q330
RippleRest.Account.settings
train
def settings data = RippleRest.get("v1/accounts/#{@address}/settings")["settings"] obj = AccountSettings.new data obj.account = self obj end
ruby
{ "resource": "" }
q331
RippleRest.Account.payments
train
def payments payments ||= lambda { obj = Payments.new obj.account = self obj }.call end
ruby
{ "resource": "" }
q332
RippleRest.Payments.find_path
train
def find_path destination_account, destination_amount, source_currencies = nil uri = "v1/accounts/#{account.address}/payments/paths/#{destination_account.to_s}/#{destination_amount.to_s}" if source_currencies cur = source_currencies.join(",") uri += "?source_currencies=#{cur}" e...
ruby
{ "resource": "" }
q333
RippleRest.Payments.create
train
def create destination_account, destination_amount payment = Payment.new payment.account = account payment.destination_account = destination_account.to_s payment.destination_amount = Amount.from_string(destination_amount) payment end
ruby
{ "resource": "" }
q334
RippleRest.Payments.query
train
def query options = {} qs = "" if options && options.size > 0 qs = "?" + options.map { |k,v| "#{k}=#{CGI::escape(v.to_s)}" }.join('&') end uri = "v1/accounts/#{account.address}/payments#{qs}" RippleRest.get(uri)["payments"].map do |i| payment = Payment.new(i["...
ruby
{ "resource": "" }
q335
QUnited.Application.handle_options
train
def handle_options drivers = ::QUnited::Driver.constants.reject { |d| d == :Base } valid_drivers_string = "Valid drivers include: #{drivers.map { |d| d.to_s }.join(', ')}" args_empty = ARGV.empty? # This is a bit of a hack, but OptionParser removes the -- that separates the source # and ...
ruby
{ "resource": "" }
q336
AmpleAssets.ViewHelper.image_asset
train
def image_asset(object, args={}) # Gracefully handle nil return if object.try(:file).nil? && args[:object].nil? # Define default opts and merge with parameter args opts = { :alt => '', :video_dimensions => '500x350', :encode => :png }.merge(args) # Override...
ruby
{ "resource": "" }
q337
BlueprintClient.AssetTypeConfigsApi.get
train
def get(namespace, asset_type, opts = {}) data, _status_code, _headers = get_with_http_info(namespace, asset_type, opts) return data end
ruby
{ "resource": "" }
q338
AgglomerativeClustering.SilhouetteCoefficient.measure
train
def measure clusters silhouettes = [] average_distances = [] main_cluster.points.each do |point1| a1 = calculate_a1(point1) (clusters - [main_cluster]).each do |cluster| distances = [] cluster.points.each do |point2| distances << euclidean_di...
ruby
{ "resource": "" }
q339
AgglomerativeClustering.SilhouetteCoefficient.calculate_a1
train
def calculate_a1 point distances = [] main_cluster.points.each do |point1| distances << euclidean_distance(point, point1).round(2) end return 0 if distances.size == 1 (distances.inject(:+)/(distances.size - 1)).round(2) end
ruby
{ "resource": "" }
q340
ActsAsSolr.CommonMethods.get_solr_field_type
train
def get_solr_field_type(field_type) if field_type.is_a?(Symbol) t = TypeMapping[field_type] raise "Unknown field_type symbol: #{field_type}" if t.nil? t elsif field_type.is_a?(String) return field_type else raise "Unknown field_type class: #{field_type.class}: #...
ruby
{ "resource": "" }
q341
ActsAsSolr.CommonMethods.solr_add
train
def solr_add(add_xml) ActsAsSolr::Post.execute(Solr::Request::AddDocument.new(add_xml)) end
ruby
{ "resource": "" }
q342
ActsAsSolr.CommonMethods.solr_delete
train
def solr_delete(solr_ids) ActsAsSolr::Post.execute(Solr::Request::Delete.new(:id => solr_ids)) end
ruby
{ "resource": "" }
q343
Dk::Remote.BaseCmd.build_ssh_cmd_str
train
def build_ssh_cmd_str(cmd_str, host, args, host_args) Dk::Remote.ssh_cmd_str(cmd_str, host, args, host_args) end
ruby
{ "resource": "" }
q344
QUnited.RakeTask.files_array
train
def files_array(files) return [] unless files files.is_a?(Array) ? files : pattern_to_filelist(files.to_s) end
ruby
{ "resource": "" }
q345
LibComponent.Pin.introspect
train
def introspect iface = Hash.new pin = Hash.new meth = Array.new if self.respond_to?(:read) meth << "read" end if self.respond_to?(:write) meth << "write" end iface[@interface] = meth pin[@name] = iface return pin end
ruby
{ "resource": "" }
q346
LibComponent.Component.<<
train
def <<(pin_) if pin_.kind_of?(Input) @inputs << pin_ elsif pin_.kind_of?(Output) @outputs << pin_ elsif pin_.kind_of?(Array) # push an array of pin pin_.each { |p| self << p } end pin_.set_component(self) end
ruby
{ "resource": "" }
q347
LibComponent.Component.run
train
def run # execute startup methods @inputs.each do |inp| inp.start if inp.respond_to?(:start) end @outputs.each do |outp| outp.start if outp.respond_to?(:start) end intro = introspect if @options[:introspect] print intro.to_yaml else ...
ruby
{ "resource": "" }
q348
LibComponent.Component.introspect
train
def introspect inputs_h = Hash.new outputs_h = Hash.new #call all inputs introspect and merge values @inputs.each { |input| inputs_h.merge!(input.introspect) { |key, old, new| old.merge(new) } } #call all outputs introspect and merge values @outputs.each { |outpu...
ruby
{ "resource": "" }
q349
LibComponent.Component.quit_server
train
def quit_server(status_, str_) $stderr.puts str_ if (!@options.nil?) && !@options[:debug] bus = DBus::ASessionBus.new server = bus.service("org.openplacos.server.internal") opos = server.object("/plugins") opos.introspect opos.default_iface = "org.openpl...
ruby
{ "resource": "" }
q350
Zadt.FaceGraph.make_original_face
train
def make_original_face(num_edges) num_edges_check(num_edges) # Make the vertices vert_ref = Array.new(num_edges) {Vertex.new} edge_ref = [] # Connect each vertex to the one before it (including the first one :) (num_edges).times do |vert_id| edge_ref << make_connection(vert_...
ruby
{ "resource": "" }
q351
Zadt.FaceGraph.add_attached_face
train
def add_attached_face(vertex_array, num_edges) vertex_array_check(vertex_array) num_edges_check(num_edges) # Make the vertices into a line vertex_line = confirm_vertex_line(vertex_array) # This finds the "ends" of the vertex line end_vertices = [vertex_line.first, vertex_line.last] ...
ruby
{ "resource": "" }
q352
Zadt.FaceGraph.find_neighbors
train
def find_neighbors(vertex_array) vertex_array_check(vertex_array) neighbors = [] vertex_array.each do |vertex| @faces.each do |face| neighbors << face if face.vertices.include?(vertex) end end neighbors.uniq end
ruby
{ "resource": "" }
q353
Zadt.FaceGraph.find_face_neighbors
train
def find_face_neighbors(face) raise "not a face" unless face.is_a?(Face) neighbors = find_neighbors(face.vertices) neighbors - [face] end
ruby
{ "resource": "" }
q354
CrmFormatter.Proper.check_proper_status
train
def check_proper_status(hsh) proper = hsh[:proper] proper_f = hsh[:proper_f] status = 'invalid' status = proper != proper_f ? 'formatted' : 'unchanged' if proper && proper_f hsh[:proper_status] = status if status.present? hsh end
ruby
{ "resource": "" }
q355
Finitio.UnionType.dress
train
def dress(value, handler = DressHelper.new) error = nil # Do nothing on TypeError as the next candidate could be the good one! candidates.each do |c| success, uped = handler.just_try do c.dress(value, handler) end return uped if success error ||= uped e...
ruby
{ "resource": "" }
q356
Eluka.FeatureVectors.define_features
train
def define_features @fvs.each do |vector, label| vector.each do |term, value| @features.add(term) end end end
ruby
{ "resource": "" }
q357
BlueprintClient.IntegrationsApi.add_integration
train
def add_integration(namespace, body, opts = {}) data, _status_code, _headers = add_integration_with_http_info(namespace, body, opts) return data end
ruby
{ "resource": "" }
q358
BlueprintClient.IntegrationsApi.delete_integration
train
def delete_integration(namespace, integration_id, integration_type, opts = {}) delete_integration_with_http_info(namespace, integration_id, integration_type, opts) return nil end
ruby
{ "resource": "" }
q359
BlueprintClient.IntegrationsApi.get_integration
train
def get_integration(namespace, integration_type, integration_id, opts = {}) data, _status_code, _headers = get_integration_with_http_info(namespace, integration_type, integration_id, opts) return data end
ruby
{ "resource": "" }
q360
BlueprintClient.IntegrationsApi.replace_integration
train
def replace_integration(namespace, integration_id, integration_type, body, opts = {}) data, _status_code, _headers = replace_integration_with_http_info(namespace, integration_id, integration_type, body, opts) return data end
ruby
{ "resource": "" }
q361
TinyCI.GitUtils.repo_root
train
def repo_root return git_directory_path if inside_bare_repo? if inside_git_directory? File.expand_path('..', git_directory_path) elsif inside_work_tree? execute(git_cmd('rev-parse', '--show-toplevel')) else raise 'not in git directory or work tree!?' end ...
ruby
{ "resource": "" }
q362
ActsAsSolr.ParserMethods.parse_results
train
def parse_results(solr_data, options = {}) results = { :docs => [], :total => 0 } configuration = { :format => :objects } results.update(:spellcheck => solr_data.data['spellcheck']) unless solr_data.nil? results.update(:facets => {'facet_fields' => []}) if op...
ruby
{ "resource": "" }
q363
ActsAsSolr.ParserMethods.reorder
train
def reorder(things, ids) ordered_things = [] ids.each do |id| thing = things.find{ |t| t.id.to_s == id.to_s } ordered_things |= [thing] if thing end ordered_things end
ruby
{ "resource": "" }
q364
ActsAsSolr.ParserMethods.add_scores
train
def add_scores(results, solr_data) with_score = [] solr_data.hits.each do |doc| with_score.push([doc["score"], results.find {|record| scorable_record?(record, doc) }]) end with_score.each do |score, object| class << object; attr_accessor :solr_score; end object....
ruby
{ "resource": "" }
q365
CrmFormatter.Web.check_web_status
train
def check_web_status(hsh) status = 'invalid' if hsh[:web_neg]&.include?('error') if hsh[:url] && hsh[:url_f] && status.nil? status = hsh[:url] != hsh[:url_f] ? 'formatted' : 'unchanged' end hsh[:web_status] = status if status.present? hsh end
ruby
{ "resource": "" }
q366
CrmFormatter.Web.extract_path
train
def extract_path(url_hash) path_parts = url_hash[:url_f].split('//').last.split('/')[1..-1] path = "/#{path_parts.join('/')}" if path&.length > 2 url_hash[:url_path] = path url_hash[:url_f] = url_hash[:url_f].gsub(url_hash[:url_path], '') end url_hash end
ruby
{ "resource": "" }
q367
ColumnPack.ViewHelpers.pack_element
train
def pack_element(height, content = nil, &block) return if @column_packer.nil? if block_given? @column_packer.add(height.to_i, capture(&block)) else @column_packer.add(height.to_i, content) end end
ruby
{ "resource": "" }
q368
PsUtilities.PreBuiltPost.u_students_extension
train
def u_students_extension(data) db_extensions = { "name"=>"u_students_extension", "recordFound"=>false, "_field"=> [] } data.each do |key, value| db_extensions["_field"] << {"name"=>"#{key}", "type"=>"String", "value"=>"#{value}"} end db_extensions end
ruby
{ "resource": "" }
q369
PsUtilities.PreBuiltPost.u_studentsuserfields
train
def u_studentsuserfields(data) db_extensions = { "name"=>"u_studentsuserfields", "recordFound"=>false, "_field"=> [] } data.each do |key, value| db_extensions["_field"] << {"name"=>"#{key}", "type"=>"String", "value"=>"#{value}"} end db_extensions end
ruby
{ "resource": "" }
q370
Rews.Util.strip_bang
train
def strip_bang(k) if k.is_a? Symbol k.to_s[0...-1].to_sym else k.to_s[0...-1] end end
ruby
{ "resource": "" }
q371
Rews.Util.camelize
train
def camelize(s) if s.is_a?(Symbol) s.to_s.split('_').map(&:capitalize).join.to_sym else s.split('_').map(&:capitalize).join end end
ruby
{ "resource": "" }
q372
Rews.Util.camel_keys
train
def camel_keys(h) Hash[h.map{|k,v| [camelize(k.to_s), v]}] end
ruby
{ "resource": "" }
q373
Rews.Util.apply_namespace
train
def apply_namespace(qname, apply_prefix, apply_uri) local_part, prefix, uri = qname if !prefix prefix = apply_prefix uri = apply_uri end [local_part, prefix, uri].compact end
ruby
{ "resource": "" }
q374
Rews.Util.camelize_qname
train
def camelize_qname(qname) local_part, prefix, uri = qname [camelize(local_part), prefix, uri].compact end
ruby
{ "resource": "" }
q375
Rews.Util.with_error_check
train
def with_error_check(client, *response_msg_keys) raise "no block" if !block_given? begin response = yield hash_response = response.to_hash statuses = hash_response.fetch_in(*response_msg_keys) if statuses.is_a?(Array) all_statuses = statuses else ...
ruby
{ "resource": "" }
q376
Rews.Util.single_error_check
train
def single_error_check(client, status) begin response_class = status[:response_class] rescue raise "no response_class found: #{status.inspect}" if !response_class end if status[:response_class] == "Error" return "#{status[:response_code]} - #{status[:message_text]}" ...
ruby
{ "resource": "" }
q377
Finitio.Attribute.fetch_on
train
def fetch_on(arg, &bl) unless arg.respond_to?(:fetch) raise ArgumentError, "Object responding to `fetch` expected" end arg.fetch(name) do arg.fetch(name.to_s, &bl) end end
ruby
{ "resource": "" }
q378
YaLoremJa.WordResource.sentences
train
def sentences(total) list = [] total.times do word_count = rand(word_count_range_in_a_sentence) sentence_len = word_count.times.inject(0){ |sum| sum + rand(char_count_range_in_a_word) } sentence_key = bsearch(sentence_map_keys, sentence_len) unless sentence_key sent...
ruby
{ "resource": "" }
q379
Skyper.SkypeObject.set_property
train
def set_property(property, value) cmd = ["SET",self.class.object_name, id, property, value].compact.join(" ") Skyper::Skype.send_command(cmd) end
ruby
{ "resource": "" }
q380
Finitio.TypeFactory.subtype
train
def subtype(super_type, constraints = nil, name = nil, metadata = nil, &bl) super_type = type(super_type) constraints = constraints(constraints, &bl) name = name(name) meta = metadata(metadata) SubType.new(super_type, constraints, name, metadata) end
ruby
{ "resource": "" }
q381
Finitio.TypeFactory.tuple
train
def tuple(heading, name = nil, metadata = nil) heading = heading(heading) name = name(name) meta = metadata(metadata) TupleType.new(heading, name, meta) end
ruby
{ "resource": "" }
q382
YaLoremJa.Lorem.image
train
def image(size, options={}) domain = options[:domain] || 'http://placehold.it' src = "#{domain}/#{size}" hex = %w(a b c d e f 0 1 2 3 4 5 6 7 8 9) background_color = options[:background_color] color = options[:color] if options[:random_...
ruby
{ "resource": "" }
q383
RippleRest.AccountSettings.save
train
def save raise ArgumentError.new("Account is missing.") unless account account.require_secret hash = {} hash["settings"] = to_hash hash["secret"] = account.secret RippleRest.post "v1/accounts/#{account.address}/settings", hash end
ruby
{ "resource": "" }
q384
RippleRest.Payment.submit
train
def submit @account.require_secret hash = {} hash["payment"] = self.to_hash hash["secret"] = @account.secret hash["client_resource_id"] = client_resource_id = RippleRest.next_uuid source_account = self.to_hash[:source_account] RippleRest.post("v1/accounts/#{source...
ruby
{ "resource": "" }
q385
Rews.Item.read_items
train
def read_items(client, items) return [] if !items items.map do |item_class,items_of_class| items_of_class = [items_of_class] if !items_of_class.is_a?(Array) items_of_class.map do |item| Item.new(client, item_class, item) end end.flatten end
ruby
{ "resource": "" }
q386
Rews.Item.read_get_item_response_messages
train
def read_get_item_response_messages(client, get_item_response_messages) get_item_response_messages = [get_item_response_messages] if !get_item_response_messages.is_a?(Array) items = get_item_response_messages.map do |girm| read_items(client, girm[:items]) end.flatten end
ruby
{ "resource": "" }
q387
Krikri::Enrichments.DcmiTypeMap.most_similar
train
def most_similar(value, threshold = 0.5) @white ||= Text::WhiteSimilarity.new result = @map.max_by { |str, _| @white.similarity(value, str) } return result[1] if @white.similarity(value, result.first) > threshold nil end
ruby
{ "resource": "" }
q388
Restful.Actions.index
train
def index(options = {}, &block) respond_with(collection, options, &block) if stale?(collection, last_modified: collection.maximum(:updated_at)) end
ruby
{ "resource": "" }
q389
Restful.Actions.create
train
def create(options = {}, &block) object = get_resource_ivar || create_resource options[:location] = collection_path if object.errors.empty? respond_with_dual(object, options, &block) end
ruby
{ "resource": "" }
q390
Krikri::Harvesters.PrimoHarvester.enumerate_records
train
def enumerate_records(xml) doc = Nokogiri::XML(xml) doc.root.add_namespace_definition('nmbib', PRIMO_NS) doc.xpath('//sear:DOC').lazy.map do |record| identifier = record.xpath('./nmbib:PrimoNMBib/nmbib:record/' \ 'nmbib:control/nmbib:recordid') ...
ruby
{ "resource": "" }
q391
RiceCooker.Helpers.sortable_fields_for
train
def sortable_fields_for(model) if model.respond_to?(:sortable_fields) model.sortable_fields.map(&:to_sym) elsif model.respond_to?(:column_names) model.column_names.map(&:to_sym) else [] end end
ruby
{ "resource": "" }
q392
RiceCooker.Helpers.filterable_fields_for
train
def filterable_fields_for(model) if model.respond_to?(:filterable_fields) model.filterable_fields.map(&:to_sym) elsif model.respond_to?(:column_names) model.column_names.map(&:to_sym) else [] end end
ruby
{ "resource": "" }
q393
StatusCat.StatusHelper.status_report
train
def status_report(checkers) format, format_length = status_report_format(checkers) header = status_report_header(format) length = [format_length, header.length].max separator = ('-' * length) + "\n" result = separator + header + separator checkers.each { |checker| result << checker....
ruby
{ "resource": "" }
q394
StatusCat.StatusHelper.status_report_format
train
def status_report_format(checkers) name_max = status_report_format_max_length(checkers, :name) value_max = status_report_format_max_length(checkers, :value) status_max = status_report_format_max_length(checkers, :status) format = "%#{name_max}s | %#{value_max}s | %#{status_max}s\n" length...
ruby
{ "resource": "" }
q395
StatusCat.StatusHelper.status_report_header
train
def status_report_header(format = StatusCat::Checkers::Base::FORMAT) name = I18n.t(:name, scope: :status_cat) value = I18n.t(:value, scope: :status_cat) status = I18n.t(:status, scope: :status_cat) return format(format, name, value, status) end
ruby
{ "resource": "" }
q396
Vnstat.Parser.extract_month_from_xml_element
train
def extract_month_from_xml_element(element) month = element.xpath('date/month').text.to_i year = element.xpath('date/year').text.to_i [year, month] end
ruby
{ "resource": "" }
q397
Vnstat.Parser.extract_date_from_xml_element
train
def extract_date_from_xml_element(element) day = element.xpath('date/day').text.to_i year, month = extract_month_from_xml_element(element) Date.new(year, month, day) end
ruby
{ "resource": "" }
q398
Vnstat.Parser.extract_datetime_from_xml_element
train
def extract_datetime_from_xml_element(element) date = extract_date_from_xml_element(element) hour = element.xpath('time/hour').text.to_i minute = element.xpath('time/minute').text.to_i offset = Time.now.strftime('%:z') Time.new(date.year, date.month, date.day, hour, minute, 0, offset) ...
ruby
{ "resource": "" }
q399
Vnstat.Parser.extract_transmitted_bytes_from_xml_element
train
def extract_transmitted_bytes_from_xml_element(element) bytes_received = element.xpath('rx').text.to_i * 1024 bytes_sent = element.xpath('tx').text.to_i * 1024 [bytes_received, bytes_sent] end
ruby
{ "resource": "" }