_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q6600
|
BasicCache.TimeCache.prune
|
train
|
def prune
@store.keys.reject { |k| include? k }.map { |k| clear!(k) && k }
end
|
ruby
|
{
"resource": ""
}
|
q6601
|
Refheap.Paste.create
|
train
|
def create(contents, params = {:language => "Plain Text", :private => false})
params = params.merge({:contents => contents}.merge(@base_params))
self.class.post("/paste", :body => params).parsed_response
end
|
ruby
|
{
"resource": ""
}
|
q6602
|
Zomato2.Restaurant.details
|
train
|
def details(start: nil, count: nil)
# warn "\tRestaurant#details: This method is currently useless, since, " +
# "as of January 2017, Zomato's API doesn't give any additional info here."
q = {res_id: @id }
q[:start] = start if start
q[:count] = count if count
results = get('restaurant', q)
@location ||= Location.new zom_conn, attributes["location"]
@city_id ||= @location.city_id
results.each do |k,v|
if k == 'apikey'
next
elsif k == 'R'
@id = v['res_id']
# Zomato never returns this?? bad API doc!
elsif k == 'location'
next
elsif k == 'all_reviews'
@reviews ||= v.map{ |r| Review.new(zom_conn, r) }
elsif k == 'establishment_types'
@establishments ||= v.map{ |e,ev| Establishment.new(zom_conn, @city_id, ev) }
# elsif k == 'cuisines' the returned cuisines here are just a string..
else
#puts "ATTR @#{k} val #{v}"
self.instance_variable_set("@#{k}", v)
end
end
self
end
|
ruby
|
{
"resource": ""
}
|
q6603
|
BarkestCore.FormHelper.label_with_small
|
train
|
def label_with_small(f, method, text=nil, options = {}, &block)
if text.is_a?(Hash)
options = text
text = nil
end
small_text = options.delete(:small_text)
text = text || options.delete(:text) || method.to_s.humanize.capitalize
lbl = f.label(method, text, options, &block) #do
# contents = text
# contents += "<small>#{h small_text}</small>" if small_text
# contents += yield if block_given?
# contents.html_safe
#end
lbl += " <small>(#{h small_text})</small>".html_safe if small_text
lbl.html_safe
end
|
ruby
|
{
"resource": ""
}
|
q6604
|
BarkestCore.FormHelper.text_form_group
|
train
|
def text_form_group(f, method, options = {})
gopt, lopt, fopt = split_form_group_options(options)
lbl = f.label_with_small method, lopt.delete(:text), lopt
fld = gopt[:wrap].call(f.text_field(method, fopt))
form_group lbl, fld, gopt
end
|
ruby
|
{
"resource": ""
}
|
q6605
|
BarkestCore.FormHelper.multi_input_form_group
|
train
|
def multi_input_form_group(f, methods, options = {})
gopt, lopt, fopt = split_form_group_options(options)
lopt[:text] ||= gopt[:label]
if lopt[:text].blank?
lopt[:text] = methods.map {|k,_| k.to_s.humanize }.join(', ')
end
lbl = f.label_with_small methods.map{|k,_| k}.first, lopt[:text], lopt
fld = gopt[:wrap].call(multi_input_field(f, methods, fopt))
form_group lbl, fld, gopt
end
|
ruby
|
{
"resource": ""
}
|
q6606
|
BarkestCore.FormHelper.checkbox_form_group
|
train
|
def checkbox_form_group(f, method, options = {})
gopt, lopt, fopt = split_form_group_options({ class: 'checkbox', field_class: ''}.merge(options))
if gopt[:h_align]
gopt[:class] = gopt[:class].blank? ?
"col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}" :
"#{gopt[:class]} col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}"
end
lbl = f.label method do
f.check_box(method, fopt) +
h(lopt[:text] || method.to_s.humanize) +
if lopt[:small_text]
"<small>#{h lopt[:small_text]}</small>"
else
''
end.html_safe
end
"<div class=\"#{gopt[:h_align] ? 'row' : 'form-group'}\"><div class=\"#{gopt[:class]}\">#{lbl}</div></div>".html_safe
end
|
ruby
|
{
"resource": ""
}
|
q6607
|
BarkestCore.FormHelper.select_form_group
|
train
|
def select_form_group(f, method, collection, value_method = nil, text_method = nil, options = {})
gopt, lopt, fopt = split_form_group_options({ field_include_blank: true }.merge(options))
lbl = f.label_with_small method, lopt.delete(:text), lopt
value_method ||= :to_s
text_method ||= :to_s
opt = {}
[:include_blank, :prompt, :include_hidden].each do |attr|
if fopt[attr] != nil
opt[attr] = fopt[attr]
fopt.except! attr
end
end
fld = gopt[:wrap].call(f.collection_select(method, collection, value_method, text_method, opt, fopt))
form_group lbl, fld, gopt
end
|
ruby
|
{
"resource": ""
}
|
q6608
|
Bebox.NodeCommands.generate_node_command
|
train
|
def generate_node_command(node_command, command, send_command, description)
node_command.desc description
node_command.command command do |generated_command|
generated_command.action do |global_options,options,args|
environment = get_environment(options)
info _('cli.current_environment')%{environment: environment}
Bebox::NodeWizard.new.send(send_command, project_root, environment)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6609
|
Familia.ClassMethods.install_redis_object
|
train
|
def install_redis_object name, klass, opts
raise ArgumentError, "Name is blank" if name.to_s.empty?
name = name.to_s.to_sym
opts ||= {}
redis_objects_order << name
redis_objects[name] = OpenStruct.new
redis_objects[name].name = name
redis_objects[name].klass = klass
redis_objects[name].opts = opts
self.send :attr_reader, name
define_method "#{name}=" do |v|
self.send(name).replace v
end
define_method "#{name}?" do
!self.send(name).empty?
end
redis_objects[name]
end
|
ruby
|
{
"resource": ""
}
|
q6610
|
Familia.ClassMethods.install_class_redis_object
|
train
|
def install_class_redis_object name, klass, opts
raise ArgumentError, "Name is blank" if name.to_s.empty?
name = name.to_s.to_sym
opts = opts.nil? ? {} : opts.clone
opts[:parent] = self unless opts.has_key?(:parent)
# TODO: investigate using metaclass.redis_objects
class_redis_objects_order << name
class_redis_objects[name] = OpenStruct.new
class_redis_objects[name].name = name
class_redis_objects[name].klass = klass
class_redis_objects[name].opts = opts
# An accessor method created in the metclass will
# access the instance variables for this class.
metaclass.send :attr_reader, name
metaclass.send :define_method, "#{name}=" do |v|
send(name).replace v
end
metaclass.send :define_method, "#{name}?" do
!send(name).empty?
end
redis_object = klass.new name, opts
redis_object.freeze
self.instance_variable_set("@#{name}", redis_object)
class_redis_objects[name]
end
|
ruby
|
{
"resource": ""
}
|
q6611
|
Familia.ClassMethods.load_or_create
|
train
|
def load_or_create idx
return from_redis(idx) if exists?(idx)
obj = from_index idx
obj.save
obj
end
|
ruby
|
{
"resource": ""
}
|
q6612
|
Familia.ClassMethods.rediskey
|
train
|
def rediskey idx, suffix=self.suffix
raise RuntimeError, "No index for #{self}" if idx.to_s.empty?
idx = Familia.join *idx if Array === idx
idx &&= idx.to_s
Familia.rediskey(prefix, idx, suffix)
end
|
ruby
|
{
"resource": ""
}
|
q6613
|
Familia.InstanceMethods.initialize_redis_objects
|
train
|
def initialize_redis_objects
# Generate instances of each RedisObject. These need to be
# unique for each instance of this class so they can refer
# to the index of this specific instance.
#
# i.e.
# familia_object.rediskey == v1:bone:INDEXVALUE:object
# familia_object.redis_object.rediskey == v1:bone:INDEXVALUE:name
#
# See RedisObject.install_redis_object
self.class.redis_objects.each_pair do |name, redis_object_definition|
klass, opts = redis_object_definition.klass, redis_object_definition.opts
opts = opts.nil? ? {} : opts.clone
opts[:parent] = self unless opts.has_key?(:parent)
redis_object = klass.new name, opts
redis_object.freeze
self.instance_variable_set "@#{name}", redis_object
end
end
|
ruby
|
{
"resource": ""
}
|
q6614
|
RHapi.Lead.method_missing
|
train
|
def method_missing(method, *args, &block)
attribute = ActiveSupport::Inflector.camelize(method.to_s, false)
if attribute =~ /=$/
attribute = attribute.chop
return super unless self.attributes.include?(attribute)
self.changed_attributes[attribute] = args[0]
self.attributes[attribute] = args[0]
else
return super unless self.attributes.include?(attribute)
self.attributes[attribute]
end
end
|
ruby
|
{
"resource": ""
}
|
q6615
|
UsBankHolidays.HolidayYear.bank_holidays
|
train
|
def bank_holidays
@bank_holidays ||= begin
holidays = [ new_years_day,
mlk_day,
washingtons_birthday,
memorial_day,
independence_day,
labor_day,
columbus_day,
veterans_day,
thanksgiving,
christmas
]
if Date.new(year + 1, 1, 1).saturday?
holidays << Date.new(year, 12, 31)
end
holidays.freeze
end
end
|
ruby
|
{
"resource": ""
}
|
q6616
|
UsBankHolidays.HolidayYear.init_fixed_holidays
|
train
|
def init_fixed_holidays
# Third Monday of January
@mlk_day = january.mondays[2]
# Third Monday of February
@washingtons_birthday = february.mondays[2]
# Last Monday of May
@memorial_day = may.mondays.last
# First Monday of September
@labor_day = september.mondays.first
# Second Monday of October
@columbus_day = october.mondays[1]
# Fourth Thursday of November
@thanksgiving = november.thursdays[3]
end
|
ruby
|
{
"resource": ""
}
|
q6617
|
UsBankHolidays.HolidayYear.init_rolled_holidays
|
train
|
def init_rolled_holidays
# First of the year, rolls either forward or back.
@new_years_day = roll_nominal(Date.new(year, 1, 1))
# 4'th of July
@independence_day = roll_nominal(Date.new(year, 7, 4))
# November 11
@veterans_day = roll_nominal(Date.new(year, 11, 11))
# December 25
@christmas = roll_nominal(Date.new(year, 12, 25))
end
|
ruby
|
{
"resource": ""
}
|
q6618
|
Guard.Shopify.upgrade_config_file
|
train
|
def upgrade_config_file
puts "Old config file found, upgrading..."
credentials = File.read(config_file_path).split("\n")
config = {}
config['api_key'] = credentials[0]
config['password'] = credentials[1]
config['url'] = credentials[2]
config['secret'] = prompt "Please enter your API Shared Secret"
write_config config
puts 'Upgraded old config file to new format'
config
end
|
ruby
|
{
"resource": ""
}
|
q6619
|
Seedable.ObjectTracker.contains?
|
train
|
def contains?(object)
key, id = to_key_and_id(object)
@graph[key].is_a?(Enumerable) ? @graph[key].include?(id) : @graph[key]
end
|
ruby
|
{
"resource": ""
}
|
q6620
|
Seedable.ObjectTracker.add
|
train
|
def add(object)
key, id = to_key_and_id(object)
@graph[key] ? @graph[key] << id : @graph[key] = [id]
end
|
ruby
|
{
"resource": ""
}
|
q6621
|
Tangle.BaseGraph.subgraph
|
train
|
def subgraph(included = nil, &selector)
result = clone
result.select_vertices!(included) unless included.nil?
result.select_vertices!(&selector) if block_given?
result
end
|
ruby
|
{
"resource": ""
}
|
q6622
|
Tangle.BaseGraph.add_vertex
|
train
|
def add_vertex(vertex, name: nil)
name ||= callback(vertex, :name)
insert_vertex(vertex, name)
define_currified_methods(vertex, :vertex) if @currify
callback(vertex, :added_to_graph, self)
self
end
|
ruby
|
{
"resource": ""
}
|
q6623
|
Tangle.BaseGraph.remove_vertex
|
train
|
def remove_vertex(vertex)
@vertices[vertex].each do |edge|
remove_edge(edge) if edge.include?(vertex)
end
delete_vertex(vertex)
callback(vertex, :removed_from_graph, self)
end
|
ruby
|
{
"resource": ""
}
|
q6624
|
Tangle.BaseGraph.add_edge
|
train
|
def add_edge(*vertices, **kvargs)
edge = new_edge(*vertices, mixins: @mixins, **kvargs)
insert_edge(edge)
vertices.each { |vertex| callback(vertex, :edge_added, edge) }
edge
end
|
ruby
|
{
"resource": ""
}
|
q6625
|
Tangle.BaseGraph.remove_edge
|
train
|
def remove_edge(edge)
delete_edge(edge)
edge.each_vertex { |vertex| callback(vertex, :edge_removed, edge) }
end
|
ruby
|
{
"resource": ""
}
|
q6626
|
Lightstreamer.Session.disconnect
|
train
|
def disconnect
control_request LS_op: :destroy if @stream_connection
@processing_thread.join 5 if @processing_thread
ensure
@stream_connection.disconnect if @stream_connection
@processing_thread.exit if @processing_thread
@subscriptions.each { |subscription| subscription.after_control_request :stop }
@subscriptions = []
@processing_thread = @stream_connection = nil
end
|
ruby
|
{
"resource": ""
}
|
q6627
|
Lightstreamer.Session.create_processing_thread
|
train
|
def create_processing_thread
@processing_thread = Thread.new do
Thread.current.abort_on_exception = true
loop { break unless processing_thread_tick @stream_connection.read_line }
@processing_thread = @stream_connection = nil
end
end
|
ruby
|
{
"resource": ""
}
|
q6628
|
Lightstreamer.Session.process_stream_line
|
train
|
def process_stream_line(line)
return if @mutex.synchronize { @subscriptions.any? { |subscription| subscription.process_stream_data line } }
return if process_send_message_outcome line
warn "Lightstreamer: unprocessed stream data '#{line}'"
end
|
ruby
|
{
"resource": ""
}
|
q6629
|
Lightstreamer.Session.process_send_message_outcome
|
train
|
def process_send_message_outcome(line)
outcome = SendMessageOutcomeMessage.parse line
return unless outcome
@mutex.synchronize do
@callbacks[:on_message_result].each do |callback|
callback.call outcome.sequence, outcome.numbers, outcome.error
end
end
true
end
|
ruby
|
{
"resource": ""
}
|
q6630
|
Mongoid.AtomicVotes.vote
|
train
|
def vote(value, voted_by)
mark = Vote.new(value: value, voted_by_id: voted_by.id, voter_type: voted_by.class.name)
add_vote_mark(mark)
end
|
ruby
|
{
"resource": ""
}
|
q6631
|
Mongoid.AtomicVotes.retract
|
train
|
def retract(voted_by)
mark = votes.find_by(voted_by_id: voted_by.id)
mark && remove_vote_mark(mark)
end
|
ruby
|
{
"resource": ""
}
|
q6632
|
Mongoid.AtomicVotes.voted_by?
|
train
|
def voted_by?(voted_by)
!!votes.find_by(voted_by_id: voted_by.id)
rescue NoMethodError, Mongoid::Errors::DocumentNotFound
false
end
|
ruby
|
{
"resource": ""
}
|
q6633
|
Shells.ShellBase.run
|
train
|
def run(&block)
sync do
raise Shells::AlreadyRunning if running?
self.run_flag = true
end
begin
run_hook :on_before_run
debug 'Connecting...'
connect
debug 'Starting output buffering...'
buffer_output
debug 'Starting session thread...'
self.session_thread = Thread.start(self) do |sh|
begin
begin
debug 'Executing setup...'
sh.instance_eval { setup }
debug 'Executing block...'
block.call sh
ensure
debug 'Executing teardown...'
sh.instance_eval { teardown }
end
rescue Shells::QuitNow
# just exit the session.
rescue =>e
# if the exception is handled by the hook no further processing is required, otherwise we store the exception
# to propagate it in the main thread.
unless sh.run_hook(:on_exception, e) == :break
sh.sync { sh.instance_eval { self.session_exception = e } }
end
end
end
# process the input buffer while the thread is alive and the shell is active.
debug 'Entering IO loop...'
io_loop do
if active?
begin
if session_thread.status # not dead
# process input from the session.
unless wait_for_output
inp = next_input
if inp
send_data inp
self.wait_for_output = (options[:unbuffered_input] == :echo)
end
end
# continue running the IO loop
true
elsif session_exception
# propagate the exception.
raise session_exception.class, session_exception.message, session_exception.backtrace
else
# the thread has exited, but no exception exists.
# regardless, the IO loop should now exit.
false
end
rescue IOError
if ignore_io_error
# we were (sort of) expecting the IO error, so just tell the IO loop to exit.
false
else
raise
end
end
else
# the shell session is no longer active, tell the IO loop to exit.
false
end
end
rescue
# when an error occurs, try to disconnect, but ignore any further errors.
begin
debug 'Disconnecting...'
disconnect
rescue
# ignore
end
raise
else
# when no error occurs, try to disconnect and propagate any errors (unless we are ignoring IO errors).
begin
debug 'Disconnecting...'
disconnect
rescue IOError
raise unless ignore_io_error
end
ensure
# cleanup
run_hook :on_after_run
self.run_flag = false
end
self
end
|
ruby
|
{
"resource": ""
}
|
q6634
|
Ruck.Clock.fast_forward
|
train
|
def fast_forward(dt)
adjusted_dt = dt * @relative_rate
@now += adjusted_dt
@children.each { |sub_clock| sub_clock.fast_forward(adjusted_dt) }
end
|
ruby
|
{
"resource": ""
}
|
q6635
|
Ruck.Clock.schedule
|
train
|
def schedule(obj, time = nil)
time ||= now
@occurrences[obj] = time
parent.schedule([:clock, self], unscale_time(time)) if parent && @occurrences.min_key == obj
end
|
ruby
|
{
"resource": ""
}
|
q6636
|
Ruck.Clock.unschedule
|
train
|
def unschedule(obj)
if @occurrences.has_key? obj
last_priority = @occurrences.min_priority
obj, time = @occurrences.delete obj
if parent && @occurrences.min_priority != last_priority
if @occurrences.min_priority
parent.schedule([:clock, self], unscale_time(@occurrences.min_priority))
else
parent.unschedule([:clock, self])
end
end
unscale_time(time)
else
relative_time = @children.first_non_nil { |clock| clock.unschedule(obj) }
unscale_relative_time(relative_time) if relative_time
end
end
|
ruby
|
{
"resource": ""
}
|
q6637
|
SearchMe.Search.attr_search
|
train
|
def attr_search(*attributes)
options = attributes.last.is_a?(Hash) ? attributes.pop : {}
type = (options.fetch(:type) { :simple }).to_sym
accepted_keys = [:simple] + self.reflections.keys.map(&:to_sym)
unless accepted_keys.include?(type.to_sym)
raise ArgumentError, 'incorect type given'
end
search_attributes_hash!(attributes, type, search_attributes)
end
|
ruby
|
{
"resource": ""
}
|
q6638
|
Persistable.ClassMethods.reify_from_row
|
train
|
def reify_from_row(row)
#the tap method allows preconfigured methods and values to
#be associated with the instance during instantiation while also automatically returning
#the object after its creation is concluded.
self.new.tap do |card|
self.attributes.keys.each.with_index do |key, index|
#sending the new instance the key name as a setter with the value located at the 'row' index
card.send("#{key}=", row[index])
#string interpolation is used as the method doesn't know the key name yet
#but an = sign is implemented into the string in order to asssociate it as a setter
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6639
|
Shells.ShellBase.exec
|
train
|
def exec(command, options = {}, &block)
raise Shells::NotRunning unless running?
options ||= {}
options = { timeout_error: true, get_output: true }.merge(options)
options = self.options.merge(options.inject({}) { |m,(k,v)| m[k.to_sym] = v; m })
options[:retrieve_exit_code] = self.options[:retrieve_exit_code] if options[:retrieve_exit_code] == :default
options[:on_non_zero_exit_code] = self.options[:on_non_zero_exit_code] unless [:raise, :ignore].include?(options[:on_non_zero_exit_code])
options[:silence_timeout] = self.options[:silence_timeout] if options[:silence_timeout] == :default
options[:command_timeout] = self.options[:command_timeout] if options[:command_timeout] == :default
options[:command_is_echoed] = true if options[:command_is_echoed].nil?
ret = ''
merge_local_buffer do
begin
# buffer while also passing data to the supplied block.
if block_given?
buffer_output(&block)
end
command = command.to_s
# send the command and wait for the prompt to return.
debug 'Queueing command: ' + command
queue_input command + line_ending
if wait_for_prompt(options[:silence_timeout], options[:command_timeout], options[:timeout_error])
# get the output of the command, minus the trailing prompt.
ret =
if options[:get_output]
debug 'Reading output of command...'
command_output command, options[:command_is_echoed]
else
''
end
if options[:retrieve_exit_code]
self.last_exit_code = get_exit_code
if options[:on_non_zero_exit_code] == :raise
raise NonZeroExitCode.new(last_exit_code) unless last_exit_code == 0 || last_exit_code == :undefined
end
else
self.last_exit_code = nil
end
else
# A timeout occurred and timeout_error was set to false.
self.last_exit_code = :timeout
ret = output
end
ensure
# return buffering to normal.
if block_given?
buffer_output
end
end
end
ret
end
|
ruby
|
{
"resource": ""
}
|
q6640
|
Shells.ShellBase.command_output
|
train
|
def command_output(command, expect_command = true) #:doc:
# get everything except for the ending prompt.
ret =
if (prompt_pos = (output =~ prompt_match))
output[0...prompt_pos]
else
output
end
if expect_command
command_regex = command_match(command)
# Go until we run out of data or we find one of the possible command starts.
# Note that we EXPECT the command to the first line of the output from the command because we expect the
# shell to echo it back to us.
result_cmd,_,result_data = ret.partition("\n")
until result_data.to_s.strip == '' || result_cmd.strip =~ command_regex
result_cmd,_,result_data = result_data.partition("\n")
end
if result_cmd.nil? || !(result_cmd =~ command_regex)
STDERR.puts "SHELL WARNING: Failed to match #{command_regex.inspect}."
end
result_data
else
ret
end
end
|
ruby
|
{
"resource": ""
}
|
q6641
|
Garcon.Crypto.decrypt
|
train
|
def decrypt(encrypted_text, password = nil, salt = nil)
password = password.nil? ? Garcon.crypto.password : password
salt = salt.nil? ? Garcon.crypto.salt : salt
iv_ciphertext = Base64.decode64(encrypted_text)
cipher = new_cipher(:decrypt, password, salt)
cipher.iv, ciphertext = separate_iv_ciphertext(cipher, iv_ciphertext)
plain_text = cipher.update(ciphertext)
plain_text << cipher.final
plain_text
end
|
ruby
|
{
"resource": ""
}
|
q6642
|
Garcon.Crypto.salted_hash
|
train
|
def salted_hash(password)
salt = SecureRandom.random_bytes(SALT_BYTE_SIZE)
pbkdf2 = OpenSSL::PKCS5::pbkdf2_hmac_sha1(
password, salt, CRYPTERATIONS, HASH_BYTE_SIZE
)
{ salt: salt, pbkdf2: Base64.encode64(pbkdf2) }
end
|
ruby
|
{
"resource": ""
}
|
q6643
|
Garcon.Crypto.new_cipher
|
train
|
def new_cipher(direction, password, salt)
cipher = OpenSSL::Cipher::Cipher.new(CIPHER_TYPE)
direction == :encrypt ? cipher.encrypt : cipher.decrypt
cipher.key = encrypt_key(password, salt)
cipher
end
|
ruby
|
{
"resource": ""
}
|
q6644
|
Garcon.Crypto.combine_iv_ciphertext
|
train
|
def combine_iv_ciphertext(iv, message)
message.force_encoding('BINARY') if message.respond_to?(:force_encoding)
iv.force_encoding('BINARY') if iv.respond_to?(:force_encoding)
iv + message
end
|
ruby
|
{
"resource": ""
}
|
q6645
|
Garcon.Crypto.separate_iv_ciphertext
|
train
|
def separate_iv_ciphertext(cipher, iv_ciphertext)
idx = cipher.iv_len
[iv_ciphertext[0..(idx - 1)], iv_ciphertext[idx..-1]]
end
|
ruby
|
{
"resource": ""
}
|
q6646
|
Garcon.Crypto.encrypt_key
|
train
|
def encrypt_key(password, salt)
iterations, length = CRYPTERATIONS, HASH_BYTE_SIZE
OpenSSL::PKCS5::pbkdf2_hmac_sha1(password, salt, iterations, length)
end
|
ruby
|
{
"resource": ""
}
|
q6647
|
Bebox.EnvironmentCommands.environment_list_command
|
train
|
def environment_list_command(environment_command)
environment_command.desc 'List the remote environments in the project'
environment_command.command :list do |environment_list_command|
environment_list_command.action do |global_options,options,args|
environments = Bebox::Environment.list(project_root)
title _('cli.environment.list.current_envs')
environments.map{|environment| msg(environment)}
warn(_('cli.environment.list.no_envs')) if environments.empty?
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6648
|
AnsiSys.CSSFormatter.hash_to_styles
|
train
|
def hash_to_styles(hash, separator = '; ')
unless hash.empty?
return hash.map{|e| "#{e[0]}: #{e[1].join(' ')}"}.join(separator)
else
return nil
end
end
|
ruby
|
{
"resource": ""
}
|
q6649
|
AnsiSys.Lexer.lex!
|
train
|
def lex!
r = Array.new
@buffer.gsub!(/(?:\r\n|\n\r)/, "\n")
while @code_start_re =~ @buffer
r << [:string, $`] unless $`.empty?
if CODE_EQUIVALENT.has_key?($&)
CODE_EQUIVALENT[$&].each do |c|
r << [:code, c]
end
@buffer = $'
else
csi = $&
residual = $'
if PARAMETER_AND_LETTER =~ residual
r << [:code, $&]
@buffer = $'
else
@buffer = csi + residual
return r
end
end
end
r << [:string, @buffer] unless @buffer.empty?
@buffer = ''
return r
end
|
ruby
|
{
"resource": ""
}
|
q6650
|
AnsiSys.Characters.echo_on
|
train
|
def echo_on(screen, cursor)
each_char do |c|
w = width(c)
cursor.fit!(w)
screen.write(c, w, cursor.cur_col, cursor.cur_row, @sgr.dup)
cursor.advance!(w)
end
return self
end
|
ruby
|
{
"resource": ""
}
|
q6651
|
AnsiSys.Cursor.apply_code!
|
train
|
def apply_code!(letter, *pars)
case letter
when 'A'
@cur_row -= pars[0] ? pars[0] : 1
@cur_row = @max_row if @max_row and @cur_row > @max_row
when 'B'
@cur_row += pars[0] ? pars[0] : 1
@cur_row = @max_row if @max_row and @cur_row > @max_row
when 'C'
@cur_col += pars[0] ? pars[0] : 1
when 'D'
@cur_col -= pars[0] ? pars[0] : 1
when 'E'
@cur_row += pars[0] ? pars[0] : 1
@cur_col = 1
@max_row = @cur_row if @max_row and @cur_row > @max_row
when 'F'
@cur_row -= pars[0] ? pars[0] : 1
@cur_col = 1
@max_row = @cur_row if @max_row and @cur_row > @max_row
when 'G'
@cur_col = pars[0] ? pars[0] : 1
when 'H'
@cur_row = pars[0] ? pars[0] : 1
@cur_col = pars[1] ? pars[1] : 1
@max_row = @cur_row if @max_row and @cur_row > @max_row
when 'f'
@cur_row = pars[0] ? pars[0] : 1
@cur_col = pars[1] ? pars[1] : 1
@max_row = @cur_row if @max_row and @cur_row > @max_row
end
if @cur_row < 1
@cur_row = 1
end
if @cur_col < 1
@cur_col = 1
elsif @cur_col > @max_col
@cur_col = @max_col
end
return self
end
|
ruby
|
{
"resource": ""
}
|
q6652
|
AnsiSys.SGR.css_styles
|
train
|
def css_styles(colors = Screen.default_css_colors)
r = Hash.new{|h, k| h[k] = Array.new}
# intensity is not (yet) implemented
r['font-style'] << 'italic' if @italic == :on
r['text-decoration'] << 'underline' unless @underline == :none
r['text-decoration'] << 'blink' unless @blink == :off
case @image
when :positive
fg = @foreground
bg = @background
when :negative
fg = @background
bg = @foreground
end
fg = bg if @conceal == :on
r['color'] << colors[@intensity][fg] unless fg == :white
r['background-color'] << colors[@intensity][bg] unless bg == :black
return r
end
|
ruby
|
{
"resource": ""
}
|
q6653
|
AnsiSys.Screen.write
|
train
|
def write(char, char_width, col, row, sgr)
@lines[Integer(row)][Integer(col)] = [char, char_width, sgr.dup]
end
|
ruby
|
{
"resource": ""
}
|
q6654
|
PseudoHiki.HtmlPlugin.anchor
|
train
|
def anchor
name, anchor_mark = @data.split(/,\s*/o, 2)
anchor_mark = "_" if (anchor_mark.nil? or anchor_mark.empty?)
HtmlElement.create("a", anchor_mark,
"name" => name,
"href" => "#" + name)
end
|
ruby
|
{
"resource": ""
}
|
q6655
|
Hornetseye.GCCFunction.params
|
train
|
def params
idx = 0
@param_types.collect do |param_type|
args = GCCType.new( param_type ).identifiers.collect do
arg = GCCValue.new self, "param#{idx}"
idx += 1
arg
end
param_type.construct *args
end
end
|
ruby
|
{
"resource": ""
}
|
q6656
|
NForm.HTML.tag
|
train
|
def tag(name, attributes={}, &block)
open = sjoin name, attrs(attributes)
body = block.call if block_given?
if VOID_ELEMENTS.include?(name.to_sym)
raise BuilderError, "Void elements cannot have content" if body
"<#{open}>"
else
"<#{open}>#{body}</#{name}>"
end
end
|
ruby
|
{
"resource": ""
}
|
q6657
|
Sumac.Objects.process_forget
|
train
|
def process_forget(object, quiet: )
reference = convert_object_to_reference(object, build: false)
raise UnexposedObjectError unless reference
reference.local_forget_request(quiet: quiet)
end
|
ruby
|
{
"resource": ""
}
|
q6658
|
Sumac.Objects.process_forget_message
|
train
|
def process_forget_message(message, quiet: )
reference = convert_properties_to_reference(message.object, build: false)
reference.remote_forget_request(quiet: quiet)
end
|
ruby
|
{
"resource": ""
}
|
q6659
|
Hornetseye.Node.memorise
|
train
|
def memorise
if memory
contiguous_strides = (0 ... dimension).collect do |i|
shape[0 ... i].inject 1, :*
end
if strides == contiguous_strides
self
else
dup
end
else
dup
end
end
|
ruby
|
{
"resource": ""
}
|
q6660
|
Hornetseye.Node.to_a
|
train
|
def to_a
if dimension == 0
force
else
n = shape.last
( 0 ... n ).collect { |i| element( i ).to_a }
end
end
|
ruby
|
{
"resource": ""
}
|
q6661
|
Hornetseye.Node.inspect
|
train
|
def inspect( indent = nil, lines = nil )
if variables.empty?
if dimension == 0 and not indent
"#{typecode.inspect}(#{force.inspect})"
else
if indent
prepend = ''
else
prepend = "#{Hornetseye::MultiArray(typecode, dimension).inspect}:\n"
indent = 0
lines = 0
end
if empty?
retval = '[]'
else
retval = '[ '
for i in 0 ... shape.last
x = element i
if x.dimension > 0
if i > 0
retval += ",\n "
lines += 1
if lines >= 10
retval += '...' if indent == 0
break
end
retval += ' ' * indent
end
str = x.inspect indent + 1, lines
lines += str.count "\n"
retval += str
if lines >= 10
retval += '...' if indent == 0
break
end
else
retval += ', ' if i > 0
str = x.force.inspect
if retval.size + str.size >= 74 - '...'.size -
'[ ]'.size * indent.succ
retval += '...'
break
else
retval += str
end
end
end
retval += ' ]' unless lines >= 10
end
prepend + retval
end
else
to_s
end
end
|
ruby
|
{
"resource": ""
}
|
q6662
|
Hornetseye.Node.check_shape
|
train
|
def check_shape(*args)
_shape = shape
args.each do |arg|
_arg_shape = arg.shape
if _shape.size < _arg_shape.size
raise "#{arg.inspect} has #{arg.dimension} dimension(s) " +
"but should not have more than #{dimension}"
end
if ( _shape + _arg_shape ).all? { |s| s.is_a? Integer }
if _shape.last( _arg_shape.size ) != _arg_shape
raise "#{arg.inspect} has shape #{arg.shape.inspect} " +
"(does not match last value(s) of #{shape.inspect})"
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6663
|
Hornetseye.Node.force
|
train
|
def force
if finalised?
get
elsif (dimension > 0 and Thread.current[:lazy]) or not variables.empty?
self
elsif compilable?
retval = allocate
GCCFunction.run Store.new(retval, self)
retval.demand.get
else
retval = allocate
Store.new(retval, self).demand
retval.demand.get
end
end
|
ruby
|
{
"resource": ""
}
|
q6664
|
Ruck.ShredConvenienceMethods.yield
|
train
|
def yield(dt, clock = nil)
clock ||= $shreduler.clock
$shreduler.shredule(Shred.current, clock.now + dt, clock)
Shred.current.pause
end
|
ruby
|
{
"resource": ""
}
|
q6665
|
Ruck.ShredConvenienceMethods.wait_on
|
train
|
def wait_on(event)
$shreduler.shredule(Shred.current, event, $shreduler.event_clock)
Shred.current.pause
end
|
ruby
|
{
"resource": ""
}
|
q6666
|
Ruck.Shreduler.run_one
|
train
|
def run_one
shred, relative_time = @clock.unschedule_next
return nil unless shred
fast_forward(relative_time) if relative_time > 0
invoke_shred(shred)
end
|
ruby
|
{
"resource": ""
}
|
q6667
|
Ruck.Shreduler.run_until
|
train
|
def run_until(target_time)
return if target_time < now
loop do
shred, relative_time = next_shred
break unless shred
break unless now + relative_time <= target_time
run_one
end
# I hope rounding errors are okay
fast_forward(target_time - now)
end
|
ruby
|
{
"resource": ""
}
|
q6668
|
CoinOp::Bit.Transaction.validate_syntax
|
train
|
def validate_syntax
update_native
validator = Bitcoin::Validation::Tx.new(@native, nil)
valid = validator.validate :rules => [:syntax]
{:valid => valid, :error => validator.error}
end
|
ruby
|
{
"resource": ""
}
|
q6669
|
CoinOp::Bit.Transaction.validate_script_sigs
|
train
|
def validate_script_sigs
bad_inputs = []
valid = true
@inputs.each_with_index do |input, index|
# TODO: confirm whether we need to mess with the block_timestamp arg
unless self.native.verify_input_signature(index, input.output.transaction.native)
valid = false
bad_inputs << index
end
end
{:valid => valid, :inputs => bad_inputs}
end
|
ruby
|
{
"resource": ""
}
|
q6670
|
CoinOp::Bit.Transaction.add_input
|
train
|
def add_input(input, network: @network)
# TODO: allow specifying prev_tx and index with a Hash.
# Possibly stop using SparseInput.
input = Input.new(input.merge(transaction: self,
index: @inputs.size,
network: network)
) unless input.is_a?(Input)
@inputs << input
self.update_native do |native|
native.add_in input.native
end
input
end
|
ruby
|
{
"resource": ""
}
|
q6671
|
CoinOp::Bit.Transaction.add_output
|
train
|
def add_output(output, network: @network)
if output.is_a?(Output)
output.set_transaction(self, @outputs.size)
else
output = Output.new(output.merge(transaction: self,
index: @outputs.size),
network: network)
end
@outputs << output
self.update_native do |native|
native.add_out(output.native)
end
end
|
ruby
|
{
"resource": ""
}
|
q6672
|
CoinOp::Bit.Transaction.set_script_sigs
|
train
|
def set_script_sigs(*input_args, &block)
# No sense trying to authorize when the transaction isn't usable.
report = validate_syntax
unless report[:valid] == true
raise "Invalid syntax: #{report[:errors].to_json}"
end
# Array#zip here allows us to iterate over the inputs in lockstep with any
# number of sets of values.
self.inputs.zip(*input_args) do |input, *input_arg|
input.script_sig = yield input, *input_arg
end
end
|
ruby
|
{
"resource": ""
}
|
q6673
|
CoinOp::Bit.Transaction.input_value_for
|
train
|
def input_value_for(addresses)
own = inputs.select { |input| addresses.include?(input.output.address) }
own.inject(0) { |sum, input| input.output.value }
end
|
ruby
|
{
"resource": ""
}
|
q6674
|
CoinOp::Bit.Transaction.output_value_for
|
train
|
def output_value_for(addresses)
own = outputs.select { |output| addresses.include?(output.address) }
own.inject(0) { |sum, output| output.value }
end
|
ruby
|
{
"resource": ""
}
|
q6675
|
CoinOp::Bit.Transaction.add_change
|
train
|
def add_change(address, metadata={})
add_output(
value: change_value,
address: address,
metadata: {memo: "change"}.merge(metadata)
)
end
|
ruby
|
{
"resource": ""
}
|
q6676
|
SwaggerDocsGenerator.Extractor.path
|
train
|
def path
temporary = []
actual_route = nil
router do |route|
actual_route = extract_and_format_route(route)
temporary.push(actual_route) unless temporary.include?(actual_route)
actual_route
end
temporary
end
|
ruby
|
{
"resource": ""
}
|
q6677
|
Tst.Assertions.assert_raises
|
train
|
def assert_raises(expected=StandardError)
begin
yield
rescue => actual
return actual if actual.kind_of?(expected)
raise Failure.new("Failure: Unexpected Exception", expected, actual)
end
raise Failure.new("Failure: No Exception", expected, "Nothing raised.")
end
|
ruby
|
{
"resource": ""
}
|
q6678
|
Tst.Runner.tst
|
train
|
def tst(name, &block)
start = Time.now
block.call
status = SUCCEEDED
rescue Failure => exception
status = FAILED
rescue StandardError => exception
status = RAISED
ensure
elapsed = Time.now - start
__record(name, status, elapsed, exception)
end
|
ruby
|
{
"resource": ""
}
|
q6679
|
Jinx.Propertied.add_attribute
|
train
|
def add_attribute(attribute, type, *flags)
prop = create_nonjava_property(attribute, type, *flags)
add_property(prop)
prop
end
|
ruby
|
{
"resource": ""
}
|
q6680
|
Jinx.Propertied.init_property_classifiers
|
train
|
def init_property_classifiers
@local_std_prop_hash = {}
@alias_std_prop_map = append_ancestor_enum(@local_std_prop_hash) { |par| par.alias_standard_attribute_hash }
@local_prop_hash = {}
@prop_hash = append_ancestor_enum(@local_prop_hash) { |par| par.property_hash }
@attributes = Enumerable::Enumerator.new(@prop_hash, :each_key)
@local_mndty_attrs = Set.new
@local_defaults = {}
@defaults = append_ancestor_enum(@local_defaults) { |par| par.defaults }
end
|
ruby
|
{
"resource": ""
}
|
q6681
|
Jinx.Propertied.compose_property
|
train
|
def compose_property(property, other)
if other.inverse.nil? then
raise ArgumentError.new("Can't compose #{qp}.#{property} with inverseless #{other.declarer.qp}.#{other}")
end
# the source -> intermediary access methods
sir, siw = property.accessors
# the intermediary -> target access methods
itr, itw = other.accessors
# the target -> intermediary reader method
tir = other.inverse
# The reader composes the source -> intermediary -> target readers.
define_method(itr) do
ref = send(sir)
ref.send(itr) if ref
end
# The writer sets the source intermediary to the target intermediary.
define_method(itw) do |tgt|
if tgt then
ref = block_given? ? yield(tgt) : tgt.send(tir)
raise ArgumentError.new("#{tgt} does not reference a #{other.inverse}") if ref.nil?
end
send(siw, ref)
end
prop = add_attribute(itr, other.type)
logger.debug { "Created #{qp}.#{prop} which composes #{qp}.#{property} and #{other.declarer.qp}.#{other}." }
prop.qualify(:collection) if other.collection?
prop
end
|
ruby
|
{
"resource": ""
}
|
q6682
|
Jinx.Propertied.most_specific_domain_attribute
|
train
|
def most_specific_domain_attribute(klass, attributes=nil)
attributes ||= domain_attributes
candidates = attributes.properties
best = candidates.inject(nil) do |better, prop|
# If the attribute can return the klass then the return type is a candidate.
# In that case, the klass replaces the best candidate if it is more specific than
# the best candidate so far.
klass <= prop.type ? (better && better.type <= prop.type ? better : prop) : better
end
if best then
logger.debug { "Most specific #{qp} -> #{klass.qp} reference from among #{candidates.qp} is #{best.declarer.qp}.#{best}." }
best.to_sym
end
end
|
ruby
|
{
"resource": ""
}
|
q6683
|
Jinx.Propertied.set_attribute_type
|
train
|
def set_attribute_type(attribute, klass)
prop = property(attribute)
# degenerate no-op case
return if klass == prop.type
# If this class is the declarer, then simply set the attribute type.
# Otherwise, if the attribute type is unspecified or is a superclass of the given class,
# then make a new attribute metadata for this class.
if prop.declarer == self then
prop.type = klass
logger.debug { "Set #{qp}.#{attribute} type to #{klass.qp}." }
elsif prop.type.nil? or klass < prop.type then
prop.restrict(self, :type => klass)
logger.debug { "Restricted #{prop.declarer.qp}.#{attribute}(#{prop.type.qp}) to #{qp} with return type #{klass.qp}." }
else
raise ArgumentError.new("Cannot reset #{qp}.#{attribute} type #{prop.type.qp} to incompatible #{klass.qp}")
end
end
|
ruby
|
{
"resource": ""
}
|
q6684
|
Jinx.Propertied.remove_attribute
|
train
|
def remove_attribute(attribute)
sa = standard_attribute(attribute)
# if the attribute is local, then delete it, otherwise filter out the superclass attribute
sp = @local_prop_hash.delete(sa)
if sp then
# clear the inverse, if any
clear_inverse(sp)
# remove from the mandatory attributes, if necessary
@local_mndty_attrs.delete(sa)
# remove from the attribute => metadata hash
@local_std_prop_hash.delete_if { |aliaz, pa| pa == sa }
else
# Filter the superclass hashes.
anc_prop_hash = @prop_hash.components[1]
@prop_hash.components[1] = anc_prop_hash.filter_on_key { |pa| pa != attribute }
anc_alias_hash = @alias_std_prop_map.components[1]
@alias_std_prop_map.components[1] = anc_alias_hash.filter_on_key { |pa| pa != attribute }
end
logger.debug { "Removed the #{qp} #{attribute} property." }
end
|
ruby
|
{
"resource": ""
}
|
q6685
|
Jinx.Propertied.register_property_alias
|
train
|
def register_property_alias(aliaz, attribute)
std = standard_attribute(attribute)
raise ArgumentError.new("#{self} attribute not found: #{attribute}") if std.nil?
@local_std_prop_hash[aliaz.to_sym] = std
end
|
ruby
|
{
"resource": ""
}
|
q6686
|
IRCSupport.Formatting.strip_color!
|
train
|
def strip_color!(string)
[@@mirc_color, @@rgb_color, @@ecma48_color].each do |pattern|
string.gsub!(pattern, '')
end
# strip cancellation codes too if there are no formatting codes
string.gsub!(@@normal) if !has_color?(string)
return string
end
|
ruby
|
{
"resource": ""
}
|
q6687
|
Gen.Gen::Code.generate_binding
|
train
|
def generate_binding(a_binding=binding)
a_binding.local_variables do |local_var|
a_binding.local_variable_set local_var, nil
end
@bound_procs.each_with_index do |bound_proc, index|
a_binding.local_variable_set "proc_#{index}", bound_proc
end
@bound_constants.each_with_index do |bound_const, index|
a_binding.local_variable_set "const_#{index}", bound_const
end
a_binding
end
|
ruby
|
{
"resource": ""
}
|
q6688
|
Evvnt.Persistence.save_as_new_record
|
train
|
def save_as_new_record
new_attributes = attributes.reject { |k, _v| k.to_s =~ /^(id|uuid)$/ }
self.class.create(new_attributes)
end
|
ruby
|
{
"resource": ""
}
|
q6689
|
Evvnt.Persistence.save_as_persisted_record
|
train
|
def save_as_persisted_record
new_attributes = attributes.reject { |k, _v| k.to_s =~ /^(id|uuid)$/ }
self.class.update(id, new_attributes)
end
|
ruby
|
{
"resource": ""
}
|
q6690
|
GodvilleKit.APIRequester.request_raw_hero_data
|
train
|
def request_raw_hero_data
return unless authenticated?
response = RestClient.get(
"https://godvillegame.com/fbh/feed?a=#{@hero_guid}",
cookies: @cookies, content_type: :json, accept: :json
)
JSON.parse(response)
end
|
ruby
|
{
"resource": ""
}
|
q6691
|
Garcon.Obligation.compare_and_set_state
|
train
|
def compare_and_set_state(next_state, expected_current) # :nodoc:
mutex.lock
if @state == expected_current
@state = next_state
true
else
false
end
ensure
mutex.unlock
end
|
ruby
|
{
"resource": ""
}
|
q6692
|
Garcon.Obligation.if_state
|
train
|
def if_state(*expected_states)
mutex.lock
raise ArgumentError, 'no block given' unless block_given?
if expected_states.include? @state
yield
else
false
end
ensure
mutex.unlock
end
|
ruby
|
{
"resource": ""
}
|
q6693
|
PolyDelegate.Delegator.method_missing
|
train
|
def method_missing(name, *args, &block)
super unless respond_to_missing?(name)
# Send self as the delegator
@__delegated_object__.__send__(name, self, *args, &block)
end
|
ruby
|
{
"resource": ""
}
|
q6694
|
Observatory.Stack.delete
|
train
|
def delete(observer)
old_size = @stack.size
@stack.delete_if do |o|
o[:observer] == observer
end
old_size == @stack.size ? nil : observer
end
|
ruby
|
{
"resource": ""
}
|
q6695
|
Observatory.Stack.push
|
train
|
def push(observer, priority = nil)
raise ArgumentError, 'Observer is not callable' unless observer.respond_to?(:call)
raise ArgumentError, 'Priority must be Fixnum' unless priority.nil? || priority.is_a?(Fixnum)
@stack.push({ :observer => observer, :priority => (priority || default_priority) })
sort_by_priority
observer
end
|
ruby
|
{
"resource": ""
}
|
q6696
|
Incline.SafeNameValidator.validate_each
|
train
|
def validate_each(record, attribute, value)
unless value.blank?
unless value =~ VALID_MASK
if value =~ /\A[^a-z]/i
record.errors[attribute] << (options[:message] || 'must start with a letter')
elsif value =~ /_\z/
record.errors[attribute] << (options[:message] || 'must not end with an underscore')
else
record.errors[attribute] << (options[:message] || 'must contain only letters, numbers, and underscore')
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6697
|
Kajiki.Runner.validate_command
|
train
|
def validate_command(cmd = ARGV)
fail 'Specify one action.' unless cmd.count == 1
cmd = cmd.shift
fail 'Invalid action.' unless SUB_COMMANDS.include?(cmd)
cmd
end
|
ruby
|
{
"resource": ""
}
|
q6698
|
Kajiki.Runner.validate_options
|
train
|
def validate_options
if @opts[:daemonize]
fail 'Must specify PID file.' unless @opts[:pid_given]
end
@opts[:pid] = File.expand_path(@opts[:pid]) if @opts[:pid_given]
@opts[:log] = File.expand_path(@opts[:log]) if @opts[:log_given]
@opts[:error] = File.expand_path(@opts[:error]) if @opts[:error_given]
@opts[:config] = File.expand_path(@opts[:config]) if @opts[:config_given]
end
|
ruby
|
{
"resource": ""
}
|
q6699
|
Kajiki.Runner.start
|
train
|
def start(&block)
fail 'No start block given.' if block.nil?
check_existing_pid
puts "Starting process..."
Process.daemon if @opts[:daemonize]
change_privileges if @opts[:auto_default_actions]
redirect_outputs if @opts[:auto_default_actions]
write_pid
trap_default_signals if @opts[:auto_default_actions]
block.call('start')
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.