_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q21500
Spark.RDD.subtract
train
def subtract(other, num_partitions=nil) mapping_function = 'lambda{|x| [x,nil]}' self.map(mapping_function) .subtract_by_key(other.map(mapping_function), num_partitions) .keys end
ruby
{ "resource": "" }
q21501
Spark.RDD.sort_by
train
def sort_by(key_function=nil, ascending=true, num_partitions=nil) key_function ||= 'lambda{|x| x}' num_partitions ||= default_reduce_partitions command_klass = Spark::Command::SortByKey # Allow spill data to disk due to memory limit # spilling = config['spark.shuffle.spill'] || false spilling = false memory = '' # Set spilling to false if worker has unlimited memory if memory.empty? spilling = false memory = nil else memory = to_memory_size(memory) end # Sorting should do one worker if num_partitions == 1 rdd = self rdd = rdd.coalesce(1) if partitions_size > 1 return rdd.new_rdd_from_command(command_klass, key_function, ascending, spilling, memory, serializer) end # Compute boundary of collection # Collection should be evenly distributed # 20.0 is from scala RangePartitioner (for roughly balanced output partitions) count = self.count sample_size = num_partitions * 20.0 fraction = [sample_size / [count, 1].max, 1.0].min samples = self.sample(false, fraction, 1).map(key_function).collect samples.sort! # Reverse is much faster than reverse sort_by samples.reverse! if !ascending # Determine part bounds bounds = determine_bounds(samples, num_partitions) shuffled = _partition_by(num_partitions, Spark::Command::PartitionBy::Sorting, key_function, bounds, ascending, num_partitions) shuffled.new_rdd_from_command(command_klass, key_function, ascending, spilling, memory, serializer) end
ruby
{ "resource": "" }
q21502
Spark.RDD._reduce
train
def _reduce(klass, seq_op, comb_op, zero_value=nil) if seq_op.nil? # Partitions are already reduced rdd = self else rdd = new_rdd_from_command(klass, seq_op, zero_value) end # Send all results to one worker and combine results rdd = rdd.coalesce(1).compact # Add the same function to new RDD comm = rdd.add_command(klass, comb_op, zero_value) comm.deserializer = @command.serializer # Value is returned in array PipelinedRDD.new(rdd, comm).collect[0] end
ruby
{ "resource": "" }
q21503
Spark.RDD._combine_by_key
train
def _combine_by_key(combine, merge, num_partitions) num_partitions ||= default_reduce_partitions # Combine key combined = new_rdd_from_command(combine.shift, *combine) # Merge items shuffled = combined.partition_by(num_partitions) merge_comm = shuffled.add_command(merge.shift, *merge) PipelinedRDD.new(shuffled, merge_comm) end
ruby
{ "resource": "" }
q21504
Spark.Logger.disable
train
def disable jlogger.setLevel(level_off) JLogger.getLogger('org').setLevel(level_off) JLogger.getLogger('akka').setLevel(level_off) JLogger.getRootLogger.setLevel(level_off) end
ruby
{ "resource": "" }
q21505
Spark.Context.accumulator
train
def accumulator(value, accum_param=:+, zero_value=0) Spark::Accumulator.new(value, accum_param, zero_value) end
ruby
{ "resource": "" }
q21506
Spark.Context.parallelize
train
def parallelize(data, num_slices=nil, serializer=nil) num_slices ||= default_parallelism serializer ||= default_serializer serializer.check_each(data) # Through file file = Tempfile.new('to_parallelize', temp_dir) serializer.dump_to_io(data, file) file.close # not unlink jrdd = RubyRDD.readRDDFromFile(jcontext, file.path, num_slices) Spark::RDD.new(jrdd, self, serializer) ensure file && file.unlink end
ruby
{ "resource": "" }
q21507
Spark.Context.run_job
train
def run_job(rdd, f, partitions=nil, allow_local=false) run_job_with_command(rdd, partitions, allow_local, Spark::Command::MapPartitions, f) end
ruby
{ "resource": "" }
q21508
Spark.Context.run_job_with_command
train
def run_job_with_command(rdd, partitions, allow_local, command, *args) if !partitions.nil? && !partitions.is_a?(Array) raise Spark::ContextError, 'Partitions must be nil or Array' end partitions_size = rdd.partitions_size # Execute all parts if partitions.nil? partitions = (0...partitions_size).to_a end # Can happend when you use coalesce partitions.delete_if {|part| part >= partitions_size} # Rjb represent Fixnum as Integer but Jruby as Long partitions = to_java_array_list(convert_to_java_int(partitions)) # File for result file = Tempfile.new('collect', temp_dir) mapped = rdd.new_rdd_from_command(command, *args) RubyRDD.runJob(rdd.context.sc, mapped.jrdd, partitions, allow_local, file.path) mapped.collect_from_file(file) end
ruby
{ "resource": "" }
q21509
Spark.StatCounter.merge
train
def merge(other) if other.is_a?(Spark::StatCounter) merge_stat_counter(other) elsif other.respond_to?(:each) merge_array(other) else merge_value(other) end self end
ruby
{ "resource": "" }
q21510
Caze.ClassMethods.raise_use_case_error
train
def raise_use_case_error(use_case, error) name = error.class.name.split('::').last klass = define_use_case_error(use_case, name) wrapped = klass.new(error.message) wrapped.set_backtrace(error.backtrace) raise wrapped end
ruby
{ "resource": "" }
q21511
SchemaEvolutionManager.Db.bootstrap!
train
def bootstrap! scripts = Scripts.new(self, Scripts::BOOTSTRAP_SCRIPTS) dir = File.join(Library.base_dir, "scripts") scripts.each_pending(dir) do |filename, path| psql_file(filename, path) scripts.record_as_run!(filename) end end
ruby
{ "resource": "" }
q21512
SchemaEvolutionManager.Db.psql_command
train
def psql_command(sql_command) Preconditions.assert_class(sql_command, String) command = "psql --no-align --tuples-only --no-psqlrc --command \"%s\" %s" % [sql_command, @url] Library.system_or_error(command) end
ruby
{ "resource": "" }
q21513
SchemaEvolutionManager.MigrationFile.parse_attribute_values
train
def parse_attribute_values values = [] each_property do |name, value| values << AttributeValue.new(name, value) end DEFAULTS.each do |default| if values.find { |v| v.attribute.name == default.attribute.name }.nil? values << default end end values end
ruby
{ "resource": "" }
q21514
SchemaEvolutionManager.Scripts.each_pending
train
def each_pending(dir) files = {} Scripts.all(dir).each do |path| name = File.basename(path) files[name] = path end scripts_previously_run(files.keys).each do |filename| files.delete(filename) end files.keys.sort.each do |filename| ## We have to recheck if this script is still pending. Some ## upgrade scripts may modify the scripts table themselves. This ## is actually useful in cases like when we migrated gilt from ## util_schema => schema_evolution_manager schema if !has_run?(filename) yield filename, files[filename] end end end
ruby
{ "resource": "" }
q21515
SchemaEvolutionManager.Scripts.has_run?
train
def has_run?(filename) if @db.schema_schema_evolution_manager_exists? query = "select count(*) from %s.%s where filename = '%s'" % [Db.schema_name, @table_name, filename] @db.psql_command(query).to_i > 0 else false end end
ruby
{ "resource": "" }
q21516
SchemaEvolutionManager.Scripts.record_as_run!
train
def record_as_run!(filename) Preconditions.check_state(filename.match(/^\d\d\d\d\d\d+\-\d\d\d\d\d\d\.sql$/), "Invalid filename[#{filename}]. Must be like: 20120503-173242.sql") command = "insert into %s.%s (filename) select '%s' where not exists (select 1 from %s.%s where filename = '%s')" % [Db.schema_name, @table_name, filename, Db.schema_name, @table_name, filename] @db.psql_command(command) end
ruby
{ "resource": "" }
q21517
SchemaEvolutionManager.Scripts.scripts_previously_run
train
def scripts_previously_run(scripts) if scripts.empty? || !@db.schema_schema_evolution_manager_exists? [] else sql = "select filename from %s.%s where filename in (%s)" % [Db.schema_name, @table_name, "'" + scripts.join("', '") + "'"] @db.psql_command(sql).strip.split end end
ruby
{ "resource": "" }
q21518
SchemaEvolutionManager.InstallTemplate.generate
train
def generate template = Template.new template.add('timestamp', Time.now.to_s) template.add('lib_dir', @lib_dir) template.add('bin_dir', @bin_dir) template.parse(TEMPLATE) end
ruby
{ "resource": "" }
q21519
Wp2txt.Runner.fill_buffer
train
def fill_buffer while true do begin new_lines = @file_pointer.read(10485760) rescue => e return nil end return nil unless new_lines # temp_buf is filled with text split by "\n" temp_buf = [] ss = StringScanner.new(new_lines) while ss.scan(/.*?\n/m) temp_buf << ss[0] end temp_buf << ss.rest unless ss.eos? new_first_line = temp_buf.shift if new_first_line[-1, 1] == "\n" # new_first_line.index("\n") @buffer.last << new_first_line @buffer << "" else @buffer.last << new_first_line end @buffer += temp_buf unless temp_buf.empty? if @buffer.last[-1, 1] == "\n" # @buffer.last.index("\n") @buffer << "" end break if @buffer.size > 1 end return true end
ruby
{ "resource": "" }
q21520
LanguageFilter.Filter.replace
train
def replace(word) case @replacement when :vowels then word.gsub(/[aeiou]/i, '*') when :stars then '*' * word.size when :nonconsonants then word.gsub(/[^bcdfghjklmnpqrstvwxyz]/i, '*') when :default, :garbled then '$@!#%' else raise LanguageFilter::UnknownReplacement.new("#{@replacement} is not a known replacement type.") end end
ruby
{ "resource": "" }
q21521
Jekyll.StaticFile.to_page
train
def to_page page = Jekyll::Page.new(@site, @base, @dir, @name) page.data["permalink"] = File.dirname(url) + "/" page end
ruby
{ "resource": "" }
q21522
AppleSystemStatus.Crawler.perform
train
def perform(country: nil, title: nil) @session.visit(apple_url(country)) response = { title: @session.find(".section-date .date-copy").text.strip, services: [], } MAX_RETRY_COUNT.times do services = fetch_services if services.empty? # wait until the page is fully loaded sleep 1 else response[:services] = services break end end raise "Not found services" if response[:services].empty? unless self.class.blank_string?(title) response[:services].select! { |service| service[:title] == title } end response[:services].sort_by! { |service| service[:title] } response end
ruby
{ "resource": "" }
q21523
FioAPI.List.fetch_and_deserialize_response
train
def fetch_and_deserialize_response(path) self.request = FioAPI::Request.get(path, parser: ListResponseDeserializer) self.response = request.parsed_response request end
ruby
{ "resource": "" }
q21524
Archangel.FlashHelper.flash_class_for
train
def flash_class_for(flash_type) flash_type = flash_type.to_s.downcase.parameterize { success: "success", error: "danger", alert: "warning", notice: "info" }.fetch(flash_type.to_sym, flash_type) end
ruby
{ "resource": "" }
q21525
Momentum::OpsWorks.Deployer.execute_recipe!
train
def execute_recipe!(stack_name, layer, recipe, app_name = Momentum.config[:app_base_name]) raise "No recipe provided" unless recipe stack = Momentum::OpsWorks.get_stack(@ow, stack_name) app = Momentum::OpsWorks.get_app(@ow, stack, app_name) layer_names = layer ? [layer] : Momentum.config[:app_layers] layers = Momentum::OpsWorks.get_layers(@ow, stack, layer_names) instance_ids = layers.inject([]) { |ids, l| ids + Momentum::OpsWorks.get_online_instance_ids(@ow, layer_id: l[:layer_id]) } raise 'No online instances found!' if instance_ids.empty? @ow.create_deployment( stack_id: stack[:stack_id], app_id: app[:app_id], command: { name: 'execute_recipes', args: { 'recipes' => [recipe.to_s] } }, instance_ids: instance_ids ) end
ruby
{ "resource": "" }
q21526
Fix.On.it
train
def it(*, &spec) i = It.new(described, challenges, helpers) result = i.verify(&spec) if configuration.fetch(:verbose, true) print result.to_char(configuration.fetch(:color, false)) end results << result end
ruby
{ "resource": "" }
q21527
Fix.On.on
train
def on(method_name, *args, &block) o = On.new(described, results, (challenges + [Defi.send(method_name, *args)]), helpers.dup, configuration) o.instance_eval(&block) end
ruby
{ "resource": "" }
q21528
Fix.On.context
train
def context(*, &block) o = On.new(described, [], challenges, helpers.dup, configuration) results.concat(Aw.fork! { o.instance_eval(&block) }) end
ruby
{ "resource": "" }
q21529
Emittance.Watcher.watch
train
def watch(identifier, callback_method = nil, **params, &callback) if callback _dispatcher(params).register identifier, params, &callback else _dispatcher(params).register_method_call identifier, self, callback_method, params end end
ruby
{ "resource": "" }
q21530
Archangel.RenderService.call
train
def call liquid = ::Liquid::Template.parse(template) liquid.send(:render, stringify_assigns, liquid_options).html_safe end
ruby
{ "resource": "" }
q21531
Archangel.ApplicationHelper.frontend_resource_path
train
def frontend_resource_path(resource) permalink_path = proc do |permalink| archangel.frontend_page_path(permalink).gsub("%2F", "/") end return permalink_path.call(resource) unless resource.class == Page return archangel.frontend_root_path if resource.homepage? permalink_path.call(resource.permalink) end
ruby
{ "resource": "" }
q21532
Seoshop.Client.get
train
def get(url, params = {}) params = params.inject({}){|memo,(k,v)| memo[k.to_s] = v; memo} preform(url, :get, params: params) do return connection.get(url, params) end end
ruby
{ "resource": "" }
q21533
Seoshop.Client.post
train
def post(url, params) params = convert_hash_keys(params) preform(url, :post, params: params) do return connection.post(url, params) end end
ruby
{ "resource": "" }
q21534
Seoshop.Client.put
train
def put(url, params) params = convert_hash_keys(params) preform(url, :put, params: params) do return connection.put(url, params) end end
ruby
{ "resource": "" }
q21535
Archangel.LiquidView.render
train
def render(template, local_assigns = {}) default_controller.headers["Content-Type"] ||= "text/html; charset=utf-8" assigns = default_assigns(local_assigns) options = { registers: default_registers } Archangel::RenderService.call(template, assigns, options) end
ruby
{ "resource": "" }
q21536
BibTeX.Lexer.push
train
def push(value) case value[0] when :CONTENT, :STRING_LITERAL value[1].gsub!(/\n\s*/, ' ') if strip_line_breaks? if !@stack.empty? && value[0] == @stack[-1][0] @stack[-1][1] << value[1] else @stack.push(value) end when :ERROR @stack.push(value) if @include_errors leave_object when :META_CONTENT @stack.push(value) if @include_meta_content else @stack.push(value) end self end
ruby
{ "resource": "" }
q21537
BibTeX.Lexer.analyse
train
def analyse(string = nil) raise(ArgumentError, 'Lexer: failed to start analysis: no source given!') unless string || @scanner self.data = string || @scanner.string until @scanner.eos? send("parse_#{MODE[@mode]}") end push([false, '$end']) end
ruby
{ "resource": "" }
q21538
BibTeX.Lexer.enter_object
train
def enter_object @brace_level = 0 push [:AT,'@'] case when @scanner.scan(Lexer.patterns[:string]) @mode = @active_object = :string push [:STRING, @scanner.matched] when @scanner.scan(Lexer.patterns[:preamble]) @mode = @active_object = :preamble push [:PREAMBLE, @scanner.matched] when @scanner.scan(Lexer.patterns[:comment]) @mode = @active_object = :comment push [:COMMENT, @scanner.matched] when @scanner.scan(Lexer.patterns[:entry]) @mode = @active_object = :entry push [:NAME, @scanner.matched] # TODO: DRY - try to parse key if @scanner.scan(Lexer.patterns[:lbrace]) @brace_level += 1 push([:LBRACE,'{']) @mode = :content if @brace_level > 1 || @brace_level == 1 && active?(:comment) if @scanner.scan(Lexer.patterns[allow_missing_keys? ? :optional_key : :key]) push [:KEY, @scanner.matched.chop.strip] end end else error_unexpected_object end end
ruby
{ "resource": "" }
q21539
BibTeX.Entry.initialize_copy
train
def initialize_copy(other) @fields = {} self.type = other.type self.key = other.key add(other.fields) end
ruby
{ "resource": "" }
q21540
BibTeX.Entry.key=
train
def key=(key) key = key.to_s if registered? bibliography.entries.delete(@key) key = register(key) end @key = key rescue => e raise BibTeXError, "failed to set key to #{key.inspect}: #{e.message}" end
ruby
{ "resource": "" }
q21541
BibTeX.Entry.provide
train
def provide(name) return nil unless name.respond_to?(:to_sym) name = name.to_sym fields[name] || fields[aliases[name]] end
ruby
{ "resource": "" }
q21542
BibTeX.Entry.field_names
train
def field_names(filter = [], include_inherited = true) names = fields.keys if include_inherited && has_parent? names.concat(inherited_fields) end unless filter.empty? names = names & filter.map(&:to_sym) end names.sort! names end
ruby
{ "resource": "" }
q21543
BibTeX.Entry.inherited_fields
train
def inherited_fields return [] unless has_parent? names = parent.fields.keys - fields.keys names.concat(parent.aliases.reject { |k,v| !parent.has_field?(v) }.keys) names.sort! names end
ruby
{ "resource": "" }
q21544
BibTeX.Entry.rename!
train
def rename!(*arguments) Hash[*arguments.flatten].each_pair do |from,to| if fields.has_key?(from) && !fields.has_key?(to) fields[to] = fields[from] fields.delete(from) end end self end
ruby
{ "resource": "" }
q21545
BibTeX.Entry.valid?
train
def valid? REQUIRED_FIELDS[type].all? do |f| f.is_a?(Array) ? !(f & fields.keys).empty? : !fields[f].nil? end end
ruby
{ "resource": "" }
q21546
BibTeX.Entry.digest
train
def digest(filter = []) names = field_names(filter) digest = type.to_s names.zip(values_at(*names)).each do |key, value| digest << "|#{key}:#{value}" end digest = yield(digest, self) if block_given? digest end
ruby
{ "resource": "" }
q21547
BibTeX.Entry.added_to_bibliography
train
def added_to_bibliography(bibliography) super @key = register(key) [:parse_names, :parse_months].each do |parser| send(parser) if bibliography.options[parser] end if bibliography.options.has_key?(:filter) [*bibliography.options[:filter]].each do |filter| convert!(filter) end end self end
ruby
{ "resource": "" }
q21548
BibTeX.Entry.register
train
def register(key) return nil if bibliography.nil? k = key.dup k.succ! while bibliography.has_key?(k) bibliography.entries[k] = self k end
ruby
{ "resource": "" }
q21549
BibTeX.Entry.parse_names
train
def parse_names strings = bibliography ? bibliography.strings.values : [] NAME_FIELDS.each do |key| if name = fields[key] name = name.dup.replace(strings).join.to_name fields[key] = name unless name.nil? end end self end
ruby
{ "resource": "" }
q21550
BibTeX.Entry.convert!
train
def convert!(*filters) filters = filters.flatten.map { |f| Filters.resolve!(f) } fields.each_pair do |k, v| (!block_given? || yield(k, v)) ? v.convert!(*filters) : v end self end
ruby
{ "resource": "" }
q21551
BibTeX.Entry.default_key
train
def default_key k = names[0] k = k.respond_to?(:family) ? k.family : k.to_s k = BibTeX.transliterate(k).gsub(/["']/, '') k = k[/[A-Za-z-]+/] || 'unknown' k << (year.to_s[/\d+/] || '-') k << 'a' k.downcase! k end
ruby
{ "resource": "" }
q21552
BibTeX.Bibliography.initialize_copy
train
def initialize_copy(other) @options = other.options.dup @errors = other.errors.dup @data, @strings = [], {} @entries = Hash.new { |h,k| h.fetch(k.to_s, nil) } other.each do |element| add element.dup end self end
ruby
{ "resource": "" }
q21553
BibTeX.Bibliography.add
train
def add(*arguments) Element.parse(arguments.flatten, @options).each do |element| data << element.added_to_bibliography(self) end self end
ruby
{ "resource": "" }
q21554
BibTeX.Bibliography.save_to
train
def save_to(path, options = {}) options[:quotes] ||= %w({ }) File.open(path, 'w:UTF-8') do |f| f.write(to_s(options)) end self end
ruby
{ "resource": "" }
q21555
BibTeX.Bibliography.delete
train
def delete(*arguments, &block) objects = q(*arguments, &block).map { |o| o.removed_from_bibliography(self) } @data = @data - objects objects.length == 1 ? objects[0] : objects end
ruby
{ "resource": "" }
q21556
BibTeX.Bibliography.extend_initials!
train
def extend_initials! groups = Hash.new do |h,k| h[k] = { :prototype => nil, :names => [] } end # group names together names.each do |name| group = groups[name.sort_order(:initials => true).downcase] group[:names] << name if group[:prototype].nil? || group[:prototype].first.to_s.length < name.first.to_s.length group[:prototype] = name end end # extend all names in group to prototype groups.each_value do |group| group[:names].each do |name| name.set(group[:prototype]) end end self end
ruby
{ "resource": "" }
q21557
BibTeX.Element.matches?
train
def matches?(query) return true if query.nil? || query.respond_to?(:empty?) && query.empty? case query when Symbol query.to_s == id.to_s when Element query == self when Regexp to_s.match(query) when /^\/(.+)\/$/ to_s.match(Regexp.new($1)) when /@(\*|\w+)(?:\[([^\]]*)\])?/ query.scan(/(!)?@(\*|\w+)(?:\[([^\]]*)\])?/).any? do |non, type, condition| if (non ? !has_type?(type) : has_type?(type)) if condition.nil? || condition.empty? true else condition.to_s.split(/\s*\|\|\s*/).any? do |conditions| meets_all? conditions.split(/\s*(?:,|&&)\s*/) end end end end else id.to_s == query end end
ruby
{ "resource": "" }
q21558
BibTeX.Name.set
train
def set(attributes = {}) attributes.each_pair do |key, value| send("#{key}=", value) if respond_to?(key) end self end
ruby
{ "resource": "" }
q21559
BibTeX.Name.extend_initials
train
def extend_initials(with_first, for_last) rename_if :first => with_first do |name| if name.last == for_last mine = name.initials.split(/\.[^[:alpha:]]*/) other = initials(with_first).split(/\.[^[:alpha:]]*/) mine == other || mine.length < other.length && mine == other[0, mine.length] end end end
ruby
{ "resource": "" }
q21560
BibTeX.Name.rename_if
train
def rename_if(attributes, conditions = {}) if block_given? set(attributes) if yield self else set(attributes) if conditions.all? do |key, value| respond_to?(key) && send(key) == value end end self end
ruby
{ "resource": "" }
q21561
Assert.Context.assert
train
def assert(assertion, desc = nil) if assertion pass else what = if block_given? yield else "Failed assert: assertion was "\ "`#{Assert::U.show(assertion, __assert_config__)}`." end fail(fail_message(desc, what)) end end
ruby
{ "resource": "" }
q21562
Assert.Context.pass
train
def pass(pass_msg = nil) if @__assert_pending__ == 0 capture_result(Assert::Result::Pass, pass_msg) else capture_result(Assert::Result::Fail, "Pending pass (make it "\ "not pending)") end end
ruby
{ "resource": "" }
q21563
Assert.Context.fail
train
def fail(message = nil) if @__assert_pending__ == 0 if halt_on_fail? raise Result::TestFailure, message || "" else capture_result(Assert::Result::Fail, message || "") end else if halt_on_fail? raise Result::TestSkipped, "Pending fail: #{message || ""}" else capture_result(Assert::Result::Skip, "Pending fail: #{message || ""}") end end end
ruby
{ "resource": "" }
q21564
ResqueUnit.Scheduler.enqueue_in
train
def enqueue_in(number_of_seconds_from_now, klass, *args) enqueue_at(Time.now + number_of_seconds_from_now, klass, *args) end
ruby
{ "resource": "" }
q21565
ResqueUnit.Helpers.decode
train
def decode(object) return unless object if defined? Yajl begin Yajl::Parser.parse(object, :check_utf8 => false) rescue Yajl::ParseError end else begin JSON.parse(object) rescue JSON::ParserError end end end
ruby
{ "resource": "" }
q21566
ResqueUnit.Helpers.constantize
train
def constantize(camel_cased_word) camel_cased_word = camel_cased_word.to_s if camel_cased_word.include?('-') camel_cased_word = classify(camel_cased_word) end names = camel_cased_word.split('::') names.shift if names.empty? || names.first.empty? constant = Object names.each do |name| constant = constant.const_get(name) || constant.const_missing(name) end constant end
ruby
{ "resource": "" }
q21567
Unitwise.Term.atom=
train
def atom=(value) value.is_a?(Atom) ? super(value) : super(Atom.find(value.to_s)) end
ruby
{ "resource": "" }
q21568
Unitwise.Term.prefix=
train
def prefix=(value) value.is_a?(Prefix) ? super(value) : super(Prefix.find(value.to_s)) end
ruby
{ "resource": "" }
q21569
Unitwise.Term.root_terms
train
def root_terms if terminal? [self] else atom.scale.root_terms.map do |t| self.class.new(:atom => t.atom, :exponent => t.exponent * exponent) end end end
ruby
{ "resource": "" }
q21570
Unitwise.Term.operate
train
def operate(operator, other) exp = operator == '/' ? -1 : 1 if other.respond_to?(:terms) Unit.new(other.terms.map { |t| t ** exp } << self) elsif other.respond_to?(:atom) Unit.new([self, other ** exp]) elsif other.is_a?(Numeric) self.class.new(to_hash.merge(:factor => factor.send(operator, other))) end end
ruby
{ "resource": "" }
q21571
Unitwise.Base.to_s
train
def to_s(mode = :primary_code) res = send(mode) || primary_code res.respond_to?(:each) ? res.first.to_s : res.to_s end
ruby
{ "resource": "" }
q21572
Unitwise.Atom.scale=
train
def scale=(attrs) @scale = if attrs[:function_code] Functional.new(attrs[:value], attrs[:unit_code], attrs[:function_code]) else Scale.new(attrs[:value], attrs[:unit_code]) end end
ruby
{ "resource": "" }
q21573
Unitwise.Atom.validate!
train
def validate! missing_properties = %i{primary_code names scale}.select do |prop| val = liner_get(prop) val.nil? || (val.respond_to?(:empty) && val.empty?) end if !missing_properties.empty? missing_list = missing_properties.join(',') raise Unitwise::DefinitionError, "Atom has missing properties: #{missing_list}." end msg = "Atom definition could not be resolved. Ensure that it is a base " \ "unit or is defined relative to existing units." begin !scalar.nil? && !magnitude.nil? || raise(Unitwise::DefinitionError, msg) rescue Unitwise::ExpressionError raise Unitwise::DefinitionError, msg end end
ruby
{ "resource": "" }
q21574
Unitwise.Compatible.composition
train
def composition root_terms.reduce(SignedMultiset.new) do |s, t| s.increment(t.atom.dim, t.exponent) if t.atom s end end
ruby
{ "resource": "" }
q21575
Unitwise.Compatible.composition_string
train
def composition_string composition.sort.map do |k, v| v == 1 ? k.to_s : "#{k}#{v}" end.join('.') end
ruby
{ "resource": "" }
q21576
Unitwise.Unit.terms
train
def terms unless frozen? unless @terms decomposer = Expression.decompose(@expression) @mode = decomposer.mode @terms = decomposer.terms end freeze end @terms end
ruby
{ "resource": "" }
q21577
Unitwise.Unit.expression
train
def expression(mode=nil) if @expression && (mode.nil? || mode == self.mode) @expression else Expression.compose(terms, mode || self.mode) end end
ruby
{ "resource": "" }
q21578
Unitwise.Unit.scalar
train
def scalar(magnitude = 1) terms.reduce(1) do |prod, term| prod * term.scalar(magnitude) end end
ruby
{ "resource": "" }
q21579
Unitwise.Unit.**
train
def **(other) if other.is_a?(Numeric) self.class.new(terms.map { |t| t ** other }) else fail TypeError, "Can't raise #{self} to #{other}." end end
ruby
{ "resource": "" }
q21580
Unitwise.Unit.operate
train
def operate(operator, other) exp = operator == '/' ? -1 : 1 if other.respond_to?(:terms) self.class.new(terms + other.terms.map { |t| t ** exp }) elsif other.respond_to?(:atom) self.class.new(terms << other ** exp) elsif other.is_a?(Numeric) self.class.new(terms.map { |t| t.send(operator, other) }) end end
ruby
{ "resource": "" }
q21581
Unitwise.Measurement.convert_to
train
def convert_to(other_unit) other_unit = Unit.new(other_unit) if compatible_with?(other_unit) new(converted_value(other_unit), other_unit) else fail ConversionError, "Can't convert #{self} to #{other_unit}." end end
ruby
{ "resource": "" }
q21582
Unitwise.Measurement.**
train
def **(other) if other.is_a?(Numeric) new(value ** other, unit ** other) else fail TypeError, "Can't raise #{self} to #{other} power." end end
ruby
{ "resource": "" }
q21583
Unitwise.Measurement.round
train
def round(digits = nil) rounded_value = digits ? value.round(digits) : value.round self.class.new(rounded_value, unit) end
ruby
{ "resource": "" }
q21584
Unitwise.Measurement.method_missing
train
def method_missing(meth, *args, &block) if args.empty? && !block_given? && (match = /\Ato_(\w+)\Z/.match(meth.to_s)) begin convert_to(match[1]) rescue ExpressionError super(meth, *args, &block) end else super(meth, *args, &block) end end
ruby
{ "resource": "" }
q21585
Unitwise.Measurement.converted_value
train
def converted_value(other_unit) if other_unit.special? other_unit.magnitude scalar else scalar / other_unit.scalar end end
ruby
{ "resource": "" }
q21586
Unitwise.Measurement.combine
train
def combine(operator, other) if other.respond_to?(:composition) && compatible_with?(other) new(value.send(operator, other.convert_to(unit).value), unit) end end
ruby
{ "resource": "" }
q21587
Unitwise.Measurement.operate
train
def operate(operator, other) if other.is_a?(Numeric) new(value.send(operator, other), unit) elsif other.respond_to?(:composition) if compatible_with?(other) converted = other.convert_to(unit) new(value.send(operator, converted.value), unit.send(operator, converted.unit)) else new(value.send(operator, other.value), unit.send(operator, other.unit)) end end end
ruby
{ "resource": "" }
q21588
Unitwise.Scale.scalar
train
def scalar(magnitude = value) if special? unit.scalar(magnitude) else Number.rationalize(value) * Number.rationalize(unit.scalar) end end
ruby
{ "resource": "" }
q21589
Unitwise.Scale.magnitude
train
def magnitude(scalar = scalar()) if special? unit.magnitude(scalar) else value * unit.magnitude end end
ruby
{ "resource": "" }
q21590
Unitwise.Scale.to_s
train
def to_s(mode = nil) unit_string = unit.to_s(mode) if unit_string && unit_string != '1' "#{simplified_value} #{unit_string}" else simplified_value.to_s end end
ruby
{ "resource": "" }
q21591
QML.Engine.evaluate
train
def evaluate(str, file = '<in QML::Engine#evaluate>', lineno = 1) evaluate_impl(str, file, lineno).tap do |result| raise result.to_error if result.is_a?(JSObject) && result.error? end end
ruby
{ "resource": "" }
q21592
QML.Component.load_path
train
def load_path(path) path = path.to_s check_error_string do @path = Pathname.new(path) load_path_impl(path) end self end
ruby
{ "resource": "" }
q21593
QML.Signal.emit
train
def emit(*args) if args.size != @arity fail ::ArgumentError ,"wrong number of arguments for signal (#{args.size} for #{@arity})" end @listeners.each do |listener| listener.call(*args) end end
ruby
{ "resource": "" }
q21594
QML.ListModel.moving
train
def moving(range, destination) return if range.count == 0 @access.begin_move(range.min, range.max, destination) ret = yield @access.end_move ret end
ruby
{ "resource": "" }
q21595
QML.ListModel.inserting
train
def inserting(range, &block) return if range.count == 0 @access.begin_insert(range.min, range.max) ret = yield @access.end_insert ret end
ruby
{ "resource": "" }
q21596
QML.ListModel.removing
train
def removing(range, &block) return if range.count == 0 @access.begin_remove(range.min, range.max) ret = yield @access.end_remove ret end
ruby
{ "resource": "" }
q21597
QML.ArrayModel.insert
train
def insert(index, *items) inserting(index ... index + items.size) do @array.insert(index, *items) end self end
ruby
{ "resource": "" }
q21598
QML.JSObject.method_missing
train
def method_missing(method, *args, &block) if method[-1] == '=' # setter key = method.slice(0...-1).to_sym unless has_key?(key) super end self[key] = args[0] else unless has_key?(method) super end prop = self[method] if prop.is_a? JSFunction prop.call_with_instance(self, *args, &block) else prop end end end
ruby
{ "resource": "" }
q21599
ZPNG.Adam7Decoder.convert_coords
train
def convert_coords x,y # optimizing this into one switch/case statement gives # about 1-2% speed increase (ruby 1.9.3p286) if y%2 == 1 # 7th pass: last height/2 full scanlines [x, y/2 + @pass_starts[7]] elsif x%2 == 1 && y%2 == 0 # 6th pass [x/2, y/2 + @pass_starts[6]] elsif x%8 == 0 && y%8 == 0 # 1st pass, starts at 0 [x/8, y/8] elsif x%8 == 4 && y%8 == 0 # 2nd pass [x/8, y/8 + @pass_starts[2]] elsif x%4 == 0 && y%8 == 4 # 3rd pass [x/4, y/8 + @pass_starts[3]] elsif x%4 == 2 && y%4 == 0 # 4th pass [x/4, y/4 + @pass_starts[4]] elsif x%2 == 0 && y%4 == 2 # 5th pass [x/2, y/4 + @pass_starts[5]] else raise "invalid coords" end end
ruby
{ "resource": "" }