_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q6100
Hornetseye.Node.histogram
train
def histogram( *ret_shape ) options = ret_shape.last.is_a?( Hash ) ? ret_shape.pop : {} options = { :weight => UINT.new( 1 ), :safe => true }.merge options unless options[:weight].matched? options[:weight] = Node.match(options[:weight]).maxint.new options[:weight] end if ( shape.first != 1 or dimension == 1 ) and ret_shape.size == 1 [ self ].histogram *( ret_shape + [ options ] ) else ( 0 ... shape.first ).collect { |i| unroll[i] }. histogram *( ret_shape + [ options ] ) end end
ruby
{ "resource": "" }
q6101
Hornetseye.Node.lut
train
def lut( table, options = {} ) if ( shape.first != 1 or dimension == 1 ) and table.dimension == 1 [ self ].lut table, options else ( 0 ... shape.first ).collect { |i| unroll[i] }.lut table, options end end
ruby
{ "resource": "" }
q6102
Hornetseye.Node.warp
train
def warp( *field ) options = field.last.is_a?( Hash ) ? field.pop : {} options = { :safe => true, :default => typecode.default }.merge options if options[ :safe ] if field.size > dimension raise "Number of arrays for warp (#{field.size}) is greater than the " + "number of dimensions of source (#{dimension})" end Hornetseye::lazy do ( 0 ... field.size ). collect { |i| ( field[i] >= 0 ).and( field[i] < shape[i] ) }. inject :and end.conditional Lut.new( *( field + [ self ] ) ), options[ :default ] else field.lut self, :safe => false end end
ruby
{ "resource": "" }
q6103
Hornetseye.Node.integral
train
def integral left = allocate block = Integral.new left, self if block.compilable? GCCFunction.run block else block.demand end left end
ruby
{ "resource": "" }
q6104
Hornetseye.Node.components
train
def components( options = {} ) if shape.any? { |x| x <= 1 } raise "Every dimension must be greater than 1 (shape was #{shape})" end options = { :target => UINT, :default => typecode.default }.merge options target = options[ :target ] default = options[ :default ] default = typecode.new default unless default.matched? left = Hornetseye::MultiArray(target, dimension).new *shape labels = Sequence.new target, size; labels[0] = 0 rank = Sequence.uint size; rank[0] = 0 n = Hornetseye::Pointer( INT ).new; n.store INT.new( 0 ) block = Components.new left, self, default, target.new(0), labels, rank, n if block.compilable? Hornetseye::GCCFunction.run block else block.demand end labels = labels[0 .. n.demand.get] left.lut labels.lut(labels.histogram(labels.size, :weight => target.new(1)). minor(1).integral - 1) end
ruby
{ "resource": "" }
q6105
Hornetseye.Node.mask
train
def mask( m ) check_shape m left = MultiArray.new typecode, *( shape.first( dimension - m.dimension ) + [ m.size ] ) index = Hornetseye::Pointer( INT ).new index.store INT.new( 0 ) block = Mask.new left, self, m, index if block.compilable? GCCFunction.run block else block.demand end left[0 ... index[]].roll end
ruby
{ "resource": "" }
q6106
Hornetseye.Node.unmask
train
def unmask( m, options = {} ) options = { :safe => true, :default => typecode.default }.merge options default = options[:default] default = typecode.new default unless default.matched? m.check_shape default if options[ :safe ] if m.to_ubyte.sum > shape.last raise "#{m.to_ubyte.sum} value(s) of the mask are true but the last " + "dimension of the array for unmasking only has #{shape.last} value(s)" end end left = Hornetseye::MultiArray(typecode, dimension - 1 + m.dimension). coercion(default.typecode).new *(shape[1 .. -1] + m.shape) index = Hornetseye::Pointer(INT).new index.store INT.new(0) block = Unmask.new left, self, m, index, default if block.compilable? GCCFunction.run block else block.demand end left end
ruby
{ "resource": "" }
q6107
Hornetseye.Node.flip
train
def flip( *dimensions ) field = ( 0 ... dimension ).collect do |i| if dimensions.member? i Hornetseye::lazy( *shape ) { |*args| shape[i] - 1 - args[i] } else Hornetseye::lazy( *shape ) { |*args| args[i] } end end warp *( field + [ :safe => false ] ) end
ruby
{ "resource": "" }
q6108
Hornetseye.Node.shift
train
def shift( *offset ) if offset.size != dimension raise "#{offset.size} offset(s) were given but array has " + "#{dimension} dimension(s)" end retval = Hornetseye::MultiArray(typecode, dimension).new *shape target, source, open, close = [], [], [], [] ( shape.size - 1 ).step( 0, -1 ) do |i| callcc do |pass| delta = offset[i] % shape[i] source[i] = 0 ... shape[i] - delta target[i] = delta ... shape[i] callcc do |c| open[i] = c pass.call end source[i] = shape[i] - delta ... shape[i] target[i] = 0 ... delta callcc do |c| open[i] = c pass.call end close[i].call end end retval[ *target ] = self[ *source ] unless target.any? { |t| t.size == 0 } for i in 0 ... shape.size callcc do |c| close[i] = c open[i].call end end retval end
ruby
{ "resource": "" }
q6109
Hornetseye.Node.downsample
train
def downsample( *rate ) options = rate.last.is_a?( Hash ) ? rate.pop : {} options = { :offset => rate.collect { |r| r - 1 } }.merge options offset = options[ :offset ] if rate.size != dimension raise "#{rate.size} sampling rate(s) given but array has " + "#{dimension} dimension(s)" end if offset.size != dimension raise "#{offset.size} sampling offset(s) given but array has " + "#{dimension} dimension(s)" end ret_shape = ( 0 ... dimension ).collect do |i| ( shape[i] + rate[i] - 1 - offset[i] ).div rate[i] end field = ( 0 ... dimension ).collect do |i| Hornetseye::lazy( *ret_shape ) { |*args| args[i] * rate[i] + offset[i] } end warp *( field + [ :safe => false ] ) end
ruby
{ "resource": "" }
q6110
CoinOp::Bit.MultiWallet.signatures
train
def signatures(transaction, names: [:primary]) transaction.inputs.map do |input| path = input.output.metadata[:wallet_path] node = self.path(path) sig_hash = transaction.sig_hash(input, node.script) node.signatures(sig_hash, names: names) end end
ruby
{ "resource": "" }
q6111
CoinOp::Bit.MultiWallet.authorize
train
def authorize(transaction, *signers) transaction.set_script_sigs *signers do |input, *sig_dicts| node = self.path(input.output.metadata[:wallet_path]) signatures = combine_signatures(*sig_dicts) node.script_sig(signatures) end transaction end
ruby
{ "resource": "" }
q6112
CoinOp::Bit.MultiWallet.combine_signatures
train
def combine_signatures(*sig_dicts) combined = {} sig_dicts.each do |sig_dict| sig_dict.each do |tree, signature| decoded_sig = decode_base58(signature) low_s_der_sig = Bitcoin::Script.is_low_der_signature?(decoded_sig) ? decoded_sig : Bitcoin::OpenSSL_EC.signature_to_low_s(decoded_sig) combined[tree] = Bitcoin::OpenSSL_EC.repack_der_signature(low_s_der_sig) end end # Order of signatures is important for validation, so we always # sort public keys and signatures by the name of the tree # they belong to. combined.sort_by { |tree, value| tree }.map { |tree, sig| sig } end
ruby
{ "resource": "" }
q6113
Forwarder.Arguments.evaluable?
train
def evaluable? !lambda? && !aop? && ( !args || args.all?{|a| Evaller.evaluable? a } ) && ( !custom_target? || Evaller.evaluable?( custom_target? ) ) end
ruby
{ "resource": "" }
q6114
Gogcom.Sale.fetch
train
def fetch() url = "http://www.gog.com/" page = Net::HTTP.get(URI(url)) @data = JSON.parse(page[/(?<=var gogData = )(.*)(?=;)/,1]) end
ruby
{ "resource": "" }
q6115
Gogcom.Sale.parse
train
def parse(data) items = [] data["on_sale"].each do |item| sale_item = SaleItem.new(get_title(item), get_current_price(item), get_original_price(item), get_discount_percentage(item), get_discount_amount(item)) if @type.nil? items.push(sale_item) else if (@type == "games" && is_game?(item)) items.push(sale_item) end if (@type == "movies" && is_movie?(item)) items.push(sale_item) end end end unless @limit.nil? items.take(@limit) else items end end
ruby
{ "resource": "" }
q6116
SplitCat.Experiment.choose_hypothesis
train
def choose_hypothesis total = 0 roll = Kernel.rand( total_weight ) + 1 hypothesis = nil hypotheses.each do |h| if roll <= ( total += h.weight ) hypothesis ||= h end end hypothesis ||= hypotheses.first return hypothesis end
ruby
{ "resource": "" }
q6117
SplitCat.Experiment.same_structure?
train
def same_structure?( experiment ) return nil if name.to_sym != experiment.name.to_sym return nil if goal_hash.keys != experiment.goal_hash.keys return nil if hypothesis_hash.keys != experiment.hypothesis_hash.keys return experiment end
ruby
{ "resource": "" }
q6118
Detroit.DNote.current?
train
def current? output_mapping.each do |file, format| return false if outofdate?(file, *dnote_session.files) end "DNotes are current (#{output})" end
ruby
{ "resource": "" }
q6119
Detroit.DNote.document
train
def document session = dnote_session output_mapping.each do |file, format| #next unless verify_format(format) dir = File.dirname(file) mkdir_p(dir) unless File.directory?(dir) session.output = file session.format = format session.run report "Updated #{file.sub(Dir.pwd+'/','')}" end end
ruby
{ "resource": "" }
q6120
Detroit.DNote.reset
train
def reset output.each do |file, format| if File.exist?(file) utime(0,0,file) report "Marked #{file} as out-of-date." end end end
ruby
{ "resource": "" }
q6121
Detroit.DNote.purge
train
def purge output.each do |file, format| if File.exist?(file) rm(file) report "Removed #{file}" end end end
ruby
{ "resource": "" }
q6122
Detroit.DNote.output_mapping
train
def output_mapping @output_mapping ||= ( hash = {} case output when Array output.each do |path| hash[path] = format(path) end when String hash[output] = format(output) when Hash hash = output end hash ) end
ruby
{ "resource": "" }
q6123
Detroit.DNote.format
train
def format(file) type = File.extname(file).sub('.','') type = DEFAULT_FORMAT if type.empty? type end
ruby
{ "resource": "" }
q6124
Detroit.DNote.dnote_session
train
def dnote_session ::DNote::Session.new do |s| s.paths = files s.exclude = exclude s.ignore = ignore s.labels = labels s.title = title s.context = lines s.dryrun = trial? end end
ruby
{ "resource": "" }
q6125
JawboneUP.Session.get
train
def get(path, query=nil, headers={}) response = execute :get, path, query, headers hash = JSON.parse response.body end
ruby
{ "resource": "" }
q6126
Baidumap.Request.request
train
def request http_segments = @segments.clone @params.each do |key,value| http_segments[key] = value end uri = URI::HTTP.build( :host => HOST, :path => @action_path, :query => URI.encode_www_form(http_segments) ).to_s result = JSON.parse(HTTParty.get(uri).parsed_response) Baidumap::Response.new(result,self) end
ruby
{ "resource": "" }
q6127
Vissen.Parameterized.bind
train
def bind(param, target) raise ScopeError unless scope.include? target @_params.fetch(param).bind target end
ruby
{ "resource": "" }
q6128
Vissen.Parameterized.inspect
train
def inspect format INSPECT_FORMAT, name: self.class.name, object_id: object_id, params: params_with_types, type: Value.canonicalize(@_value.class) end
ruby
{ "resource": "" }
q6129
Vissen.Parameterized.each_parameterized
train
def each_parameterized return to_enum(__callee__) unless block_given? @_params.each do |_, param| next if param.constant? target = param.target yield target if target.is_a? Parameterized end end
ruby
{ "resource": "" }
q6130
TriglavClient.AuthApi.create_token
train
def create_token(credential, opts = {}) data, _status_code, _headers = create_token_with_http_info(credential, opts) return data end
ruby
{ "resource": "" }
q6131
BarkestCore.AuthConfig.to_h
train
def to_h { enable_db_auth: enable_db_auth?, enable_ldap_auth: enable_ldap_auth?, ldap_host: ldap_host.to_s, ldap_port: ldap_port.to_s.to_i, ldap_ssl: ldap_ssl?, ldap_base_dn: ldap_base_dn.to_s, ldap_browse_user: ldap_browse_user.to_s, ldap_browse_password: ldap_browse_password.to_s, ldap_auto_activate: ldap_auto_activate?, ldap_system_admin_groups: ldap_system_admin_groups.to_s, } end
ruby
{ "resource": "" }
q6132
NRSER.Message.send_to
train
def send_to receiver, publicly: true if publicly receiver.public_send symbol, *args, &block else receiver.send symbol, *args, &block end end
ruby
{ "resource": "" }
q6133
Nucleon.Core.logger=
train
def logger=logger Util::Logger.loggers.delete(self.logger.resource) if self.logger if logger.is_a?(Util::Logger) @logger = logger else @logger = Util::Logger.new(logger) end end
ruby
{ "resource": "" }
q6134
Nucleon.Core.ui=
train
def ui=ui if ui.is_a?(Util::Console) @ui = ui else @ui = Util::Console.new(ui) end end
ruby
{ "resource": "" }
q6135
Nucleon.Core.ui_group
train
def ui_group(resource, color = :cyan) # :yields: ui ui_resource = ui.resource ui.resource = Util::Console.colorize(resource, color) yield(ui) ensure ui.resource = ui_resource end
ruby
{ "resource": "" }
q6136
HtmlMockup.Release.log
train
def log(part, msg, verbose = false, &block) if !verbose || verbose && self.project.options[:verbose] self.project.shell.say "\033[37m#{part.class.to_s}\033[0m" + " : " + msg.to_s, nil, true end if block_given? begin self.project.shell.padding = self.project.shell.padding + 1 yield ensure self.project.shell.padding = self.project.shell.padding - 1 end end end
ruby
{ "resource": "" }
q6137
HtmlMockup.Release.validate_stack!
train
def validate_stack! mockup_options = {} relativizer_options = {} run_relativizer = true if @extractor_options mockup_options = {:env => @extractor_options[:env]} relativizer_options = {:url_attributes => @extractor_options[:url_attributes]} run_relativizer = @extractor_options[:url_relativize] end unless @stack.find{|(processor, options)| processor.class == HtmlMockup::Release::Processors::Mockup } @stack.unshift([HtmlMockup::Release::Processors::UrlRelativizer.new, relativizer_options]) @stack.unshift([HtmlMockup::Release::Processors::Mockup.new, mockup_options]) end end
ruby
{ "resource": "" }
q6138
Garcon.MutexPriorityQueue.delete
train
def delete(item) original_length = @length k = 1 while k <= @length if @queue[k] == item swap(k, @length) @length -= 1 sink(k) @queue.pop else k += 1 end end @length != original_length end
ruby
{ "resource": "" }
q6139
Garcon.MutexPriorityQueue.sink
train
def sink(k) while (j = (2 * k)) <= @length do j += 1 if j < @length && ! ordered?(j, j+1) break if ordered?(k, j) swap(k, j) k = j end end
ruby
{ "resource": "" }
q6140
Garcon.MutexPriorityQueue.swim
train
def swim(k) while k > 1 && ! ordered?(k/2, k) do swap(k, k/2) k = k/2 end end
ruby
{ "resource": "" }
q6141
Yummi.TextBox.add
train
def add (obj, params = {}) text = obj.to_s params = { :width => style.width, :align => style.align }.merge! params if params[:width] width = params[:width] words = text.gsub($/, ' ').split(' ') unless params[:raw] words ||= [text] buff = '' words.each do |word| # go to next line if the current word blows up the width limit if buff.size + word.size >= width and not buff.empty? _add_ buff, params buff = '' end buff << ' ' unless buff.empty? buff << word end unless buff.empty? _add_ buff, params end else text.each_line do |line| _add_ line, params end end end
ruby
{ "resource": "" }
q6142
Yummi.TextBox.separator
train
def separator (params = {}) params = style.separator.merge params params[:width] ||= style.width raise Exception::new('Define a width for using separators') unless params[:width] line = fill(params[:pattern], params[:width]) #replace the width with the box width to align the separator params[:width] = style.width add line, params end
ruby
{ "resource": "" }
q6143
Aerogel::Render.BlockHelper.render
train
def render content = output_capture(@block) do instance_exec( *@args, &@block ) end content_wrapped = output_capture() { wrap( content ) } output_concat content_wrapped end
ruby
{ "resource": "" }
q6144
Incline::Extensions.Application.app_instance_name
train
def app_instance_name @app_instance_name ||= begin yaml = Rails.root.join('config','instance.yml') if File.exist?(yaml) yaml = (YAML.load(ERB.new(File.read(yaml)).result) || {}).symbolize_keys yaml[:name].blank? ? 'default' : yaml[:name] else 'default' end end end
ruby
{ "resource": "" }
q6145
Incline::Extensions.Application.restart_pending?
train
def restart_pending? return false unless File.exist?(restart_file) request_time = File.mtime(restart_file) request_time > Incline.start_time end
ruby
{ "resource": "" }
q6146
Incline::Extensions.Application.request_restart!
train
def request_restart! Incline::Log::info 'Requesting an application restart.' FileUtils.touch restart_file File.mtime restart_file end
ruby
{ "resource": "" }
q6147
Ducktrap.Formatter.nest
train
def nest(label, nested) indented = indent indented.puts("#{label}:") nested.pretty_dump(indented.indent) self end
ruby
{ "resource": "" }
q6148
Ducktrap.Formatter.puts
train
def puts(string) util = output util.write(prefix) util.puts(string) self end
ruby
{ "resource": "" }
q6149
BmcDaemonLib.Logger.build_context
train
def build_context context # Skip if no format defined return unless @format[:context].is_a? Hash # Call the instance's method to get hash context return unless context.is_a? Hash # Build each context part return @format[:context].collect do |key, format| sprintf(format, context[key]) end.join rescue KeyError, ArgumentError => ex return "[context: #{ex.message}]" end
ruby
{ "resource": "" }
q6150
SimpleMock.MockDelegator.expect
train
def expect name, retval, args = [] method_definition = Module.new do define_method name do |*args, &block| __tracer.assert name, args retval end end extend method_definition __tracer.register name, args self end
ruby
{ "resource": "" }
q6151
RComp.Reporter.report
train
def report(test) case test.result when :success if @type == :test print_test_success(test) else print_generate_success(test) end @success += 1 when :skipped if @type == :test print_test_skipped(test) else print_generate_skipped(test) end @skipped += 1 # Generate can't fail directly when :failed print_test_failed(test) @failed += 1 when :timedout if @type == :test print_test_timeout(test) else print_generate_timeout(test) end @failed += 1 end end
ruby
{ "resource": "" }
q6152
SermepaWebTpv.Request.url_for
train
def url_for(option) host = SermepaWebTpv.response_host path = SermepaWebTpv.send(option) return if !host.present? || !path.present? URI.join(host, path).to_s end
ruby
{ "resource": "" }
q6153
Locman.Manager.background=
train
def background=(background) if !background.is_a?(TrueClass) && !background.is_a?(FalseClass) fail(ArgumentError, "Background should be boolean") end manager.allowsBackgroundLocationUpdates = background @background = background end
ruby
{ "resource": "" }
q6154
Hornetseye.Methods.define_unary_method
train
def define_unary_method( mod, op, conversion = :identity ) mod.module_eval do define_method "#{op}_with_hornetseye" do |a| if a.matched? if a.dimension == 0 and a.variables.empty? target = a.typecode.send conversion target.new mod.send( op, a.simplify.get ) else Hornetseye::ElementWise( proc { |x| mod.send op, x }, "#{mod}.#{op}", proc { |x| x.send conversion } ). new(a).force end else send "#{op}_without_hornetseye", a end end alias_method_chain op, :hornetseye module_function "#{op}_without_hornetseye" module_function op end end
ruby
{ "resource": "" }
q6155
Hornetseye.Methods.define_binary_method
train
def define_binary_method( mod, op, coercion = :coercion ) mod.module_eval do define_method "#{op}_with_hornetseye" do |a,b| if a.matched? or b.matched? a = Node.match(a, b).new a unless a.matched? b = Node.match(b, a).new b unless b.matched? if a.dimension == 0 and a.variables.empty? and b.dimension == 0 and b.variables.empty? target = a.typecode.send coercion, b.typecode target.new mod.send(op, a.simplify.get, b.simplify.get) else Hornetseye::ElementWise( proc { |x,y| mod.send op, x, y }, "#{mod}.#{op}", proc { |t,u| t.send coercion, u } ). new(a, b).force end else send "#{op}_without_hornetseye", a, b end end alias_method_chain op, :hornetseye module_function "#{op}_without_hornetseye" module_function op end end
ruby
{ "resource": "" }
q6156
Jinx.ClassPathModifier.expand_to_class_path
train
def expand_to_class_path(path) # the path separator sep = path[WINDOWS_PATH_SEP] ? WINDOWS_PATH_SEP : UNIX_PATH_SEP # the path directories dirs = path.split(sep).map { |dir| File.expand_path(dir) } expanded = expand_jars(dirs) expanded.each { |dir| add_to_classpath(dir) } end
ruby
{ "resource": "" }
q6157
Jinx.ClassPathModifier.add_to_classpath
train
def add_to_classpath(file) unless File.exist?(file) then logger.warn("File to place on Java classpath does not exist: #{file}") return end if File.extname(file) == '.jar' then # require is preferred to classpath append for a jar file. require file else # A directory must end in a slash since JRuby uses an URLClassLoader. if File.directory?(file) then last = file[-1, 1] if last == "\\" then file = file[0...-1] + '/' elsif last != '/' then file = file + '/' end end # Append the file to the classpath. $CLASSPATH << file end end
ruby
{ "resource": "" }
q6158
Jinx.ClassPathModifier.expand_jars
train
def expand_jars(directories) # If there are jar files, then the file list is the sorted jar files. # Otherwise, the file list is a singleton directory array. expanded = directories.map do |dir| jars = Dir[File.join(dir , "**", "*.jar")].sort jars.empty? ? [dir] : jars end expanded.flatten end
ruby
{ "resource": "" }
q6159
Sumac.Messenger.validate_message_broker
train
def validate_message_broker message_broker = @connection.message_broker raise TypeError, "'message_broker' must respond to #close" unless message_broker.respond_to?(:close) raise TypeError, "'message_broker' must respond to #kill" unless message_broker.respond_to?(:kill) raise TypeError, "'message_broker' must respond to #object_request_broker=" unless message_broker.respond_to?(:object_request_broker=) raise TypeError, "'message_broker' must respond to #send" unless message_broker.respond_to?(:send) end
ruby
{ "resource": "" }
q6160
Bootstrap.TypographyHelper.list
train
def list(options = {}, &block) builder = List.new(self, options) capture(builder, &block) if block_given? builder.to_s end
ruby
{ "resource": "" }
q6161
TableMe.TableMePresenter.set_defaults_for
train
def set_defaults_for model options[:page] = 1 options[:per_page] ||= 10 options[:name] ||= model.to_s.downcase options[:order] ||= 'created_at ASC' self.name = options[:name] end
ruby
{ "resource": "" }
q6162
TableMe.TableMePresenter.get_data_for
train
def get_data_for model model = apply_search_to(model) @data = model.limit(options[:per_page]).offset(start_item).order(options[:order]) options[:total_count] = model.count options[:page_total] = (options[:total_count] / options[:per_page].to_f).ceil end
ruby
{ "resource": "" }
q6163
RForce.WSDL.retrieve
train
def retrieve(fieldList, from, ids) soap.retrieve(Retrieve.new(fieldList, from, ids)).result end
ruby
{ "resource": "" }
q6164
Familia.RedisObject.rediskey
train
def rediskey if parent? # We need to check if the parent has a specific suffix # for the case where we have specified one other than :object. suffix = parent.kind_of?(Familia) && parent.class.suffix != :object ? parent.class.suffix : name k = parent.rediskey(name, nil) else k = [name].flatten.compact.join(Familia.delim) end if @opts[:quantize] args = case @opts[:quantize] when Numeric [@opts[:quantize]] # :quantize => 1.minute when Array @opts[:quantize] # :quantize => [1.day, '%m%D'] else [] # :quantize => true end k = [k, qstamp(*args)].join(Familia.delim) end k end
ruby
{ "resource": "" }
q6165
HotTub.Pool.clean!
train
def clean! HotTub.logger.info "[HotTub] Cleaning pool #{@name}!" if HotTub.logger @mutex.synchronize do begin @_pool.each do |clnt| clean_client(clnt) end ensure @cond.signal end end nil end
ruby
{ "resource": "" }
q6166
HotTub.Pool.drain!
train
def drain! HotTub.logger.info "[HotTub] Draining pool #{@name}!" if HotTub.logger @mutex.synchronize do begin while clnt = @_pool.pop close_client(clnt) end ensure @_out.clear @_pool.clear @pid = Process.pid @cond.broadcast end end nil end
ruby
{ "resource": "" }
q6167
HotTub.Pool.shutdown!
train
def shutdown! HotTub.logger.info "[HotTub] Shutting down pool #{@name}!" if HotTub.logger @shutdown = true kill_reaper if @reaper drain! @shutdown = false nil end
ruby
{ "resource": "" }
q6168
HotTub.Pool.reap!
train
def reap! HotTub.logger.info "[HotTub] Reaping pool #{@name}!" if HotTub.log_trace? while !@shutdown reaped = nil @mutex.synchronize do begin if _reap? if _dead_clients? reaped = @_out.select { |clnt, thrd| !thrd.alive? }.keys @_out.delete_if { |k,v| reaped.include? k } else reaped = [@_pool.shift] end else reaped = nil end ensure @cond.signal end end if reaped reaped.each do |clnt| close_client(clnt) end else break end end nil end
ruby
{ "resource": "" }
q6169
HotTub.Pool.push
train
def push(clnt) if clnt orphaned = false @mutex.synchronize do begin if !@shutdown && @_out.delete(clnt) @_pool << clnt else orphaned = true end ensure @cond.signal end end close_orphan(clnt) if orphaned reap! if @blocking_reap end nil end
ruby
{ "resource": "" }
q6170
HotTub.Pool.pop
train
def pop alarm = (Time.now + @wait_timeout) clnt = nil dirty = false while !@shutdown raise_alarm if (Time.now > alarm) @mutex.synchronize do begin if clnt = @_pool.pop dirty = true else clnt = _fetch_new(&@client_block) end ensure if clnt _checkout(clnt) @cond.signal else @reaper.wakeup if @reaper && _dead_clients? @cond.wait(@mutex,@wait_timeout) end end end break if clnt end clean_client(clnt) if dirty && clnt clnt end
ruby
{ "resource": "" }
q6171
HotTub.Pool._fetch_new
train
def _fetch_new(&client_block) if (@never_block || (_total_current_size < @max_size)) if client_block.arity == 0 nc = yield else nc = yield @sessions_key end HotTub.logger.info "[HotTub] Adding client: #{nc.class.name} to #{@name}." if HotTub.log_trace? nc end end
ruby
{ "resource": "" }
q6172
CLIntegracon.Diff.each
train
def each(options = {}, &block) options = { :source => compares_files? ? 'files' : 'strings', :context => 3 }.merge options Diffy::Diff.new(preprocessed_expected.to_s, preprocessed_produced.to_s, options).each &block end
ruby
{ "resource": "" }
q6173
Immutability.ClassMethods.new
train
def new(*args, &block) instance = allocate.tap { |obj| obj.__send__(:initialize, *args, &block) } IceNine.deep_freeze(instance) end
ruby
{ "resource": "" }
q6174
HashRedactor.HashRedactor.whitelist_redact_hash
train
def whitelist_redact_hash redact_hash digest_hash = {} redact_hash.each do |key,how| if (how.to_sym == :digest) digest_hash[digest_key(key)] = :keep end end digest_hash.merge redact_hash end
ruby
{ "resource": "" }
q6175
Nameko.Mecab.parse
train
def parse(str) node = MecabNode.new mecab_sparse_tonode(@mecab, str) result = [] while !node.null? do if node.surface.empty? node = node.next next end result << node node = node.next end result end
ruby
{ "resource": "" }
q6176
Mongoid.Siblings.siblings_and_self
train
def siblings_and_self(options = {}) scopes = options[:scope] || self.default_sibling_scope scope_values = options[:scope_values] || {} scopes = Array.wrap(scopes).compact criteria = base_document_class.all detail_scopes = [] # Find out what scope determines the root criteria. This can be # [klass].all or self.[relation]. # It is assumed that for `scopes: [:rel1, :rel2]`, sibling objects always # have the same `rel1` *and* `rel2`, and that two objects with the same # `rel1` will always have the same `rel2`. scopes.reverse_each do |scope| scope_value = scope_values.fetch(scope) { self.send(scope) } relation_metadata = self.reflect_on_association(scope) if relation_metadata && scope_value proxy = self.siblings_through_relation(scope, scope_value) if proxy criteria = proxy.criteria next end end detail_scopes << scope end # Apply detail criteria, to make sure siblings share every simple # attribute or nil-relation. detail_scopes.each do |scope| scope_value = scope_values.fetch(scope) { self.send(scope) } relation_metadata = self.reflect_on_association(scope) if relation_metadata criteria = criteria.where(relation_metadata.key => scope_value) if scope_value && relation_metadata.polymorphic? type = scope_value.class.name inverse_of = send(relation_metadata.inverse_of_field) criteria = criteria.where(relation_metadata.inverse_type => type) criteria = criteria.any_in(relation_metadata.inverse_of_field => [inverse_of, nil]) end else criteria = criteria.where(scope => scope_value) end end criteria end
ruby
{ "resource": "" }
q6177
Mongoid.Siblings.sibling_of?
train
def sibling_of?(other, options = {}) scopes = options[:scope] || self.default_sibling_scope scope_values = options[:scope_values] || {} other_scope_values = options[:other_scope_values] || {} scopes = Array.wrap(scopes).compact return false if base_document_class != base_document_class(other) scopes.each do |scope| scope_value = scope_values.fetch(scope) { self.send(scope) } other_scope_value = other_scope_values.fetch(scope) { other.send(scope) } return false if scope_value != other_scope_value end true end
ruby
{ "resource": "" }
q6178
Mongoid.Siblings.become_sibling_of
train
def become_sibling_of(other, options = {}) return true if self.sibling_of?(other, options) scopes = options[:scope] || self.default_sibling_scope other_scope_values = options[:other_scope_values] || {} scopes = Array.wrap(scopes).compact return false if base_document_class != base_document_class(other) scopes.each do |scope| other_scope_value = other_scope_values.fetch(scope) { other.send(scope) } relation_metadata = self.reflect_on_association(scope) if relation_metadata && other_scope_value inverse_metadata = other.intelligent_inverse_metadata(scope, other_scope_value) if inverse_metadata inverse = inverse_metadata.name if inverse_metadata.many? other_scope_value.send(inverse) << self else other_scope_value.send("#{inverse}=", self) end next end end self.send("#{scope}=", other_scope_value) end end
ruby
{ "resource": "" }
q6179
Bundler.Finder.search
train
def search(dependency) @cache[dependency.hash] ||= begin find_by_name(dependency.name).select do |spec| dependency =~ spec end.sort_by {|s| s.version } end end
ruby
{ "resource": "" }
q6180
Jido.Conjugator.search_current_el
train
def search_current_el xpath # try to find the rule in the current verb desired_el = @current_el.at_xpath xpath return desired_el unless desired_el.nil? # check all the verb's parents, walking up the hierarchy @current_el_parents.each do |parent| desired_el = parent.at_xpath xpath return desired_el unless desired_el.nil? end nil end
ruby
{ "resource": "" }
q6181
Lightstreamer.StreamBuffer.process
train
def process(data) @buffer << data lines = @buffer.split "\n" @buffer = @buffer.end_with?("\n") ? '' : lines.pop lines.each do |line| yield line.strip end end
ruby
{ "resource": "" }
q6182
SidekiqSpread.ClassMethods.perform_spread
train
def perform_spread(*args) spread_duration = get_sidekiq_options['spread_duration'] || 1.hour spread_in = 0 spread_at = nil spread_method = get_sidekiq_options['spread_method'] || :rand spread_mod_value = nil spread_method = spread_method.to_sym if spread_method.present? # process spread_* options has_options = false opts = if !args.empty? && args.last.is_a?(::Hash) has_options = true args.pop else {} end sd = _extract_spread_opt(opts, :duration) spread_duration = sd if sd.present? si = _extract_spread_opt(opts, :in) spread_in = si if si.present? sa = _extract_spread_opt(opts, :at) spread_at = sa if sa.present? sm = _extract_spread_opt(opts, :method) spread_method = sm.to_sym if sm.present? smv = _extract_spread_opt(opts, :mod_value) spread_mod_value = smv if smv.present? # get left over options / keyword args remaining_opts = opts.reject { |o| PERFORM_SPREAD_OPTS.include?(o.to_sym) } # check args num_args = args.length # figure out the require params for #perform params = new.method(:perform).parameters num_req_args = params.select { |p| p[0] == :req }.length num_opt_args = params.select { |p| p[0] == :opt }.length num_req_key_args = params.select { |p| p[0] == :keyreq }.length num_opt_key_args = params.select { |p| p[0] == :key }.length # Sidekiq doesn't play nicely with named args raise ArgumentError, "#{name}#perform should not use keyword args" if num_req_key_args > 0 || num_opt_key_args > 0 if has_options # if we popped something off to process, push it back on # if it contains arguments we need if num_args < num_req_args args.push(remaining_opts) elsif num_args < (num_req_args + num_opt_args) && !remaining_opts.empty? args.push(remaining_opts) end end # if a spread_mod_value is not provided use the first argument, # assumes it is an Integer spread_mod_value = args.first if spread_mod_value.blank? && spread_method == :mod # validate the spread_* options _check_spread_args!(spread_duration, spread_method, spread_mod_value) # calculate the offset for this job spread = _set_spread(spread_method, spread_duration.to_i, spread_mod_value) # call the correct perform_* method if spread_at.present? t = spread_at.to_i + spread perform_at(t, *args) else t = spread_in.to_i + spread if t.zero? perform_async(*args) else perform_in(t, *args) end end end
ruby
{ "resource": "" }
q6183
Motivation.ClassMethods.translation_key
train
def translation_key key = name.gsub(/Motivation\z/, '') key.gsub!(/^.*::/, '') key.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2') key.gsub!(/([a-z\d])([A-Z])/,'\1_\2') key.tr!("-", "_") key.downcase! end
ruby
{ "resource": "" }
q6184
Motivation.ClassMethods.check
train
def check(name = @current_step_name, &block) raise "No step name" unless name @current_step_name ||= name checks << CheckBlock.new("progression_name", name, &block) define_method("#{name}?") do check = checks.find { |s| s.name == name } !! check.run(self) end end
ruby
{ "resource": "" }
q6185
Motivation.ClassMethods.complete
train
def complete(&block) name = @current_step_name or raise "No step name" completions << CompletionBlock.new("progression_name", name, &block) define_method("complete_#{name}") do completion = completions.find { |c| c.name == name } completion.run(self) end end
ruby
{ "resource": "" }
q6186
Asset.Helpers.tag
train
def tag(type, *paths, &block) paths.map do |path| # Yield the source back to the tag builder item = ::Asset.manifest.find{|i| i.path == path} # Src is same as path if item not found item ? item.sources.map{|f| yield(asset_url(f))} : yield(path) end.flatten.join("\n") end
ruby
{ "resource": "" }
q6187
Offroad.CargoStreamer.each_cargo_section
train
def each_cargo_section(name) raise CargoStreamerError.new("Mode must be 'r' to read cargo data") unless @mode == "r" locations = @cargo_locations[name] or return locations.each do |seek_location| @ioh.seek(seek_location) digest = "" encoded_data = "" @ioh.each_line do |line| line.chomp! if line == CARGO_END break elsif digest == "" digest = line else encoded_data += line end end yield verify_and_decode_cargo(digest, encoded_data) end end
ruby
{ "resource": "" }
q6188
AudioHero.Sox.extract_features
train
def extract_features(options={}) rate = options[:sample_rate] || "8000" begin parameters = [] parameters << "-r #{rate}" parameters << ":source" parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ") success = Cocaine::CommandLine.new("yaafehero", parameters).run(:source => get_path(@file)) rescue => e raise AudioHeroError, "These was an issue getting stats from #{@basename}" end garbage_collect(@file) if options[:gc] == "true" MessagePack.unpack(success) end
ruby
{ "resource": "" }
q6189
Roroacms.Admin::RevisionsController.restore
train
def restore post = Post.find(params[:id]) # do the restore restore = Post.restore(post) url = if restore.post_type == 'page' "/admin/pages/#{restore.id}/edit" elsif restore.post_type == 'post' "/admin/articles/#{restore.id}/edit" end # redirect to either the post or page area depending on what post_type the post has redirect_to URI.parse(url).path, notice: I18n.t("controllers.admin.revisions.restore.flash.notice", post_type: restore.post_type.capitalize) end
ruby
{ "resource": "" }
q6190
Fingerjam.Helpers.rewrite_asset_path
train
def rewrite_asset_path(source, path = nil) if Fingerjam::Base.enabled? && Fingerjam::Base.cached?(source) Fingerjam::Base.cached_url(source) else if path && path.respond_to?(:call) return path.call(source) elsif path && path.is_a?(String) return path % [source] end asset_id = rails_asset_id(source) if asset_id.blank? source else source + "?#{asset_id}" end end end
ruby
{ "resource": "" }
q6191
NRSER::Props::Mutable::Stash.InstanceMethods.put
train
def put key, value key = convert_key key if (prop = self.class.metadata[ key ]) prop.set self, value else # We know {#convert_value} is a no-op so can skip it _raw_put key, value end end
ruby
{ "resource": "" }
q6192
RubyDesk.Connector.sign
train
def sign(params) RubyDesk.logger.debug {"Params to sign: #{params.inspect}"} # sort parameters by its names (keys) sorted_params = params.sort { |a, b| a.to_s <=> b.to_s} RubyDesk.logger.debug {"Sorted params: #{sorted_params.inspect}"} # Unescape escaped params sorted_params.map! do |k, v| [k, URI.unescape(v)] end # concatenate secret with names, values concatenated = @api_secret + sorted_params.join RubyDesk.logger.debug {"concatenated: #{concatenated}"} # Calculate and return md5 of concatenated string md5 = Digest::MD5.hexdigest(concatenated) RubyDesk.logger.debug {"md5: #{md5}"} return md5 end
ruby
{ "resource": "" }
q6193
RubyDesk.Connector.invoke_api_call
train
def invoke_api_call(api_call) url = URI.parse(api_call[:url]) http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE # Concatenate parameters to form data data = api_call[:params].to_a.map{|pair| pair.map{|x| URI.escape(x.to_s)}.join '='}.join('&') headers = { 'Content-Type' => 'application/x-www-form-urlencoded' } RubyDesk.logger.info "URL: #{api_call[:url]}" RubyDesk.logger.info "method: #{api_call[:method]}" RubyDesk.logger.info "Params: #{data}" case api_call[:method] when :get, 'get' then resp, data = http.request(Net::HTTP::Get.new(url.path+"?"+data, headers)) when :post, 'post' then resp, data = http.request(Net::HTTP::Post.new(url.path, headers), data) when :delete, 'delete' then resp, data = http.request(Net::HTTP::Delete.new(url.path, headers), data) end RubyDesk.logger.info "Response code: #{resp.code}" RubyDesk.logger.info "Returned data: #{data}" case resp.code when "200" then return data when "400" then raise RubyDesk::BadRequest, data when "401", "403" then raise RubyDesk::UnauthorizedError, data when "404" then raise RubyDesk::PageNotFound, data when "500" then raise RubyDesk::ServerError, data else raise RubyDesk::Error, data end end
ruby
{ "resource": "" }
q6194
RubyDesk.Connector.prepare_and_invoke_api_call
train
def prepare_and_invoke_api_call(path, options = {}) api_call = prepare_api_call(path, options) data = invoke_api_call(api_call) parsed_data = case options[:format] when 'json' then JSON.parse(data) when 'xml' then REXML::Document.new(data) else JSON.parse(data) rescue REXML::Document.new(data) rescue data end RubyDesk.logger.info "Parsed data: #{parsed_data.inspect}" return parsed_data end
ruby
{ "resource": "" }
q6195
RubyDesk.Connector.auth_url
train
def auth_url auth_call = prepare_api_call("", :params=>{:api_key=>@api_key}, :base_url=>ODESK_AUTH_URL, :format=>nil, :method=>:get, :auth=>false) data = auth_call[:params].to_a.map{|pair| pair.join '='}.join('&') return auth_call[:url]+"?"+data end
ruby
{ "resource": "" }
q6196
RubyDesk.Connector.desktop_auth_url
train
def desktop_auth_url raise "Frob should be requested first. Use RubyDesk::Controller#get_frob()" unless @frob auth_call = prepare_api_call("", :params=>{:api_key=>@api_key, :frob=>@frob}, :base_url=>ODESK_AUTH_URL, :format=>nil, :method=>:get, :auth=>false) data = auth_call[:params].to_a.map{|pair| pair.join '='}.join('&') return auth_call[:url]+"?"+data end
ruby
{ "resource": "" }
q6197
Rack.SecureOnly.handle?
train
def handle?(req) if @opts.key?(:if) cond = @opts[:if] cond = cond.call(req) if cond.respond_to?(:call) return cond end true end
ruby
{ "resource": "" }
q6198
SystemMetrics.Metric.parent_of?
train
def parent_of?(metric) if new_record? start = (started_at - metric.started_at) * 1000.0 start <= 0 && (start + duration >= metric.duration) else self.id == metric.parent_id end end
ruby
{ "resource": "" }
q6199
SuperpayApi.ItemPedido.to_request
train
def to_request item_pedido = { codigo_produto: self.codigo_produto, codigo_categoria: self.codigo_categoria, nome_produto: self.nome_produto, quantidade_produto: self.quantidade_produto, valor_unitario_produto: self.valor_unitario_produto, nome_categoria: self.nome_categoria, } return item_pedido end
ruby
{ "resource": "" }