_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q9400 | Activr.Registry.classes_from_path | train | def classes_from_path(dir_path)
Dir["#{dir_path}/*.rb"].sort.inject({ }) do |memo, file_path|
klass = File.basename(file_path, '.rb').camelize.constantize
if !memo[klass.kind].nil?
raise "Kind #{klass.kind} already used by class #{memo[klass.kind]} so can't use it for class #{klass}"
... | ruby | {
"resource": ""
} |
q9401 | SycLink.InternetExplorer.read | train | def read
files = Dir.glob(File.join(path, "**/*"))
regex = Regexp.new("(?<=#{path}).*")
files.map do |file|
unless ((File.directory? file) || (File.extname(file).upcase != ".URL"))
url = File.read(file).scan(/(?<=\nURL=)(.*)$/).flatten.first.chomp
name = url_name(Fi... | ruby | {
"resource": ""
} |
q9402 | GMath3D.::Matrix.multi_new | train | def multi_new(rhs)
if(rhs.kind_of?(Vector3))
ans = self.multi_inner(rhs.to_column_vector)
return Vector3.new(ans[0,0], ans[1,0], ans[2,0])
end
multi_inner(rhs)
end | ruby | {
"resource": ""
} |
q9403 | LatoBlog.Tag.check_meta_permalink | train | def check_meta_permalink
candidate = (self.meta_permalink ? self.meta_permalink : self.title.parameterize)
accepted = nil
counter = 0
while accepted.nil?
if LatoBlog::Tag.find_by(meta_permalink: candidate)
counter += 1
candidate = "#{candidate}-#{counter}"
el... | ruby | {
"resource": ""
} |
q9404 | LatoBlog.Tag.check_lato_blog_tag_parent | train | def check_lato_blog_tag_parent
tag_parent = LatoBlog::TagParent.find_by(id: lato_blog_tag_parent_id)
if !tag_parent
errors.add('Tag parent', 'not exist for the tag')
throw :abort
return
end
same_language_tag = tag_parent.tags.find_by(meta_language: meta_language)
i... | ruby | {
"resource": ""
} |
q9405 | Tinycert.Request.prepare_params | train | def prepare_params p
results = {}
# Build a new hash with string keys
p.each { |k, v| results[k.to_s] = v }
# Sort nested structures
results.sort.to_h
end | ruby | {
"resource": ""
} |
q9406 | ProgneTapera::EnumList.ClassMethods.enum_constants | train | def enum_constants
constants.select { |constant|
value = const_get constant
value.is_a? ProgneTapera::EnumItem
}
end | ruby | {
"resource": ""
} |
q9407 | ChronuscopClient.Configuration.load_yaml_configuration | train | def load_yaml_configuration
yaml_config = YAML.load_file("#{@rails_root_dir}/config/chronuscop.yml")
@redis_db_number = yaml_config[@rails_environment]['redis_db_number']
@redis_server_port = yaml_config[@rails_environment]['redis_server_port']
@project_number = yaml_config[@rails_environment]['... | ruby | {
"resource": ""
} |
q9408 | Ponder.User.whois | train | def whois
connected do
fiber = Fiber.current
callbacks = {}
# User is online.
callbacks[311] = @thaum.on(311) do |event_data|
nick = event_data[:params].split(' ')[1]
if nick.downcase == @nick.downcase
@online = true
# TODO: Add properti... | ruby | {
"resource": ""
} |
q9409 | Lazymodel.Base.attributes | train | def attributes
_attributes.inject(HashWithIndifferentAccess.new) do |hash, attribute|
hash.update attribute => send(attribute)
end
end | ruby | {
"resource": ""
} |
q9410 | Joinable.PermissionsAttributeWrapper.permission_attributes= | train | def permission_attributes=(permissions)
self.permissions = [] # Reset permissions in anticipation for re-population
permissions.each do |key, value|
key, value = key.dup, value.dup
# Component Permissions
if key.ends_with? "_permissions"
grant_permissions(value)... | ruby | {
"resource": ""
} |
q9411 | Joinable.PermissionsAttributeWrapper.has_permission? | train | def has_permission?(*levels)
if levels.all? { |level| permissions.include? level.to_sym }
return true
else
return false
end
end | ruby | {
"resource": ""
} |
q9412 | Joinable.PermissionsAttributeWrapper.method_missing | train | def method_missing(method_name, *args, &block)
# NOTE: As of Rails 4, respond_to? must be checked inside the case statement otherwise it breaks regular AR attribute accessors
case method_name.to_s
when /.+_permissions/
return component_permissions_reader(method_name) if respond_to?(:join... | ruby | {
"resource": ""
} |
q9413 | Joinable.PermissionsAttributeWrapper.verify_and_sort_permissions | train | def verify_and_sort_permissions
# DefaultPermissionSet is allowed to have blank permissions (private joinable), the other models need at least find and view
self.permissions += [:find, :view] unless is_a?(DefaultPermissionSet)
raise "Invalid permissions: #{(permissions - allowed_permissions).insp... | ruby | {
"resource": ""
} |
q9414 | RSpec.Approvals.verify | train | def verify( options={}, &block )
approval = Git::Approvals::Approval.new( approval_path, options )
approval.diff( block.call ) do |err|
::RSpec::Expectations.fail_with err
end
rescue Errno::ENOENT => e
::RSpec::Expectations.fail_with e.message
EOS
end | ruby | {
"resource": ""
} |
q9415 | RSpec.Approvals.approval_filename | train | def approval_filename
parts = [ example, *example.example_group.parent_groups ].map do |ex|
Git::Approvals::Utils.filenamify ex.description
end
File.join parts.to_a.reverse
end | ruby | {
"resource": ""
} |
q9416 | Octo.Trends.aggregate_and_create | train | def aggregate_and_create(oftype, ts = Time.now.floor)
Octo::Enterprise.each do |enterprise|
calculate(enterprise.id, oftype, ts)
end
end | ruby | {
"resource": ""
} |
q9417 | Octo.Trends.aggregate! | train | def aggregate!(ts = Time.now.floor)
aggregate_and_create(Octo::Counter::TYPE_MINUTE, ts)
end | ruby | {
"resource": ""
} |
q9418 | Octo.Trends.calculate | train | def calculate(enterprise_id, trend_type, ts = Time.now.floor)
args = {
enterprise_id: enterprise_id,
ts: ts,
type: trend_type
}
klass = @trend_for.constantize
hitsResult = klass.public_send(:where, args)
trends = hitsResult.map { |h| counter2trend(h... | ruby | {
"resource": ""
} |
q9419 | Octo.Trends.get_trending | train | def get_trending(enterprise_id, type, opts={})
ts = opts.fetch(:ts, Time.now.floor)
args = {
enterprise_id: enterprise_id,
ts: opts.fetch(:ts, Time.now.floor),
type: type
}
res = where(args).limit(opts.fetch(:limit, DEFAULT_COUNT))
enterprise = Octo::Enterprise.find... | ruby | {
"resource": ""
} |
q9420 | Octo.Trends.counter2trend | train | def counter2trend(counter)
self.new({
enterprise: counter.enterprise,
score: score(counter.divergence),
uid: counter.uid,
ts: counter.ts
})
end | ruby | {
"resource": ""
} |
q9421 | Uninhibited.Formatter.example_pending | train | def example_pending(example)
if example_group.metadata[:feature] && example.metadata[:skipped]
@skipped_examples << pending_examples.delete(example)
@skipped_count += 1
output.puts cyan("#{current_indentation}#{example.description}")
else
super
end
end | ruby | {
"resource": ""
} |
q9422 | Uninhibited.Formatter.summary_line | train | def summary_line(example_count, failure_count, pending_count)
pending_count -= skipped_count
summary = pluralize(example_count, "example")
summary << " ("
summary << red(pluralize(failure_count, "failure"))
summary << ", " << yellow("#{pending_count} pending") if pending_count > 0
su... | ruby | {
"resource": ""
} |
q9423 | PayuLatam.SubscriptionInterceptor.run | train | def run
PayuLatam::SubscriptionService.new(context.params, context.current_user).call
rescue => exception
fail!(exception.message)
end | ruby | {
"resource": ""
} |
q9424 | Logsly::Logging182::Stats.Sampler.coalesce | train | def coalesce( other )
@sum += other.sum
@sumsq += other.sumsq
if other.num > 0
@min = other.min if @min > other.min
@max = other.max if @max < other.max
@last = other.last
end
@num += other.num
end | ruby | {
"resource": ""
} |
q9425 | Logsly::Logging182::Stats.Sampler.sample | train | def sample( s )
@sum += s
@sumsq += s * s
if @num == 0
@min = @max = s
else
@min = s if @min > s
@max = s if @max < s
end
@num += 1
@last = s
end | ruby | {
"resource": ""
} |
q9426 | Logsly::Logging182::Stats.Sampler.sd | train | def sd
return 0.0 if num < 2
# (sqrt( ((s).sumsq - ( (s).sum * (s).sum / (s).num)) / ((s).num-1) ))
begin
return Math.sqrt( (sumsq - ( sum * sum / num)) / (num-1) )
rescue Errno::EDOM
return 0.0
end
end | ruby | {
"resource": ""
} |
q9427 | Logsly::Logging182::Stats.Tracker.coalesce | train | def coalesce( other )
sync {
other.stats.each do |name,sampler|
stats[name].coalesce(sampler)
end
}
end | ruby | {
"resource": ""
} |
q9428 | Logsly::Logging182::Stats.Tracker.time | train | def time( event )
sync {stats[event].mark}
yield
ensure
sync {stats[event].tick}
end | ruby | {
"resource": ""
} |
q9429 | Logsly::Logging182::Stats.Tracker.periodically_run | train | def periodically_run( period, &block )
raise ArgumentError, 'a runner already exists' unless @runner.nil?
@runner = Thread.new do
start = stop = Time.now.to_f
loop do
seconds = period - (stop-start)
seconds = period if seconds <= 0
sleep seconds
star... | ruby | {
"resource": ""
} |
q9430 | Palimpsest.Assets.write | train | def write(target, gzip: options[:gzip], hash: options[:hash])
asset = assets[target]
return if asset.nil?
name = hash ? asset.digest_path : asset.logical_path.to_s
name = File.join(options[:output], name) unless options[:output].nil?
path = name
path = File.join(directory, path) u... | ruby | {
"resource": ""
} |
q9431 | BreadcrumbTrail.Breadcrumb.computed_path | train | def computed_path(context)
@_path ||= case @path
when String, Hash
@path
when Symbol
context.public_send(@path) # todo
when Proc
context.instance_exec(&@path)
else
raise ArgumentError,
"Expected one of String, Symbol, or Proc, " \
"got #{... | ruby | {
"resource": ""
} |
q9432 | BreadcrumbTrail.Breadcrumb.computed_name | train | def computed_name(context)
@_name ||= case @name
when String
@name
when Symbol
I18n.translate(@name)
when Proc
context.instance_exec(&@name)
when nil
computed_path(context)
else
raise ArgumentError,
"Expected one of String, Symbol, or... | ruby | {
"resource": ""
} |
q9433 | SycLink.Firefox.read | train | def read
bookmark_file = Dir.glob(File.expand_path(path)).shift
raise "Did not find file #{path}" unless bookmark_file
db = SQLite3::Database.new(path)
import = db.execute(QUERY_STRING)
end | ruby | {
"resource": ""
} |
q9434 | SycLink.Firefox.rows | train | def rows
read.map do |row|
a = row[0]; b = row[1]; c = row[2]; d = row[3]; e = row[4]; f = row[5]
[a,
b || c,
(d || '').gsub("\n", ' '),
[e, f].join(',').gsub(/^,|,$/, '')]
end
end | ruby | {
"resource": ""
} |
q9435 | FaviconParty.Image.to_png | train | def to_png
return @png_data if !@png_data.nil?
image = minimagick_image
image.resize '16x16!'
image.format 'png'
image.strip
@png_data = image.to_blob
raise FaviconParty::InvalidData.new("Empty png") if @png_data.empty?
@png_data
end | ruby | {
"resource": ""
} |
q9436 | Palimpsest.Repo.extract_repo | train | def extract_repo(path, destination, reference)
fail 'Git not installed' unless Utils.command? 'git'
Dir.chdir path do
system "git archive #{reference} | tar -x -C #{destination}"
end
end | ruby | {
"resource": ""
} |
q9437 | BreadcrumbTrail.BlockBuilder.call | train | def call
buffer = ActiveSupport::SafeBuffer.new
@breadcrumbs.each do |breadcrumb|
buffer << @block.call(breadcrumb.computed(@context))
end
buffer
end | ruby | {
"resource": ""
} |
q9438 | BreadcrumbTrail.HTMLBuilder.call | train | def call
outer_tag = @options.fetch(:outer, "ol")
inner_tag = @options.fetch(:inner, "li")
outer = tag(outer_tag,
@options.fetch(:outer_options, nil),
true) if outer_tag
inner = tag(inner_tag,
@options.fetch(:inner_options, nil),
... | ruby | {
"resource": ""
} |
q9439 | Swift.FiberConnectionPool.acquire | train | def acquire id, fiber
if conn = @available.pop
@reserved[id] = conn
else
Fiber.yield @pending.push(fiber)
acquire(id, fiber)
end
end | ruby | {
"resource": ""
} |
q9440 | Swift.FiberConnectionPool.method_missing | train | def method_missing method, *args, &blk
__reserve__ do |conn|
if @trace
conn.trace(@trace) {conn.__send__(method, *args, &blk)}
else
conn.__send__(method, *args, &blk)
end
end
end | ruby | {
"resource": ""
} |
q9441 | LegoNXT::LowLevel.UsbConnection.transmit! | train | def transmit! bits
bytes_sent = @handle.bulk_transfer dataOut: bits, endpoint: USB_ENDPOINT_OUT
bytes_sent == bits.length
end | ruby | {
"resource": ""
} |
q9442 | LegoNXT::LowLevel.UsbConnection.transceive | train | def transceive bits
raise ::LegoNXT::BadOpCodeError unless bytestring(DirectOps::REQUIRE_RESPONSE, SystemOps::REQUIRE_RESPONSE).include? bits[0]
raise ::LegoNXT::TransmitError unless transmit! bits
bytes_received = @handle.bulk_transfer dataIn: 64, endpoint: USB_ENDPOINT_IN
return bytes_received... | ruby | {
"resource": ""
} |
q9443 | LegoNXT::LowLevel.UsbConnection.open | train | def open
context = LIBUSB::Context.new
device = context.devices(:idVendor => LEGO_VENDOR_ID, :idProduct => NXT_PRODUCT_ID).first
raise ::LegoNXT::NoDeviceError.new("Please make sure the device is plugged in and powered on") if device.nil?
@handle = device.open
@handle.claim_interface(0)
... | ruby | {
"resource": ""
} |
q9444 | Gricer.RequestsController.handle_special_fields | train | def handle_special_fields
if ['referer_host', 'referer_path', 'referer_params', 'search_engine', 'search_query'].include?(params[:field])
@items = @items.only_first_in_session
end
if ['search_engine', 'search_query'].include?(params[:field])
@items = @items.without_nil_in params... | ruby | {
"resource": ""
} |
q9445 | StixSchemaSpy.Node.referenced_element | train | def referenced_element
ref = @xml.attributes['ref'].value
@referenced_element ||= if ref =~ /:/
prefix, element = ref.split(':')
schema.find_element(element) || schema.find_attribute("@#{element}") if schema = Schema.find(prefix)
else
self.schema.find_element(ref) || self.schem... | ruby | {
"resource": ""
} |
q9446 | HasPrice.PriceBuilder.item | train | def item(price, item_name)
@current_nesting_level[item_name.to_s] = price.respond_to?(:to_hash) ? price.to_hash : price.to_i
end | ruby | {
"resource": ""
} |
q9447 | HasPrice.PriceBuilder.group | train | def group(group_name, &block)
group_key = group_name.to_s
@current_nesting_level[group_key] ||= {}
if block_given?
within_group(group_key) do
instance_eval &block
end
end
end | ruby | {
"resource": ""
} |
q9448 | Kat.Search.query= | train | def query=(search_term)
@search_term =
case search_term
when nil, '' then []
when String, Symbol then [search_term]
when Array then search_term.flatten.select { |e| [String, Symbol].include? e.class }
else fail ArgumentError, 'search_term must be a String, S... | ruby | {
"resource": ""
} |
q9449 | Kat.Search.options= | train | def options=(options)
fail ArgumentError, 'options must be a Hash. ' \
"#{ options.inspect } given." unless options.is_a?(Hash)
@options.merge! options
build_query
end | ruby | {
"resource": ""
} |
q9450 | Kat.Search.build_query | train | def build_query
@query = @search_term.dup
@pages = -1
@results = []
@query << "\"#{ @options[:exact] }\"" if @options[:exact]
@query << @options[:or].join(' OR ') unless @options[:or].nil? or @options[:or].empty?
@query += @options[:without].map { |s| "-#{ s }" } if @options[:wi... | ruby | {
"resource": ""
} |
q9451 | Kat.Search.results_column | train | def results_column(name)
@results.compact.map do |rs|
rs.map { |r| r[name] || r[name[0...-1].intern] }
end.flatten
end | ruby | {
"resource": ""
} |
q9452 | Aker.User.full_name | train | def full_name
display_name_parts = [first_name, last_name].compact
if display_name_parts.empty?
username
else
display_name_parts.join(' ')
end
end | ruby | {
"resource": ""
} |
q9453 | EasyPartials.HelperAdditions.concat_partial | train | def concat_partial(partial, *args, &block)
rendered = invoke_partial partial, *args, &block
concat rendered
end | ruby | {
"resource": ""
} |
q9454 | Aker::Authorities.Static.valid_credentials? | train | def valid_credentials?(kind, *credentials)
found_username =
(all_credentials(kind).detect { |c| c[:credentials] == credentials } || {})[:username]
@users[found_username]
end | ruby | {
"resource": ""
} |
q9455 | Aker::Authorities.Static.load! | train | def load!(io)
doc = YAML.load(io)
return self unless doc
(doc["groups"] || {}).each do |portal, top_level_groups|
@groups[portal.to_sym] = top_level_groups.collect { |group_data| build_group(group_data) }
end
(doc["users"] || {}).each do |username, config|
attr_keys = confi... | ruby | {
"resource": ""
} |
q9456 | Reaction.Client.broadcast | train | def broadcast(name, message, opts={})
# encapsulation
encap = { n: name,
m: message,
t: opts[:to] || /.*/,
e: opts[:except] || []
}
EM.next_tick {
@faye.publish BROADCAST, Base64.urlsafe_encode64(Marshal.dump(encap))
}
... | ruby | {
"resource": ""
} |
q9457 | Manage.ResourceHelper.action_link | train | def action_link(scope, link_data)
value = nil
case link_data
when Proc
value = link_data.call(scope)
when Hash
relation = link_data.keys.first
entity = Fields::Reader.field_value(scope, relation)
unless entity.present?
return ''
end
if ... | ruby | {
"resource": ""
} |
q9458 | Addresslogic.ClassMethods.apply_addresslogic | train | def apply_addresslogic(options = {})
n = options[:namespace]
options[:fields] ||= [
"#{n}street1".to_sym,
"#{n}street2".to_sym,
["#{n}city".to_sym, ["#{n}state".to_sym, "#{n}zip".to_sym]],
"#{n}country".to_sym
]
self.addresslogic_options = options
inc... | ruby | {
"resource": ""
} |
q9459 | Yargraph.UndirectedGraph.hamiltonian_cycles_dynamic_programming | train | def hamiltonian_cycles_dynamic_programming(operational_limit=nil)
stack = DS::Stack.new
return [] if @vertices.empty?
origin_vertex = @vertices.to_a[0]
hamiltonians = []
num_operations = 0
# This hash keeps track of subproblems that have already been
# solved. ie is there a p... | ruby | {
"resource": ""
} |
q9460 | Overcloud.Node.introspect_node | train | def introspect_node(node_uuid)
workflow = 'tripleo.baremetal.v1.introspect'
input = { node_uuids: [node_uuid] }
execute_workflow(workflow, input, false)
end | ruby | {
"resource": ""
} |
q9461 | SiteAnalyzer.Site.add_pages_for_scan! | train | def add_pages_for_scan!
@pages_for_scan = []
@bad_pages = []
@pages.each do |page|
@bad_pages << page.page_url unless page.page_a_tags
next unless page.page_a_tags
page.home_a.each do |link|
@pages_for_scan << link
end
end
end | ruby | {
"resource": ""
} |
q9462 | SiteAnalyzer.Site.add_page | train | def add_page(url)
unless robot_txt_allowed?(url)
@scanned_pages << url
return nil
end
page = Page.new(url)
@pages << page
@scanned_pages << url
end | ruby | {
"resource": ""
} |
q9463 | SiteAnalyzer.Site.all_titles | train | def all_titles
result = []
@pages.each do |page|
result << [page.page_url, page.all_titles] if page.page_a_tags
end
result
end | ruby | {
"resource": ""
} |
q9464 | SiteAnalyzer.Site.all_descriptions | train | def all_descriptions
result = []
@pages.each do |page|
result << [page.page_url, page.meta_desc_content] if page.page_a_tags
end
result
end | ruby | {
"resource": ""
} |
q9465 | SiteAnalyzer.Site.all_h2 | train | def all_h2
result = []
@pages.each do |page|
result << [page.page_url, page.h2_text] unless page.page_a_tags
end
result
end | ruby | {
"resource": ""
} |
q9466 | SiteAnalyzer.Site.all_a | train | def all_a
result = []
@pages.each do |page|
next unless page.page_a_tags
page.page_a_tags.compact.each do |tag|
tag[0] = '-' unless tag[0]
tag[1] = '-' unless tag[1]
tag[2] = '-' unless tag[2]
result << [page.page_url, tag[0], tag[1], tag[2]]
e... | ruby | {
"resource": ""
} |
q9467 | SiteAnalyzer.Site.convert_to_valid | train | def convert_to_valid(url)
return nil if url =~ /.jpg$/i
url.insert(0, @main_url.first(5)) if url.start_with? '//'
link = URI(url)
main_page = URI(@main_url)
if link && link.scheme && link.scheme.empty?
link.scheme = main_page.scheme
elsif link.nil?
return nil
en... | ruby | {
"resource": ""
} |
q9468 | Sawaal.Selections.read_char | train | def read_char
input = $stdin.getch
return input unless input == "\e"
begin
Timeout.timeout(0.01) do
input += $stdin.getch
input += $stdin.getch
end
rescue Timeout::Error
# ignored
end
input
end | ruby | {
"resource": ""
} |
q9469 | TodoLint.Reporter.number_of_spaces | train | def number_of_spaces
todo.character_number - 1 - (todo.line.length - todo.line.lstrip.length)
end | ruby | {
"resource": ""
} |
q9470 | Swift.Adapter.create | train | def create record, resources
result = [resources].flatten.map do |resource|
resource = record.new(resource) unless resource.kind_of?(record)
result = execute(command_create(record), *resource.tuple.values_at(*record.header.insertable))
resource.tuple[record.header.serial] = result.insert... | ruby | {
"resource": ""
} |
q9471 | Swift.Adapter.update | train | def update record, resources
result = [resources].flatten.map do |resource|
resource = record.new(resource) unless resource.kind_of?(record)
keys = resource.tuple.values_at(*record.header.keys)
# TODO: Name the key field(s) missing.
raise ArgumentError, "#{record} resource has... | ruby | {
"resource": ""
} |
q9472 | Swift.Adapter.delete | train | def delete record, resources
result = [resources].flatten.map do |resource|
resource = record.new(resource) unless resource.kind_of?(record)
keys = resource.tuple.values_at(*record.header.keys)
# TODO: Name the key field(s) missing.
raise ArgumentError, "#{record} resource has... | ruby | {
"resource": ""
} |
q9473 | Swift.Adapter.prepare | train | def prepare record = nil, command
record ? Statement.new(record, command) : db.prepare(command)
end | ruby | {
"resource": ""
} |
q9474 | Swift.Adapter.execute | train | def execute command, *bind
start = Time.now
record, command = command, bind.shift if command.kind_of?(Class) && command < Record
record ? Result.new(record, db.execute(command, *bind)) : db.execute(command, *bind)
ensure
log_command(start, command, bind) if @trace
end | ruby | {
"resource": ""
} |
q9475 | Troy.Page.method_missing | train | def method_missing(name, *args, &block)
return meta[name.to_s] if meta.key?(name.to_s)
super
end | ruby | {
"resource": ""
} |
q9476 | Troy.Page.render | train | def render
ExtensionMatcher.new(path)
.default { content }
.on("html") { compress render_erb }
.on("md") { compress render_erb }
.on("erb") { compress render_erb }
.match
end | ruby | {
"resource": ""
} |
q9477 | Troy.Page.save_to | train | def save_to(path)
File.open(path, "w") do |file|
I18n.with_locale(meta.locale) do
file << render
end
end
end | ruby | {
"resource": ""
} |
q9478 | ZeevexThreadsafe::ThreadLocals.InstanceMethods._thread_local_clean | train | def _thread_local_clean
ids = Thread.list.map &:object_id
(@_thread_local_threads.keys - ids).each { |key| @_thread_local_threads.delete(key) }
end | ruby | {
"resource": ""
} |
q9479 | CaRuby.Properties.[]= | train | def []=(key, value)
return super if has_key?(key)
alt = alternate_key(key)
has_key?(alt) ? super(alt, value) : super
end | ruby | {
"resource": ""
} |
q9480 | CaRuby.Properties.load_properties | train | def load_properties(file)
raise ConfigurationError.new("Properties file not found: #{File.expand_path(file)}") unless File.exists?(file)
properties = {}
begin
YAML.load_file(file).each { |key, value| properties[key.to_sym] = value }
rescue
raise ConfigurationError.new("Could not ... | ruby | {
"resource": ""
} |
q9481 | SycLink.Infrastructure.copy_file_if_missing | train | def copy_file_if_missing(file, to_directory)
unless File.exists? File.join(to_directory, File.basename(file))
FileUtils.cp(file, to_directory)
end
end | ruby | {
"resource": ""
} |
q9482 | SycLink.Infrastructure.load_config | train | def load_config(file)
unless File.exists? file
File.open(file, 'w') do |f|
YAML.dump({ default_website: 'default' }, f)
end
end
YAML.load_file(file)
end | ruby | {
"resource": ""
} |
q9483 | RailsViewHelpers.DatetimeHelper.datetime_to_s | train | def datetime_to_s(date_or_datetime, format)
return '' if date_or_datetime.blank?
return date_or_datetime.to_s(format) if date_or_datetime.instance_of?(Date)
date_or_datetime.localtime.to_s(format)
end | ruby | {
"resource": ""
} |
q9484 | Authpwn.HttpTokenControllerInstanceMethods.authenticate_using_http_token | train | def authenticate_using_http_token
return if current_user
authenticate_with_http_token do |token_code, options|
auth = Tokens::Api.authenticate token_code
# NOTE: Setting the instance variable directly bypasses the session
# setup. Tokens are generally used in API contexts, so the sessio... | ruby | {
"resource": ""
} |
q9485 | XES.Document.format | train | def format
raise FormatError.new(self) unless formattable?
REXML::Document.new.tap do |doc|
doc << REXML::XMLDecl.new
doc.elements << @log.format
end
end | ruby | {
"resource": ""
} |
q9486 | Polyseerio.Request.execute | train | def execute(method, *args)
new_args = args
@pre_request.each do |middleware|
new_args = middleware.call(*new_args)
end
path = new_args.empty? ? '' : new_args.shift
req = proc do ||
@resource[path].send(method, *new_args)
end
post = proc do |result|
@... | ruby | {
"resource": ""
} |
q9487 | ThumbnailHoverEffect.Image.render | train | def render(parameters = {})
has_thumbnail = parameters.fetch(:has_thumbnail, true)
effect_number = parameters.fetch(:effect_number, false)
thumbnail_template = self.get_template(effect_number)
if has_thumbnail
@attributes.map { |key, value| thumbnail_template["###{key}##"] &&= value }... | ruby | {
"resource": ""
} |
q9488 | Geo.Itudes.distance | train | def distance other, units = :km
o = Itudes.new other
raise ArgumentError.new "operand must be lat-/longitudable" if (o.latitude.nil? || o.longitude.nil?)
dlat = Itudes.radians(o.latitude - @latitude)
dlon = Itudes.radians(o.longitude - @longitude)
lat1 = Itudes.radians(@latitude... | ruby | {
"resource": ""
} |
q9489 | Checkdin.Promotions.promotions | train | def promotions(options={})
response = connection.get do |req|
req.url "promotions", options
end
return_error_or_body(response)
end | ruby | {
"resource": ""
} |
q9490 | Checkdin.Promotions.promotion_votes_leaderboard | train | def promotion_votes_leaderboard(id, options={})
response = connection.get do |req|
req.url "promotions/#{id}/votes_leaderboard", options
end
return_error_or_body(response)
end | ruby | {
"resource": ""
} |
q9491 | Fishbans.PlayerSkins.get_player_image | train | def get_player_image(username, type, size)
url = "http://i.fishbans.com/#{type}/#{username}/#{size}"
response = get(url, false)
ChunkyPNG::Image.from_blob(response.body)
end | ruby | {
"resource": ""
} |
q9492 | CopyCsv.ClassMethods.write_to_csv | train | def write_to_csv(file_name, mode = "w")
File.open(file_name, mode) do |file|
all.copy_csv(file)
end
end | ruby | {
"resource": ""
} |
q9493 | Gricer.BaseController.process_stats | train | def process_stats
@items = basic_collection
handle_special_fields
data = {
alternatives: [
{
type: 'spread',
uri: url_for(action: "spread_stats", field: params[:field], filters: params[:filters], only_path: true)
},
{
... | ruby | {
"resource": ""
} |
q9494 | Gricer.BaseController.spread_stats | train | def spread_stats
@items = basic_collection.between_dates(@stat_from, @stat_thru)
handle_special_fields
data = {
alternatives: [
{
type: 'spread'
},
{
type: 'process',
uri: url_for(action: "process_stats", fiel... | ruby | {
"resource": ""
} |
q9495 | Gricer.BaseController.guess_from_thru | train | def guess_from_thru
begin
@stat_thru = Time.parse(params[:thru]).to_date
rescue
end
begin
@stat_from = Time.parse(params[:from]).to_date
rescue
end
if @stat_from.nil?
if @stat_thru.nil?
@stat_thru = Time.now.localtime.to_date ... | ruby | {
"resource": ""
} |
q9496 | PutText.POFile.write_to | train | def write_to(io)
deduplicate
io.write(@header_entry.to_s)
@entries.each do |entry|
io.write("\n")
io.write(entry.to_s)
end
end | ruby | {
"resource": ""
} |
q9497 | CaRuby.Cache.clear | train | def clear
if @sticky.empty? then
@ckh.clear
else
@ckh.each { |klass, ch| ch.clear unless @sticky.include?(klass) }
end
end | ruby | {
"resource": ""
} |
q9498 | HS.Chapter.find_module | train | def find_module(slug)
modules.find { |m| m.slug.to_s == slug.to_s }
end | ruby | {
"resource": ""
} |
q9499 | LolitaPaypal.TransactionsController.answer | train | def answer
if request.post?
if ipn_notify.acknowledge
LolitaPaypal::Transaction.create_transaction(ipn_notify, payment_from_ipn, request)
end
render nothing: true
else
if payment_from_ipn
redirect_to payment_from_ipn.paypal_return_path
else
... | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.