_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q16500 | Fast.ExperimentFile.ok_with | train | def ok_with(combination)
@ok_experiments << combination
return unless combination.is_a?(Array)
combination.each do |element|
@ok_experiments.delete(element)
end
end | ruby | {
"resource": ""
} |
q16501 | Fast.ExperimentFile.run_partial_replacement_with | train | def run_partial_replacement_with(combination)
content = partial_replace(*combination)
experimental_file = experimental_filename(combination)
File.open(experimental_file, 'w+') { |f| f.puts content }
raise 'No changes were made to the file.' if FileUtils.compare_file(@file, experimental_file)
result = experiment.ok_if.call(experimental_file)
if result
ok_with(combination)
puts "✅ #{experimental_file} - Combination: #{combination}"
else
failed_with(combination)
puts "🔴 #{experimental_file} - Combination: #{combination}"
end
end | ruby | {
"resource": ""
} |
q16502 | LinkThumbnailer.Grader.call | train | def call
probability = 1.0
graders.each do |lambda|
instance = lambda.call(description)
probability *= instance.call.to_f ** instance.weight
end
probability
end | ruby | {
"resource": ""
} |
q16503 | ProMotion.Table.tableView | train | def tableView(_, viewForHeaderInSection: index)
section = promotion_table_data.section(index)
view = section[:title_view]
view = section[:title_view].new if section[:title_view].respond_to?(:new)
view.on_load if view.respond_to?(:on_load)
view.title = section[:title] if view.respond_to?(:title=)
view
end | ruby | {
"resource": ""
} |
q16504 | ProMotion.WebScreenModule.webView | train | def webView(in_web, shouldStartLoadWithRequest:in_request, navigationType:in_type)
if %w(http https).include?(in_request.URL.scheme)
if self.external_links == true && in_type == UIWebViewNavigationTypeLinkClicked
if defined?(OpenInChromeController)
open_in_chrome in_request
else
open_in_safari in_request
end
return false # don't allow the web view to load the link.
end
end
load_request_enable = true #return true on default for local file loading.
load_request_enable = !!on_request(in_request, in_type) if self.respond_to?(:on_request)
load_request_enable
end | ruby | {
"resource": ""
} |
q16505 | ProMotion.SplitScreen.splitViewController | train | def splitViewController(svc, willHideViewController: vc, withBarButtonItem: button, forPopoverController: _)
button ||= self.displayModeButtonItem if self.respond_to?(:displayModeButtonItem)
return unless button
button.title = @pm_split_screen_button_title || vc.title
svc.detail_screen.navigationItem.leftBarButtonItem = button
end | ruby | {
"resource": ""
} |
q16506 | ProMotion.SplitScreen.splitViewController | train | def splitViewController(svc, willChangeToDisplayMode: display_mode)
vc = svc.viewControllers.first
vc = vc.topViewController if vc.respond_to?(:topViewController)
case display_mode
# when UISplitViewControllerDisplayModeAutomatic then do_something?
when UISplitViewControllerDisplayModePrimaryHidden
self.splitViewController(svc, willHideViewController: vc, withBarButtonItem: nil, forPopoverController: nil)
# TODO: Add `self.master_screen.try(:will_hide_split_screen)` or similar?
when UISplitViewControllerDisplayModeAllVisible
self.splitViewController(svc, willShowViewController: vc, invalidatingBarButtonItem: nil)
# TODO: Add `self.master_screen.try(:will_show_split_screen)` or similar?
# when UISplitViewControllerDisplayModePrimaryOverlay
# TODO: Add `self.master_screen.try(:will_show_split_screen_overlay)` or similar?
end
end | ruby | {
"resource": ""
} |
q16507 | ProMotion.Styling.closest_parent | train | def closest_parent(type, this_view = nil)
this_view ||= view_or_self.superview
while this_view != nil do
return this_view if this_view.is_a? type
this_view = this_view.superview
end
nil
end | ruby | {
"resource": ""
} |
q16508 | Tod.Shift.include? | train | def include?(tod)
second = tod.to_i
second += TimeOfDay::NUM_SECONDS_IN_DAY if second < @range.first
@range.cover?(second)
end | ruby | {
"resource": ""
} |
q16509 | Tod.Shift.overlaps? | train | def overlaps?(other)
max_seconds = TimeOfDay::NUM_SECONDS_IN_DAY
# Standard case, when Shifts are on the same day
a, b = [self, other].map(&:range).sort_by(&:first)
op = a.exclude_end? ? :> : :>=
return true if a.last.send(op, b.first)
# Special cases, when Shifts span to the next day
return false if (a.last < max_seconds) && (b.last < max_seconds)
a = Range.new(a.first, a.last - max_seconds, a.exclude_end?) if a.last > max_seconds
b = Range.new(b.first, b.last - max_seconds, b.exclude_end?) if b.last > max_seconds
a, b = [a, b].sort_by(&:last)
b.last.send(op, a.last) && a.last.send(op, b.first)
end | ruby | {
"resource": ""
} |
q16510 | Tod.TimeOfDay.round | train | def round(round_sec = 1)
down = self - (self.to_i % round_sec)
up = down + round_sec
difference_down = self - down
difference_up = up - self
if (difference_down < difference_up)
return down
else
return up
end
end | ruby | {
"resource": ""
} |
q16511 | Tod.TimeOfDay.- | train | def -(other)
if other.instance_of?(TimeOfDay)
TimeOfDay.from_second_of_day @second_of_day - other.second_of_day
else
TimeOfDay.from_second_of_day @second_of_day - other
end
end | ruby | {
"resource": ""
} |
q16512 | Tod.TimeOfDay.on | train | def on(date, time_zone=Tod::TimeOfDay.time_zone)
time_zone.local date.year, date.month, date.day, @hour, @minute, @second
end | ruby | {
"resource": ""
} |
q16513 | OpenTracing.Tracer.extract | train | def extract(format, carrier)
case format
when OpenTracing::FORMAT_TEXT_MAP, OpenTracing::FORMAT_BINARY, OpenTracing::FORMAT_RACK
return SpanContext::NOOP_INSTANCE
else
warn 'Unknown extract format'
nil
end
end | ruby | {
"resource": ""
} |
q16514 | Mailboxer.RecipientFilter.call | train | def call
return recipients unless mailable.respond_to?(:conversation)
recipients.each_with_object([]) do |recipient, array|
array << recipient if mailable.conversation.has_subscriber?(recipient)
end
end | ruby | {
"resource": ""
} |
q16515 | DynamicSitemaps.IndexGenerator.generate | train | def generate
sitemaps.group_by(&:folder).each do |folder, sitemaps|
index_path = "#{DynamicSitemaps.temp_path}/#{folder}/#{DynamicSitemaps.index_file_name}"
if !DynamicSitemaps.always_generate_index && sitemaps.count == 1 && sitemaps.first.files.count == 1
file_path = "#{DynamicSitemaps.temp_path}/#{folder}/#{sitemaps.first.files.first}"
FileUtils.copy file_path, index_path
File.delete file_path
else
File.open(index_path, "w") do |file|
write_beginning(file)
write_sitemaps(file, sitemaps)
write_end(file)
end
end
end
end | ruby | {
"resource": ""
} |
q16516 | ArduinoCI.CppLibrary.cpp_files_in | train | def cpp_files_in(some_dir)
raise ArgumentError, 'some_dir is not a Pathname' unless some_dir.is_a? Pathname
return [] unless some_dir.exist? && some_dir.directory?
real = some_dir.realpath
files = Find.find(real).map { |p| Pathname.new(p) }.reject(&:directory?)
cpp = files.select { |path| CPP_EXTENSIONS.include?(path.extname.downcase) }
not_hidden = cpp.reject { |path| path.basename.to_s.start_with?(".") }
not_hidden.sort_by(&:to_s)
end | ruby | {
"resource": ""
} |
q16517 | ArduinoCI.CppLibrary.cpp_files_libraries | train | def cpp_files_libraries(aux_libraries)
arduino_library_src_dirs(aux_libraries).map { |d| cpp_files_in(d) }.flatten.uniq
end | ruby | {
"resource": ""
} |
q16518 | ArduinoCI.CppLibrary.header_dirs | train | def header_dirs
real = @base_dir.realpath
all_files = Find.find(real).map { |f| Pathname.new(f) }.reject(&:directory?)
unbundled = all_files.reject { |path| vendor_bundle?(path) }
files = unbundled.select { |path| HPP_EXTENSIONS.include?(path.extname.downcase) }
files.map(&:dirname).uniq
end | ruby | {
"resource": ""
} |
q16519 | ArduinoCI.CppLibrary.run_gcc | train | def run_gcc(gcc_binary, *args, **kwargs)
full_args = [gcc_binary] + args
@last_cmd = " $ #{full_args.join(' ')}"
ret = Host.run_and_capture(*full_args, **kwargs)
@last_err = ret[:err]
@last_out = ret[:out]
ret[:success]
end | ruby | {
"resource": ""
} |
q16520 | ArduinoCI.CppLibrary.arduino_library_src_dirs | train | def arduino_library_src_dirs(aux_libraries)
# Pull in all possible places that headers could live, according to the spec:
# https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification
# TODO: be smart and implement library spec (library.properties, etc)?
subdirs = ["", "src", "utility"]
all_aux_include_dirs_nested = aux_libraries.map do |libdir|
subdirs.map { |subdir| Pathname.new(@arduino_lib_dir) + libdir + subdir }
end
all_aux_include_dirs_nested.flatten.select(&:exist?).select(&:directory?)
end | ruby | {
"resource": ""
} |
q16521 | ArduinoCI.CppLibrary.include_args | train | def include_args(aux_libraries)
all_aux_include_dirs = arduino_library_src_dirs(aux_libraries)
places = [ARDUINO_HEADER_DIR, UNITTEST_HEADER_DIR] + header_dirs + all_aux_include_dirs
places.map { |d| "-I#{d}" }
end | ruby | {
"resource": ""
} |
q16522 | ArduinoCI.ArduinoDownloader.execute | train | def execute
error_preparing = prepare
unless error_preparing.nil?
@output.puts "Arduino force-install failed preparation: #{error_preparing}"
return false
end
attempts = 0
loop do
if File.exist? package_file
@output.puts "Arduino package seems to have been downloaded already" if attempts.zero?
break
elsif attempts >= DOWNLOAD_ATTEMPTS
break @output.puts "After #{DOWNLOAD_ATTEMPTS} attempts, failed to download #{package_url}"
else
@output.print "Attempting to download Arduino package with #{downloader}"
download
@output.puts
end
attempts += 1
end
if File.exist? extracted_file
@output.puts "Arduino package seems to have been extracted already"
elsif File.exist? package_file
@output.print "Extracting archive with #{extracter}"
extract
@output.puts
end
if File.exist? self.class.force_install_location
@output.puts "Arduino package seems to have been installed already"
elsif File.exist? extracted_file
install
else
@output.puts "Could not find extracted archive (tried #{extracted_file})"
end
File.exist? self.class.force_install_location
end | ruby | {
"resource": ""
} |
q16523 | ArduinoCI.ArduinoCmd.parse_pref_string | train | def parse_pref_string(arduino_output)
lines = arduino_output.split("\n").select { |l| l.include? "=" }
ret = lines.each_with_object({}) do |e, acc|
parts = e.split("=", 2)
acc[parts[0]] = parts[1]
acc
end
ret
end | ruby | {
"resource": ""
} |
q16524 | ArduinoCI.ArduinoCmd.run_and_output | train | def run_and_output(*args, **kwargs)
_wrap_run((proc { |*a, **k| Host.run_and_output(*a, **k) }), *args, **kwargs)
end | ruby | {
"resource": ""
} |
q16525 | ArduinoCI.ArduinoCmd.run_and_capture | train | def run_and_capture(*args, **kwargs)
ret = _wrap_run((proc { |*a, **k| Host.run_and_capture(*a, **k) }), *args, **kwargs)
@last_err = ret[:err]
@last_out = ret[:out]
ret
end | ruby | {
"resource": ""
} |
q16526 | ArduinoCI.ArduinoCmd.install_boards | train | def install_boards(boardfamily)
# TODO: find out why IO.pipe fails but File::NULL succeeds :(
result = run_and_capture(flag_install_boards, boardfamily)
already_installed = result[:err].include?("Platform is already installed!")
result[:success] || already_installed
end | ruby | {
"resource": ""
} |
q16527 | ArduinoCI.ArduinoCmd._install_library | train | def _install_library(library_name)
result = run_and_capture(flag_install_library, library_name)
already_installed = result[:err].include?("Library is already installed: #{library_name}")
success = result[:success] || already_installed
@libraries_indexed = (@libraries_indexed || success) if library_name == WORKAROUND_LIB
success
end | ruby | {
"resource": ""
} |
q16528 | ArduinoCI.ArduinoCmd.use_board! | train | def use_board!(boardname)
return true if use_board(boardname)
boardfamily = boardname.split(":")[0..1].join(":")
puts "Board '#{boardname}' not found; attempting to install '#{boardfamily}'"
return false unless install_boards(boardfamily) # guess board family from first 2 :-separated fields
use_board(boardname)
end | ruby | {
"resource": ""
} |
q16529 | ArduinoCI.ArduinoCmd.install_local_library | train | def install_local_library(path)
src_path = path.realpath
library_name = src_path.basename
destination_path = library_path(library_name)
# things get weird if the sketchbook contains the library.
# check that first
if destination_path.exist?
uhoh = "There is already a library '#{library_name}' in the library directory"
return destination_path if destination_path == src_path
# maybe it's a symlink? that would be OK
if destination_path.symlink?
return destination_path if destination_path.readlink == src_path
@last_msg = "#{uhoh} and it's not symlinked to #{src_path}"
return nil
end
@last_msg = "#{uhoh}. It may need to be removed manually."
return nil
end
# install the library
Host.symlink(src_path, destination_path)
destination_path
end | ruby | {
"resource": ""
} |
q16530 | ArduinoCI.CIConfig.validate_data | train | def validate_data(rootname, source, schema)
return nil if source.nil?
good_data = {}
source.each do |key, value|
ksym = key.to_sym
expected_type = schema[ksym].class == Class ? schema[ksym] : Hash
if !schema.include?(ksym)
puts "Warning: unknown field '#{ksym}' under definition for #{rootname}"
elsif value.nil?
good_data[ksym] = nil
elsif value.class != expected_type
puts "Warning: expected field '#{ksym}' of #{rootname} to be '#{expected_type}', got '#{value.class}'"
else
good_data[ksym] = value.class == Hash ? validate_data(key, value, schema[ksym]) : value
end
end
good_data
end | ruby | {
"resource": ""
} |
q16531 | ArduinoCI.CIConfig.load_yaml | train | def load_yaml(path)
yml = YAML.load_file(path)
raise ConfigurationError, "The YAML file at #{path} failed to load" unless yml
apply_configuration(yml)
end | ruby | {
"resource": ""
} |
q16532 | ArduinoCI.CIConfig.apply_configuration | train | def apply_configuration(yml)
if yml.include?("packages")
yml["packages"].each do |k, v|
valid_data = validate_data("packages", v, PACKAGE_SCHEMA)
@package_info[k] = valid_data
end
end
if yml.include?("platforms")
yml["platforms"].each do |k, v|
valid_data = validate_data("platforms", v, PLATFORM_SCHEMA)
@platform_info[k] = valid_data
end
end
if yml.include?("compile")
valid_data = validate_data("compile", yml["compile"], COMPILE_SCHEMA)
valid_data.each { |k, v| @compile_info[k] = v }
end
if yml.include?("unittest")
valid_data = validate_data("unittest", yml["unittest"], UNITTEST_SCHEMA)
valid_data.each { |k, v| @unittest_info[k] = v }
end
self
end | ruby | {
"resource": ""
} |
q16533 | ArduinoCI.CIConfig.with_config | train | def with_config(base_dir, val_when_no_match)
CONFIG_FILENAMES.each do |f|
path = base_dir.nil? ? f : File.join(base_dir, f)
return (yield path) if File.exist?(path)
end
val_when_no_match
end | ruby | {
"resource": ""
} |
q16534 | ArduinoCI.CIConfig.from_example | train | def from_example(example_path)
base_dir = File.directory?(example_path) ? example_path : File.dirname(example_path)
with_config(base_dir, self) { |path| with_override(path) }
end | ruby | {
"resource": ""
} |
q16535 | OffsitePayments.ActionViewHelper.payment_service_for | train | def payment_service_for(order, account, options = {}, &proc)
raise ArgumentError, "Missing block" unless block_given?
integration_module = OffsitePayments::integration(options.delete(:service).to_s)
service_class = integration_module.const_get('Helper')
form_options = options.delete(:html) || {}
service = service_class.new(order, account, options)
form_options[:method] = service.form_method
result = []
service_url = service.respond_to?(:credential_based_url) ? service.credential_based_url : integration_module.service_url
result << form_tag(service_url, form_options)
result << capture(service, &proc)
service.form_fields.each do |field, value|
result << hidden_field_tag(field, value)
end
service.raw_html_fields.each do |field, value|
result << "<input id=\"#{field}\" name=\"#{field}\" type=\"hidden\" value=\"#{value}\" />\n"
end
result << '</form>'
result= result.join("\n")
concat(result.respond_to?(:html_safe) ? result.html_safe : result)
nil
end | ruby | {
"resource": ""
} |
q16536 | OffsitePayments.Notification.valid_sender? | train | def valid_sender?(ip)
return true if OffsitePayments.mode == :test || production_ips.blank?
production_ips.include?(ip)
end | ruby | {
"resource": ""
} |
q16537 | OffsitePayments.Helper.add_field | train | def add_field(name, value)
return if name.blank? || value.blank?
@fields[name.to_s] = value.to_s
end | ruby | {
"resource": ""
} |
q16538 | Airtable.Record.[]= | train | def []=(name, value)
@column_keys << name
@attrs[to_key(name)] = value
define_accessor(name) unless respond_to?(name)
end | ruby | {
"resource": ""
} |
q16539 | Airtable.Record.override_attributes! | train | def override_attributes!(attrs={})
@column_keys = attrs.keys
@attrs = HashWithIndifferentAccess.new(Hash[attrs.map { |k, v| [ to_key(k), v ] }])
@attrs.map { |k, v| define_accessor(k) }
end | ruby | {
"resource": ""
} |
q16540 | Airtable.Table.find | train | def find(id)
result = self.class.get(worksheet_url + "/" + id).parsed_response
check_and_raise_error(result)
Record.new(result_attributes(result)) if result.present? && result["id"]
end | ruby | {
"resource": ""
} |
q16541 | Airtable.Table.create | train | def create(record)
result = self.class.post(worksheet_url,
:body => { "fields" => record.fields }.to_json,
:headers => { "Content-type" => "application/json" }).parsed_response
check_and_raise_error(result)
record.override_attributes!(result_attributes(result))
record
end | ruby | {
"resource": ""
} |
q16542 | Airtable.Table.update | train | def update(record)
result = self.class.put(worksheet_url + "/" + record.id,
:body => { "fields" => record.fields_for_update }.to_json,
:headers => { "Content-type" => "application/json" }).parsed_response
check_and_raise_error(result)
record.override_attributes!(result_attributes(result))
record
end | ruby | {
"resource": ""
} |
q16543 | Numo.NArray.triu! | train | def triu!(k=0)
if ndim < 2
raise NArray::ShapeError, "must be >= 2-dimensional array"
end
if contiguous?
*shp,m,n = shape
idx = tril_indices(k-1)
reshape!(*shp,m*n)
self[false,idx] = 0
reshape!(*shp,m,n)
else
store(triu(k))
end
end | ruby | {
"resource": ""
} |
q16544 | Numo.NArray.tril! | train | def tril!(k=0)
if ndim < 2
raise NArray::ShapeError, "must be >= 2-dimensional array"
end
if contiguous?
idx = triu_indices(k+1)
*shp,m,n = shape
reshape!(*shp,m*n)
self[false,idx] = 0
reshape!(*shp,m,n)
else
store(tril(k))
end
end | ruby | {
"resource": ""
} |
q16545 | Numo.NArray.diag_indices | train | def diag_indices(k=0)
if ndim < 2
raise NArray::ShapeError, "must be >= 2-dimensional array"
end
m,n = shape[-2..-1]
NArray.diag_indices(m,n,k)
end | ruby | {
"resource": ""
} |
q16546 | Numo.NArray.diag | train | def diag(k=0)
*shp,n = shape
n += k.abs
a = self.class.zeros(*shp,n,n)
a.diagonal(k).store(self)
a
end | ruby | {
"resource": ""
} |
q16547 | Numo.NArray.trace | train | def trace(offset=nil,axis=nil,nan:false)
diagonal(offset,axis).sum(nan:nan,axis:-1)
end | ruby | {
"resource": ""
} |
q16548 | Numo.NArray.dot | train | def dot(b)
t = self.class::UPCAST[b.class]
if defined?(Linalg) && [SFloat,DFloat,SComplex,DComplex].include?(t)
Linalg.dot(self,b)
else
b = self.class.asarray(b)
case b.ndim
when 1
mulsum(b, axis:-1)
else
case ndim
when 0
b.mulsum(self, axis:-2)
when 1
self[true,:new].mulsum(b, axis:-2)
else
unless @@warn_slow_dot
nx = 200
ns = 200000
am,an = shape[-2..-1]
bm,bn = b.shape[-2..-1]
if am > nx && an > nx && bm > nx && bn > nx &&
size > ns && b.size > ns
@@warn_slow_dot = true
warn "\nwarning: Built-in matrix dot is slow. Consider installing Numo::Linalg.\n\n"
end
end
self[false,:new].mulsum(b[false,:new,true,true], axis:-2)
end
end
end
end | ruby | {
"resource": ""
} |
q16549 | Numo.NArray.kron | train | def kron(b)
b = NArray.cast(b)
nda = ndim
ndb = b.ndim
shpa = shape
shpb = b.shape
adim = [:new]*(2*[ndb-nda,0].max) + [true,:new]*nda
bdim = [:new]*(2*[nda-ndb,0].max) + [:new,true]*ndb
shpr = (-[nda,ndb].max..-1).map{|i| (shpa[i]||1) * (shpb[i]||1)}
(self[*adim] * b[*bdim]).reshape(*shpr)
end | ruby | {
"resource": ""
} |
q16550 | Boxr.Client.pending_collaborations | train | def pending_collaborations(fields: [])
query = build_fields_query(fields, COLLABORATION_FIELDS_QUERY)
query[:status] = :pending
pending_collaborations, response = get(COLLABORATIONS_URI, query: query)
pending_collaborations['entries']
end | ruby | {
"resource": ""
} |
q16551 | Hanami.Router.redirect | train | def redirect(path, options = {}, &endpoint)
destination_path = @router.find(options)
get(path).redirect(destination_path, options[:code] || 301).tap do |route|
route.dest = Hanami::Routing::RedirectEndpoint.new(destination_path, route.dest)
end
end | ruby | {
"resource": ""
} |
q16552 | Hanami.Router.recognize | train | def recognize(env, options = {}, params = nil)
require 'hanami/routing/recognized_route'
env = env_for(env, options, params)
responses, _ = *@router.recognize(env)
Routing::RecognizedRoute.new(
responses.nil? ? responses : responses.first,
env, @router)
end | ruby | {
"resource": ""
} |
q16553 | Hanami.Router.env_for | train | def env_for(env, options = {}, params = nil)
env = case env
when String
Rack::MockRequest.env_for(env, options)
when Symbol
begin
url = path(env, params || options)
return env_for(url, options)
rescue Hanami::Routing::InvalidRouteException
{}
end
else
env
end
end | ruby | {
"resource": ""
} |
q16554 | Turnout.AcceptLanguageParser.user_preferred_languages | train | def user_preferred_languages
return [] if header.to_s.strip.empty?
@user_preferred_languages ||= begin
header.to_s.gsub(/\s+/, '').split(',').map do |language|
locale, quality = language.split(';q=')
raise ArgumentError, 'Not correctly formatted' unless locale =~ /^[a-z\-0-9]+|\*$/i
locale = locale.downcase.gsub(/-[a-z0-9]+$/i, &:upcase) # Uppercase territory
locale = nil if locale == '*' # Ignore wildcards
quality = quality ? quality.to_f : 1.0
[locale, quality]
end.sort do |(_, left), (_, right)|
right <=> left
end.map(&:first).compact
rescue ArgumentError # Just rescue anything if the browser messed up badly.
[]
end
end | ruby | {
"resource": ""
} |
q16555 | Turnout.AcceptLanguageParser.compatible_language_from | train | def compatible_language_from(available_languages)
user_preferred_languages.map do |preferred| #en-US
preferred = preferred.downcase
preferred_language = preferred.split('-', 2).first
available_languages.find do |available| # en
available = available.to_s.downcase
preferred == available || preferred_language == available.split('-', 2).first
end
end.compact.first
end | ruby | {
"resource": ""
} |
q16556 | Turnout.AcceptLanguageParser.sanitize_available_locales | train | def sanitize_available_locales(available_languages)
available_languages.map do |available|
available.to_s.split(/[_-]/).reject { |part| part.start_with?("x") }.join("-")
end
end | ruby | {
"resource": ""
} |
q16557 | Turnout.AcceptLanguageParser.language_region_compatible_from | train | def language_region_compatible_from(available_languages)
available_languages = sanitize_available_locales(available_languages)
user_preferred_languages.map do |preferred| #en-US
preferred = preferred.downcase
preferred_language = preferred.split('-', 2).first
lang_group = available_languages.select do |available| # en
preferred_language == available.downcase.split('-', 2).first
end
lang_group.find { |lang| lang.downcase == preferred } || lang_group.first #en-US, en-UK
end.compact.first
end | ruby | {
"resource": ""
} |
q16558 | Turnout.OrderedOptions.update | train | def update(other_hash)
if other_hash.is_a? Hash
super(other_hash)
else
other_hash.to_hash.each_pair do |key, value|
if block_given?
value = yield(key, value)
end
self[key] = value
end
self
end
end | ruby | {
"resource": ""
} |
q16559 | DocBook.Epub.has_callouts? | train | def has_callouts?
parser = REXML::Parsers::PullParser.new(File.new(@docbook_file))
while parser.has_next?
el = parser.pull
if el.start_element? and (el[0] == "calloutlist" or el[0] == "co")
return true
end
end
return false
end | ruby | {
"resource": ""
} |
q16560 | Pastel.Delegator.evaluate_block | train | def evaluate_block(&block)
delegator = self.class.new(resolver, DecoratorChain.empty)
delegator.instance_eval(&block)
end | ruby | {
"resource": ""
} |
q16561 | Pastel.Color.decorate | train | def decorate(string, *colors)
return string if blank?(string) || !enabled || colors.empty?
ansi_colors = lookup(*colors.dup.uniq)
if eachline
string.dup.split(eachline).map! do |line|
apply_codes(line, ansi_colors)
end.join(eachline)
else
apply_codes(string.dup, ansi_colors)
end
end | ruby | {
"resource": ""
} |
q16562 | Pastel.Color.strip | train | def strip(*strings)
modified = strings.map { |string| string.dup.gsub(ANSI_COLOR_REGEXP, '') }
modified.size == 1 ? modified[0] : modified
end | ruby | {
"resource": ""
} |
q16563 | Pastel.Color.code | train | def code(*colors)
attribute = []
colors.each do |color|
value = ANSI::ATTRIBUTES[color] || ALIASES[color]
if value
attribute << value
else
validate(color)
end
end
attribute
end | ruby | {
"resource": ""
} |
q16564 | Pastel.Color.alias_color | train | def alias_color(alias_name, *colors)
validate(*colors)
if !(alias_name.to_s =~ /^[\w]+$/)
fail InvalidAliasNameError, "Invalid alias name `#{alias_name}`"
elsif ANSI::ATTRIBUTES[alias_name]
fail InvalidAliasNameError,
"Cannot alias standard color `#{alias_name}`"
end
ALIASES[alias_name.to_sym] = colors.map(&ANSI::ATTRIBUTES.method(:[]))
colors
end | ruby | {
"resource": ""
} |
q16565 | Pastel.AliasImporter.import | train | def import
color_aliases = env['PASTEL_COLORS_ALIASES']
return unless color_aliases
color_aliases.split(',').each do |color_alias|
new_color, old_colors = color_alias.split('=')
if !new_color || !old_colors
output.puts "Bad color mapping `#{color_alias}`"
else
color.alias_color(new_color.to_sym,
*old_colors.split('.').map(&:to_sym))
end
end
end | ruby | {
"resource": ""
} |
q16566 | GoogleVisualr.BaseChart.draw_js_spreadsheet | train | def draw_js_spreadsheet(data, element_id=SecureRandom.uuid)
js = ''
js << "\n function #{chart_function_name(element_id)}() {"
js << "\n var query = new google.visualization.Query('#{data}');"
js << "\n query.send(#{query_response_function_name(element_id)});"
js << "\n }"
js << "\n function #{query_response_function_name(element_id)}(response) {"
js << "\n var data_table = response.getDataTable();"
js << "\n var chart = new google.#{chart_class}.#{chart_name}"\
"(document.getElementById('#{element_id}'));"
js << add_listeners_js('chart')
js << "\n chart.draw(data_table, #{js_parameters(@options)});"
js << "\n };"
js
end | ruby | {
"resource": ""
} |
q16567 | GoogleVisualr.DataTable.to_js_full_script | train | def to_js_full_script(element_id=SecureRandom.uuid)
js = ''
js << '\n<script type=\'text/javascript\'>'
js << load_js(element_id)
js << draw_js(element_id)
js << '\n</script>'
js
end | ruby | {
"resource": ""
} |
q16568 | GoogleVisualr.DataTable.draw_js | train | def draw_js(element_id)
js = ''
js << "\n function #{chart_function_name(element_id)}() {"
js << "\n #{to_js}"
js << "\n var table = new google.visualization.Table("
js << "document.getElementById('#{element_id}'));"
js << add_listeners_js('table')
js << "\n table.draw(data_table, #{js_parameters(@options)}); "
js << "\n };"
js
end | ruby | {
"resource": ""
} |
q16569 | GoogleVisualr.DataTable.draw_js_spreadsheet | train | def draw_js_spreadsheet(data, element_id)
js = ''
js << "\n function #{chart_function_name(element_id)}() {"
js << "\n var query = new google.visualization.Query('#{data}');"
js << "\n query.send(#{query_response_function_name(element_id)});"
js << "\n }"
js << "\n function #{query_response_function_name(element_id)}(response) {"
js << "\n var data_table = response.getDataTable();"
js << "\n var table = new google.visualization.Table"\
"(document.getElementById('#{element_id}'));"
js << add_listeners_js('table')
js << "\n table.draw(data_table, #{js_parameters(@options)});"
js << "\n };"
js
end | ruby | {
"resource": ""
} |
q16570 | LazyHighCharts.HighChart.to_html_iruby | train | def to_html_iruby(placeholder=random_canvas_id)
# TODO : placeholder pass, in plot#div
@div_id = placeholder
load_dependencies('iruby')
chart_hash_must_be_present
script = high_chart_css(placeholder)
script << high_chart_iruby(extract_chart_class, placeholder, self)
script
end | ruby | {
"resource": ""
} |
q16571 | LazyHighCharts.HighChart.load_dependencies | train | def load_dependencies(type)
dep_js = extract_dependencies
if type == 'iruby'
LazyHighCharts.init_iruby(dep_js) unless dep_js.nil?
elsif type == 'web_frameworks'
dep_js.nil? ? '' : LazyHighCharts.init_javascript(dep_js)
end
end | ruby | {
"resource": ""
} |
q16572 | LazyHighCharts.HighChart.export_iruby | train | def export_iruby(export_type='png', file_name='chart')
js = ''
js << to_html_iruby
js << extract_export_code_iruby(@div_id, export_type, file_name)
IRuby.html js
end | ruby | {
"resource": ""
} |
q16573 | LazyHighCharts.HighChart.extract_export_code | train | def extract_export_code(
placeholder=random_canvas_id, export_type='png', file_name='chart'
)
js = ''
js << "\n <script>"
js << "\n (function() {"
js << "\n \tvar onload = window.onload;"
js << "\n \twindow.onload = function(){"
js << "\n \t\tif (typeof onload == 'function') onload();"
js << "\n \t\tvar chartDom = document.getElementById('#{placeholder}');"
js << "\n \t\tvar chart = Highcharts.charts[Highcharts.attr(chartDom,"
js << " 'data-highcharts-chart')]"
js << "\n \t\tchart.exportChartLocal({"
js << "\n \t\t\t" + append_chart_type(export_type)
js << "\n \t\t\tfilename: '#{file_name}'"
js << "\n \t\t});\n \t};\n })();"
js << "\n </script>"
js
end | ruby | {
"resource": ""
} |
q16574 | LazyHighCharts.HighChart.extract_export_code_iruby | train | def extract_export_code_iruby(
placeholder=random_canvas_id, export_type='png', file_name='chart'
)
js = ''
js << "\n <script>"
js << "\n (function() {"
js << "\n \tvar chartDom = document.getElementById('#{placeholder}');"
js << "\n \tvar chart = Highcharts.charts[Highcharts.attr(chartDom,"
js << " 'data-highcharts-chart')]"
js << "\n \tchart.exportChart({"
js << "\n \t\t" + append_chart_type(export_type)
js << "\n \t\tfilename: '#{file_name}'"
js << "\n \t});"
js << "\n })();"
js << "\n </script>"
js
end | ruby | {
"resource": ""
} |
q16575 | Omnibus.Ctl.get_all_commands_hash | train | def get_all_commands_hash
without_categories = {}
category_command_map.each do |category, commands|
without_categories.merge!(commands)
end
command_map.merge(without_categories)
end | ruby | {
"resource": ""
} |
q16576 | Omnibus.Ctl.run_sv_command_for_service | train | def run_sv_command_for_service(sv_cmd, service_name)
if service_enabled?(service_name)
status = run_command("#{base_path}/init/#{service_name} #{sv_cmd}")
status.exitstatus
else
log "#{service_name} disabled" if sv_cmd == "status" && verbose
0
end
end | ruby | {
"resource": ""
} |
q16577 | Omnibus.Ctl.parse_options | train | def parse_options(args)
args.select do |option|
case option
when "--quiet", "-q"
@quiet = true
false
when "--verbose", "-v"
@verbose = true
false
end
end
end | ruby | {
"resource": ""
} |
q16578 | Omnibus.Ctl.retrieve_command | train | def retrieve_command(command_to_run)
if command_map.has_key?(command_to_run)
command_map[command_to_run]
else
command = nil
category_command_map.each do |category, commands|
command = commands[command_to_run] if commands.has_key?(command_to_run)
end
# return the command, or nil if it wasn't found
command
end
end | ruby | {
"resource": ""
} |
q16579 | Omnibus.Ctl.run | train | def run(args)
# Ensure Omnibus related binaries are in the PATH
ENV["PATH"] = [File.join(base_path, "bin"),
File.join(base_path, "embedded","bin"),
ENV['PATH']].join(":")
command_to_run = args[0]
## when --help is run as the command itself, we need to strip off the
## `--` to ensure the command maps correctly.
if command_to_run == "--help"
command_to_run = "help"
end
# This piece of code checks if the argument is an option. If it is,
# then it sets service to nil and adds the argument into the options
# argument. This is ugly. A better solution is having a proper parser.
# But if we are going to implement a proper parser, we might as well
# port this to Thor rather than reinventing Thor. For now, this preserves
# the behavior to complain and exit with an error if one attempts to invoke
# a pcc command that does not accept an argument. Like "help".
options = args[2..-1] || []
if is_option?(args[1])
options.unshift(args[1])
service = nil
else
service = args[1]
end
# returns either hash content of command or nil
command = retrieve_command(command_to_run)
if command.nil?
log "I don't know that command."
if args.length == 2
log "Did you mean: #{exe_name} #{service} #{command_to_run}?"
end
help
Kernel.exit 1
end
if args.length > 1 && command[:arity] != 2
log "The command #{command_to_run} does not accept any arguments"
Kernel.exit 2
end
parse_options options
@force_exit = false
exit_code = 0
run_global_pre_hooks
# Filter args to just command and service. If you are loading
# custom commands and need access to the command line argument,
# use ARGV directly.
actual_args = [command_to_run, service].reject(&:nil?)
if command_pre_hook(*actual_args)
method_to_call = to_method_name(command_to_run)
begin
ret = send(method_to_call, *actual_args)
rescue SystemExit => e
@force_exit = true
ret = e.status
end
command_post_hook(*actual_args)
exit_code = ret unless ret.nil?
else
exit_code = 8
@force_exit = true
end
if @force_exit
Kernel.exit exit_code
else
exit_code
end
end | ruby | {
"resource": ""
} |
q16580 | Omnibus.Ctl.status_post_hook | train | def status_post_hook(service = nil)
if service.nil?
log_external_service_header
external_services.each_key do |service_name|
status = send(to_method_name("external_status_#{service_name}"), :sparse)
log status
end
else
# Request verbose status if the service is asked for by name.
if service_external?(service)
status = send(to_method_name("external_status_#{service}"), :verbose)
log status
end
end
end | ruby | {
"resource": ""
} |
q16581 | Algolia.Client.enable_rate_limit_forward | train | def enable_rate_limit_forward(admin_api_key, end_user_ip, rate_limit_api_key)
headers[Protocol::HEADER_API_KEY] = admin_api_key
headers[Protocol::HEADER_FORWARDED_IP] = end_user_ip
headers[Protocol::HEADER_FORWARDED_API_KEY] = rate_limit_api_key
end | ruby | {
"resource": ""
} |
q16582 | Algolia.Client.multiple_queries | train | def multiple_queries(queries, options = nil, strategy = nil)
if options.is_a?(Hash)
index_name_key = options.delete(:index_name_key) || options.delete('index_name_key')
strategy = options.delete(:strategy) || options.delete('strategy')
request_options = options.delete(:request_options) || options.delete('request_options')
else
# Deprecated def multiple_queries(queries, index_name_key, strategy)
index_name_key = options
end
index_name_key ||= :index_name
strategy ||= 'none'
request_options ||= {}
requests = {
:requests => queries.map do |query|
query = query.dup
index_name = query.delete(index_name_key) || query.delete(index_name_key.to_s)
raise ArgumentError.new("Missing '#{index_name_key}' option") if index_name.nil?
encoded_params = Hash[query.map { |k, v| [k.to_s, v.is_a?(Array) ? v.to_json : v] }]
{ :indexName => index_name, :params => Protocol.to_query(encoded_params) }
end
}
post(Protocol.multiple_queries_uri(strategy), requests.to_json, :search, request_options)
end | ruby | {
"resource": ""
} |
q16583 | Algolia.Client.move_index | train | def move_index(src_index, dst_index, request_options = {})
request = { 'operation' => 'move', 'destination' => dst_index }
post(Protocol.index_operation_uri(src_index), request.to_json, :write, request_options)
end | ruby | {
"resource": ""
} |
q16584 | Algolia.Client.move_index! | train | def move_index!(src_index, dst_index, request_options = {})
res = move_index(src_index, dst_index, request_options)
wait_task(dst_index, res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end | ruby | {
"resource": ""
} |
q16585 | Algolia.Client.copy_index | train | def copy_index(src_index, dst_index, scope = nil, request_options = {})
request = { 'operation' => 'copy', 'destination' => dst_index }
request['scope'] = scope unless scope.nil?
post(Protocol.index_operation_uri(src_index), request.to_json, :write, request_options)
end | ruby | {
"resource": ""
} |
q16586 | Algolia.Client.copy_index! | train | def copy_index!(src_index, dst_index, scope = nil, request_options = {})
res = copy_index(src_index, dst_index, scope, request_options)
wait_task(dst_index, res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end | ruby | {
"resource": ""
} |
q16587 | Algolia.Client.copy_settings! | train | def copy_settings!(src_index, dst_index, request_options = {})
res = copy_settings(src_index, dst_index, request_options)
wait_task(dst_index, res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end | ruby | {
"resource": ""
} |
q16588 | Algolia.Client.copy_synonyms! | train | def copy_synonyms!(src_index, dst_index, request_options = {})
res = copy_synonyms(src_index, dst_index, request_options)
wait_task(dst_index, res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end | ruby | {
"resource": ""
} |
q16589 | Algolia.Client.copy_rules! | train | def copy_rules!(src_index, dst_index, request_options = {})
res = copy_rules(src_index, dst_index, request_options)
wait_task(dst_index, res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end | ruby | {
"resource": ""
} |
q16590 | Algolia.Client.get_logs | train | def get_logs(options = nil, length = nil, type = nil)
if options.is_a?(Hash)
offset = options.delete('offset') || options.delete(:offset)
length = options.delete('length') || options.delete(:length)
type = options.delete('type') || options.delete(:type)
request_options = options.delete('request_options') || options.delete(:request_options)
else
# Deprecated def get_logs(offset, length, type)
offset = options
end
length ||= 10
type = 'all' if type.nil?
type = type ? 'error' : 'all' if type.is_a?(true.class)
request_options ||= {}
get(Protocol.logs(offset, length, type), :write, request_options)
end | ruby | {
"resource": ""
} |
q16591 | Algolia.Client.batch! | train | def batch!(operations, request_options = {})
res = batch(operations, request_options)
res['taskID'].each do |index, taskID|
wait_task(index, taskID, WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
end
end | ruby | {
"resource": ""
} |
q16592 | Algolia.Client.get_task_status | train | def get_task_status(index_name, taskID, request_options = {})
get(Protocol.task_uri(index_name, taskID), :read, request_options)['status']
end | ruby | {
"resource": ""
} |
q16593 | Algolia.Client.request | train | def request(uri, method, data = nil, type = :write, request_options = {})
exceptions = []
connect_timeout = @connect_timeout
send_timeout = if type == :search
@search_timeout
elsif type == :batch
type = :write
@batch_timeout
else
@send_timeout
end
receive_timeout = type == :search ? @search_timeout : @receive_timeout
thread_local_hosts(type != :write).each_with_index do |host, i|
connect_timeout += 2 if i == 2
send_timeout += 10 if i == 2
receive_timeout += 10 if i == 2
thread_index_key = type != :write ? "algolia_search_host_index_#{application_id}" : "algolia_host_index_#{application_id}"
Thread.current[thread_index_key] = host[:index]
host[:last_call] = Time.now.to_i
host[:session].connect_timeout = connect_timeout
host[:session].send_timeout = send_timeout
host[:session].receive_timeout = receive_timeout
begin
return perform_request(host[:session], host[:base_url] + uri, method, data, request_options)
rescue AlgoliaProtocolError => e
raise if e.code / 100 == 4
exceptions << e
rescue => e
exceptions << e
end
host[:session].reset_all
end
raise AlgoliaProtocolError.new(0, "Cannot reach any host: #{exceptions.map { |e| e.to_s }.join(', ')}")
end | ruby | {
"resource": ""
} |
q16594 | Algolia.Client.thread_local_hosts | train | def thread_local_hosts(read)
thread_hosts_key = read ? "algolia_search_hosts_#{application_id}" : "algolia_hosts_#{application_id}"
Thread.current[thread_hosts_key] ||= (read ? search_hosts : hosts).each_with_index.map do |host, i|
client = HTTPClient.new
client.ssl_config.ssl_version = @ssl_version if @ssl && @ssl_version
client.transparent_gzip_decompression = @gzip
client.ssl_config.add_trust_ca File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'resources', 'ca-bundle.crt'))
{
:index => i,
:base_url => "http#{@ssl ? 's' : ''}://#{host}",
:session => client,
:last_call => nil
}
end
hosts = Thread.current[thread_hosts_key]
thread_index_key = read ? "algolia_search_host_index_#{application_id}" : "algolia_host_index_#{application_id}"
current_host = Thread.current[thread_index_key].to_i # `to_i` to ensure first call is 0
# we want to always target host 0 first
# if the current host is not 0, then we want to use it first only if (we never used it OR we're using it since less than 1 minute)
if current_host != 0 && (hosts[current_host][:last_call].nil? || hosts[current_host][:last_call] > Time.now.to_i - 60)
# first host will be `current_host`
first = hosts[current_host]
[first] + hosts.reject { |h| h[:index] == 0 || h == first } + hosts.select { |h| h[:index] == 0 }
else
# first host will be `0`
hosts
end
end | ruby | {
"resource": ""
} |
q16595 | Algolia.Index.delete! | train | def delete!(request_options = {})
res = delete(request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end | ruby | {
"resource": ""
} |
q16596 | Algolia.Index.add_object | train | def add_object(object, objectID = nil, request_options = {})
check_object(object)
if objectID.nil? || objectID.to_s.empty?
client.post(Protocol.index_uri(name), object.to_json, :write, request_options)
else
client.put(Protocol.object_uri(name, objectID), object.to_json, :write, request_options)
end
end | ruby | {
"resource": ""
} |
q16597 | Algolia.Index.add_object! | train | def add_object!(object, objectID = nil, request_options = {})
res = add_object(object, objectID, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end | ruby | {
"resource": ""
} |
q16598 | Algolia.Index.add_objects! | train | def add_objects!(objects, request_options = {})
res = add_objects(objects, request_options)
wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options)
res
end | ruby | {
"resource": ""
} |
q16599 | Algolia.Index.search | train | def search(query, params = {}, request_options = {})
encoded_params = Hash[params.map { |k, v| [k.to_s, v.is_a?(Array) ? v.to_json : v] }]
encoded_params[:query] = query
client.post(Protocol.search_post_uri(name), { :params => Protocol.to_query(encoded_params) }.to_json, :search, request_options)
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.