_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q7800
Taxonomite.Tree.ancestors
train
def ancestors a = Array.new self.parent._ancestors(a) unless self.parent.nil? return a end
ruby
{ "resource": "" }
q7801
Taxonomite.Tree.move_children_to_parent
train
def move_children_to_parent children.each do |c| self.parent.children << c c.parent = self.parent # is this necessary? end end
ruby
{ "resource": "" }
q7802
Taxonomite.Tree.validate_child!
train
def validate_child!(ch) raise InvalidChild.create(self, ch) if (ch == nil) raise CircularRelation.create(self, ch) if self.descendant_of?(ch) if base_class.method_defined? :validate_child self.validate_child(ch) # this should throw an error if not valid end end
ruby
{ "resource": "" }
q7803
Taxonomite.Entity.do_setup
train
def do_setup if (self.taxonomy_node == nil) self.taxonomy_node = self.respond_to?(:create_taxonomy_node) ? self.create_taxonomy_node : Taxonomite::Node.new self.taxonomy_node.owner = self end end
ruby
{ "resource": "" }
q7804
Calculated.Service.check_response
train
def check_response(response) case response.code when 200, 201 true when 401 raise Calculated::Session::PermissionDenied.new("Your Request could not be authenticated is your api key valid?") when 404 raise Calculated::Session::NotFound.new("Resource was not found") when 412 raise Calculated::Session::MissingParameter.new("Missing Parameter: #{response.body}") else raise Calculated::Session::UnknownError.new("super strange type unknown error: #{response.code} :body #{response.body}") end end
ruby
{ "resource": "" }
q7805
SpeakyCsv.AttrImport.add_fields
train
def add_fields(row, attrs) fields = (@config.fields - @config.export_only_fields).map(&:to_s) fields.each do |name| row.has_key? name or next attrs[name] = row.field name end end
ruby
{ "resource": "" }
q7806
SpeakyCsv.AttrImport.add_has_manys
train
def add_has_manys(row, attrs) headers_length = row.headers.compact.length pairs_start_on_evens = headers_length.even? (headers_length..row.fields.length).each do |i| i.send(pairs_start_on_evens ? :even? : :odd?) || next row[i] || next m = row[i].match(/^(\w+)_(\d+)_(\w+)$/) m || next has_many_name = m[1].pluralize has_many_index = m[2].to_i has_many_field = m[3] has_many_value = row[i + 1] has_many_config = @config.has_manys[has_many_name.to_sym] next unless has_many_config next unless has_many_config.fields.include?(has_many_field.to_sym) next if has_many_config.export_only_fields.include?(has_many_field.to_sym) attrs[has_many_name] ||= [] attrs[has_many_name][has_many_index] ||= {} attrs[has_many_name][has_many_index][has_many_field] = has_many_value end end
ruby
{ "resource": "" }
q7807
SpeakyCsv.AttrImport.add_has_ones
train
def add_has_ones(row, attrs) @config.has_ones.each do |name,assoc_config| fields = (assoc_config.fields - assoc_config.export_only_fields).map(&:to_s) fields.each do |f| csv_name = "#{name}_#{f}" row.has_key? csv_name or next (attrs[name.to_s] ||= {})[f] = row.field "#{name}_#{f}" end end end
ruby
{ "resource": "" }
q7808
Sjekksum.Damm.of
train
def of number raise_on_type_mismatch number digits = convert_number_to_digits(number) digits.reduce(0){ |check, digit| QUASIGROUP[check][digit] } end
ruby
{ "resource": "" }
q7809
YARD.SitemapGenerator.generate_sitemap
train
def generate_sitemap(basedir) sitemap_file = File.join(basedir, 'sitemap.xml') File.open(sitemap_file, 'w') do |file| file.write(sitemap_contents(basedir)) end end
ruby
{ "resource": "" }
q7810
SimpleActivity.ActivityProcessor.save
train
def save if validate_attrs Activity.create(activity_attrs).tap do |activity| Callbacks.run(activity) end else warning end end
ruby
{ "resource": "" }
q7811
Rack.WebProfiler::Request.http_headers
train
def http_headers env.select { |k, _v| (k.start_with?("HTTP_") && k != "HTTP_VERSION") || k == "CONTENT_TYPE" } .collect { |k, v| [k.sub(/^HTTP_/, ""), v] } .collect { |k, v| [k.split("_").collect(&:capitalize).join("-"), v] } end
ruby
{ "resource": "" }
q7812
Rack.WebProfiler::Request.raw
train
def raw headers = http_headers.map { |k, v| "#{k}: #{v}\r\n" }.join format "%s %s %s\r\n%s\r\n%s", request_method.upcase, fullpath, env["SERVER_PROTOCOL"], headers, body_string end
ruby
{ "resource": "" }
q7813
DuckMap.FilterStack.copy_filter
train
def copy_filter(filter) buffer = {exclude: {}, include: {}} filter[:exclude].each do |part| buffer[:exclude][part[0]] = part[1].dup end filter[:include].each do |part| buffer[:include][part[0]] = part[1].dup end return buffer end
ruby
{ "resource": "" }
q7814
DuckMap.FilterStack.clear_filter
train
def clear_filter(section, key) key = key.kind_of?(Symbol) ? key : key.to_sym self.current_filter[section][key] = [] return nil end
ruby
{ "resource": "" }
q7815
ActiveNode.Graph.many?
train
def many? if block_given? to_a.many? { |*block_args| yield(*block_args) } else limit_value ? to_a.many? : size > 1 end end
ruby
{ "resource": "" }
q7816
LXC.Container.status
train
def status output = run("info") result = output.scan(/^state:\s+([\w]+)|pid:\s+(-?[\d]+)$/).flatten LXC::Status.new(result.first, result.last) end
ruby
{ "resource": "" }
q7817
LXC.Container.wait
train
def wait(state) if !LXC::Shell.valid_state?(status.state) raise ArgumentError, "Invalid container state: #{state}" end run("wait", "-s", state) end
ruby
{ "resource": "" }
q7818
LXC.Container.cpu_usage
train
def cpu_usage result = run("cgroup", "cpuacct.usage").to_s.strip result.empty? ? nil : Float("%.4f" % (result.to_i / 1E9)) end
ruby
{ "resource": "" }
q7819
LXC.Container.processes
train
def processes raise ContainerError, "Container is not running" if !running? str = run("ps", "--", "-eo pid,user,%cpu,%mem,args").strip lines = str.split("\n") ; lines.delete_at(0) lines.map { |l| parse_process_line(l) } end
ruby
{ "resource": "" }
q7820
LXC.Container.create
train
def create(path) raise ContainerError, "Container already exists." if exists? if path.is_a?(Hash) args = "-n #{name}" if !!path[:config_file] unless File.exists?(path[:config_file]) raise ArgumentError, "File #{path[:config_file]} does not exist." end args += " -f #{path[:config_file]}" end if !!path[:template] template_dir = path[:template_dir] || "/usr/lib/lxc/templates" template_path = File.join(template_dir,"lxc-#{path[:template]}") unless File.exists?(template_path) raise ArgumentError, "Template #{path[:template]} does not exist." end args += " -t #{path[:template]} " end args += " -B #{path[:backingstore]}" if !!path[:backingstore] args += " -- #{path[:template_options].join(" ")}".strip if !!path[:template_options] LXC.run("create", args) exists? else unless File.exists?(path) raise ArgumentError, "File #{path} does not exist." end LXC.run("create", "-n", name, "-f", path) exists? end end
ruby
{ "resource": "" }
q7821
LXC.Container.clone_to
train
def clone_to(target) raise ContainerError, "Container does not exist." unless exists? if LXC.container(target).exists? raise ContainerError, "New container already exists." end LXC.run("clone", "-o", name, "-n", target) LXC.container(target) end
ruby
{ "resource": "" }
q7822
LXC.Container.clone_from
train
def clone_from(source) raise ContainerError, "Container already exists." if exists? unless LXC.container(source).exists? raise ContainerError, "Source container does not exist." end run("clone", "-o", source) exists? end
ruby
{ "resource": "" }
q7823
CpMgmt.Host.add
train
def add(name, ip_address, options={}) client = CpMgmt.configuration.client CpMgmt.logged_in? params = {name: name, "ip-address": ip_address} body = params.merge(options).to_json response = client.post do |req| req.url '/web_api/add-host' req.headers['Content-Type'] = 'application/json' req.headers['X-chkp-sid'] = ENV.fetch("sid") req.body = body end CpMgmt.transform_response(response) end
ruby
{ "resource": "" }
q7824
CpMgmt.Host.show
train
def show(name) client = CpMgmt.configuration.client CpMgmt.logged_in? body = {name: name}.to_json response = client.post do |req| req.url '/web_api/show-host' req.headers['Content-Type'] = 'application/json' req.headers['X-chkp-sid'] = ENV.fetch("sid") req.body = body end CpMgmt.transform_response(response) end
ruby
{ "resource": "" }
q7825
CpMgmt.Host.show_all
train
def show_all client = CpMgmt.configuration.client CpMgmt.logged_in? response = client.post do |req| req.url '/web_api/show-hosts' req.headers['Content-Type'] = 'application/json' req.headers['X-chkp-sid'] = ENV.fetch("sid") req.body = "{}" end CpMgmt.transform_response(response) end
ruby
{ "resource": "" }
q7826
Rattler::Runtime.ExtendedPackratParser.apply
train
def apply(match_method_name) start_pos = @scanner.pos if m = memo_lr(match_method_name, start_pos) recall m, match_method_name else lr = LR.new(false, match_method_name, nil) @lr_stack.push lr m = inject_memo match_method_name, start_pos, lr, start_pos result = eval_rule match_method_name @lr_stack.pop if lr.head m.end_pos = @scanner.pos lr.seed = result lr_answer match_method_name, start_pos, m else save m, result end end end
ruby
{ "resource": "" }
q7827
Calculated.ObjectTemplateApiCalls.generic_objects_for_object_template
train
def generic_objects_for_object_template(name, params = {}) api_call(:get, "/object_templates/#{name}/generic_objects", params) do |response| Calculated::Models::ObjectTemplate.new(response["object_template"]) end end
ruby
{ "resource": "" }
q7828
Calculated.ObjectTemplateApiCalls.relatable_categories_for_object_template
train
def relatable_categories_for_object_template(name, related_attribute, params = {}) api_call(:get, "/object_templates/#{name}/relatable_categories", params.merge!(:related_attribute => related_attribute)) do |response| Calculated::Models::ObjectTemplate.new(response["object_template"]) end end
ruby
{ "resource": "" }
q7829
Calculated.ObjectTemplateApiCalls.generic_objects_for_object_template_with_filter
train
def generic_objects_for_object_template_with_filter(name, filter, params = {}) api_call(:get, "/object_templates/#{name}/generic_objects/filter", params.merge!(:filter => filter)) do |response| Calculated::Models::ObjectTemplate.new(response["object_template"]) end end
ruby
{ "resource": "" }
q7830
RProgram.Program.sudo
train
def sudo(*arguments) options = case arguments.last when Hash then arguments.pop else {} end task = SudoTask.new(options.delete(:sudo) || {}) task.command = [@path] + arguments arguments = task.arguments arguments << options unless options.empty? return System.sudo(*arguments) end
ruby
{ "resource": "" }
q7831
RProgram.Program.run_task
train
def run_task(task,options={}) arguments = task.arguments arguments << options unless options.empty? return run(*arguments) end
ruby
{ "resource": "" }
q7832
RProgram.Program.sudo_task
train
def sudo_task(task,options={},&block) arguments = task.arguments arguments << options unless options.empty? return sudo(*arguments,&block) end
ruby
{ "resource": "" }
q7833
DuckMap.Mapper.sitemap
train
def sitemap(name = :sitemap, options = {}, &block) options = name.kind_of?(Hash) ? name : options name = name.kind_of?(String) || name.kind_of?(Symbol) ? name : :sitemap config = {controller: :sitemap, url_limit: nil}.merge(options) sitemap_raw_route_name = "#{name}_sitemap" sitemap_route_name = name_for_action(sitemap_raw_route_name, nil) begin unless @set.routes.find {|route| route.name.eql?(sitemap_route_name)} # create a route for the sitemap using the name that was passed to the sitemap method inside config/routes. match %(/#{name}.:format), controller: config[:controller], action: name, via: [:get], as: sitemap_raw_route_name # if not found here, then, there must be a real problem. # later, i will implement an exception, etc. sitemap_route = @set.routes.find {|route| route.name.eql?(sitemap_route_name)} # identify the route as a "sitemap" route and build it's full name. sitemap_route.is_sitemap = true sitemap_route.url_limit = config[:url_limit] sitemap_route.sitemap_route_name = sitemap_route_name sitemap_route.sitemap_raw_route_name = sitemap_raw_route_name # this is how I am faking to always point to the SitemapController # regardless of namespace sitemap_route.defaults[:controller] = "sitemap" end rescue ArgumentError => e unless e.message.include?("Invalid route name") raise e end end # now, find the route again, because, we need to set the following boolean and there might be several # calls to sitemap without a block. if we were to set this boolean in the code above when checking # if the route already exists, then, the boolean may never be set. sitemap_route = @set.routes.find {|route| route.is_sitemap? && route.name.eql?(sitemap_route_name) } # once a sitemap route has been flagged as being defined with a block, then, you should never set it back to false. # one of the features is to be able to encapsulate a set of routes within a sitemap as many times as you need. # meaning, you might want to wrap five routes at the top of the file, three in the middle, and two at the bottom and # have all of them included in the default sitemap. # Since all routes within a sitemap block will be marked with the same name, # I am not keeping track of sitemaps being defined with or without a block, so, all I need to know is about one of them. unless sitemap_route.sitemap_with_block? sitemap_route.sitemap_with_block = true if block_given? end # DuckMap::SitemapControllerHelpers is a module that is included in SitemapBaseController and contains # methods such as sitemap_build, etc. Define a method to handle the sitemap on DuckMap::SitemapControllerHelpers # so that method is visible to the default sitemap controller as well as any custom controllers that inherit from it. # originally, I was simply defining the method directly on SitemapBaseController, however, it was causing problems # during the development cycle of edit and refresh. Defining methods here seemed to cure that problem. # for example, the default sitemap: /sitemap.xml will define a method named: sitemap # on the DuckMap::SitemapControllerHelpers module. unless DuckMap::SitemapControllerHelpers.public_method_defined?(name) DuckMap::SitemapControllerHelpers.send :define_method, name do if DuckMap::Config.attributes[:sitemap_content].eql?(:xml) sitemap_build end respond_to do |format| format.xml { render } end end end # determine if the sitemap definition included a block. if block_given? # the starting point would be after the current set of routes and would be length plus one. # however, the starting point index is the length of routes, since arrays are zero based. start_point = @set.routes.length # push a copy of the current filter settings onto an array. # this will allow you to specify criteria setting within a sitemap definition without affecting # the default settings after the block is finished executing. @set.sitemap_filters.push # yield to the block. all standard route code should execute just fine and define namespaces, resource, matches, etc. yield total = run_filter(sitemap_route.sitemap_route_name, start_point) # knock the current filter setting off of the stack @set.sitemap_filters.pop DuckMap.logger.debug %(total routes filtered: #{@set.routes.length - start_point} included? #{total}) @set.routes.each do |route| DuckMap.logger.debug %( Route name: #{route.name}) if route.sitemap_route_name.eql?(sitemap_route.sitemap_route_name) end end return nil end
ruby
{ "resource": "" }
q7834
PackedStruct.Package.pack
train
def pack(data) values = [] data.each do |k, v| values.push([k, v]) end mapped_directives = @directives.map(&:name) values = values.select { |x| mapped_directives.include?(x[0]) } values.sort! do |a, b| mapped_directives.index(a[0]) <=> mapped_directives.index(b[0]) end ary = values.map(&:last) ary.pack to_s(data) end
ruby
{ "resource": "" }
q7835
PackedStruct.Package.unpack
train
def unpack(string) total = "" parts = {} directives.each_with_index do |directive, i| total << directive.to_s(parts) parts[directive.name] = string.unpack(total)[i] end parts.delete(:null) {} parts end
ruby
{ "resource": "" }
q7836
PackedStruct.Package.fast_unpack
train
def fast_unpack(string) out = string.unpack(to_s) parts = {} directives.each_with_index do |directive, i| parts[directive.name] = out[i] end parts.delete(:null) {} parts end
ruby
{ "resource": "" }
q7837
PackedStruct.Package.method_missing
train
def method_missing(method, *arguments, &block) super if @finalized if arguments.length == 1 && arguments.first.is_a?(Directive) arguments.first.add_modifier Modifier.new(method) else (directives.push Directive.new(method)).last end end
ruby
{ "resource": "" }
q7838
Nake.FileTask.invoke_dependencies
train
def invoke_dependencies(*args, options) self.dependencies.each do |name| if task = self.class[name] # first try if there is a task with given name task.call(*args, options) # TODO: what about arguments? elsif File.exist?(name) # if not, then fallback to file task_will_run?(name) else raise TaskNotFound, "Task with name #{name} doesn't exist" end end end
ruby
{ "resource": "" }
q7839
TypedArray.Functions._ensure_all_items_in_array_are_allowed
train
def _ensure_all_items_in_array_are_allowed(ary) # If we're getting an instance of self, accept return if ary.is_a? self.class _ensure_item_is_allowed(ary, [Array]) ary.each { |item| _ensure_item_is_allowed(item) } end
ruby
{ "resource": "" }
q7840
TypedArray.Functions._ensure_item_is_allowed
train
def _ensure_item_is_allowed(item, expected=nil) return if item.nil? #allow nil entries expected ||= self.class.restricted_types return if expected.any? { |allowed| item.class <= allowed } raise TypedArray::UnexpectedTypeException.new(expected, item.class) end
ruby
{ "resource": "" }
q7841
Rattler::Parsers.Sequence.parse
train
def parse(scanner, rules, scope = ParserScope.empty) backtracking(scanner) do if scope = parse_children(scanner, rules, scope.nest) yield scope if block_given? parse_result(scope) end end end
ruby
{ "resource": "" }
q7842
Herbalist.Token.get_tag
train
def get_tag(tag_type) matches = @tags.select { |m| m.type==tag_type } return matches.first end
ruby
{ "resource": "" }
q7843
SafetyCone.Configuration.add
train
def add(options = {}) self.options = options raise(ArgumentError, 'Mandatory param :name missing') unless options[:name] if options[:feature] features << options SafetyCone::ViewHelpers.add_method(options[:feature]) else paths[make_key] = options end end
ruby
{ "resource": "" }
q7844
SafetyCone.Configuration.make_key
train
def make_key if options.key? :method options[:method].to_sym elsif options.include?(:controller) && options.include?(:action) "#{options[:controller]}_#{options[:action]}".to_sym else raise(ArgumentError, 'Options should contain :controller and :action or :method.') end end
ruby
{ "resource": "" }
q7845
Oembedr.Client.get
train
def get options = {} additional_params = options.delete(:params) || {} connection(options).get do |req| req.url parsed_url.path req.params = additional_params.merge({ :url => resource_url, :format => "json" }) end end
ruby
{ "resource": "" }
q7846
Campaigning.List.create_custom_field!
train
def create_custom_field!(params) response = @@soap.createListCustomField( :apiKey => @apiKey, :listID => @listID, :fieldName => params[:fieldName], :dataType => params[:dataType], :options => params.fetch(:options, "") ) handle_response response.list_CreateCustomFieldResult end
ruby
{ "resource": "" }
q7847
Campaigning.List.get_all_active_subscribers
train
def get_all_active_subscribers find_active_subscribers(DateTime.new(y=1911,m=1,d=01, h=01,min=00,s=00)) end
ruby
{ "resource": "" }
q7848
Plz.CommandBuilder.base_url_from_schema
train
def base_url_from_schema json_schema.links.find do |link| if link.href && link.rel == "self" return link.href end end end
ruby
{ "resource": "" }
q7849
Relp.RelpProtocol.frame_read
train
def frame_read(socket) begin socket_content = socket.read_nonblock(4096) frame = Hash.new if match = socket_content.match(/(^[0-9]+) ([\S]*) (\d+)([\s\S]*)/) frame[:txnr], frame[:command], frame[:data_length], frame[:message] = match.captures # check_message_length(frame) - currently unstable, needs some more work frame[:message].lstrip! #message could be empty else raise Relp::FrameReadException.new('Problem with reading RELP frame') end @logger.debug "Reading Frame #{frame.inspect}" rescue IOError @logger.error 'Problem with reading RELP frame' raise Relp::FrameReadException.new 'Problem with reading RELP frame' rescue Errno::ECONNRESET @logger.error 'Connection reset' raise Relp::ConnectionClosed.new 'Connection closed' end is_valid_command(frame[:command]) return frame end
ruby
{ "resource": "" }
q7850
Relp.RelpProtocol.is_valid_command
train
def is_valid_command(command) valid_commands = ["open", "close", "rsp", "syslog"] if !valid_commands.include?(command) @logger.error 'Invalid RELP command' raise Relp::InvalidCommand.new('Invalid command') end end
ruby
{ "resource": "" }
q7851
SquadGoals.Helpers.client_call
train
def client_call(method, *args) key = cache_key(method, args) cached = dalli.get(key) return cached if cached response = client.send(method, *args) dalli.set(key, response) response end
ruby
{ "resource": "" }
q7852
Helmsman.ViewHelper.current_state_by_controller
train
def current_state_by_controller(*given_controller_names, actions: []) if given_controller_names.any? { |name| name == controller_name.to_sym } if actions.present? Array(actions).include?(action_name.to_sym) else true end end end
ruby
{ "resource": "" }
q7853
SalesforceAdapter.Base.call_webservice
train
def call_webservice(method_name, arguments, schema_url, service_path) # Perform the call to the webservice and returns the result Operations::WebserviceCall.new(@rforce_binding, method_name, arguments, schema_url, service_path).run() end
ruby
{ "resource": "" }
q7854
NASA.Client.neo_feed
train
def neo_feed(start_date = Time.now.strftime('%Y-%m-%d'), end_date = (Time.now + 604800).strftime('%Y-%m-%d')) request .neo .rest .v1('feed') .get(:params => { :api_key => @application_id.dup, :start_date => start_date, :end_date => end_date }) .to_h end
ruby
{ "resource": "" }
q7855
Nuggets.RubyMixin.ruby_executable
train
def ruby_executable @ruby_executable ||= begin dir, name, ext = CONFIG.values_at(*%w[bindir RUBY_INSTALL_NAME EXEEXT]) ::File.join(dir, name + ext).sub(/.*\s.*/m, '"\&"') end end
ruby
{ "resource": "" }
q7856
Nuggets.RubyMixin.command_for_ruby_tool
train
def command_for_ruby_tool(name) filename = respond_to?(name) ? send(name) : locate_ruby_tool(name) shebang_command(filename) =~ /ruby/ ? "#{ruby_command} #{filename}" : filename end
ruby
{ "resource": "" }
q7857
RightDevelop::CI.Util.pseudo_java_class_name
train
def pseudo_java_class_name(name) result = '' name.each_char do |chr| if chr =~ JAVA_CLASS_NAME result << chr elsif chr == JAVA_PACKAGE_SEPARATOR result << JAVE_PACKAGE_SEPARATOR_HOMOGLYPH else chr = chr.unpack('U')[0].to_s(16) result << "&#x#{chr};" end end result end
ruby
{ "resource": "" }
q7858
RightDevelop::CI.Util.purify
train
def purify(untrusted) # First pass: strip bad UTF-8 characters if RUBY_VERSION =~ /^1\.8/ iconv = Iconv.new('UTF-8//IGNORE', 'UTF-8') result = iconv.iconv(untrusted) else result = untrusted.force_encoding(Encoding::BINARY).encode('UTF-8', :undef=>:replace, :replace=>'') end # Second pass: entity escape characters that can't appear in XML CDATA. result.gsub(INVALID_CDATA_CHARACTER) do |ch| "&#x%s;" % [ch.unpack('H*').first] end end
ruby
{ "resource": "" }
q7859
Oembedr.Providers.service_endpoint
train
def service_endpoint url endpoint = LIST.find do |(pattern, endpoint)| url =~ pattern end endpoint ? endpoint.last : false end
ruby
{ "resource": "" }
q7860
Desi.IndexManager.delete!
train
def delete!(pattern) warn "You must provide a pattern" and exit if pattern.nil? @outputter.puts "The following indices from host #{@host} are now deleted" if @verbose indices(Regexp.new(pattern)).each do |index| @client.delete("/#{index}") @outputter.puts " * #{index.inspect}" if @verbose end end
ruby
{ "resource": "" }
q7861
Desi.IndexManager.close!
train
def close!(pattern) warn "You must provide a pattern" and exit if pattern.nil? @outputter.puts "The following indices from host #{@host} are now closed" if @verbose indices(Regexp.new(pattern)).each do |index| @client.post("/#{index}/_close") @outputter.puts " * #{index.inspect}" if @verbose end end
ruby
{ "resource": "" }
q7862
Toccatore.UsageUpdate.push_data
train
def push_data(items, options={}) if items.empty? puts "No works found in the Queue." 0 elsif options[:access_token].blank? puts "An error occured: Access token missing." options[:total] else error_total = 0 Array(items).each do |item| puts item puts "*************" error_total += push_item(item, options) end error_total end end
ruby
{ "resource": "" }
q7863
Hatt.Configuration.init_config
train
def init_config unless instance_variable_defined? :@hatt_configuration @hatt_configuration = TCFG::Base.new # build up some default configuration @hatt_configuration.tcfg_set 'hatt_services', {} @hatt_configuration.tcfg_set 'hatt_globs', DEFAULT_HATT_GLOBS @hatt_configuration.tcfg_set_env_var_prefix 'HATT_' end if hatt_config_file_path # if a config file was specified, we assume it exists @hatt_configuration.tcfg_config_file hatt_config_file_path else Log.warn 'No configuration file specified or found. Make a hatt.yml file and point hatt at it.' end @hatt_configuration.tcfg_set 'hatt_config_file', hatt_config_file_path normalize_services_config @hatt_configuration nil end
ruby
{ "resource": "" }
q7864
Logan.Client.auth=
train
def auth=(auth_hash) # symbolize the keys new_auth_hash = {} auth_hash.each {|k, v| new_auth_hash[k.to_sym] = v} auth_hash = new_auth_hash if auth_hash.has_key? :access_token # clear the basic_auth, if it's set self.class.default_options.reject!{ |k| k == :basic_auth } # set the Authorization headers self.class.headers.merge!("Authorization" => "Bearer #{auth_hash[:access_token]}") elsif auth_hash.has_key?(:username) && auth_hash.has_key?(:password) self.class.basic_auth auth_hash[:username], auth_hash[:password] # remove the access_token from the headers, if it exists self.class.headers.reject!{ |k, v| k == "Authorization" } else raise """ Incomplete authorization information passed in authorization hash. You must have either an :access_token or a username password combination (:username, :password). """ end end
ruby
{ "resource": "" }
q7865
Logan.Client.project_templates
train
def project_templates response = self.class.get '/project_templates.json' handle_response(response, Proc.new {|h| Logan::ProjectTemplate.new(h) }) end
ruby
{ "resource": "" }
q7866
Logan.Client.todolists
train
def todolists response = self.class.get '/todolists.json' handle_response(response, Proc.new { |h| list = Logan::TodoList.new(h) # grab the project ID for this list from the url list.project_id = list.url.scan( /projects\/(\d+)/).last.first # return the list so this method returns an array of lists list } ) end
ruby
{ "resource": "" }
q7867
NetfilterWriter.Rules.chain
train
def chain(cmd, chain, p = {}) cmds = { new: '-N', rename: '-E', delete: '-X', flush: '-F', list_rules: '-S', list: '-L', zero: '-Z', policy: '-P' } @buffer << [ 'iptables', option('-t', @table), cmds[cmd], option('-n', p[:numeric]), chain, option(false, p[:rulenum]), option(false, p[:to]) ].compact.join(' ') << "\n" self end
ruby
{ "resource": "" }
q7868
Akasha.Changeset.append
train
def append(event_name, **data) id = SecureRandom.uuid event = Akasha::Event.new(event_name, id, { aggregate_id: aggregate_id }, **data) @aggregate.apply_events([event]) @events << event end
ruby
{ "resource": "" }
q7869
Bixby.Client.exec_api
train
def exec_api(json_req) begin req = sign_request(json_req) return HttpChannel.new(api_uri).execute(req) rescue Curl::Err::CurlError => ex return JsonResponse.new("fail", ex.message) end end
ruby
{ "resource": "" }
q7870
Sjekksum.Luhn.of
train
def of number raise_on_type_mismatch number digits = convert_number_to_digits(number) sum = digits.reverse.map.with_index do |digit, idx| idx.even? ? (digit * 2).divmod(10).reduce(&:+) : digit end.reduce(&:+) (10 - sum % 10) % 10 end
ruby
{ "resource": "" }
q7871
Taxonomite.Taxonomy.valid_parent_types
train
def valid_parent_types(child) # could be a node object, or maybe a string str = child.respond_to?(:entity_type) ? child.entity_type : child self.up_taxonomy[str] end
ruby
{ "resource": "" }
q7872
Taxonomite.Taxonomy.valid_child_types
train
def valid_child_types(parent) # could be a node object, or maybe a string str = parent.respond_to?(:entity_type) ? parent.entity_type : child self.down_taxonomy[str] end
ruby
{ "resource": "" }
q7873
RiotRails.ActionControllerMiddleware.nested_handle?
train
def nested_handle?(context) (handle?(context.description) || nested_handle?(context.parent)) if context.respond_to?(:description) end
ruby
{ "resource": "" }
q7874
Gxapi.Base.get_variant
train
def get_variant(identifier, override = nil) # identifier object to handle finding and caching the # experiment identifier = GxApi::ExperimentIdentifier.new(identifier) Celluloid::Future.new do # allows us to override and get back a variant # easily that conforms to the api if override.nil? self.get_variant_value(identifier) else Ostruct.new(self.default_values.merge(name: override)) end end end
ruby
{ "resource": "" }
q7875
Gxapi.Base.get_variant_value
train
def get_variant_value(identifier) data = Gxapi.with_error_handling do Timeout::timeout(2.0) do Gxapi.cache.fetch(self.cache_key(identifier)) do @interface.get_variant(identifier).to_hash end end end Ostruct.new( data.is_a?(Hash) ? data : self.default_values ) end
ruby
{ "resource": "" }
q7876
RiotRails.TransactionalMiddleware.hijack_local_run
train
def hijack_local_run(context) (class << context; self; end).class_eval do alias_method :transactionless_local_run, :local_run def local_run(*args) ::ActiveRecord::Base.transaction do transactionless_local_run(*args) raise ::ActiveRecord::Rollback end end # local_run end # metaclass end
ruby
{ "resource": "" }
q7877
PackedStruct.Directive.[]
train
def [](new_size) if new_size.is_a? Directive tags.merge! new_size.tags_for_sized_directive else tags[:size] = new_size end self end
ruby
{ "resource": "" }
q7878
PackedStruct.Directive.finalize!
train
def finalize! return if finalized? modifiers.each do |modifier| modifier.type.each_with_index do |type, i| case type when :endian, :signedness, :precision, :type, :string_type tags[type] = modifier.value[i] when :size tags[:size] = modifier.value[i] unless tags[:size] else raise UnknownModifierError, "Unknown modifier: #{type}" end end end @finalized = true cache_string end
ruby
{ "resource": "" }
q7879
PackedStruct.Directive.bytesize
train
def bytesize(data = {}) case tags[:type] when nil (size(data) || 8) / 8 when :short, :int, :long BYTES_IN_STRING.fetch tags[:type] when :float if tags[:precision] == :double BYTES_IN_STRING[:float_double] else BYTES_IN_STRING[:float_single] end when :null size(data) || 1 when :string size(data) else 0 end end
ruby
{ "resource": "" }
q7880
PackedStruct.Directive.modify_if_needed
train
def modify_if_needed(str, include_endian = true) base = if @tags[:signedness] == :signed str.swapcase else str end if include_endian modify_for_endianness(base) else base end end
ruby
{ "resource": "" }
q7881
PackedStruct.Directive.modify_for_endianness
train
def modify_for_endianness(str, use_case = false) case [tags[:endian], use_case] when [:little, true] str.swapcase when [:little, false] str + "<" when [:big, true] str when [:big, false] str + ">" else str end end
ruby
{ "resource": "" }
q7882
ActsAsTrashable.TrashRecord.restore
train
def restore restore_class = self.trashable_type.constantize sti_type = self.trashable_attributes[restore_class.inheritance_column] if sti_type begin if !restore_class.store_full_sti_class && !sti_type.start_with?("::") sti_type = "#{restore_class.parent.name}::#{sti_type}" end restore_class = sti_type.constantize rescue NameError => e raise e # Seems our assumption was wrong and we have no STI end end attrs, association_attrs = attributes_and_associations(restore_class, self.trashable_attributes) record = restore_class.new attrs.each_pair do |key, value| record.send("#{key}=", value) end association_attrs.each_pair do |association, attribute_values| restore_association(record, association, attribute_values) end return record end
ruby
{ "resource": "" }
q7883
ActsAsTrashable.TrashRecord.trashable_attributes
train
def trashable_attributes return nil unless self.data uncompressed = Zlib::Inflate.inflate(self.data) rescue uncompressed = self.data # backward compatibility with uncompressed data Marshal.load(uncompressed) end
ruby
{ "resource": "" }
q7884
Ork.Document.save
train
def save __robject.content_type = model.content_type __robject.data = __persist_attributes __check_unique_indices __update_indices __robject.store @id = __robject.key self end
ruby
{ "resource": "" }
q7885
Ork.Document.load!
train
def load!(id) self.__robject.key = id __load_robject! id, @__robject.reload(force: true) end
ruby
{ "resource": "" }
q7886
Ork.Document.__update_indices
train
def __update_indices model.indices.values.each do |index| __robject.indexes[index.riak_name] = index.value_from(attributes) end end
ruby
{ "resource": "" }
q7887
Ork.Document.__check_unique_indices
train
def __check_unique_indices model.uniques.each do |uniq| if value = attributes[uniq] index = model.indices[uniq] records = model.bucket.get_index(index.riak_name, value) unless records.empty? || records == [self.id] raise Ork::UniqueIndexViolation, "#{uniq} is not unique" end end end end
ruby
{ "resource": "" }
q7888
Words.TokyoWordnetConnection.open!
train
def open! unless connected? if @data_path.exist? @connection = Rufus::Tokyo::Table.new(@data_path.to_s, :mode => 'r') @connected = true else @connected = false raise BadWordnetDataset, "Failed to locate the tokyo words dataset at #{@data_path}. Please insure you have created it using the words gems provided 'build_wordnet' command." end end return nil end
ruby
{ "resource": "" }
q7889
Halibut::Core.Resource.set_property
train
def set_property(property, value) if property == '_links' || property == '_embedded' raise ArgumentError, "Argument #{property} is a reserved property" end tap { @properties[property] = value } end
ruby
{ "resource": "" }
q7890
Halibut::Core.Resource.add_link
train
def add_link(relation, href, opts={}) @links.add relation, Link.new(href, opts) end
ruby
{ "resource": "" }
q7891
Halibut::Core.Resource.to_hash
train
def to_hash {}.merge(@properties).tap do |h| h['_links'] = {}.merge @links unless @links.empty? combined_embedded = {} combined_embedded.merge! @embedded unless @embedded.empty? combined_embedded.merge! @embedded_arrays unless @embedded_arrays.empty? h['_embedded'] = combined_embedded unless combined_embedded.empty? end end
ruby
{ "resource": "" }
q7892
Bitpagos.Client.get_transaction_type_from_symbol
train
def get_transaction_type_from_symbol(transaction_type) begin target_type = transaction_type.to_s.upcase return if target_type.empty? self.class.const_get(target_type) rescue NameError => error raise Bitpagos::Errors::InvalidTransactionType.new(error.message) end end
ruby
{ "resource": "" }
q7893
Bitpagos.Client.retrieve_transactions
train
def retrieve_transactions(query = nil, transaction_id = nil) headers.merge!(params: query) if query url = "#{API_BASE}/transaction/#{transaction_id}" begin response = RestClient.get(url, headers) JSON.parse(response) rescue RestClient::Unauthorized => error raise Bitpagos::Errors::Unauthorized.new(error.message) end end
ruby
{ "resource": "" }
q7894
Retrospec.Plugins.discover_plugin
train
def discover_plugin(module_path) plugin = plugin_classes.find {|c| c.send(:valid_module_dir?, module_path) } raise NoSuitablePluginFoundException unless plugin plugin end
ruby
{ "resource": "" }
q7895
Revenant.Task.run
train
def run(&block) unless @work = block raise ArgumentError, "Usage: run { while_we_have_the_lock }" end @shutdown = false @restart = false install_plugins startup # typically daemonizes the process, can have various implementations on_load.call(self) if on_load run_loop(&@work) on_exit.call(self) if on_exit shutdown end
ruby
{ "resource": "" }
q7896
Fleet.Cluster.build_from
train
def build_from(*ip_addrs) ip_addrs = [*ip_addrs].flatten.compact begin Fleetctl.logger.info 'building from hosts: ' + ip_addrs.inspect built_from = ip_addrs.detect { |ip_addr| fetch_machines(ip_addr) } Fleetctl.logger.info 'built successfully from host: ' + built_from.inspect if built_from built_from rescue => e Fleetctl.logger.error 'ERROR building from hosts: ' + ip_addrs.inspect Fleetctl.logger.error e.message Fleetctl.logger.error e.backtrace.join("\n") nil end end
ruby
{ "resource": "" }
q7897
Fleet.Cluster.fetch_machines
train
def fetch_machines(host) Fleetctl.logger.info 'Fetching machines from host: '+host.inspect clear Fleetctl::Command.new('list-machines', '-l') do |runner| runner.run(host: host) new_machines = parse_machines(runner.output) if runner.exit_code == 0 return true else return false end end end
ruby
{ "resource": "" }
q7898
Fleet.Cluster.discover!
train
def discover! known_hosts = [Fleetctl.options.fleet_host] | fleet_hosts.to_a clear success_host = build_from(known_hosts) || build_from(Fleet::Discovery.hosts) if success_host Fleetctl.logger.info 'Successfully recovered from host: ' + success_host.inspect else Fleetctl.logger.info 'Unable to recover!' end end
ruby
{ "resource": "" }
q7899
Rattler::Parsers.Token.parse
train
def parse(scanner, rules, scope = ParserScope.empty) p = scanner.pos child.parse(scanner, rules, scope) && scanner.string[p...(scanner.pos)] end
ruby
{ "resource": "" }