_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q19700
Instana.Trace.add_backtrace_to_span
train
def add_backtrace_to_span(bt, limit = nil, span) frame_count = 0 span[:stack] = [] bt.each do |i| # If the stack has the full instana gem version in it's path # then don't include that frame. Also don't exclude the Rack module. if !i.match(/instana\/instrumentation\/rack.rb/).nil? || (i.match(::Instana::VERSION_FULL).nil? && i.match('lib/instana/').nil?) break if limit && frame_count >= limit x = i.split(':') span[:stack] << { :f => x[0], :n => x[1], :m => x[2] } frame_count = frame_count + 1 if limit end end end
ruby
{ "resource": "" }
q19701
Origen.Parameters.param?
train
def param?(name) _param = name.to_s =~ /^params./ ? name.to_s : 'params.' + name.to_s begin val = eval("self.#{_param}") rescue nil else val end end
ruby
{ "resource": "" }
q19702
Origen.Controller.model
train
def model @model ||= begin if self.class.path_to_model m = eval(self.class.path_to_model) if m if m.respond_to?(:_controller=) m.send(:_controller=, self) end else fail "No model object found at path: #{self.class.path_to_model}" end m end end end
ruby
{ "resource": "" }
q19703
Origen.Controller.method_missing
train
def method_missing(method, *args, &block) if model.respond_to?(method) # This method is handled separately since it is important to produce a proxy method # that takes no arguments, otherwise the register address lookup system mistakes it # for a legacy way of calculating the base address whereby the register itself was # given as an argument. if method.to_sym == :base_address define_singleton_method(method) do model.send(method) end base_address else define_singleton_method(method) do |*args, &block| model.send(method, *args, &block) end send(method, *args, &block) end else super end end
ruby
{ "resource": "" }
q19704
Origen.Chips.has_chip?
train
def has_chip?(s, options = {}) _chips options = { group: nil, family: nil, performance: nil, chip: nil, creating_spec: false }.update(options) options[:chip] = s !!show_chips(options) end
ruby
{ "resource": "" }
q19705
Origen.Chips.filter_hash
train
def filter_hash(hash, filter) fail 'Hash argument is not a Hash!' unless hash.is_a? Hash filtered_hash = {} select_logic = case filter when String then 'k[Regexp.new(filter)]' when (Fixnum || Integer || Float || Numeric) then "k[Regexp.new('#{filter}')]" when Regexp then 'k[filter]' when Symbol then 'k == filter' when NilClass then true # Return all specs if a filter is set to nil (i.e. user doesn't care about this filter) else true end # rubocop:disable UnusedBlockArgument filtered_hash = hash.select do |k, v| [TrueClass, FalseClass].include?(select_logic.class) ? select_logic : eval(select_logic) end filtered_hash end
ruby
{ "resource": "" }
q19706
C99.NVMSub.add_reg_with_block_format
train
def add_reg_with_block_format # ** Data Register 3 ** # This is dreg add_reg :dreg, 0x1000, size: 16 do |reg| # This is dreg bit 15 reg.bit 15, :bit15, reset: 1 # **Bit 14** - This does something cool # # 0 | Coolness is disabled # 1 | Coolness is enabled reg.bits 14, :bit14 # This is dreg bit upper reg.bits 13..8, :upper # This is dreg bit lower # This is dreg bit lower line 2 reg.bit 7..0, :lower, writable: false, reset: 0x55 end # This is dreg2 reg :dreg2, 0x1000, size: 16 do # This is dreg2 bit 15 bit 15, :bit15, reset: 1 # This is dreg2 bit upper bits 14..8, :upper # This is dreg2 bit lower # This is dreg2 bit lower line 2 bit 7..0, :lower, writable: false, reset: 0x55 end # Finally a test that descriptions can be supplied via the API reg :dreg3, 0x1000, size: 16, description: "** Data Register 3 **\nThis is dreg3" do bit 15, :bit15, reset: 1, description: 'This is dreg3 bit 15' bit 14, :bit14, description: "**Bit 14** - This does something cool\n\n0 | Coolness is disabled\n1 | Coolness is enabled" bits 13..8, :upper, description: 'This is dreg3 bit upper' bit 7..0, :lower, writable: false, reset: 0x55, description: "This is dreg3 bit lower\nThis is dreg3 bit lower line 2" end reg :dreg4, 0x1000, size: 8, description: "** Data Register 4 **\nThis is dreg4" do bit 7..0, :busy, reset: 0x55, description: "**Busy Bits** - These do something super cool\n\n0 | Job0\n1 | Job1\n10 | Job2\n11 | Job3\n100 | Job4\n101 | Job5\n110 | Job6\n111 | Job7\n1000 | Job8\n1001 | Job9\n1010 | Job10\n1011 | Job11\n1100 | Job12\n1101 | Job13\n1110 | Job14\n1111 | Job15\n10000 | Job16\n10001 | Job17\n10010 | Job18" end end
ruby
{ "resource": "" }
q19707
Origen.Registers.add_reg
train
def add_reg(id, address, size = nil, bit_info = {}, &_block) if address.is_a?(Hash) fail 'add_reg requires the address to be supplied as the 2nd argument, e.g. add_reg :my_reg, 0x1000' end size, bit_info = nil, size if size.is_a?(Hash) size ||= bit_info.delete(:size) || 32 description = bit_info.delete(:description) local_vars = {} Reg::REG_LEVEL_ATTRIBUTES.each do |attribute, meta| aliases = [attribute[1..-1].to_sym] aliases += meta[:aliases] if meta[:aliases] aliases.each { |_a| local_vars[attribute] = bit_info.delete(_a) if bit_info.key?(_a) } end local_vars[:_reset] ||= :memory if local_vars[:_memory] @min_reg_address ||= address @max_reg_address ||= address # Must set an initial value, otherwise max_address_reg_size will be nil if a sub_block contains only # a single register. @max_address_reg_size = size unless @max_address_reg_size @min_reg_address = address if address < @min_reg_address if address > @max_reg_address @max_address_reg_size = size @max_reg_address = address end @reg_define_file ||= define_file(caller[0]) if block_given? @new_reg_attrs = { meta: bit_info } yield self bit_info = @new_reg_attrs else # If no block given then init with all writable bits unless bit_info has # been supplied unless bit_info.any? { |k, v| v.is_a?(Hash) && v[:pos] } bit_info = { d: { pos: 0, bits: size }.merge(bit_info) } end end if _registers[id] && Origen.config.strict_errors puts '' puts "Add register error, you have already added a register named #{id} to #{self.class}" puts '' fail 'Duplicate register error!' else attributes = { define_file: @reg_define_file, address: address, size: size, bit_info: bit_info, description: description } Reg::REG_LEVEL_ATTRIBUTES.each do |attribute, _meta| attributes[attribute] = local_vars[attribute] end _registers[id] = Placeholder.new(self, id, attributes) end @reg_define_file = nil end
ruby
{ "resource": "" }
q19708
Origen.Registers.bit
train
def bit(index, name, attrs = {}) if index.is_a?(Range) msb = index.first lsb = index.last msb, lsb = lsb, msb if lsb > msb pos = lsb bits = (msb - lsb).abs + 1 elsif index.is_a?(Numeric) pos = index bits = 1 else fail 'No valid index supplied when defining a register bit!' end # Traynor, this could be more elegant # its just a dirty way to make the value of the # key in @new_reg_atts hash array (ie name) tie to # a value that is an array of hashes describing # data for each scrambled bit attrs = attrs.merge(pos: pos, bits: bits) temparray = [] if @new_reg_attrs[name].nil? @new_reg_attrs[name] = attrs else if @new_reg_attrs[name].is_a? Hash temparray = temparray.push(@new_reg_attrs[name]) else temparray = @new_reg_attrs[name] end temparray = temparray.push(attrs) # added the sort so that the order the registers bits is described is not important @new_reg_attrs[name] = temparray.sort { |a, b| b[:pos] <=> a[:pos] } end end
ruby
{ "resource": "" }
q19709
Origen.Registers.default_reg_metadata
train
def default_reg_metadata Origen::Registers.reg_metadata[self.class] ||= {} if block_given? collector = Origen::Utility::Collector.new yield collector Origen::Registers.reg_metadata[self.class].merge!(collector.to_h) end Origen::Registers.reg_metadata[self.class] end
ruby
{ "resource": "" }
q19710
Origen.Registers.has_reg?
train
def has_reg?(name, params = {}) params = { test_for_true_false: true }.update(params) if params.key?(:enabled_features) || params.key?(:enabled_feature) return !!get_registers(params).include?(name) else params[:enabled_features] = :default return !!get_registers(params).include?(name) end end
ruby
{ "resource": "" }
q19711
Origen.Registers.reg
train
def reg(*args, &block) if block_given? || (args[1].is_a?(Integer) && !try(:_initialized?)) @reg_define_file = define_file(caller[0]) add_reg(*args, &block) else # Example use cases: # reg(:reg2) # reg(:name => :reg2) # reg('/reg2/') if !args.empty? && args.size == 1 && (args[0].class != Hash || (args[0].key?(:name) && args[0].size == 1)) if args[0].class == Hash name = args[0][:name] else name = args.first end if has_reg(name) return _registers[name] elsif name =~ /\/(.+)\// regex = Regexp.last_match(1) return match_registers(regex) else if Origen.config.strict_errors puts '' if regs.empty? puts "#{self.class} does not have a register named #{name} or it is not enabled." else puts "#{self.class} does not have a register named #{name} or it is not enabled." puts 'You may need to add it. This could also be a typo, these are the valid register names:' puts regs.keys end puts '' fail 'Missing register error!' end end # Example use cases: # reg(:enabled_features => :all) # reg(:name => :reg2, enabled_features => :all) # reg(:name => :reg2, enabled_features => :fac) elsif !args.empty? && args.size == 1 && args[0].class == Hash params = args[0] # Example use case: # reg(:name => :reg2, :enabled_features => :all) if (params.key?(:enabled_features) || params.key?(:enabled_feature)) && params.key?(:name) name = params[:name] if has_reg(name, params) _registers[name] else reg_missing_error(params) end # Example use case: # reg(:enabled_features =>[:fac, fac2]) elsif params.size == 1 && params.key?(:enabled_features) return get_registers(enabled_features: params[:enabled_features]) end # Example use case: # reg(:reg2, :enabled_features => :all) # reg(:reg2, :enabled_features => :default) # reg(:reg2, :enabled_features => :fac) elsif !args.empty? && args.size == 2 name = args[0] params = args[1] name, params = params, name if name.class == Hash if has_reg(name, params) _registers[name] else reg_missing_error(params) end elsif args.empty? if _registers.empty? return _registers else return get_registers(enabled_features: :default) end else if Origen.config.strict_errors fail 'Invalid call to reg method or invalid arguments specified' end end end end
ruby
{ "resource": "" }
q19712
Origen.RegressionManager.prepare_targets
train
def prepare_targets(options) targets = [options[:target], options[:targets]].flatten.compact if targets.empty? puts 'You must supply the targets you are going to run in the options' puts 'passed to regression_manager.run.' fail end Origen.target.loop(options) { |_options| } targets end
ruby
{ "resource": "" }
q19713
Origen.RegressionManager.regression_command_file
train
def regression_command_file first_call = caller.find { |line| line =~ /regression_manager.rb.*run/ } app_caller_line = caller[caller.index(first_call) + 1] app_caller_line =~ /(.*\.rb)/ path = Pathname.new(Regexp.last_match[1]) end
ruby
{ "resource": "" }
q19714
Origen.Componentable._add
train
def _add(name, options = {}, &block) # Add the name and parent to the options if they aren't already given # If the parent isn't available on the includer class, it will remain nil. options = { name: name, parent: parent }.merge(options) options = Origen::Utility.collector(hash: options, merge_method: :keep_hash, &block).to_h # Instantiate the class. This will place the object in the @_componentable_container at the indicated name _instantiate_class(name, options) # Create an accessor for the new item, if indicated to do so. _push_accessor(name, options) @_componentable_container[name] end
ruby
{ "resource": "" }
q19715
Origen.Componentable.move
train
def move(to_move, new_name, options = {}) overwrite = options[:overwrite] || false if @_componentable_container.key?(new_name) && !overwrite # The move location already exists and override was not specified fail Origen::Componentable::NameInUseError, "#{_singleton_name} name :#{new_name} is already in use" end unless @_componentable_container.key?(to_move) # The to_move name doesn't exist fail Origen::Componentable::NameDoesNotExistError, "#{_singleton_name} name :#{to_move} does not exist" end to_move_object = @_componentable_container.delete(to_move) @_componentable_container[new_name] = to_move_object end
ruby
{ "resource": "" }
q19716
Origen.Componentable.delete
train
def delete(to_delete) obj = delete!(to_delete) fail Origen::Componentable::NameDoesNotExistError, "#{_singleton_name} name :#{to_delete} does not exist" if obj.nil? obj end
ruby
{ "resource": "" }
q19717
Origen.Componentable.delete_all
train
def delete_all # delete individual objects one by one, making sure to delete all accessors as well returns = {} @_componentable_container.each do |key, val| delete!(key) returns[key] = val end returns end
ruby
{ "resource": "" }
q19718
Origen.SubBlocks.init_sub_blocks
train
def init_sub_blocks(*args) options = args.find { |a| a.is_a?(Hash) } @custom_attrs = (options ? options.dup : {}).with_indifferent_access # Delete these keys which are either meta data added by Origen or are already covered by # dedicated methods %w(parent name base_address reg_base_address base).each do |key| @custom_attrs.delete(key) end if options # Using reg_base_address for storage to avoid class with the original Origen base # address API, but will accept any of these @reg_base_address = options.delete(:reg_base_address) || options.delete(:base_address) || options.delete(:base) || 0 if options[:_instance] # to be deprecated as part of multi-instance removal below if @reg_base_address.is_a?(Array) @reg_base_address = @reg_base_address[options[:_instance]] elsif options[:base_address_step] @reg_base_address = @reg_base_address + (options[:_instance] * options[:base_address_step]) end end @domain_names = [options.delete(:domain) || options.delete(:domains)].flatten.compact @domain_specified = !@domain_names.empty? @path = options.delete(:path) @abs_path = options.delete(:abs_path) || options.delete(:absolute_path) end if is_a?(SubBlock) options.each do |k, v| send("#{k}=", v) end end end
ruby
{ "resource": "" }
q19719
Origen.SubBlocks.owns_registers?
train
def owns_registers? if regs regs.is_a?(Origen::Registers::RegCollection) && !regs.empty? else false end end
ruby
{ "resource": "" }
q19720
Origen.SubBlock.method_missing
train
def method_missing(method, *args, &block) super rescue NoMethodError return regs(method) if self.has_reg?(method) return ports(method) if self.has_port?(method) if method.to_s =~ /=$/ define_singleton_method(method) do |val| instance_variable_set("@#{method.to_s.sub('=', '')}", val) end else define_singleton_method(method) do instance_variable_get("@#{method}") end end send(method, *args, &block) end
ruby
{ "resource": "" }
q19721
Origen.Specs.documentation
train
def documentation(header_info, selection, applicable_devices, link) _documentation # Create a new documenation and place it in the 5-D hash @_documentation[header_info[:section]][header_info[:subsection]][selection[:interface]][selection[:type]][selection[:sub_type]][selection[:mode]][selection[:audience]] = Documentation.new(header_info, selection, applicable_devices, link) end
ruby
{ "resource": "" }
q19722
Origen.Specs.spec_feature
train
def spec_feature(id, attrs, device, text, internal_comment) # Welguisz: No idea why this is here, but keeping it here because it follows other blocks _spec_features # Create a new feature and place it in the features 2-D Hash @_spec_features[id][device] = Spec_Features.new(id, attrs, device, text, internal_comment) end
ruby
{ "resource": "" }
q19723
Origen.Specs.notes
train
def notes(options = {}) # Create a default 2 item hash and update if options is supplied options = { id: nil, type: nil }.update(options) return nil if @_notes.nil? return nil if @_notes.empty? # Empty 2-D Hash to be used for notes found based on id and type notes_found = Hash.new do |h, k| # h is the id portion of the hash # k is the type portion of the hash h[k] = {} end # Filter @notes based off of the id filter_hash(@_notes, options[:id]).each do |id, hash| # Filter hash based off of the type filter_hash(hash, options[:type]).each do |type, note| # Store the note into note_found notes_found[id][type] = note end end if notes_found.empty? return nil elsif notes_found.size == 1 notes_found.values.first.values.first else return notes_found end end
ruby
{ "resource": "" }
q19724
Origen.Specs.specs_to_table_string
train
def specs_to_table_string(specs_to_be_shown) whitespace_padding = 3 table = [] attrs_to_be_shown = { name: SpecTableAttr.new('Name', true, 'Name'.length + whitespace_padding), symbol: SpecTableAttr.new('Symbol', false, 'Symbol'.length + whitespace_padding), mode: SpecTableAttr.new('Mode', true, 'Mode'.length + whitespace_padding), type: SpecTableAttr.new('Type', true, 'Type'.length + whitespace_padding), sub_type: SpecTableAttr.new('Sub-Type', false, 'Sub-Type'.length + whitespace_padding), # spec SpecTableAttribute :description is called parameter in the spec table output to match historical docs description: SpecTableAttr.new('Parameter', false, 'Parameter'.length + whitespace_padding), min: SpecTableAttr.new('Min', false, 'Min'.length + whitespace_padding), typ: SpecTableAttr.new('Typ', false, 'Typ'.length + whitespace_padding), max: SpecTableAttr.new('Max', false, 'Max'.length + whitespace_padding), unit: SpecTableAttr.new('Unit', false, 'Unit'.length + whitespace_padding), audience: SpecTableAttr.new('Audience', false, 'Audience'.length + whitespace_padding) # notes: SpecTableAttr.new('Notes', false, 'Notes'.length + whitespace_padding) } # Calculate the padding needed in the spec table for the longest attr of all specs specs_to_be_shown.each do |spec| attrs_to_be_shown.each do |attr_name, attr_struct| unless spec.send(attr_name).nil? if spec.send(attr_name).class == Origen::Specs::Spec::Limit next if spec.send(attr_name).value.nil? current_padding = spec.send(attr_name).value.to_s.length + whitespace_padding else current_padding = spec.send(attr_name).to_s.length + whitespace_padding end attr_struct.padding = current_padding if attr_struct.padding < current_padding attr_struct.show = true # We found real data for this attr on at least one spec so show it in the spec table end end end # Now that each spec attribute padding construct the spec table header header = '' attrs_to_be_shown.each do |_attr_name, attr_struct| next if attr_struct.show == false header += "| #{attr_struct.table_text}".ljust(attr_struct.padding) end header += '|' ip_header = "| IP: #{specs_to_be_shown.first.ip_name} ".ljust(header.length - 1) ip_header += '|' table << '=' * header.length table << ip_header table << '=' * header.length table << header table << '-' * header.length # Create the data lines in the spec table specs_to_be_shown.each do |spec| data = '' attrs_to_be_shown.each do |attr_name, attr_struct| next if attr_struct.show == false if spec.send(attr_name).class == Origen::Specs::Spec::Limit data += "| #{spec.send(attr_name).value}".ljust(attr_struct.padding) else data += "| #{spec.send(attr_name)}".ljust(attr_struct.padding) end end table << data += '|' end table << '-' * header.length table.flatten.join("\n") end
ruby
{ "resource": "" }
q19725
Origen.Application.maillist_parse
train
def maillist_parse(file) maillist = [] # if file doesn't exist, just return empty array, otherwise, parse for emails if File.exist?(file) File.readlines(file).each do |line| if index = (line =~ /\#/) # line contains some kind of comment # check if there is any useful info, ignore it not unless line[0, index].strip.empty? maillist << Origen::Users::User.new(line[0, index].strip).email end else # if line is not empty, generate an email unless line.strip.empty? maillist << Origen::Users::User.new(line.strip).email end end end end maillist end
ruby
{ "resource": "" }
q19726
Origen.Application.server_data
train
def server_data if name == :origen @server_data ||= Origen.client.origen else @server_data ||= Origen.client.plugins.find { |p| p[:origen_name].downcase == name.to_s.downcase } end end
ruby
{ "resource": "" }
q19727
Origen.Application.release_date
train
def release_date(version = Origen.app.version.prefixed) time = release_time(version) time ? time.to_date : nil end
ruby
{ "resource": "" }
q19728
Origen.Application.dynamic_resource
train
def dynamic_resource(name, default, options = {}) @static_resources ||= {} @transient_resources ||= {} if @load_event == :static || (!@load_event && options[:adding]) if options[:set] @static_resources[name] = default else @static_resources[name] ||= default end elsif @load_event == :transient if options[:set] @transient_resources[name] = default else @transient_resources[name] ||= default end else static = @static_resources[name] ||= default transient = @transient_resources[name] ||= default if static.respond_to?('+') static + transient else static.merge(transient) end end end
ruby
{ "resource": "" }
q19729
Origen.Client.release!
train
def release! version = Origen.app.version body = { version: version.to_s } if version.production? body[:type] = :production else body[:type] = :development end post("plugins/#{Origen.app.name}/release", body: body) end
ruby
{ "resource": "" }
q19730
Origen.Model.current_mode=
train
def current_mode=(id) @current_mode = id.is_a?(ChipMode) ? id.id : id Origen.app.listeners_for(:on_mode_changed).each do |listener| listener.on_mode_changed(mode: @current_mode, instance: self) end @current_mode end
ruby
{ "resource": "" }
q19731
Origen.Model.modes
train
def modes(id = nil, _options = {}) id = nil if id.is_a?(Hash) if id _modes[id] else _modes.ids end end
ruby
{ "resource": "" }
q19732
Origen.Model.with_each_mode
train
def with_each_mode begin orig = current_mode rescue orig = nil end modes.each do |_id, mode| self.current_mode = mode yield mode end self.current_mode = orig end
ruby
{ "resource": "" }
q19733
Origen.Model.find_specs
train
def find_specs specs_found = [] # Check for specs the object owns if self.respond_to? :specs object_specs = specs unless object_specs.nil? if object_specs.class == Origen::Specs::Spec specs_found << object_specs else specs_found.concat(object_specs) end end end sub_blocks.each do |_name, sb| next unless sb.respond_to? :specs child_specs = sb.specs unless child_specs.nil? if child_specs.class == Origen::Specs::Spec specs_found << child_specs else specs_found.concat(child_specs) end end end specs_found end
ruby
{ "resource": "" }
q19734
Origen.Model.delete_all_specs_and_notes
train
def delete_all_specs_and_notes(obj = nil) obj = self if obj.nil? obj.delete_all_specs obj.delete_all_notes obj.delete_all_exhibits obj.children.each do |_name, child| next unless child.has_specs? delete_all_specs_and_notes(child) end end
ruby
{ "resource": "" }
q19735
Origen.Model.method_missing
train
def method_missing(method, *args, &block) if controller.respond_to?(method) define_singleton_method(method) do |*args, &block| controller.send(method, *args, &block) end send(method, *args, &block) else super end end
ruby
{ "resource": "" }
q19736
Origen.Users.current_user
train
def current_user core_id = Origen::Users::User.current_user_id user = app_users.find { |user| user.core_id == core_id } user || User.new(core_id) end
ruby
{ "resource": "" }
q19737
Origen.VersionString.numeric
train
def numeric if latest? 1_000_000_000_000_000_000_000_000_000 elsif semantic? # This assumes each counter will never go > 1000 if development? self =~ /v?(\d+).(\d+).(\d+).(dev|pre)(\d+)/ (Regexp.last_match[1].to_i * 1000 * 1000 * 1000) + (Regexp.last_match[2].to_i * 1000 * 1000) + (Regexp.last_match[3].to_i * 1000) + Regexp.last_match[5].to_i else self =~ /v?(\d+).(\d+).(\d+)/ (Regexp.last_match[1].to_i * 1000 * 1000 * 1000) + (Regexp.last_match[2].to_i * 1000 * 1000) + (Regexp.last_match[3].to_i * 1000) end elsif timestamp? to_time.to_i else validate! end end
ruby
{ "resource": "" }
q19738
Origen.VersionString.to_time
train
def to_time if latest? Time.new(10_000, 1, 1) elsif timestamp? if development? self =~ /\w+_(\d\d\d\d)_(\d\d)_(\d\d)_(\d\d)_(\d\d)$/ Time.new(Regexp.last_match[1], Regexp.last_match[2], Regexp.last_match[3], Regexp.last_match[4], Regexp.last_match[5]) else self =~ /Rel(\d\d\d\d)(\d\d)(\d\d)/ Time.new(Regexp.last_match[1], Regexp.last_match[2], Regexp.last_match[3]) end else fail "Version tag #{self} cannot be converted to a time!" end end
ruby
{ "resource": "" }
q19739
Origen.VersionString.validate_condition!
train
def validate_condition!(condition, tag) tag = VersionString.new(tag) tag.validate!("The version condition, #{condition}, is not valid!") tag end
ruby
{ "resource": "" }
q19740
Origen.RemoteManager.delete_symlink
train
def delete_symlink(path) if Origen.running_on_windows? # Don't use regular rm on windows symlink, will delete into the remote dir! system("call cmd /c rmdir #{path.to_s.gsub('/', '\\')}") FileUtils.rm_f("#{path}_is_a_symlink") else FileUtils.rm_f(path) end end
ruby
{ "resource": "" }
q19741
Origen.RemoteManager.process_remotes
train
def process_remotes remotes.each do |_name, remote| dir = workspace_of(remote) rc_url = remote[:rc_url] || remote[:vault] tag = remote[:tag].nil? ? Origen::VersionString.new(remote[:version]) : Origen::VersionString.new(remote[:tag]) version_file = dir.to_s + '/.current_version' begin if File.exist?("#{dir}/.initial_populate_successful") FileUtils.rm_f(version_file) if File.exist?(version_file) rc = RevisionControl.new remote: rc_url, local: dir rc.send rc.remotes_method, version: prefix_tag(tag), force: true File.open(version_file, 'w') do |f| f.write tag end else rc = RevisionControl.new remote: rc_url, local: dir rc.send rc.remotes_method, version: prefix_tag(tag), force: true FileUtils.touch "#{dir}/.initial_populate_successful" File.open(version_file, 'w') do |f| f.write tag end end rescue Origen::GitError, Origen::DesignSyncError, Origen::PerforceError => e # If Git failed in the remote, its usually easy to see what the problem is, but now *where* it is. # This will prepend the failing remote along with the error from the revision control system, # then rethrow the error e.message.prepend "When updating remotes for #{remote[:importer].name}: " raise e end end end
ruby
{ "resource": "" }
q19742
Origen.RemoteManager.path_enabled?
train
def path_enabled?(remote) dir = workspace_of(remote) File.exist?(dir) && symlink?(dir) end
ruby
{ "resource": "" }
q19743
Origen.RemoteManager.update!
train
def update! ensure_remotes_directory dirty_remotes.each do |_name, remote| dir = workspace_of(remote) if remote[:path] || path_enabled?(remote) if symlink?(dir) delete_symlink(dir) else FileUtils.rm_rf(dir) if File.exist?(dir) end end if remote[:path] create_symlink(remote[:path], dir) else rc_url = remote[:rc_url] || remote[:vault] tag = remote[:tag].nil? ? Origen::VersionString.new(remote[:version]) : Origen::VersionString.new(remote[:tag]) version_file = dir.to_s + '/.current_version' begin if File.exist?("#{dir}/.initial_populate_successful") FileUtils.rm_f(version_file) if File.exist?(version_file) rc = RevisionControl.new remote: rc_url, local: dir rc.send rc.remotes_method, version: prefix_tag(tag), force: true File.open(version_file, 'w') do |f| f.write tag end else rc = RevisionControl.new remote: rc_url, local: dir rc.send rc.remotes_method, version: prefix_tag(tag), force: true FileUtils.touch "#{dir}/.initial_populate_successful" File.open(version_file, 'w') do |f| f.write tag end end rescue Origen::GitError, Origen::DesignSyncError, Origen::PerforceError => e # If Git failed in the remote, its usually easy to see what the problem is, but now *where* it is. # This will prepend the failing remote along with the error from the revision control system, # then rethrow the error e.message.prepend "When updating remotes for #{remote[:importer].name}: " raise e end end end end
ruby
{ "resource": "" }
q19744
Origen.RemoteManager.prefix_tag
train
def prefix_tag(tag) tag = Origen::VersionString.new(tag) if tag.semantic? tag.prefixed else tag end end
ruby
{ "resource": "" }
q19745
Origen.TopLevel.current_package=
train
def current_package=(val) @current_package_id = case val when ChipPackage val.id else packages.include?(val) ? val : nil end end
ruby
{ "resource": "" }
q19746
Origen.TopLevel.packages
train
def packages(id = nil, _options = {}) id, options = nil, id if id.is_a?(Hash) if id _packages[id] else _packages.ids end end
ruby
{ "resource": "" }
q19747
Origen.Errata.erratum
train
def erratum(id, ip_block, overview = {}, status = {}, sw_workaround = {}) _errata @_errata[id][ip_block][status[:disposition]] = HwErratum.new(id, ip_block, overview, status, sw_workaround) end
ruby
{ "resource": "" }
q19748
Origen.Errata.errata
train
def errata(options = {}) options = { id: nil, ip_block: nil, disposition: nil }.update(options) return nil if @_errata.nil? return nil if @_errata.empty? errata_found = Hash.new do |h, k| h[k] = Hash.new do |hh, kk| hh[kk] = {} end end # First filter on id, then ip_block, then disposition filter_hash(@_errata, options[:id]).each do |id, hash| filter_hash(hash, options[:ip_block]).each do |ip_block, hash1| filter_hash(hash1, options[:disposition]).each do |disposition, errata| errata_found[id][ip_block][disposition] = errata end end end # Return nil if there are no errata that meet criteria if errata_found.empty? return nil # If only one errata meets criteria, return that HwErratum object elsif errata_found.size == 1 errata_found.values.first.values.first.values.first else return errata_found end end
ruby
{ "resource": "" }
q19749
Origen.Errata.sw_workaround
train
def sw_workaround(id, overview = {}, resolution = {}) _sw_workarounds @_sw_workarounds[id] = SwErratumWorkaround.new(id, overview, resolution) end
ruby
{ "resource": "" }
q19750
Origen.Errata.sw_workarounds
train
def sw_workarounds(options = {}) options = { id: nil }.update(options) return nil if @_sw_workarounds.nil? return nil if @_sw_workarounds.empty? sw_workarounds_found = Hash.new do |h, k| h[k] = {} end # filter on id filter_hash(@_sw_workarounds, options[:id]).each do |id, workarounds| sw_workarounds_found[id] = workarounds end if sw_workarounds_found.empty? return nil elsif sw_workarounds_found.size == 1 sw_workarounds_found.values.first # .values.first else return sw_workarounds_found end end
ruby
{ "resource": "" }
q19751
Origen.SiteConfig.add_as_highest
train
def add_as_highest(var, value) # Don't want to override anything, so just shift in a dummy site config instance at the highest level and # set the value there. c = Config.new(path: :runtime, parent: self, values: { var.to_s => value }) configs.prepend(Config.new(path: :runtime, parent: self, values: { var.to_s => value })) end
ruby
{ "resource": "" }
q19752
Origen.SiteConfig.add_as_lowest
train
def add_as_lowest(var, value) # Don't want to override anything, so just shift in a dummy site config at the lowest level and # set the value there. configs.append(Config.new(path: :runtime, parent: self, values: { var.to_s => value })) end
ruby
{ "resource": "" }
q19753
Origen.SiteConfig.vars_by_configs
train
def vars_by_configs vars = {} configs.each do |c| vars = c.values.map { |k, v| [k, c] }.to_h.merge(vars) end vars end
ruby
{ "resource": "" }
q19754
Origen.SiteConfig.configs!
train
def configs! # This global is set when Origen is first required, it generally means that what is considered # to be the pwd for the purposes of looking for a site_config file is the place from where the # user invoked Origen. Otherwise if the running app switches the PWD it can lead to confusing # behavior - this was a particular problem when testing the new app generator which switches the # pwd to /tmp to build the new app path = $_origen_invocation_pwd @configs = [] # Add any site_configs from where we are currently running from, i.e. the application # directory area until path.root? load_directory(path) path = path.parent end # Add and any site_configs from the directory hierarchy where Ruby is installed path = Pathname.new($LOAD_PATH.last) until path.root? load_directory(path) path = path.parent end # Add the one from the Origen core as the lowest priority, this one defines # the default values load_directory(File.expand_path('../../../', __FILE__)) # Add the site_config from the user's home directory as highest priority, if it exists # But, make sure we take the site installation's setup into account. # That is, if user's home directories are somewhere else, make sure we use that directory to the find # the user's overwrite file. The user can then override that if they want." load_directory(File.expand_path(user_install_dir), prepend: true) # Load any centralized site configs now. centralized_site_config = find_val('centralized_site_config') if centralized_site_config # We know the last two site configs will exists (they are in Origen core) and that they contain the default # values. We want the centralized config to load right after those. @configs.insert(-3, Config.new(path: centralized_site_config, parent: self)) end # After all configs have been populated, see if the centralized needs refreshing @configs.each { |c| c.refresh if c.needs_refresh? } @configs end
ruby
{ "resource": "" }
q19755
Origen.FileHandler.open_list
train
def open_list(file) f = clean_path_to(file, allow_missing: true) if f f = File.open(f, 'r') elsif File.exist?("#{Origen.root}/list/#{File.basename(file)}") f = File.open("#{Origen.root}/list/#{File.basename(file)}", 'r') elsif @last_opened_list_dir && File.exist?("#{@last_opened_list_dir}/#{file}") f = File.open("#{@last_opened_list_dir}/#{file}", 'r') else fail "Could not find list file: #{file}" end lines = f.readlines f.close # Before we go save the directory of this list, this will help # us to resolve any relative path references to other lists that # it may contain @last_opened_list_dir = clean_path_to(Pathname.new(f).dirname) lines end
ruby
{ "resource": "" }
q19756
Origen.FileHandler.clean_path_to
train
def clean_path_to(file, options = {}) # Allow individual calls to this method to specify additional custom load paths to consider if options[:load_paths] [options[:load_paths]].each do |root| if File.exist?("#{root}/#{file}") return Pathname.new("#{root}/#{file}") end end end if File.exist?(file) if Pathname.new(file).absolute? Pathname.new(file) else Pathname.new("#{Pathname.pwd}/#{file}") end # Is it a relative reference within a list file? elsif @last_opened_list_dir && File.exist?("#{@last_opened_list_dir}/#{file}") Pathname.new("#{@last_opened_list_dir}/#{file}") # Is it a relative reference to the current base directory? elsif File.exist?("#{base_directory}/#{file}") Pathname.new("#{base_directory}/#{file}") # Is it a path relative to Origen.root? elsif File.exist?("#{Origen.root}/#{file}") Pathname.new("#{Origen.root}/#{file}") # Is it a path relative to the current directory? elsif current_directory && File.exist?("#{current_directory}/#{file}") Pathname.new("#{current_directory}/#{file}") # Is it a path relative to the current plugin's Origen.root? elsif Origen.app.plugins.current && File.exist?("#{Origen.app.plugins.current.root}/#{file}") Pathname.new("#{Origen.app.plugins.current.root}/#{file}") elsif options[:default_dir] m = all_matches(file, options) if m Pathname.new(m) else if options[:allow_missing] return nil else fail "Can't find: #{file}" end end else if options[:allow_missing] return nil else fail "Can't find: #{file}" end end end
ruby
{ "resource": "" }
q19757
Origen.FileHandler.relative_to_absolute
train
def relative_to_absolute(path) if Pathname.new(path).absolute? Pathname.new(path) else Pathname.new("#{Pathname.pwd}/#{path}") end end
ruby
{ "resource": "" }
q19758
Origen.FileHandler.inject_import_path
train
def inject_import_path(path, options = {}) path = path.to_s unless path.is_a?(String) if path =~ /(.*?)\/.*/ import_name = Regexp.last_match[1].downcase.to_sym if import_name == :origen || import_name == :origen_core || Origen.app.plugins.names.include?(import_name) || import_name == :doc_helpers # Special case to allow a shortcut for this common import plugin and to also handle legacy # code from when it was called doc_helpers instead of origen_doc_helpers if import_name == :doc_helpers root = Origen.app(:origen_doc_helpers).root else unless import_name == :origen || import_name == :origen_core root = Origen.app(import_name).root end end if options[:type] == :template if import_name == :origen || import_name == :origen_core path.sub! 'origen', "#{Origen.top}/templates/shared" else path.sub! Regexp.last_match[1], "#{root}/templates/shared" end else fail 'Unknown import path type!' end end end path end
ruby
{ "resource": "" }
q19759
Origen.FileHandler.add_underscore_to
train
def add_underscore_to(file) f = Pathname.new(file) if f.basename.to_s =~ /^_/ file else "#{f.dirname}/_#{f.basename}" end end
ruby
{ "resource": "" }
q19760
Origen.FileHandler.sub_dir_of
train
def sub_dir_of(file, base = base_directory) file = Pathname.new(file) unless file.respond_to?(:relative_path_from) base = Pathname.new(base) unless base.respond_to?(:relative_path_from) rel = file.relative_path_from(base) if file.directory? rel else rel.dirname end end
ruby
{ "resource": "" }
q19761
Origen.FileHandler.open_for_write
train
def open_for_write(path) dir = Pathname.new(path).dirname FileUtils.mkdir_p(dir) unless File.exist?(dir) File.open(path, 'w') do |f| yield f end end
ruby
{ "resource": "" }
q19762
Origen.Bugs.has_bug?
train
def has_bug?(name, _options = {}) unless self.respond_to?(:version) && version puts 'To test for the presence of a bug the object must implement an attribute' puts "called 'version' which returns the IP version represented by the the object." fail 'Version undefined!' end name = name.to_s.downcase.to_sym if bugs[name] bugs[name].present_on_version?(version) else false end end
ruby
{ "resource": "" }
q19763
Origen.Log.level=
train
def level=(val) unless LEVELS.include?(val) fail "Unknown log level, valid values are: #{LEVELS}" end # Map the log4r levels to our simplified 3 level system # log4r level order is DEBUG < INFO < WARN < ERROR < FATAL case val when :normal # Output everything except debug statements console.level = Logger::INFO # Output everything log_files(:level=, Logger::DEBUG) unless console_only? when :verbose console.level = Logger::DEBUG log_files(:level=, Logger::DEBUG) unless console_only? when :silent # We don't use any fatal messages, so this is effectively OFF console.level = Logger::FATAL log_files(:level=, Logger::DEBUG) unless console_only? end @level = val end
ruby
{ "resource": "" }
q19764
Origen.Log.log_files
train
def log_files(method, *args) # When running remotely on an LSF client, the LSF manager will capture STDOUT (i.e. the console log output) # and save it to a log file. # Don't write to the last log file in that case because we would have multiple processes all vying to # write to it at the same time. last_file.send(method, *args) unless Origen.running_remotely? @job_file.send(method, *args) if @job_file end
ruby
{ "resource": "" }
q19765
Origen.Pins.pin_pattern_order
train
def pin_pattern_order(*pin_ids) if pin_ids.last.is_a?(Hash) options = pin_ids.pop else options = {} end pin_ids.each do |id| if pin_aliases[id] Origen.app.pin_names[pin_aliases[id].first] = id id = pin_aliases[id].first end Origen.app.pin_pattern_order << id end Origen.app.pin_pattern_order << options unless options.empty? end
ruby
{ "resource": "" }
q19766
Origen.Pins.all_power_pins
train
def all_power_pins(id = nil, _options = {}, &_block) if id pin = Origen.pin_bank.find(id, ignore_context: true, power_pin: true) else Origen.pin_bank.all_power_pins end end
ruby
{ "resource": "" }
q19767
Origen.Pins.all_other_pins
train
def all_other_pins(id = nil, _options = {}, &_block) if id pin = Origen.pin_bank.find(id, ignore_context: true, other_pin: true) else Origen.pin_bank.all_other_pins end end
ruby
{ "resource": "" }
q19768
Origen.Pins.power_pins
train
def power_pins(id = nil, options = {}, &block) id, options = nil, id if id.is_a?(Hash) options = { power_pin: true }.merge(options) pins(id, options, &block) end
ruby
{ "resource": "" }
q19769
Origen.Pins.ground_pins
train
def ground_pins(id = nil, options = {}, &block) id, options = nil, id if id.is_a?(Hash) options = { ground_pin: true }.merge(options) pins(id, options, &block) end
ruby
{ "resource": "" }
q19770
Origen.Pins.other_pins
train
def other_pins(id = nil, options = {}, &block) id, options = nil, id if id.is_a?(Hash) options = { other_pin: true }.merge(options) pins(id, options, &block) end
ruby
{ "resource": "" }
q19771
Origen.Pins.virtual_pins
train
def virtual_pins(id = nil, options = {}, &block) id, options = nil, id if id.is_a?(Hash) options = { virtual_pin: true }.merge(options) pins(id, options, &block) end
ruby
{ "resource": "" }
q19772
Origen.Pins.delete_pin
train
def delete_pin(id, options = {}) id = id.to_sym # Check if this is a Pin or a PinGroup if pin_groups.key? id Origen.pin_bank.delete_pingroup(Origen.pin_bank.find_pin_group(id, options)) elsif pins(id).class.to_s.match(/Pin/) Origen.pin_bank.delete_pin(Origen.pin_bank.find(id, options)) else fail "Error: the object #{id} you tried to delete is not a pin or pingroup" end end
ruby
{ "resource": "" }
q19773
Origen.GlobalMethods.render
train
def render(*args, &block) if $_compiler_stack && $_compiler_stack.last $_compiler_stack.last.render(*args, &block) else Origen.generator.compiler.render(*args, &block) end end
ruby
{ "resource": "" }
q19774
Origen.Features.feature
train
def feature(name = nil) if !name self.class.features.keys else if self.class.features.key?(name) self.class.features[name] else fail "Feature #{name} does not exist!" end end end
ruby
{ "resource": "" }
q19775
TTT.ComputerPlayer.imperative_move
train
def imperative_move # if we can win *this turn*, then take it because # it rates winning next turn the same as winning in 3 turns game.available_moves.each do |move| new_game = game.pristine_mark move return move if new_game.over? && new_game.winner == player_number end # if we can block the opponent from winning *this turn*, then take it, because # it rates losing this turn the same as losing in 3 turns if moves_by_rating.all? { |move, rating, game| rating == -1 } Game.winning_states do |position1, position2, position3| a, b, c = board[position1-1, 1].to_i, board[position2-1, 1].to_i, board[position3-1, 1].to_i if a + b + c == opponent_number * 2 return a.zero? ? position1 : b.zero? ? position2 : position3 end end end end
ruby
{ "resource": "" }
q19776
LightStep.Tracer.start_span
train
def start_span(operation_name, child_of: nil, references: nil, start_time: nil, tags: nil, ignore_active_scope: false) if child_of.nil? && references.nil? && !ignore_active_scope child_of = active_span end Span.new( tracer: self, operation_name: operation_name, child_of: child_of, references: references, start_micros: start_time.nil? ? LightStep.micros(Time.now) : LightStep.micros(start_time), tags: tags, max_log_records: max_log_records, ) end
ruby
{ "resource": "" }
q19777
LightStep.Tracer.extract
train
def extract(format, carrier) case format when OpenTracing::FORMAT_TEXT_MAP extract_from_text_map(carrier) when OpenTracing::FORMAT_BINARY warn 'Binary join format not yet implemented' nil when OpenTracing::FORMAT_RACK extract_from_rack(carrier) else warn 'Unknown join format' nil end end
ruby
{ "resource": "" }
q19778
LightStep.Span.set_baggage
train
def set_baggage(baggage = {}) @context = SpanContext.new( id: context.id, trace_id: context.trace_id, baggage: baggage ) end
ruby
{ "resource": "" }
q19779
LightStep.Span.to_h
train
def to_h { runtime_guid: tracer.guid, span_guid: context.id, trace_guid: context.trace_id, span_name: operation_name, attributes: tags.map {|key, value| {Key: key.to_s, Value: value} }, oldest_micros: start_micros, youngest_micros: end_micros, error_flag: false, dropped_logs: dropped_logs_count, log_records: log_records } end
ruby
{ "resource": "" }
q19780
LightStep.ScopeManager.activate
train
def activate(span:, finish_on_close: true) return active if active && active.span == span LightStep::Scope.new(manager: self, span: span, finish_on_close: finish_on_close).tap do |scope| add_scope(scope) end end
ruby
{ "resource": "" }
q19781
Lentil.InstagramHarvester.configure_connection
train
def configure_connection(opts = {}) opts['client_id'] ||= Lentil::Engine::APP_CONFIG["instagram_client_id"] opts['client_secret'] ||= Lentil::Engine::APP_CONFIG["instagram_client_secret"] opts['access_token'] ||= Lentil::Engine::APP_CONFIG["instagram_access_token"] || nil Instagram.configure do |config| config.client_id = opts['client_id'] config.client_secret = opts['client_secret'] if (opts['access_token']) config.access_token = opts['access_token'] end end end
ruby
{ "resource": "" }
q19782
Lentil.InstagramHarvester.configure_comment_connection
train
def configure_comment_connection(access_token = nil) access_token ||= Lentil::Engine::APP_CONFIG["instagram_access_token"] || nil raise "instagram_access_token must be defined as a parameter or in the application config" unless access_token configure_connection({'access_token' => access_token}) end
ruby
{ "resource": "" }
q19783
Lentil.InstagramHarvester.fetch_recent_images_by_tag
train
def fetch_recent_images_by_tag(tag = nil) configure_connection tag ||= Lentil::Engine::APP_CONFIG["default_image_search_tag"] Instagram.tag_recent_media(tag, :count=>10) end
ruby
{ "resource": "" }
q19784
Lentil.InstagramHarvester.extract_image_data
train
def extract_image_data(instagram_metadata) { url: instagram_metadata.link, external_id: instagram_metadata.id, large_url: instagram_metadata.images.standard_resolution.url, name: instagram_metadata.caption && instagram_metadata.caption.text, tags: instagram_metadata.tags, user: instagram_metadata.user, original_datetime: Time.at(instagram_metadata.created_time.to_i).to_datetime, original_metadata: instagram_metadata, media_type: instagram_metadata.type, video_url: instagram_metadata.videos && instagram_metadata.videos.standard_resolution.url } end
ruby
{ "resource": "" }
q19785
Lentil.InstagramHarvester.save_image
train
def save_image(image_data) instagram_service = Lentil::Service.where(:name => "Instagram").first user_record = instagram_service.users.where(:user_name => image_data[:user][:username]). first_or_create!({:full_name => image_data[:user][:full_name], :bio => image_data[:user][:bio]}) raise DuplicateImageError, "Duplicate image identifier" unless user_record. images.where(:external_identifier => image_data[:external_id]).first.nil? image_record = user_record.images.build({ :external_identifier => image_data[:external_id], :description => image_data[:name], :url => image_data[:url], :long_url => image_data[:large_url], :video_url => image_data[:video_url], :original_datetime => image_data[:original_datetime], :media_type => image_data[:media_type] }) image_record.original_metadata = image_data[:original_metadata].to_hash # Default to "All Rights Reserved" until we find out more about licenses # FIXME: Set the default license in the app config unless image_record.licenses.size > 0 image_record.licenses << Lentil::License.where(:short_name => "ARR").first end image_data[:tags].each {|tag| image_record.tags << Lentil::Tag.where(:name => tag).first_or_create} user_record.save! image_record.save! image_record end
ruby
{ "resource": "" }
q19786
Lentil.InstagramHarvester.save_instagram_load
train
def save_instagram_load(instagram_load, raise_dupes=false) # Handle collections of images and individual images images = instagram_load if !images.kind_of?(Array) images = [images] end images.collect {|image| begin save_image(extract_image_data(image)) rescue DuplicateImageError => e raise e if raise_dupes next rescue => e Rails.logger.error e.message puts e.message pp image next end }.compact end
ruby
{ "resource": "" }
q19787
Lentil.InstagramHarvester.harvest_image_data
train
def harvest_image_data(image) response = Typhoeus.get(image.large_url(false), followlocation: true) if response.success? raise "Invalid content type: " + response.headers['Content-Type'] unless (response.headers['Content-Type'] == 'image/jpeg') elsif response.timed_out? raise "Request timed out" elsif response.code == 0 raise "Could not get an HTTP response" else raise "HTTP request failed: " + response.code.to_s end response.body end
ruby
{ "resource": "" }
q19788
Lentil.InstagramHarvester.harvest_video_data
train
def harvest_video_data(image) response = Typhoeus.get(image.video_url, followlocation: true) if response.success? raise "Invalid content type: " + response.headers['Content-Type'] unless (response.headers['Content-Type'] == 'video/mp4') elsif response.timed_out? raise "Request timed out" elsif response.code == 0 raise "Could not get an HTTP response" else raise "HTTP request failed: " + response.code.to_s end response.body end
ruby
{ "resource": "" }
q19789
Lentil.InstagramHarvester.leave_image_comment
train
def leave_image_comment(image, comment) configure_comment_connection Instagram.client.create_media_comment(image.external_identifier, comment) end
ruby
{ "resource": "" }
q19790
Lentil.PopularityCalculator.calculate_popularity
train
def calculate_popularity(image) # A staff like is worth 10 points if (image.staff_like === false) staff_like_points = 0 else staff_like_points = 10 end # likes have diminishing returns # 10 likes is 13 points # 100 likes is 25 points if image.like_votes_count > 0 like_vote_points = Math::log(image.like_votes_count, 1.5).round else like_vote_points = 0 end # if an image has fewer than 5 battle rounds this is 0 # 5 or more and the points awarded is the win_pct/2 if image.win_pct and image.wins_count + image.losses_count > 4 battle_points = (image.win_pct/1.5).round else battle_points = 0 end battle_points + like_vote_points + staff_like_points end
ruby
{ "resource": "" }
q19791
Lentil.PopularityCalculator.update_image_popularity_score
train
def update_image_popularity_score(image_to_update = :all) def get_score_write_to_db(image) popularity_score = calculate_popularity(image) image.update_attribute(:popular_score, popularity_score) end if image_to_update == :all images = Lentil::Image.find(image_to_update) images.each do |image| get_score_write_to_db(image) end elsif image_to_update.kind_of?(Integer) image = Lentil::Image.find(image_to_update) get_score_write_to_db(image) end end
ruby
{ "resource": "" }
q19792
USPS::Request.CityAndStateLookup.build
train
def build super do |builder| @zip_codes.each_with_index do |zip, i| builder.tag!('ZipCode', :ID => i) do builder.tag!('Zip5', zip) end end end end
ruby
{ "resource": "" }
q19793
Yaks.Configurable.def_set
train
def def_set(*method_names) method_names.each do |method_name| define_singleton_method method_name do |arg = Undefined, &block| if arg.equal?(Undefined) unless block raise ArgumentError, "setting #{method_name}: no value and no block given" end self.config = config.with(method_name => block) else if block raise ArgumentError, "ambiguous invocation setting #{method_name}: give either a value or a block, not both." end self.config = config.with(method_name => arg) end end end end
ruby
{ "resource": "" }
q19794
Yaks.Configurable.def_forward
train
def def_forward(mappings, *names) if mappings.instance_of? Hash mappings.each do |method_name, target| define_singleton_method method_name do |*args, &block| self.config = config.public_send(target, *args, &block) end end else def_forward([mappings, *names].map{|name| {name => name}}.inject(:merge)) end end
ruby
{ "resource": "" }
q19795
Yaks.Configurable.def_add
train
def def_add(name, options) old_verbose, $VERBOSE = $VERBOSE, false # skip method redefinition warning define_singleton_method name do |*args, &block| defaults = options.fetch(:defaults, {}) klass = options.fetch(:create) if args.last.instance_of?(Hash) args[-1] = defaults.merge(args[-1]) else args << defaults end self.config = config.append_to( options.fetch(:append_to), klass.create(*args, &block) ) end ensure $VERBOSE = old_verbose end
ruby
{ "resource": "" }
q19796
Yaks.DefaultPolicy.derive_mapper_from_collection
train
def derive_mapper_from_collection(collection) if m = collection.first name = "#{m.class.name.split('::').last}CollectionMapper" begin return @options[:namespace].const_get(name) rescue NameError # rubocop:disable Lint/HandleExceptions end end begin return @options[:namespace].const_get(:CollectionMapper) rescue NameError # rubocop:disable Lint/HandleExceptions end CollectionMapper end
ruby
{ "resource": "" }
q19797
Yaks.DefaultPolicy.derive_mapper_from_item
train
def derive_mapper_from_item(item) klass = item.class namespaces = klass.name.split("::")[0...-1] begin return build_mapper_class(namespaces, klass) rescue NameError klass = next_class_for_lookup(item, namespaces, klass) retry if klass end raise_mapper_not_found(item) end
ruby
{ "resource": "" }
q19798
Mongoid.Tree.root
train
def root if parent_ids.present? base_class.find(parent_ids.first) else self.root? ? self : self.parent.root end end
ruby
{ "resource": "" }
q19799
Mongoid.Tree.nullify_children
train
def nullify_children children.each do |c| c.parent = c.parent_id = nil c.save end end
ruby
{ "resource": "" }