_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q20900
ArcFurnace.CSVSource.preprocess
train
def preprocess if group_by? parse_file { |row| @preprocessed_csv << csv_to_hash_with_duplicates(row) } @preprocessed_csv = @preprocessed_csv.group_by { |row| row[key_column] } end end
ruby
{ "resource": "" }
q20901
Workbook.Table.contains_row?
train
def contains_row? row raise ArgumentError, "table should be a Workbook::Row (you passed a #{t.class})" unless row.is_a?(Workbook::Row) self.collect{|r| r.object_id}.include? row.object_id end
ruby
{ "resource": "" }
q20902
Workbook.Table.dimensions
train
def dimensions height = self.count width = self.collect{|a| a.length}.max [width,height] end
ruby
{ "resource": "" }
q20903
Workbook.Template.create_or_find_format_by
train
def create_or_find_format_by name, variant=:default fs = @formats[name] fs = @formats[name] = {} if fs.nil? f = fs[variant] if f.nil? f = Workbook::Format.new if variant != :default and fs[:default] f = fs[:default].clone end @formats[name][variant] = f end return @formats[name][variant] end
ruby
{ "resource": "" }
q20904
Workbook.Book.import
train
def import filename, extension=nil, options={} extension = file_extension(filename) unless extension if ['txt','csv','xml'].include?(extension) open_text filename, extension, options else open_binary filename, extension, options end end
ruby
{ "resource": "" }
q20905
Workbook.Book.open_binary
train
def open_binary filename, extension=nil, options={} extension = file_extension(filename) unless extension f = open(filename) send("load_#{extension}".to_sym, f, options) end
ruby
{ "resource": "" }
q20906
Workbook.Book.open_text
train
def open_text filename, extension=nil, options={} extension = file_extension(filename) unless extension t = text_to_utf8(open(filename).read) send("load_#{extension}".to_sym, t, options) end
ruby
{ "resource": "" }
q20907
Workbook.Book.write
train
def write filename, options={} extension = file_extension(filename) send("write_to_#{extension}".to_sym, filename, options) end
ruby
{ "resource": "" }
q20908
Workbook.Book.text_to_utf8
train
def text_to_utf8 text unless text.valid_encoding? and text.encoding == "UTF-8" # TODO: had some ruby 1.9 problems with rchardet ... but ideally it or a similar functionality will be reintroduced source_encoding = text.valid_encoding? ? text.encoding : "US-ASCII" text = text.encode('UTF-8', source_encoding, {:invalid=>:replace, :undef=>:replace, :replace=>""}) text = text.gsub("\u0000","") # TODO: this cleanup of nil values isn't supposed to be needed... end text end
ruby
{ "resource": "" }
q20909
Workbook.Book.create_or_open_sheet_at
train
def create_or_open_sheet_at index s = self[index] s = self[index] = Workbook::Sheet.new if s == nil s.book = self s end
ruby
{ "resource": "" }
q20910
RangeOperators.ArrayOperatorDefinitions.missing
train
def missing missing, array = [], self.rangify i, length = 0, array.size - 1 while i < length current = comparison_value(array[i], :last) nextt = comparison_value(array[i+1], :first) missing << (current + 2 == nextt ? current + 1 : (current + 1)..(nextt - 1)) i += 1 end missing end
ruby
{ "resource": "" }
q20911
RangeOperators.ArrayOperatorDefinitions.comparison_value
train
def comparison_value(value, position) return value if value.class != Range position == :first ? value.first : value.last end
ruby
{ "resource": "" }
q20912
Workbook.Column.table=
train
def table= table raise(ArgumentError, "value should be nil or Workbook::Table") unless [NilClass,Workbook::Table].include? table.class @table = table end
ruby
{ "resource": "" }
q20913
RJR.Arguments.validate!
train
def validate!(*acceptable) i = 0 if acceptable.first.is_a?(Hash) # clone acceptable hash, swap keys for string acceptable = Hash[acceptable.first] acceptable.keys.each { |k| acceptable[k.to_s] = acceptable[k] acceptable.delete(k) unless k.is_a?(String) } # compare acceptable against arguments, raising error if issue found while(i < length) do val = self[i] passed = acceptable.has_key?(val) raise ArgumentError, "#{val} not an acceptable arg" unless passed skip = acceptable[val] i += (skip + 1) end else # clone acceptable array, swap values for string acceptable = Array.new(acceptable).map { |a| a.to_s } # compare acceptable against arguments, raising error if issue found while(i < length) do val = self[i].to_s passed = acceptable.include?(val) raise ArgumentError, "#{val} not an acceptable arg" unless passed i += 1 end end nil end
ruby
{ "resource": "" }
q20914
RJR.Arguments.extract
train
def extract(map) # clone map hash, swap keys for string map = Hash[map] map.keys.each { |k| map[k.to_s] = map[k] map.delete(k) unless k.is_a?(String) } groups = [] i = 0 while(i < length) do val = self[i] i += 1 next unless !!map.has_key?(val) num = map[val] group = [val] 0.upto(num-1) do |j| group << self[i] i += 1 end groups << group end groups end
ruby
{ "resource": "" }
q20915
RJR.ThreadPoolJob.exec
train
def exec(lock) lock.synchronize { @thread = Thread.current @time_started = Time.now } @handler.call *@params # ensure we do not switch to another job # before atomic check expiration / terminate # expired threads happens below lock.synchronize { @time_completed = Time.now @thread = nil } end
ruby
{ "resource": "" }
q20916
RJR.ThreadPool.launch_worker
train
def launch_worker @worker_threads << Thread.new { while work = @work_queue.pop begin #RJR::Logger.debug "launch thread pool job #{work}" @running_queue << work work.exec(@thread_lock) # TODO cleaner / more immediate way to pop item off running_queue #RJR::Logger.debug "finished thread pool job #{work}" rescue Exception => e # FIXME also send to rjr logger at a critical level puts "Thread raised Fatal Exception #{e}" puts "\n#{e.backtrace.join("\n")}" end end } end
ruby
{ "resource": "" }
q20917
RJR.ThreadPool.check_workers
train
def check_workers if @terminate @worker_threads.each { |t| t.kill } @worker_threads = [] elsif @timeout readd = [] while @running_queue.size > 0 && work = @running_queue.pop # check expiration / killing expired threads must be atomic # and mutually exclusive with the process of marking a job completed above @thread_lock.synchronize{ if work.expired?(@timeout) work.thread.kill @worker_threads.delete(work.thread) launch_worker elsif !work.completed? readd << work end } end readd.each { |work| @running_queue << work } end end
ruby
{ "resource": "" }
q20918
Workbook.Row.table=
train
def table= t raise ArgumentError, "table should be a Workbook::Table (you passed a #{t.class})" unless t.is_a?(Workbook::Table) or t == nil if t @table = t table.push(self) #unless table.index(self) and self.placeholder? end end
ruby
{ "resource": "" }
q20919
Workbook.Row.find_cells_by_background_color
train
def find_cells_by_background_color color=:any, options={} options = {:hash_keys=>true}.merge(options) cells = self.collect {|c| c if c.format.has_background_color?(color) }.compact r = Row.new cells options[:hash_keys] ? r.to_symbols : r end
ruby
{ "resource": "" }
q20920
Workbook.Row.compact
train
def compact r = self.clone r = r.collect{|c| c unless c.nil?}.compact end
ruby
{ "resource": "" }
q20921
Workbook.Format.flattened
train
def flattened ff=Workbook::Format.new() formats.each{|a| ff.merge!(a) } return ff end
ruby
{ "resource": "" }
q20922
GithubChart.Chart.load_stats
train
def load_stats(data, user) return data if data raise('No data or user provided') unless user stats = GithubStats.new(user).data raise("Failed to find data for #{user} on GitHub") unless stats stats end
ruby
{ "resource": "" }
q20923
RJR.Node.connection_event
train
def connection_event(event, *args) return unless @connection_event_handlers.keys.include?(event) @connection_event_handlers[event].each { |h| h.call(self, *args) } end
ruby
{ "resource": "" }
q20924
RJR.Node.client_for
train
def client_for(connection) # skip if an indirect node type or local return nil, nil if self.indirect? || self.node_type == :local begin return Socket.unpack_sockaddr_in(connection.get_peername) rescue Exception=>e end return nil, nil end
ruby
{ "resource": "" }
q20925
RJR.Node.handle_message
train
def handle_message(msg, connection = {}) intermediate = Messages::Intermediate.parse(msg) if Messages::Request.is_request_message?(intermediate) tp << ThreadPoolJob.new(intermediate) { |i| handle_request(i, false, connection) } elsif Messages::Notification.is_notification_message?(intermediate) tp << ThreadPoolJob.new(intermediate) { |i| handle_request(i, true, connection) } elsif Messages::Response.is_response_message?(intermediate) handle_response(intermediate) end intermediate end
ruby
{ "resource": "" }
q20926
RJR.Node.handle_request
train
def handle_request(message, notification=false, connection={}) # get client for the specified connection # TODO should grap port/ip immediately on connection and use that client_port,client_ip = client_for(connection) msg = notification ? Messages::Notification.new(:message => message, :headers => @message_headers) : Messages::Request.new(:message => message, :headers => @message_headers) callback = NodeCallback.new(:node => self, :connection => connection) result = @dispatcher.dispatch(:rjr_method => msg.jr_method, :rjr_method_args => msg.jr_args, :rjr_headers => msg.headers, :rjr_client_ip => client_ip, :rjr_client_port => client_port, :rjr_node => self, :rjr_node_id => node_id, :rjr_node_type => self.node_type, :rjr_callback => callback) unless notification response = Messages::Response.new(:id => msg.msg_id, :result => result, :headers => msg.headers, :request => msg) self.send_msg(response.to_s, connection) return response end nil end
ruby
{ "resource": "" }
q20927
RJR.Node.handle_response
train
def handle_response(message) msg = Messages::Response.new(:message => message, :headers => self.message_headers) res = err = nil begin res = @dispatcher.handle_response(msg.result) rescue Exception => e err = e end @response_lock.synchronize { result = [msg.msg_id, res] result << err if !err.nil? @responses << result @response_cv.broadcast } end
ruby
{ "resource": "" }
q20928
RJR.Node.wait_for_result
train
def wait_for_result(message) res = nil message_id = message.msg_id @pending[message_id] = Time.now while res.nil? @response_lock.synchronize{ # Prune messages that timed out if @timeout now = Time.now @pending.delete_if { |_, start_time| (now - start_time) > @timeout } end pending_ids = @pending.keys fail 'Timed out' unless pending_ids.include? message_id # Prune invalid responses @responses.keep_if { |response| @pending.has_key? response.first } res = @responses.find { |response| message.msg_id == response.first } if !res.nil? @responses.delete(res) else @response_cv.wait @response_lock, @wait_interval end } end return res end
ruby
{ "resource": "" }
q20929
RJR.Dispatcher.add_module
train
def add_module(name) require name m = name.downcase.gsub(File::SEPARATOR, '_') method("dispatch_#{m}".intern).call(self) self end
ruby
{ "resource": "" }
q20930
RJR.Dispatcher.handle
train
def handle(signature, callback = nil, &bl) if signature.is_a?(Array) signature.each { |s| handle(s, callback, &bl) } return self end @handlers[signature] = callback unless callback.nil? @handlers[signature] = bl unless bl.nil? self end
ruby
{ "resource": "" }
q20931
RJR.Dispatcher.handler_for
train
def handler_for(rjr_method) # look for exact match first handler = @handlers.find { |k,v| k == rjr_method } # if not found try to match regex's handler ||= @handlers.find { |k,v| k.is_a?(Regexp) && (k =~ rjr_method) } handler.nil? ? nil : handler.last end
ruby
{ "resource": "" }
q20932
RJR.Dispatcher.env_for
train
def env_for(rjr_method) # look for exact match first env = @environments.find { |k,v| k == rjr_method } # if not found try to match regex's env ||= @environments.find { |k,v| k.is_a?(Regexp) && (k =~ rjr_method) } env.nil? ? nil : env.last end
ruby
{ "resource": "" }
q20933
RJR.EMAdapter.start
train
def start @em_lock.synchronize{ # TODO on event of the process ending this thread will be # shutdown before a local finalizer can be run, # would be good to gracefully shut this down / wait for completion @reactor_thread = Thread.new { begin EventMachine.run rescue Exception => e # TODO option to autorestart the reactor on errors ? puts "Critical exception #{e}\n#{e.backtrace.join("\n")}" ensure @em_lock.synchronize { @reactor_thread = nil } end } unless @reactor_thread } sleep 0.01 until EventMachine.reactor_running? # XXX hack but needed self end
ruby
{ "resource": "" }
q20934
RJR.Request.handle
train
def handle node_sig = "#{@rjr_node_id}(#{@rjr_node_type})" method_sig = "#{@rjr_method}(#{@rjr_method_args.join(',')})" RJR::Logger.info "#{node_sig}->#{method_sig}" # TODO option to compare arity of handler to number # of method_args passed in ? retval = instance_exec(*@rjr_method_args, &@rjr_handler) RJR::Logger.info \ "#{node_sig}<-#{method_sig}<-#{retval.nil? ? "nil" : retval}" return retval end
ruby
{ "resource": "" }
q20935
TelephoneNumber.Parser.validate
train
def validate return [] unless country country.validations.select do |validation| normalized_number.match?(Regexp.new("^(#{validation.pattern})$")) end.map(&:name) end
ruby
{ "resource": "" }
q20936
Danger.DangerPep8.lint
train
def lint(use_inline_comments=false) ensure_flake8_is_installed errors = run_flake return if errors.empty? || errors.count <= threshold if use_inline_comments comment_inline(errors) else print_markdown_table(errors) end end
ruby
{ "resource": "" }
q20937
SalesforceOrm.Base.create!
train
def create!(attributes) new_attributes = map_to_keys(attributes) new_attributes = new_attributes.merge( RecordTypeManager::FIELD_NAME => klass.record_type_id ) if klass.record_type_id client.create!(klass.object_name, new_attributes) end
ruby
{ "resource": "" }
q20938
Rafka.Producer.produce
train
def produce(topic, msg, key: nil) Rafka.wrap_errors do redis_key = "topics:#{topic}" redis_key << ":#{key}" if key @redis.rpushx(redis_key, msg.to_s) end end
ruby
{ "resource": "" }
q20939
Maitredee.Publisher.publish
train
def publish(topic_name: nil, event_name: nil, schema_name: nil, primary_key: nil, body:) defaults = self.class.get_publish_defaults published_messages << Maitredee.publish( topic_name: topic_name || defaults[:topic_name], event_name: event_name || defaults[:event_name], schema_name: schema_name || defaults[:schema_name], primary_key: primary_key, body: body ) end
ruby
{ "resource": "" }
q20940
Rafka.Consumer.consume
train
def consume(timeout=5) raised = false msg = consume_one(timeout) return nil if !msg begin yield(msg) if block_given? rescue => e raised = true raise e end msg ensure commit(msg) if @rafka_opts[:auto_commit] && msg && !raised end
ruby
{ "resource": "" }
q20941
Rafka.Consumer.consume_batch
train
def consume_batch(timeout: 1.0, batch_size: 0, batching_max_sec: 0) if batch_size == 0 && batching_max_sec == 0 raise ArgumentError, "one of batch_size or batching_max_sec must be greater than 0" end raised = false start_time = Time.now msgs = [] loop do break if batch_size > 0 && msgs.size >= batch_size break if batching_max_sec > 0 && (Time.now - start_time >= batching_max_sec) msg = consume_one(timeout) msgs << msg if msg end begin yield(msgs) if block_given? rescue => e raised = true raise e end msgs ensure commit(*msgs) if @rafka_opts[:auto_commit] && !raised end
ruby
{ "resource": "" }
q20942
Rafka.Consumer.commit
train
def commit(*msgs) tp = prepare_for_commit(*msgs) tp.each do |topic, po| po.each do |partition, offset| Rafka.wrap_errors do @redis.rpush("acks", "#{topic}:#{partition}:#{offset}") end end end tp end
ruby
{ "resource": "" }
q20943
Rafka.Consumer.prepare_for_commit
train
def prepare_for_commit(*msgs) tp = Hash.new { |h, k| h[k] = Hash.new(0) } msgs.each do |msg| if msg.offset >= tp[msg.topic][msg.partition] tp[msg.topic][msg.partition] = msg.offset end end tp end
ruby
{ "resource": "" }
q20944
Parfait.Space.add_type
train
def add_type( type ) hash = type.hash raise "upps #{hash} #{hash.class}" unless hash.is_a?(::Integer) was = types[hash] return was if was types[hash] = type end
ruby
{ "resource": "" }
q20945
Parfait.Space.get_all_methods
train
def get_all_methods methods = [] each_type do | type | type.each_method do |meth| methods << meth end end methods end
ruby
{ "resource": "" }
q20946
OStatus2.Salmon.pack
train
def pack(body, key) signed = plaintext_signature(body, 'application/atom+xml', 'base64url', 'RSA-SHA256') signature = Base64.urlsafe_encode64(key.sign(digest, signed)) Nokogiri::XML::Builder.new do |xml| xml['me'].env({ 'xmlns:me' => XMLNS }) do xml['me'].data({ type: 'application/atom+xml' }, Base64.urlsafe_encode64(body)) xml['me'].encoding('base64url') xml['me'].alg('RSA-SHA256') xml['me'].sig({ key_id: Base64.urlsafe_encode64(key.public_key.to_s) }, signature) end end.to_xml end
ruby
{ "resource": "" }
q20947
OStatus2.Salmon.post
train
def post(salmon_url, envelope) http_client.headers(HTTP::Headers::CONTENT_TYPE => 'application/magic-envelope+xml').post(Addressable::URI.parse(salmon_url), body: envelope) end
ruby
{ "resource": "" }
q20948
OStatus2.Salmon.verify
train
def verify(raw_body, key) _, plaintext, signature = parse(raw_body) key.public_key.verify(digest, signature, plaintext) rescue OStatus2::BadSalmonError false end
ruby
{ "resource": "" }
q20949
Risc.Builder.swap_names
train
def swap_names(left , right) left , right = left.to_s , right.to_s l = @names[left] r = @names[right] raise "No such name #{left}" unless l raise "No such name #{right}" unless r @names[left] = r @names[right] = l end
ruby
{ "resource": "" }
q20950
Mom.MomCompiler.translate_method
train
def translate_method( method_compiler , translator) all = [] all << translate_cpu( method_compiler , translator ) method_compiler.block_compilers.each do |block_compiler| all << translate_cpu(block_compiler , translator) end all end
ruby
{ "resource": "" }
q20951
OStatus2.Subscription.verify
train
def verify(content, signature) hmac = OpenSSL::HMAC.hexdigest('sha1', @secret, content) signature.downcase == "sha1=#{hmac}" end
ruby
{ "resource": "" }
q20952
Dropbox.Memoization.disable_memoization
train
def disable_memoization @_memoize = false @_memo_identifiers.each { |identifier| (@_memo_cache_clear_proc || Proc.new { |ident| eval "@_memo_#{ident} = nil" }).call(identifier) } @_memo_identifiers.clear end
ruby
{ "resource": "" }
q20953
Arm.Translator.translate_Branch
train
def translate_Branch( code ) target = code.label.is_a?(Risc::Label) ? code.label.to_cpu(self) : code.label ArmMachine.b( target ) end
ruby
{ "resource": "" }
q20954
Parfait.Word.set_length
train
def set_length(len , fill_char) return if len <= 0 old = char_length return if old >= len self.char_length = len check_length fill_from_with( old + 1 , fill_char ) end
ruby
{ "resource": "" }
q20955
Parfait.Word.set_char
train
def set_char( at , char ) raise "char not fixnum #{char.class}" unless char.kind_of? ::Integer index = range_correct_index(at) set_internal_byte( index , char) end
ruby
{ "resource": "" }
q20956
Parfait.Word.range_correct_index
train
def range_correct_index( at ) index = at # index = self.length + at if at < 0 raise "index not integer #{at.class}" unless at.is_a?(::Integer) raise "index must be positive , not #{at}" if (index < 0) raise "index too large #{at} > #{self.length}" if (index >= self.length ) return index + 11 end
ruby
{ "resource": "" }
q20957
Parfait.Word.compare
train
def compare( other ) return false if other.class != self.class return false if other.length != self.length len = self.length - 1 while(len >= 0) return false if self.get_char(len) != other.get_char(len) len = len - 1 end return true end
ruby
{ "resource": "" }
q20958
Ruby.Normalizer.normalize_name
train
def normalize_name( condition ) if( condition.is_a?(ScopeStatement) and condition.single?) condition = condition.first end return [condition] if condition.is_a?(Variable) or condition.is_a?(Constant) local = "tmp_#{object_id}".to_sym assign = LocalAssignment.new( local , condition) [LocalVariable.new(local) , assign] end
ruby
{ "resource": "" }
q20959
Risc.Position.position_listener
train
def position_listener(listener) unless listener.class.name.include?("Listener") listener = PositionListener.new(listener) end register_event(:position_changed , listener) end
ruby
{ "resource": "" }
q20960
Risc.Position.get_code
train
def get_code listener = event_table.find{|one| one.class == InstructionListener} return nil unless listener listener.code end
ruby
{ "resource": "" }
q20961
Mom.NotSameCheck.to_risc
train
def to_risc(compiler) l_reg = left.to_register(compiler, self) r_reg = right.to_register(compiler, self) compiler.add_code Risc.op( self , :- , l_reg , r_reg) compiler.add_code Risc::IsZero.new( self, false_jump.risc_label(compiler)) end
ruby
{ "resource": "" }
q20962
Mom.SlotDefinition.to_register
train
def to_register(compiler, source) if known_object.respond_to?(:ct_type) type = known_object.ct_type elsif(known_object.respond_to?(:get_type)) type = known_object.get_type else type = :Object end right = compiler.use_reg( type ) case known_object when Constant parfait = known_object.to_parfait(compiler) const = Risc.load_constant(source, parfait , right) compiler.add_code const raise "Can't have slots into Constants" if slots.length > 0 when Parfait::Object , Risc::Label const = const = Risc.load_constant(source, known_object , right) compiler.add_code const if slots.length > 0 # desctructively replace the existing value to be loaded if more slots compiler.add_code Risc.slot_to_reg( source , right ,slots[0], right) end when Symbol return sym_to_risc(compiler , source) else raise "We have a #{self} #{known_object}" end if slots.length > 1 # desctructively replace the existing value to be loaded if more slots index = Risc.resolve_to_index(slots[0] , slots[1] ,compiler) compiler.add_code Risc::SlotToReg.new( source , right ,index, right) if slots.length > 2 raise "3 slots only for type #{slots}" unless slots[2] == :type compiler.add_code Risc::SlotToReg.new( source , right , Parfait::TYPE_INDEX, right) end end return const.register end
ruby
{ "resource": "" }
q20963
RubyX.RubyXCompiler.to_binary
train
def to_binary(platform) linker = to_risc(platform) linker.position_all linker.create_binary linker end
ruby
{ "resource": "" }
q20964
RubyX.RubyXCompiler.ruby_to_vool
train
def ruby_to_vool(ruby_source) ruby_tree = Ruby::RubyCompiler.compile( ruby_source ) unless(@vool) @vool = ruby_tree.to_vool return @vool end # TODO: should check if this works with reopening classes # or whether we need to unify the vool for a class unless(@vool.is_a?(Vool::ScopeStatement)) @vool = Vool::ScopeStatement.new([@vool]) end @vool << ruby_tree.to_vool end
ruby
{ "resource": "" }
q20965
PokitDok.PokitDok.request
train
def request(endpoint, method='get', file=nil, params={}) method = method.downcase if file self.send("post_file", endpoint, file) else if endpoint[0] == '/' endpoint[0] = '' end # Work around to delete the leading slash on the request endpoint # Currently the module we're using appends a slash to the base url # so an additional url will break the request. # Refer to ...faraday/connection.rb L#404 self.send("#{method}_request", endpoint, params) end end
ruby
{ "resource": "" }
q20966
PokitDok.PokitDok.pharmacy_network
train
def pharmacy_network(params = {}) npi = params.delete :npi endpoint = npi ? "pharmacy/network/#{npi}" : "pharmacy/network" get(endpoint, params) end
ruby
{ "resource": "" }
q20967
Risc.BlockCompiler.slot_type_for
train
def slot_type_for(name) if @callable.arguments_type.variable_index(name) slot_def = [:arguments] elsif @callable.frame_type.variable_index(name) slot_def = [:frame] elsif @method.arguments_type.variable_index(name) slot_def = [:caller , :caller ,:arguments ] elsif @method.frame_type.variable_index(name) slot_def = [:caller ,:caller , :frame ] elsif raise "no variable #{name} , need to resolve at runtime" end slot_def << name end
ruby
{ "resource": "" }
q20968
Mom.ArgumentTransfer.to_risc
train
def to_risc(compiler) transfer = SlotLoad.new([:message , :next_message , :receiver] , @receiver, self).to_risc(compiler) compiler.reset_regs @arguments.each do |arg| arg.to_risc(compiler) compiler.reset_regs end transfer end
ruby
{ "resource": "" }
q20969
Util.Eventable.trigger
train
def trigger(name, *args) event_table[name].each { |handler| handler.send( name.to_sym , *args) } end
ruby
{ "resource": "" }
q20970
Risc.Interpreter.execute_DynamicJump
train
def execute_DynamicJump method = get_register(@instruction.register) pos = Position.get(method.binary) log.debug "Jump to binary at: #{pos} #{method.name}:#{method.binary.class}" raise "Invalid position for #{method.name}" unless pos.valid? pos = pos + Parfait::BinaryCode.byte_offset set_pc( pos ) false end
ruby
{ "resource": "" }
q20971
Risc.Linker.position_code
train
def position_code(code_start) assemblers.each do |asm| Position.log.debug "Method start #{code_start.to_s(16)} #{asm.callable.name}" code_pos = CodeListener.init(asm.callable.binary, platform) instructions = asm.instructions InstructionListener.init( instructions, asm.callable.binary) code_pos.position_listener( LabelListener.new(instructions)) code_pos.set(code_start) code_start = Position.get(asm.callable.binary.last_code).next_slot end end
ruby
{ "resource": "" }
q20972
Risc.CodeListener.position_inserted
train
def position_inserted(position) Position.log.debug "extending one at #{position}" pos = CodeListener.init( position.object.next_code , @platform) raise "HI #{position}" unless position.valid? return unless position.valid? Position.log.debug "insert #{position.object.next_code.object_id.to_s(16)}" pos.set( position + position.object.padded_length) set_jump_for(position) end
ruby
{ "resource": "" }
q20973
Risc.CodeListener.set_jump_for
train
def set_jump_for(position) at = position.at code = position.object return unless code.next_code #dont jump beyond and jump = Branch.new("BinaryCode #{at.to_s(16)}" , code.next_code) translator = @platform.translator cpu_jump = translator.translate(jump) pos = at + code.padded_length - cpu_jump.byte_length Position.create(cpu_jump).set(pos) cpu_jump.assemble(JumpWriter.new(code)) end
ruby
{ "resource": "" }
q20974
Risc.PositionListener.position_changed
train
def position_changed(previous) add = previous.object ? previous.object.padded_length : 0 next_at = previous.at + add next_pos = Position.get(@object) next_pos.set(next_at) end
ruby
{ "resource": "" }
q20975
Risc.RegisterValue.resolve_and_add
train
def resolve_and_add(slot , compiler) index = resolve_index( slot ) new_left = get_new_left( slot , compiler ) compiler.add_code Risc::SlotToReg.new( "SlotLoad #{type}[#{slot}]" , self ,index, new_left) new_left end
ruby
{ "resource": "" }
q20976
Risc.RegisterValue.reduce_int
train
def reduce_int reduce = Risc.slot_to_reg( "int -> fix" , self , Parfait::Integer.integer_index , self) builder.add_code(reduce) if builder reduce end
ruby
{ "resource": "" }
q20977
Risc.RegisterValue.next_reg_use
train
def next_reg_use( type , extra = {} ) int = @symbol[1,3].to_i raise "No more registers #{self}" if int > 11 sym = "r#{int + 1}".to_sym RegisterValue.new( sym , type, extra) end
ruby
{ "resource": "" }
q20978
Risc.RegisterValue.op
train
def op( operator , right) ret = Risc.op( "operator #{operator}" , operator , self , right) builder.add_code(ret) if builder ret end
ruby
{ "resource": "" }
q20979
Vool.Statements.to_mom
train
def to_mom( compiler ) raise "Empty list ? #{statements.length}" if empty? stats = @statements.dup first = stats.shift.to_mom(compiler) while( nekst = stats.shift ) first.append nekst.to_mom(compiler) end first end
ruby
{ "resource": "" }
q20980
Parfait.Type.init_lists
train
def init_lists(hash) self.methods = nil self.names = List.new self.types = List.new raise "No type Type in #{hash}" unless hash[:type] private_add_instance_variable(:type , hash[:type]) #first hash.each do |name , type| private_add_instance_variable(name , type) unless name == :type end end
ruby
{ "resource": "" }
q20981
Parfait.Type.add_instance_variable
train
def add_instance_variable( name , type ) raise "No nil name" unless name raise "No nil type" unless type hash = to_hash hash[name] = type return Type.for_hash( object_class , hash) end
ruby
{ "resource": "" }
q20982
Arm.LogicInstruction.determine_operands
train
def determine_operands if( @left.is_a?(Parfait::Object) or @left.is_a?(Risc::Label) or (@left.is_a?(Symbol) and !Risc::RegisterValue.look_like_reg(@left))) left = @left left = left.address if left.is_a?(Risc::Label) # do pc relative addressing with the difference to the instuction # 8 is for the funny pipeline adjustment (ie pointing to fetch and not execute) right = Risc::Position.get(left) - 8 right -= Risc::Position.get(self).at if( (right < 0) && ((opcode == :add) || (opcode == :sub)) ) right *= -1 # this works as we never issue sub only add set_opcode :sub # so (as we can't change the sign permanently) we can change the opcode end # and the sign even for sub (beucase we created them) raise "No negatives implemented #{self} #{right} " if right < 0 return :pc , right else return @left , @right end end
ruby
{ "resource": "" }
q20983
Pluto.ManifestHelper.installed_template_manifest_patterns
train
def installed_template_manifest_patterns # 1) search . # that is, working/current dir # 2) search <config_dir> # 3) search <gem>/templates ### # Note # -- for now - no longer ship w/ builtin template packs # - download on demand if needed builtin_patterns = [ ## "#{Pluto.root}/templates/*.txt" ] config_patterns = [ ## "#{File.expand_path(opts.config_path)}/*.txt", "#{File.expand_path(opts.config_path)}/*/*.txt" ] current_patterns = [ ## "*.txt", "*/*.txt", "node_modules/*/*.txt", # note: add support for npm installs - use/make slideshow required in name? for namespace in the future??? ] patterns = [] patterns += current_patterns patterns += config_patterns patterns += builtin_patterns end
ruby
{ "resource": "" }
q20984
Risc.TextWriter.write_as_string
train
def write_as_string @stream = StringIO.new write_init(@linker.cpu_init) write_debug write_objects write_code log.debug "Assembled 0x#{stream_position.to_s(16)} bytes" return @stream.string end
ruby
{ "resource": "" }
q20985
Risc.TextWriter.write_code
train
def write_code @linker.assemblers.each do |asm| asm.callable.each_binary do |code| write_any(code) end end end
ruby
{ "resource": "" }
q20986
Risc.TextWriter.write_any
train
def write_any( obj ) write_any_log( obj , "Write") if stream_position != Position.get(obj).at raise "Write #{obj.class}:0x#{obj.object_id.to_s(16)} at 0x#{stream_position.to_s(16)} not #{Position.get(obj)}" end write_any_out(obj) write_any_log( obj , "Wrote") Position.get(obj) end
ruby
{ "resource": "" }
q20987
Risc.TextWriter.write_object
train
def write_object( object ) obj_written = write_object_variables(object) log.debug "instances=#{object.get_instance_variables.inspect} mem_len=0x#{object.padded_length.to_s(16)}" indexed_written = write_object_indexed(object) log.debug "type #{obj_written} , total #{obj_written + indexed_written} (array #{indexed_written})" log.debug "Len = 0x#{object.get_length.to_s(16)} , inst =0x#{object.get_type.instance_length.to_s(16)}" if object.is_a? Parfait::Type pad_after( obj_written + indexed_written ) Position.get(object) end
ruby
{ "resource": "" }
q20988
Risc.TextWriter.write_ref_for
train
def write_ref_for object case object when nil @stream.write_signed_int_32(0) when ::Integer @stream.write_signed_int_32(object) else @stream.write_signed_int_32(Position.get(object) + @linker.platform.loaded_at) end end
ruby
{ "resource": "" }
q20989
Parfait.List.index_of
train
def index_of( item ) max = self.get_length #puts "length #{max} #{max.class}" counter = 0 while( counter < max ) if( get(counter) == item) return counter end counter = counter + 1 end return nil end
ruby
{ "resource": "" }
q20990
Parfait.List.next_value
train
def next_value(val) index = index_of(val) return nil unless index return nil if index == (get_length - 1) return get(index + 1) end
ruby
{ "resource": "" }
q20991
Dropbox.API.download
train
def download(path, options={}) path = path.sub(/^\//, '') rest = Dropbox.check_path(path).split('/') rest << { :ssl => @ssl } api_body :get, 'files', root(options), *rest #TODO streaming, range queries end
ruby
{ "resource": "" }
q20992
Dropbox.API.delete
train
def delete(path, options={}) path = path.sub(/^\//, '') path.sub! /\/$/, '' begin api_response(:post, 'fileops', 'delete', :path => Dropbox.check_path(path), :root => root(options), :ssl => @ssl) rescue UnsuccessfulResponseError => error raise FileNotFoundError.new(path) if error.response.kind_of?(Net::HTTPNotFound) raise error end return true end
ruby
{ "resource": "" }
q20993
Dropbox.API.rename
train
def rename(path, new_name, options={}) raise ArgumentError, "Names cannot have slashes in them" if new_name.include?('/') path = path.sub(/\/$/, '') destination = path.split('/') destination[destination.size - 1] = new_name destination = destination.join('/') move path, destination, options end
ruby
{ "resource": "" }
q20994
Dropbox.API.link
train
def link(path, options={}) path = path.sub(/^\//, '') begin rest = Dropbox.check_path(path).split('/') rest << { :ssl => @ssl } api_response(:get, 'links', root(options), *rest) rescue UnsuccessfulResponseError => error return error.response['Location'] if error.response.kind_of?(Net::HTTPFound) #TODO shouldn't be using rescue blocks for normal program flow raise error end end
ruby
{ "resource": "" }
q20995
Dropbox.API.shares
train
def shares(path, options={}) path = path.sub(/^\//, '') rest = Dropbox.check_path(path).split('/') begin return JSON.parse( api_response(:post, 'shares', root(options), *rest).body ).symbolize_keys_recursively rescue UnsuccessfulResponseError => error return error.response['Location'] if error.response.kind_of?(Net::HTTPFound) #TODO shouldn't be using rescue blocks for normal program flow raise error end end
ruby
{ "resource": "" }
q20996
Dropbox.API.metadata
train
def metadata(path, options={}) path = path.sub(/^\//, '') args = [ 'metadata', root(options) ] args += Dropbox.check_path(path).split('/') args << Hash.new args.last[:file_limit] = options[:limit] if options[:limit] args.last[:hash] = options[:prior_response].hash if options[:prior_response] and options[:prior_response].hash args.last[:list] = !(options[:suppress_list].to_bool) args.last[:ssl] = @ssl begin parse_metadata(get(*args)).to_struct_recursively rescue UnsuccessfulResponseError => error raise TooManyEntriesError.new(path) if error.response.kind_of?(Net::HTTPNotAcceptable) raise FileNotFoundError.new(path) if error.response.kind_of?(Net::HTTPNotFound) return options[:prior_response] if error.response.kind_of?(Net::HTTPNotModified) raise error end end
ruby
{ "resource": "" }
q20997
Risc.InstructionListener.position_changed
train
def position_changed(position) instruction = position.object return unless instruction.is_a?(Label) instruction.address.set_value(position.at) end
ruby
{ "resource": "" }
q20998
Parfait.Dictionary.set
train
def set(key , value) index = key_index(key) if( index ) i_values.set(index , value) else i_keys.push(key) i_values.push(value) end value end
ruby
{ "resource": "" }
q20999
Parfait.Dictionary.each
train
def each index = 0 while index < i_keys.get_length key = i_keys.get(index) value = i_values.get(index) yield key , value index = index + 1 end self end
ruby
{ "resource": "" }