_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q11600
HamlLint.Utils.with_environment
train
def with_environment(env) old_env = {} env.each do |var, value| old_env[var] = ENV[var.to_s] ENV[var.to_s] = value end yield ensure old_env.each { |var, value| ENV[var.to_s] = value } end
ruby
{ "resource": "" }
q11601
HamlLint.RakeTask.run_cli
train
def run_cli(task_args) cli_args = parse_args logger = quiet ? HamlLint::Logger.silent : HamlLint::Logger.new(STDOUT) result = HamlLint::CLI.new(logger).run(Array(cli_args) + files_to_lint(task_args)) fail "#{HamlLint::APP_NAME} failed with exit code #{result}" unless result == 0 end
ruby
{ "resource": "" }
q11602
HamlLint.RakeTask.files_to_lint
train
def files_to_lint(task_args) # Note: we're abusing Rake's argument handling a bit here. We call the # first argument `files` but it's actually only the first file--we pull # the rest out of the `extras` from the task arguments. This is so we # can specify an arbitrary list of files separated by commas on the # command line or in a custom task definition. explicit_files = Array(task_args[:files]) + Array(task_args.extras) explicit_files.any? ? explicit_files : files end
ruby
{ "resource": "" }
q11603
Sensu.Daemon.log_notices
train
def log_notices(notices=[], level=:warn) notices.each do |concern| message = concern.delete(:message) @logger.send(level, message, redact_sensitive(concern)) end end
ruby
{ "resource": "" }
q11604
Sensu.Daemon.setup_spawn
train
def setup_spawn @logger.info("configuring sensu spawn", :settings => @settings[:sensu][:spawn]) threadpool_size = @settings[:sensu][:spawn][:limit] + 10 @logger.debug("setting eventmachine threadpool size", :size => threadpool_size) EM::threadpool_size = threadpool_size Spawn.setup(@settings[:sensu][:spawn]) end
ruby
{ "resource": "" }
q11605
Sensu.Utilities.retry_until_true
train
def retry_until_true(wait=0.5, &block) EM::Timer.new(wait) do unless block.call retry_until_true(wait, &block) end end end
ruby
{ "resource": "" }
q11606
Sensu.Utilities.deep_merge
train
def deep_merge(hash_one, hash_two) merged = hash_one.dup hash_two.each do |key, value| merged[key] = case when hash_one[key].is_a?(Hash) && value.is_a?(Hash) deep_merge(hash_one[key], value) when hash_one[key].is_a?(Array) && value.is_a?(Array) (hash_one[key] + value).uniq else value end end merged end
ruby
{ "resource": "" }
q11607
Sensu.Utilities.deep_dup
train
def deep_dup(obj) if obj.class == Hash new_obj = obj.dup new_obj.each do |key, value| new_obj[deep_dup(key)] = deep_dup(value) end new_obj elsif obj.class == Array arr = [] obj.each do |item| arr << deep_dup(item) end arr elsif obj.class == String obj.dup else obj end end
ruby
{ "resource": "" }
q11608
Sensu.Utilities.system_address
train
def system_address ::Socket.ip_address_list.find { |address| address.ipv4? && !address.ipv4_loopback? }.ip_address rescue nil end
ruby
{ "resource": "" }
q11609
Sensu.Utilities.find_attribute_value
train
def find_attribute_value(tree, path, default) attribute = tree[path.shift] if attribute.is_a?(Hash) find_attribute_value(attribute, path, default) else attribute.nil? ? default : attribute end end
ruby
{ "resource": "" }
q11610
Sensu.Utilities.determine_check_cron_time
train
def determine_check_cron_time(check) cron_parser = CronParser.new(check[:cron]) current_time = Time.now next_cron_time = cron_parser.next(current_time) next_cron_time - current_time end
ruby
{ "resource": "" }
q11611
ActiveRecord.LockingExtensions.with_restart_on_deadlock
train
def with_restart_on_deadlock yield rescue ActiveRecord::StatementInvalid => exception if exception.message =~ /deadlock/i || exception.message =~ /database is locked/i ActiveSupport::Notifications.publish('deadlock_restart.double_entry', :exception => exception) raise ActiveRecord::RestartTransaction else raise end end
ruby
{ "resource": "" }
q11612
DoubleEntry.BalanceCalculator.calculate
train
def calculate(account, args = {}) options = Options.new(account, args) relations = RelationBuilder.new(options) lines = relations.build if options.between? || options.code? # from and to or code lookups have to be done via sum Money.new(lines.sum(:amount), account.currency) else # all other lookups can be performed with running balances result = lines. from(lines_table_name(options)). order('id DESC'). limit(1). pluck(:balance) result.empty? ? Money.zero(account.currency) : Money.new(result.first, account.currency) end end
ruby
{ "resource": "" }
q11613
PageObject.PagePopulator.populate_page_with
train
def populate_page_with(data) data.to_h.each do |key, value| populate_section(key, value) if value.respond_to?(:to_h) populate_value(self, key, value) end end
ruby
{ "resource": "" }
q11614
PageObject.Accessors.page_url
train
def page_url(url) define_method("goto") do platform.navigate_to self.page_url_value end define_method('page_url_value') do lookup = url.kind_of?(Symbol) ? self.send(url) : url erb = ERB.new(%Q{#{lookup}}) merged_params = self.class.instance_variable_get("@merged_params") params = merged_params ? merged_params : self.class.params erb.result(binding) end end
ruby
{ "resource": "" }
q11615
PageObject.Accessors.in_frame
train
def in_frame(identifier, frame=nil, &block) frame = frame.nil? ? [] : frame.dup frame << {frame: identifier} block.call(frame) end
ruby
{ "resource": "" }
q11616
PageObject.Accessors.in_iframe
train
def in_iframe(identifier, frame=nil, &block) frame = frame.nil? ? [] : frame.dup frame << {iframe: identifier} block.call(frame) end
ruby
{ "resource": "" }
q11617
PageObject.Accessors.text_field
train
def text_field(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'text_field_for', &block) define_method(name) do return platform.text_field_value_for identifier.clone unless block_given? self.send("#{name}_element").value end define_method("#{name}=") do |value| return platform.text_field_value_set(identifier.clone, value) unless block_given? self.send("#{name}_element").value = value end end
ruby
{ "resource": "" }
q11618
PageObject.Accessors.hidden_field
train
def hidden_field(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'hidden_field_for', &block) define_method(name) do return platform.hidden_field_value_for identifier.clone unless block_given? self.send("#{name}_element").value end end
ruby
{ "resource": "" }
q11619
PageObject.Accessors.text_area
train
def text_area(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'text_area_for', &block) define_method(name) do return platform.text_area_value_for identifier.clone unless block_given? self.send("#{name}_element").value end define_method("#{name}=") do |value| return platform.text_area_value_set(identifier.clone, value) unless block_given? self.send("#{name}_element").value = value end end
ruby
{ "resource": "" }
q11620
PageObject.Accessors.select_list
train
def select_list(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'select_list_for', &block) define_method(name) do return platform.select_list_value_for identifier.clone unless block_given? self.send("#{name}_element").value end define_method("#{name}=") do |value| return platform.select_list_value_set(identifier.clone, value) unless block_given? self.send("#{name}_element").select(value) end define_method("#{name}_options") do element = self.send("#{name}_element") (element && element.options) ? element.options.collect(&:text) : [] end end
ruby
{ "resource": "" }
q11621
PageObject.Accessors.button
train
def button(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'button_for', &block) define_method(name) do return platform.click_button_for identifier.clone unless block_given? self.send("#{name}_element").click end end
ruby
{ "resource": "" }
q11622
PageObject.Accessors.div
train
def div(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'div_for', &block) define_method(name) do return platform.div_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11623
PageObject.Accessors.span
train
def span(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'span_for', &block) define_method(name) do return platform.span_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11624
PageObject.Accessors.table
train
def table(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'table_for', &block) define_method(name) do return platform.table_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11625
PageObject.Accessors.cell
train
def cell(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'cell_for', &block) define_method("#{name}") do return platform.cell_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11626
PageObject.Accessors.row
train
def row(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'row_for', &block) define_method("#{name}") do return platform.row_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11627
PageObject.Accessors.image
train
def image(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'image_for', &block) define_method("#{name}_loaded?") do return platform.image_loaded_for identifier.clone unless block_given? self.send("#{name}_element").loaded? end end
ruby
{ "resource": "" }
q11628
PageObject.Accessors.list_item
train
def list_item(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'list_item_for', &block) define_method(name) do return platform.list_item_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11629
PageObject.Accessors.unordered_list
train
def unordered_list(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'unordered_list_for', &block) define_method(name) do return platform.unordered_list_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11630
PageObject.Accessors.ordered_list
train
def ordered_list(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'ordered_list_for', &block) define_method(name) do return platform.ordered_list_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11631
PageObject.Accessors.h1
train
def h1(name, identifier={:index => 0}, &block) standard_methods(name, identifier,'h1_for', &block) define_method(name) do return platform.h1_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11632
PageObject.Accessors.h2
train
def h2(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'h2_for', &block) define_method(name) do return platform.h2_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11633
PageObject.Accessors.h3
train
def h3(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'h3_for', &block) define_method(name) do return platform.h3_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11634
PageObject.Accessors.h4
train
def h4(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'h4_for', &block) define_method(name) do return platform.h4_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11635
PageObject.Accessors.h5
train
def h5(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'h5_for', &block) define_method(name) do return platform.h5_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11636
PageObject.Accessors.h6
train
def h6(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'h6_for', &block) define_method(name) do return platform.h6_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11637
PageObject.Accessors.paragraph
train
def paragraph(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'paragraph_for', &block) define_method(name) do return platform.paragraph_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11638
PageObject.Accessors.file_field
train
def file_field(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'file_field_for', &block) define_method("#{name}=") do |value| return platform.file_field_value_set(identifier.clone, value) unless block_given? self.send("#{name}_element").value = value end end
ruby
{ "resource": "" }
q11639
PageObject.Accessors.label
train
def label(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'label_for', &block) define_method(name) do return platform.label_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11640
PageObject.Accessors.area
train
def area(name, identifier={:index => 0}, &block) standard_methods(name, identifier, 'area_for', &block) define_method(name) do return platform.click_area_for identifier.clone unless block_given? self.send("#{name}_element").click end end
ruby
{ "resource": "" }
q11641
PageObject.Accessors.b
train
def b(name, identifier={:index => 0}, &block) standard_methods(name, identifier,'b_for', &block) define_method(name) do return platform.b_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11642
PageObject.Accessors.i
train
def i(name, identifier={:index => 0}, &block) standard_methods(name, identifier,'i_for', &block) define_method(name) do return platform.i_text_for identifier.clone unless block_given? self.send("#{name}_element").text end end
ruby
{ "resource": "" }
q11643
PageObject.Accessors.element
train
def element(name, tag=:element, identifier={ :index => 0 }, &block) # # sets tag as element if not defined # if tag.is_a?(Hash) identifier = tag tag = :element end standard_methods(name, identifier, 'element_for', &block) define_method("#{name}") do element = self.send("#{name}_element") %w(Button TextField Radio Hidden CheckBox FileField).each do |klass| next unless element.element.class.to_s == "Watir::#{klass}" self.class.send(klass.gsub(/(.)([A-Z])/,'\1_\2').downcase, name, identifier, &block) return self.send name end element.text end define_method("#{name}_element") do return call_block(&block) if block_given? platform.element_for(tag, identifier.clone) end define_method("#{name}?") do self.send("#{name}_element").exists? end define_method("#{name}=") do |value| element = self.send("#{name}_element") klass = case element.element when Watir::TextField 'text_field' when Watir::TextArea 'text_area' when Watir::Select 'select_list' when Watir::FileField 'file_field' else raise "Can not set a #{element.element} element with #=" end self.class.send(klass, name, identifier, &block) self.send("#{name}=", value) end end
ruby
{ "resource": "" }
q11644
PageObject.Accessors.elements
train
def elements(name, tag=:element, identifier={:index => 0}, &block) # # sets tag as element if not defined # if tag.is_a?(Hash) identifier = tag tag = :element end define_method("#{name}_elements") do return call_block(&block) if block_given? platform.elements_for(tag, identifier.clone) end end
ruby
{ "resource": "" }
q11645
PageObject.Accessors.page_section
train
def page_section(name, section_class, identifier) define_method(name) do platform.page_for(identifier, section_class) end end
ruby
{ "resource": "" }
q11646
PageObject.Accessors.page_sections
train
def page_sections(name, section_class, identifier) define_method(name) do platform.pages_for(identifier, section_class) end end
ruby
{ "resource": "" }
q11647
PageObject.PageFactory.on_page
train
def on_page(page_class, params={:using_params => {}}, visit=false, &block) page_class = class_from_string(page_class) if page_class.is_a? String return super(page_class, params, visit, &block) unless page_class.ancestors.include? PageObject merged = page_class.params.merge(params[:using_params]) page_class.instance_variable_set("@merged_params", merged) unless merged.empty? @current_page = page_class.new(@browser, visit) block.call @current_page if block @current_page end
ruby
{ "resource": "" }
q11648
PageObject.PageFactory.if_page
train
def if_page(page_class, params={:using_params => {}},&block) page_class = class_from_string(page_class) if page_class.is_a? String return @current_page unless @current_page.class == page_class on_page(page_class, params, false, &block) end
ruby
{ "resource": "" }
q11649
Oj.EasyHash.method_missing
train
def method_missing(m, *args, &block) if m.to_s.end_with?('=') raise ArgumentError.new("wrong number of arguments (#{args.size} for 1 with #{m}) to method #{m}") if args.nil? or 1 != args.length m = m[0..-2] return store(m.to_s, args[0]) if has_key?(m.to_s) return store(m.to_sym, args[0]) if has_key?(m.to_sym) return store(m, args[0]) else raise ArgumentError.new("wrong number of arguments (#{args.size} for 0 with #{m}) to method #{m}") unless args.nil? or args.empty? return fetch(m, nil) if has_key?(m) return fetch(m.to_s, nil) if has_key?(m.to_s) return fetch(m.to_sym, nil) if has_key?(m.to_sym) end raise NoMethodError.new("undefined method #{m}", m) end
ruby
{ "resource": "" }
q11650
AutoprefixerRails.Processor.process
train
def process(css, opts = {}) opts = convert_options(opts) apply_wrapper = "(function(opts, pluginOpts) {" \ "return eval(process.apply(this, opts, pluginOpts));" \ "})" plugin_opts = params_with_browsers(opts[:from]).merge(opts) process_opts = { from: plugin_opts.delete(:from), to: plugin_opts.delete(:to), map: plugin_opts.delete(:map), } begin result = runtime.call(apply_wrapper, [css, process_opts, plugin_opts]) rescue ExecJS::ProgramError => e contry_error = "BrowserslistError: " \ "Country statistics is not supported " \ "in client-side build of Browserslist" if e.message == contry_error raise "Country statistics is not supported in AutoprefixerRails. " \ "Use Autoprefixer with webpack or other Node.js builder." else raise e end end Result.new(result["css"], result["map"], result["warnings"]) end
ruby
{ "resource": "" }
q11651
AutoprefixerRails.Processor.parse_config
train
def parse_config(config) sections = {"defaults" => []} current = "defaults" config.gsub(/#[^\n]*/, "") .split(/\n/) .map(&:strip) .reject(&:empty?) .each do |line| if IS_SECTION =~ line current = line.match(IS_SECTION)[1].strip sections[current] ||= [] else sections[current] << line end end sections end
ruby
{ "resource": "" }
q11652
AutoprefixerRails.Processor.convert_options
train
def convert_options(opts) converted = {} opts.each_pair do |name, value| if /_/ =~ name name = name.to_s.gsub(/_\w/) { |i| i.delete("_").upcase }.to_sym end value = convert_options(value) if value.is_a? Hash converted[name] = value end converted end
ruby
{ "resource": "" }
q11653
AutoprefixerRails.Processor.find_config
train
def find_config(file) path = Pathname(file).expand_path while path.parent != path config1 = path.join("browserslist") return config1.read if config1.exist? && !config1.directory? config2 = path.join(".browserslistrc") return config2.read if config2.exist? && !config1.directory? path = path.parent end nil end
ruby
{ "resource": "" }
q11654
AutoprefixerRails.Processor.runtime
train
def runtime @runtime ||= begin if ExecJS.eval("typeof Uint8Array") != "function" if ExecJS.runtime.name.start_with?("therubyracer") raise "ExecJS::RubyRacerRuntime is not supported. " \ "Please replace therubyracer with mini_racer " \ "in your Gemfile or use Node.js as ExecJS runtime." else raise "#{ExecJS.runtime.name} runtime does’t support ES6. " \ "Please update or replace your current ExecJS runtime." end end if ExecJS.runtime == ExecJS::Runtimes::Node version = ExecJS.runtime.eval("process.version") first = version.match(/^v(\d+)/)[1].to_i if first < 6 raise "Autoprefixer doesn’t support Node #{version}. Update it." end end ExecJS.compile(build_js) end end
ruby
{ "resource": "" }
q11655
AutoprefixerRails.Processor.read_js
train
def read_js @@js ||= begin root = Pathname(File.dirname(__FILE__)) path = root.join("../../vendor/autoprefixer.js") path.read end end
ruby
{ "resource": "" }
q11656
Licensed.DependencyRecord.save
train
def save(filename) data_to_save = @metadata.merge({ "licenses" => licenses, "notices" => notices }) FileUtils.mkdir_p(File.dirname(filename)) File.write(filename, data_to_save.to_yaml) end
ruby
{ "resource": "" }
q11657
Licensed.Dependency.license_contents
train
def license_contents matched_files.reject { |f| f == package_file } .group_by(&:content) .map { |content, files| { "sources" => license_content_sources(files), "text" => content } } end
ruby
{ "resource": "" }
q11658
Licensed.Dependency.notice_contents
train
def notice_contents Dir.glob(dir_path.join("*")) .grep(LEGAL_FILES_PATTERN) .select { |path| File.file?(path) } .sort # sorted by the path .map { |path| { "sources" => normalize_source_path(path), "text" => File.read(path).rstrip } } .select { |notice| notice["text"].length > 0 } # files with content only end
ruby
{ "resource": "" }
q11659
Licensed.Dependency.license_content_sources
train
def license_content_sources(files) paths = Array(files).map do |file| next file[:uri] if file[:uri] path = dir_path.join(file[:dir], file[:name]) normalize_source_path(path) end paths.join(", ") end
ruby
{ "resource": "" }
q11660
Licensed.AppConfiguration.sources
train
def sources @sources ||= Licensed::Sources::Source.sources .select { |source_class| enabled?(source_class.type) } .map { |source_class| source_class.new(self) } end
ruby
{ "resource": "" }
q11661
Licensed.AppConfiguration.enabled?
train
def enabled?(source_type) # the default is false if any sources are set to true, true otherwise default = !self["sources"].any? { |_, enabled| enabled } self["sources"].fetch(source_type, default) end
ruby
{ "resource": "" }
q11662
Passwordless.ControllerHelpers.authenticate_by_cookie
train
def authenticate_by_cookie(authenticatable_class) key = cookie_name(authenticatable_class) authenticatable_id = cookies.encrypted[key] return unless authenticatable_id authenticatable_class.find_by(id: authenticatable_id) end
ruby
{ "resource": "" }
q11663
Passwordless.ControllerHelpers.sign_in
train
def sign_in(authenticatable) key = cookie_name(authenticatable.class) cookies.encrypted.permanent[key] = {value: authenticatable.id} authenticatable end
ruby
{ "resource": "" }
q11664
Passwordless.ControllerHelpers.sign_out
train
def sign_out(authenticatable_class) key = cookie_name(authenticatable_class) cookies.encrypted.permanent[key] = {value: nil} cookies.delete(key) true end
ruby
{ "resource": "" }
q11665
Datadog.Statsd.count
train
def count(stat, count, opts=EMPTY_OPTIONS) opts = {:sample_rate => opts} if opts.is_a? Numeric send_stats stat, count, COUNTER_TYPE, opts end
ruby
{ "resource": "" }
q11666
Datadog.Statsd.gauge
train
def gauge(stat, value, opts=EMPTY_OPTIONS) opts = {:sample_rate => opts} if opts.is_a? Numeric send_stats stat, value, GAUGE_TYPE, opts end
ruby
{ "resource": "" }
q11667
Datadog.Statsd.histogram
train
def histogram(stat, value, opts=EMPTY_OPTIONS) send_stats stat, value, HISTOGRAM_TYPE, opts end
ruby
{ "resource": "" }
q11668
Datadog.Statsd.set
train
def set(stat, value, opts=EMPTY_OPTIONS) opts = {:sample_rate => opts} if opts.is_a? Numeric send_stats stat, value, SET_TYPE, opts end
ruby
{ "resource": "" }
q11669
Datadog.Statsd.service_check
train
def service_check(name, status, opts=EMPTY_OPTIONS) send_stat format_service_check(name, status, opts) end
ruby
{ "resource": "" }
q11670
Datadog.Statsd.event
train
def event(title, text, opts=EMPTY_OPTIONS) send_stat format_event(title, text, opts) end
ruby
{ "resource": "" }
q11671
JekyllRedirectFrom.Generator.generate_redirect_from
train
def generate_redirect_from(doc) doc.redirect_from.each do |path| page = RedirectPage.redirect_from(doc, path) doc.site.pages << page redirects[page.redirect_from] = page.redirect_to end end
ruby
{ "resource": "" }
q11672
JekyllRedirectFrom.RedirectPage.set_paths
train
def set_paths(from, to) @context ||= context from = ensure_leading_slash(from) data.merge!( "permalink" => from, "redirect" => { "from" => from, "to" => to =~ %r!^https?://! ? to : absolute_url(to), } ) end
ruby
{ "resource": "" }
q11673
Opal.Compiler.compile
train
def compile parse @fragments = re_raise_with_location { process(@sexp).flatten } @fragments << fragment("\n", nil, s(:newline)) unless @fragments.last.code.end_with?("\n") @result = @fragments.map(&:code).join('') end
ruby
{ "resource": "" }
q11674
Opal.Compiler.unique_temp
train
def unique_temp(name) name = name.to_s if name && !name.empty? name = name .to_s .gsub('<=>', '$lt_eq_gt') .gsub('===', '$eq_eq_eq') .gsub('==', '$eq_eq') .gsub('=~', '$eq_tilde') .gsub('!~', '$excl_tilde') .gsub('!=', '$not_eq') .gsub('<=', '$lt_eq') .gsub('>=', '$gt_eq') .gsub('=', '$eq') .gsub('?', '$ques') .gsub('!', '$excl') .gsub('/', '$slash') .gsub('%', '$percent') .gsub('+', '$plus') .gsub('-', '$minus') .gsub('<', '$lt') .gsub('>', '$gt') .gsub(/[^\w\$]/, '$') end unique = (@unique += 1) "#{'$' unless name.start_with?('$')}#{name}$#{unique}" end
ruby
{ "resource": "" }
q11675
Opal.Compiler.process
train
def process(sexp, level = :expr) return fragment('', scope) if sexp.nil? if handler = handlers[sexp.type] return handler.new(sexp, level, self).compile_to_fragments else error "Unsupported sexp: #{sexp.type}" end end
ruby
{ "resource": "" }
q11676
Opal.Compiler.returns
train
def returns(sexp) return returns s(:nil) unless sexp case sexp.type when :undef # undef :method_name always returns nil returns s(:begin, sexp, s(:nil)) when :break, :next, :redo sexp when :yield sexp.updated(:returnable_yield, nil) when :when *when_sexp, then_sexp = *sexp sexp.updated(nil, [*when_sexp, returns(then_sexp)]) when :rescue body_sexp, *resbodies, else_sexp = *sexp resbodies = resbodies.map do |resbody| returns(resbody) end if else_sexp else_sexp = returns(else_sexp) end sexp.updated( nil, [ returns(body_sexp), *resbodies, else_sexp ] ) when :resbody klass, lvar, body = *sexp sexp.updated(nil, [klass, lvar, returns(body)]) when :ensure rescue_sexp, ensure_body = *sexp sexp = sexp.updated(nil, [returns(rescue_sexp), ensure_body]) s(:js_return, sexp) when :begin, :kwbegin # Wrapping last expression with s(:js_return, ...) *rest, last = *sexp sexp.updated(nil, [*rest, returns(last)]) when :while, :until, :while_post, :until_post sexp when :return, :js_return, :returnable_yield sexp when :xstr sexp.updated(nil, [s(:js_return, *sexp.children)]) when :if cond, true_body, false_body = *sexp sexp.updated( nil, [ cond, returns(true_body), returns(false_body) ] ) else s(:js_return, sexp).updated( nil, nil, location: sexp.loc, ) end end
ruby
{ "resource": "" }
q11677
Racc.Parser.on_error
train
def on_error(t, val, vstack) raise ParseError, sprintf("\nparse error on value %s (%s)", val.inspect, token_to_str(t) || '?') end
ruby
{ "resource": "" }
q11678
Racc.Parser.racc_read_token
train
def racc_read_token(t, tok, val) @racc_debug_out.print 'read ' @racc_debug_out.print tok.inspect, '(', racc_token2str(t), ') ' @racc_debug_out.puts val.inspect @racc_debug_out.puts end
ruby
{ "resource": "" }
q11679
Benchmark.Tms.memberwise
train
def memberwise(op, x) case x when Benchmark::Tms Benchmark::Tms.new(utime.__send__(op, x.utime), stime.__send__(op, x.stime), cutime.__send__(op, x.cutime), cstime.__send__(op, x.cstime), real.__send__(op, x.real) ) else Benchmark::Tms.new(utime.__send__(op, x), stime.__send__(op, x), cutime.__send__(op, x), cstime.__send__(op, x), real.__send__(op, x) ) end end
ruby
{ "resource": "" }
q11680
Opal.Config.config_option
train
def config_option(name, default_value, options = {}) compiler = options.fetch(:compiler_option, nil) valid_values = options.fetch(:valid_values, [true, false]) config_options[name] = { default: default_value, compiler: compiler } define_singleton_method(name) { config.fetch(name, default_value) } define_singleton_method("#{name}=") do |value| unless valid_values.any? { |valid_value| valid_value === value } raise ArgumentError, "Not a valid value for option #{self}.#{name}, provided #{value.inspect}. "\ "Must be #{valid_values.inspect} === #{value.inspect}" end config[name] = value end end
ruby
{ "resource": "" }
q11681
Marshal.ReadBuffer.read_float
train
def read_float s = read_string(cache: false) result = if s == 'nan' 0.0 / 0 elsif s == 'inf' 1.0 / 0 elsif s == '-inf' -1.0 / 0 else s.to_f end @object_cache << result result end
ruby
{ "resource": "" }
q11682
Marshal.ReadBuffer.read_bignum
train
def read_bignum sign = read_char == '-' ? -1 : 1 size = read_fixnum * 2 result = 0 (0...size).each do |exp| result += read_char.ord * 2**(exp * 8) end result = result.to_i * sign @object_cache << result result end
ruby
{ "resource": "" }
q11683
Marshal.ReadBuffer.read_regexp
train
def read_regexp string = read_string(cache: false) options = read_byte result = Regexp.new(string, options) @object_cache << result result end
ruby
{ "resource": "" }
q11684
Marshal.ReadBuffer.read_struct
train
def read_struct klass_name = read(cache: false) klass = safe_const_get(klass_name) attributes = read_hash(cache: false) args = attributes.values_at(*klass.members) result = klass.new(*args) @object_cache << result result end
ruby
{ "resource": "" }
q11685
Marshal.ReadBuffer.read_class
train
def read_class klass_name = read_string(cache: false) result = safe_const_get(klass_name) unless result.class == Class raise ArgumentError, "#{klass_name} does not refer to a Class" end @object_cache << result result end
ruby
{ "resource": "" }
q11686
Marshal.ReadBuffer.read_module
train
def read_module mod_name = read_string(cache: false) result = safe_const_get(mod_name) unless result.class == Module raise ArgumentError, "#{mod_name} does not refer to a Module" end @object_cache << result result end
ruby
{ "resource": "" }
q11687
Marshal.ReadBuffer.read_object
train
def read_object klass_name = read(cache: false) klass = safe_const_get(klass_name) object = klass.allocate @object_cache << object ivars = read_hash(cache: false) ivars.each do |name, value| if name[0] == '@' object.instance_variable_set(name, value) else # MRI allows an object to have ivars that do not start from '@' # https://github.com/ruby/ruby/blob/ab3a40c1031ff3a0535f6bcf26de40de37dbb1db/range.c#L1225 `object[name] = value` end end object end
ruby
{ "resource": "" }
q11688
Marshal.ReadBuffer.read_extended_object
train
def read_extended_object mod = safe_const_get(read) object = read object.extend(mod) object end
ruby
{ "resource": "" }
q11689
MemoryProfiler.Reporter.run
train
def run(&block) start begin yield rescue Exception ObjectSpace.trace_object_allocations_stop GC.enable raise else stop end end
ruby
{ "resource": "" }
q11690
MemoryProfiler.Reporter.object_list
train
def object_list(generation) rvalue_size = GC::INTERNAL_CONSTANTS[:RVALUE_SIZE] helper = Helpers.new result = StatHash.new.compare_by_identity ObjectSpace.each_object do |obj| next unless ObjectSpace.allocation_generation(obj) == generation file = ObjectSpace.allocation_sourcefile(obj) || "(no name)" next if @ignore_files && @ignore_files =~ file next if @allow_files && !(@allow_files =~ file) klass = obj.class rescue nil unless Class === klass # attempt to determine the true Class when .class returns something other than a Class klass = Kernel.instance_method(:class).bind(obj).call end next if @trace && !trace.include?(klass) begin line = ObjectSpace.allocation_sourceline(obj) location = helper.lookup_location(file, line) class_name = helper.lookup_class_name(klass) gem = helper.guess_gem(file) # we do memsize first to avoid freezing as a side effect and shifting # storage to the new frozen string, this happens on @hash[s] in lookup_string memsize = ObjectSpace.memsize_of(obj) string = klass == String ? helper.lookup_string(obj) : nil # compensate for API bug memsize = rvalue_size if memsize > 100_000_000_000 result[obj.__id__] = MemoryProfiler::Stat.new(class_name, gem, file, location, memsize, string) rescue # give up if any any error occurs inspecting the object end end result end
ruby
{ "resource": "" }
q11691
MemoryProfiler.Results.pretty_print
train
def pretty_print(io = $stdout, **options) # Handle the special case that Ruby PrettyPrint expects `pretty_print` # to be a customized pretty printing function for a class return io.pp_object(self) if defined?(PP) && io.is_a?(PP) io = File.open(options[:to_file], "w") if options[:to_file] color_output = options.fetch(:color_output) { io.respond_to?(:isatty) && io.isatty } @colorize = color_output ? Polychrome.new : Monochrome.new if options[:scale_bytes] total_allocated_output = scale_bytes(total_allocated_memsize) total_retained_output = scale_bytes(total_retained_memsize) else total_allocated_output = "#{total_allocated_memsize} bytes" total_retained_output = "#{total_retained_memsize} bytes" end io.puts "Total allocated: #{total_allocated_output} (#{total_allocated} objects)" io.puts "Total retained: #{total_retained_output} (#{total_retained} objects)" if options[:detailed_report] != false io.puts TYPES.each do |type| METRICS.each do |metric| NAMES.each do |name| scale_data = metric == "memory" && options[:scale_bytes] dump "#{type} #{metric} by #{name}", self.send("#{type}_#{metric}_by_#{name}"), io, scale_data end end end end io.puts dump_strings(io, "Allocated", strings_allocated, limit: options[:allocated_strings]) io.puts dump_strings(io, "Retained", strings_retained, limit: options[:retained_strings]) io.close if io.is_a? File end
ruby
{ "resource": "" }
q11692
Lhm.Chunker.execute
train
def execute return unless @start && @limit @next_to_insert = @start while @next_to_insert <= @limit stride = @throttler.stride affected_rows = @connection.update(copy(bottom, top(stride))) if @throttler && affected_rows > 0 @throttler.run end @printer.notify(bottom, @limit) @next_to_insert = top(stride) + 1 break if @start == @limit end @printer.end end
ruby
{ "resource": "" }
q11693
Lhm.Migrator.rename_column
train
def rename_column(old, nu) col = @origin.columns[old.to_s] definition = col[:type] definition += ' NOT NULL' unless col[:is_nullable] definition += " DEFAULT #{@connection.quote(col[:column_default])}" if col[:column_default] ddl('alter table `%s` change column `%s` `%s` %s' % [@name, old, nu, definition]) @renames[old.to_s] = nu.to_s end
ruby
{ "resource": "" }
q11694
Lhm.Migrator.remove_index
train
def remove_index(columns, index_name = nil) columns = [columns].flatten.map(&:to_sym) from_origin = @origin.indices.find { |_, cols| cols.map(&:to_sym) == columns } index_name ||= from_origin[0] unless from_origin.nil? index_name ||= idx_name(@origin.name, columns) ddl('drop index `%s` on `%s`' % [index_name, @name]) end
ruby
{ "resource": "" }
q11695
Hutch.Worker.setup_queues
train
def setup_queues logger.info 'setting up queues' vetted = @consumers.reject { |c| group_configured? && group_restricted?(c) } vetted.each do |c| setup_queue(c) end end
ruby
{ "resource": "" }
q11696
Hutch.Worker.setup_queue
train
def setup_queue(consumer) logger.info "setting up queue: #{consumer.get_queue_name}" queue = @broker.queue(consumer.get_queue_name, consumer.get_arguments) @broker.bind_queue(queue, consumer.routing_keys) queue.subscribe(consumer_tag: unique_consumer_tag, manual_ack: true) do |*args| delivery_info, properties, payload = Hutch::Adapter.decode_message(*args) handle_message(consumer, delivery_info, properties, payload) end end
ruby
{ "resource": "" }
q11697
Hutch.Worker.handle_message
train
def handle_message(consumer, delivery_info, properties, payload) serializer = consumer.get_serializer || Hutch::Config[:serializer] logger.debug { spec = serializer.binary? ? "#{payload.bytesize} bytes" : "#{payload}" "message(#{properties.message_id || '-'}): " + "routing key: #{delivery_info.routing_key}, " + "consumer: #{consumer}, " + "payload: #{spec}" } message = Message.new(delivery_info, properties, payload, serializer) consumer_instance = consumer.new.tap { |c| c.broker, c.delivery_info = @broker, delivery_info } with_tracing(consumer_instance).handle(message) @broker.ack(delivery_info.delivery_tag) rescue => ex acknowledge_error(delivery_info, properties, @broker, ex) handle_error(properties, payload, consumer, ex) end
ruby
{ "resource": "" }
q11698
Hutch.Broker.set_up_api_connection
train
def set_up_api_connection logger.info "connecting to rabbitmq HTTP API (#{api_config.sanitized_uri})" with_authentication_error_handler do with_connection_error_handler do @api_client = CarrotTop.new(host: api_config.host, port: api_config.port, user: api_config.username, password: api_config.password, ssl: api_config.ssl) @api_client.exchanges end end end
ruby
{ "resource": "" }
q11699
Hutch.Broker.bindings
train
def bindings results = Hash.new { |hash, key| hash[key] = [] } api_client.bindings.each do |binding| next if binding['destination'] == binding['routing_key'] next unless binding['source'] == @config[:mq_exchange] next unless binding['vhost'] == @config[:mq_vhost] results[binding['destination']] << binding['routing_key'] end results end
ruby
{ "resource": "" }