_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
30
4.3k
language
stringclasses
1 value
meta_information
dict
q7800
Taxonomite.Tree.ancestors
train
def ancestors a = Array.new self.parent._ancestors(a)
ruby
{ "resource": "" }
q7801
Taxonomite.Tree.move_children_to_parent
train
def move_children_to_parent children.each do |c| self.parent.children << c
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)
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)
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 fou...
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?
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+)$/) ...
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)
ruby
{ "resource": "" }
q7808
Sjekksum.Damm.of
train
def of number raise_on_type_mismatch number digits = convert_number_to_digits(number)
ruby
{ "resource": "" }
q7809
YARD.SitemapGenerator.generate_sitemap
train
def generate_sitemap(basedir) sitemap_file = File.join(basedir, 'sitemap.xml')
ruby
{ "resource": "" }
q7810
SimpleActivity.ActivityProcessor.save
train
def save if validate_attrs Activity.create(activity_attrs).tap do
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] }
ruby
{ "resource": "" }
q7812
Rack.WebProfiler::Request.raw
train
def raw headers = http_headers.map { |k, v| "#{k}: #{v}\r\n" }.join format "%s %s
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
ruby
{ "resource": "" }
q7814
DuckMap.FilterStack.clear_filter
train
def clear_filter(section, key) key = key.kind_of?(Symbol) ? key : key.to_sym
ruby
{ "resource": "" }
q7815
ActiveNode.Graph.many?
train
def many? if block_given? to_a.many? { |*block_args| yield(*block_args)
ruby
{ "resource": "" }
q7816
LXC.Container.status
train
def status output = run("info") result = output.scan(/^state:\s+([\w]+)|pid:\s+(-?[\d]+)$/).flatten
ruby
{ "resource": "" }
q7817
LXC.Container.wait
train
def wait(state) if !LXC::Shell.valid_state?(status.state) raise ArgumentError, "Invalid container
ruby
{ "resource": "" }
q7818
LXC.Container.cpu_usage
train
def cpu_usage result = run("cgroup", "cpuacct.usage").to_s.strip result.empty? ? nil
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
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 ...
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."
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
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
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'
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'
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 r...
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|
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
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|
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) || {})
ruby
{ "resource": "" }
q7831
RProgram.Program.run_task
train
def run_task(task,options={}) arguments = task.arguments arguments << options
ruby
{ "resource": "" }
q7832
RProgram.Program.sudo_task
train
def sudo_task(task,options={},&block) arguments = task.arguments arguments << options
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...
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|
ruby
{ "resource": "" }
q7835
PackedStruct.Package.unpack
train
def unpack(string) total = "" parts = {} directives.each_with_index do |directive, i| total << directive.to_s(parts)
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|
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
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) #
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
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?
ruby
{ "resource": "" }
q7841
Rattler::Parsers.Sequence.parse
train
def parse(scanner, rules, scope = ParserScope.empty) backtracking(scanner) do if scope =
ruby
{ "resource": "" }
q7842
Herbalist.Token.get_tag
train
def get_tag(tag_type) matches = @tags.select { |m| m.type==tag_type }
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
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
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
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],
ruby
{ "resource": "" }
q7847
Campaigning.List.get_all_active_subscribers
train
def get_all_active_subscribers find_active
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"
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(fram...
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
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 =
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?
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
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,
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])
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
{ "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 ==
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
ruby
{ "resource": "" }
q7859
Oembedr.Providers.service_endpoint
train
def service_endpoint url endpoint = LIST.find do |(pattern, endpoint)| url =~ pattern
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|
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|
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
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_configura...
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 } ...
ruby
{ "resource": "" }
q7865
Logan.Client.project_templates
train
def project_templates response = self.class.get '/project_templates.json'
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)
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',
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)
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 =>
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
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)
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)
ruby
{ "resource": "" }
q7873
RiotRails.ActionControllerMiddleware.nested_handle?
train
def nested_handle?(context) (handle?(context.description) || nested_handle?(context.parent))
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
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
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
ruby
{ "resource": "" }
q7877
PackedStruct.Directive.[]
train
def [](new_size) if new_size.is_a? Directive tags.merge! new_size.tags_for_sized_directive
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
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
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
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]
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_...
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
ruby
{ "resource": "" }
q7884
Ork.Document.save
train
def save __robject.content_type = model.content_type __robject.data = __persist_attributes
ruby
{ "resource": "" }
q7885
Ork.Document.load!
train
def load!(id) self.__robject.key = id
ruby
{ "resource": "" }
q7886
Ork.Document.__update_indices
train
def __update_indices model.indices.values.each do |index| __robject.indexes[index.riak_name]
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 ==
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
ruby
{ "resource": "" }
q7889
Halibut::Core.Resource.set_property
train
def set_property(property, value) if property == '_links' || property == '_embedded' raise ArgumentError,
ruby
{ "resource": "" }
q7890
Halibut::Core.Resource.add_link
train
def add_link(relation, href, opts={})
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?
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
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}"
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) }
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
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 buil...
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
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
ruby
{ "resource": "" }
q7899
Rattler::Parsers.Token.parse
train
def parse(scanner, rules, scope = ParserScope.empty) p = scanner.pos
ruby
{ "resource": "" }