_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q5300
|
ResourcesController.InstanceMethods.load_enclosing_resources
|
train
|
def load_enclosing_resources
namespace_segments.each {|segment| update_name_prefix("#{segment}_") }
specifications.each_with_index do |spec, idx|
case spec
when '*' then load_wildcards_from(idx)
when /^\?(.*)/ then load_wildcard($1)
else load_enclosing_resource_from_specification(spec)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5301
|
ResourcesController.InstanceMethods.load_wildcards_from
|
train
|
def load_wildcards_from(start)
specs = specifications.slice(start..-1)
encls = nesting_segments.slice(enclosing_resources.size..-1)
if spec = specs.find {|s| s.is_a?(Specification)}
spec_seg = encls.index({:segment => spec.segment, :singleton => spec.singleton?}) or ResourcesController.raise_resource_mismatch(self)
number_of_wildcards = spec_seg - (specs.index(spec) -1)
else
number_of_wildcards = encls.length - (specs.length - 1)
end
number_of_wildcards.times { load_wildcard }
end
|
ruby
|
{
"resource": ""
}
|
q5302
|
ResourcesController.ResourceService.destroy
|
train
|
def destroy(*args)
resource = find(*args)
if enclosing_resource
service.destroy(*args)
resource
else
resource.destroy
end
end
|
ruby
|
{
"resource": ""
}
|
q5303
|
LatoCore.Superuser::EntityHelpers.get_permission_name
|
train
|
def get_permission_name
permission = CONFIGS[:lato_core][:superusers_permissions].values.select{|x| x[:value] === self.permission}
return permission[0][:title] if permission && !permission.empty?
end
|
ruby
|
{
"resource": ""
}
|
q5304
|
Chatrix.Matrix.sync
|
train
|
def sync(filter: nil, since: nil, full_state: false,
set_presence: true, timeout: 30_000)
options = { full_state: full_state }
options[:since] = since if since
options[:set_presence] = 'offline' unless set_presence
options[:timeout] = timeout if timeout
options[:filter] = parse_filter filter
make_request(:get, '/sync', params: options).parsed_response
end
|
ruby
|
{
"resource": ""
}
|
q5305
|
Chatrix.Matrix.search
|
train
|
def search(from: nil, options: {})
make_request(
:post, '/search', params: { next_batch: from }, content: options
).parsed_response
end
|
ruby
|
{
"resource": ""
}
|
q5306
|
Chatrix.Matrix.make_request
|
train
|
def make_request(method, path, opts = {}, &block)
path = (opts[:base] || @base_uri) + URI.encode(path)
options = make_options opts[:params], opts[:content], opts[:headers]
parse_response METHODS[method].call(path, options, &block)
end
|
ruby
|
{
"resource": ""
}
|
q5307
|
Chatrix.Matrix.make_options
|
train
|
def make_options(params, content, headers = {})
{ headers: headers }.tap do |o|
o[:query] = @access_token ? { access_token: @access_token } : {}
o[:query].merge!(params) if params.is_a? Hash
o.merge! make_body content
end
end
|
ruby
|
{
"resource": ""
}
|
q5308
|
Chatrix.Matrix.make_body
|
train
|
def make_body(content)
key = content.respond_to?(:read) ? :body_stream : :body
value = content.is_a?(Hash) ? content.to_json : content
{ key => value }
end
|
ruby
|
{
"resource": ""
}
|
q5309
|
Chatrix.Matrix.parse_response
|
train
|
def parse_response(response)
case response.code
when 200 # OK
response
else
handler = ERROR_HANDLERS[response.code]
raise handler.first.new(response.parsed_response), handler.last
end
end
|
ruby
|
{
"resource": ""
}
|
q5310
|
Chatrix.Matrix.parse_filter
|
train
|
def parse_filter(filter)
filter.is_a?(Hash) ? URI.encode(filter.to_json) : filter
end
|
ruby
|
{
"resource": ""
}
|
q5311
|
CommandLion.App.command
|
train
|
def command(index, &block)
if index.is_a? Command
cmd = index
else
cmd = Command.new
cmd.index= index
cmd.instance_eval(&block)
end
@commands = {} unless @commands
@flags = [] unless @flags
if cmd.flags?
@flags << cmd.flags.short if cmd.flags.short?
@flags << cmd.flags.long if cmd.flags.long?
elsif cmd.index # just use index
@flags << cmd.index.to_s
else
raise "No index or flags were given to use this command."
end
if cmd.options?
cmd.options.each do |_, option|
if option.flags?
@flags << option.flags.short if option.flags.short?
@flags << option.flags.long if option.flags.long?
else # just use index
@flags << option.index.to_s
end
@commands[option.index] = option
end
end
@commands[cmd.index] = cmd
cmd
end
|
ruby
|
{
"resource": ""
}
|
q5312
|
CommandLion.App.parse
|
train
|
def parse
@commands.each do |_, cmd|
if cmd.flags?
# or for the || seems to not do what I want it to do...
next unless argv_index = ARGV.index(cmd.flags.short) || ARGV.index(cmd.flags.long)
else
next unless argv_index = ARGV.index(cmd.index.to_s)
end
cmd.given = true unless argv_index.nil?
if cmd.type.nil?
yield cmd if block_given?
else
if parsed = parse_cmd(cmd, flags)
cmd.arguments = parsed || cmd.default
yield cmd if block_given?
elsif cmd.default
cmd.arguments = cmd.default
yield cmd if block_given?
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5313
|
CommandLion.App.parse_cmd
|
train
|
def parse_cmd(cmd, flags)
if cmd.flags?
args = Raw.arguments_to(cmd.flags.short, flags)
if args.nil? || args.empty?
args = Raw.arguments_to(cmd.flags.long, flags)
end
else
args = Raw.arguments_to(cmd.index.to_s, flags)
end
unless cmd.type.to_s =~ /stdin/
return nil if args.nil?
end
case cmd.type
when :stdin
args = STDIN.gets.strip
when :stdin_stream
args = STDIN
when :stdin_string
args = STDIN.gets.strip
when :stdin_strings
args = []
while arg = STDIN.gets
next if arg.nil?
arg = arg.strip
args << arg
end
args
when :stdin_integer
args = STDIN.gets.strip.to_i
when :stdin_integers
args = []
while arg = STDIN.gets
next if arg.nil?
arg = arg.strip
parse = arg.to_i
if parse.to_s == arg
args << parse
end
end
args
when :stdin_bool
args = STDIN.gets.strip.downcase == "true"
when :single, :string
args = args.first
when :strings, :multi
if cmd.delimiter?
if args.count > 1
args = args.first.split(cmd.delimiter)
else
args = args.map { |arg| arg.split(cmd.delimiter) }.flatten
end
end
args
when :integer
args = args.first.to_i
when :integers
if cmd.delimiter?
if args.count > 1
args = args.join
args = args.select { |arg| arg if arg.include?(cmd.delimiter) }
args = args.map { |arg| arg.split(cmd.delimiter) }.flatten
else
args = args.map { |arg| arg.split(cmd.delimiter) }.flatten
end
end
args = args.map(&:to_i)
when :bool, :bools
if cmd.delimiter?
if args.count > 1
args = args.join
args = args.select { |arg| arg if arg.include?(cmd.delimiter) }
args = args.map { |arg| arg.split(cmd.delimiter) }.flatten
else
args = args.map { |arg| arg.split(cmd.delimiter) }.flatten
end
end
args = args.map { |arg| arg == "true" }
end
rescue => e# this is dangerous
puts e
nil
end
|
ruby
|
{
"resource": ""
}
|
q5314
|
Configurable.ConfigHash.[]=
|
train
|
def []=(key, value)
if config = configs[key]
config.set(receiver, value)
else
store[key] = value
end
end
|
ruby
|
{
"resource": ""
}
|
q5315
|
Configurable.ConfigHash.merge!
|
train
|
def merge!(another)
configs = self.configs
another.each_pair do |key, value|
if config = configs[key]
config.set(receiver, value)
else
store[key] = value
end
end
self
end
|
ruby
|
{
"resource": ""
}
|
q5316
|
Configurable.ConfigHash.each_pair
|
train
|
def each_pair # :yields: key, value
configs.each_pair do |key, config|
yield(key, config.get(receiver))
end
store.each_pair do |key, value|
yield(key, value)
end
end
|
ruby
|
{
"resource": ""
}
|
q5317
|
Configurable.ConfigHash.to_hash
|
train
|
def to_hash
hash = {}
each_pair do |key, value|
if value.kind_of?(ConfigHash)
value = value.to_hash
end
hash[key] = value
end
hash
end
|
ruby
|
{
"resource": ""
}
|
q5318
|
Ciphers.Aes.decipher_ecb
|
train
|
def decipher_ecb(key,input,strip_padding: true)
plain = decipher_ecb_blockwise(CryptBuffer(key),CryptBuffer(input).chunks_of(@block_size_bytes)).to_crypt_buffer
strip_padding ? plain.strip_padding : plain
end
|
ruby
|
{
"resource": ""
}
|
q5319
|
Ciphers.Aes.unicipher_cbc
|
train
|
def unicipher_cbc(direction,key_str,input_buf,iv)
method="#{direction.to_s}_cbc_block"
blocks = input_buf.chunks_of(@block_size_bytes)
iv ||= blocks.shift.str
key = CryptBuffer(key_str).hex
prev_block=iv.to_crypt_buffer
strings = blocks.map.with_index do |block,i|
ctext_block = send(method,key,block,prev_block)
if direction == :encipher
prev_block = ctext_block
else
prev_block = block
end
ctext_block.str
end
CryptBuffer(strings.join)
end
|
ruby
|
{
"resource": ""
}
|
q5320
|
QnAMaker.Client.generate_answer
|
train
|
def generate_answer(question, top = 1)
response = @http.post(
"#{BASE_URL}/#{@knowledgebase_id}/generateAnswer",
json: { question: question, top: top }
)
case response.code
when 200
response.parse['answers'].map do |answer|
Answer.new(
answer['answer'].normalize,
answer['questions'].map(&:normalize),
answer['score']
)
end
when 400
raise BadArgumentError, response.parse['error']['message'].join(' ')
when 401
raise UnauthorizedError, response.parse['error']['message']
when 403
raise QuotaExceededError, response.parse['error']['message']
when 404
raise NotFoundError, response.parse['error']['message']
when 408
raise OperationTimeOutError, response.parse['error']['message']
when 429
raise RateLimitExceededError, response.parse['error']['message']
else
raise UnknownError, "Oh no! (#{response.code})"
end
end
|
ruby
|
{
"resource": ""
}
|
q5321
|
LatoCore.Helper::Cells.cell
|
train
|
def cell(*names)
# define variables
names_list = names.first.to_s.start_with?('Lato') ? names[1..-1] : names
cell_class = names.first.to_s.start_with?('Lato') ? "#{names.first}::" : 'LatoCore::'
# return correct cell
names_list.each do |name|
cell_class = "#{cell_class}#{name.capitalize}::"
end
"#{cell_class}Cell".constantize
end
|
ruby
|
{
"resource": ""
}
|
q5322
|
Boxroom.FoldersController.require_delete_permission
|
train
|
def require_delete_permission
unless @folder.is_root? || boxroom_current_user.can_delete(@folder)
redirect_to @folder.parent, :alert => t(:no_permissions_for_this_type, :method => t(:delete), :type => t(:this_folder))
else
require_delete_permissions_for(@folder.children)
end
end
|
ruby
|
{
"resource": ""
}
|
q5323
|
Reflexive.RoutingHelpers.method_call_path
|
train
|
def method_call_path(method_call_tag)
# r method_call_tag.values_at(:name, :receiver)
name, receiver, scope = method_call_tag.values_at(:name, :receiver, :scope)
scope = scope.join("::")
if receiver == :class
scope = "Kernel" if scope.empty?
new_method_path(scope, :class, name)
elsif receiver == :instance
scope = "Kernel" if scope.empty?
new_method_path(scope, :instance, name)
else
receiver = receiver.join("::")
new_method_path(Reflexive.constant_lookup(receiver, scope), :class, name)
end
# if receiver.last == :instance
# new_method_path(receiver[0..-2].join("::"), :instance, name)
# else
# new_method_path(receiver.join("::"), :class, name)
# end rescue(r(method_call_tag))
end
|
ruby
|
{
"resource": ""
}
|
q5324
|
RbTunTap.Device.validate_address!
|
train
|
def validate_address!(addr)
ip = IPAddr.new(addr)
unless ip.ipv4?
raise NotImplementedError, 'Only IPv4 is supported by this library'
end
if addr.include?('/')
raise ArgumentError, 'Please specify a host IP address (without mask)'
end
addr.to_s
end
|
ruby
|
{
"resource": ""
}
|
q5325
|
KonoUtils.SearchAttribute.cast_value
|
train
|
def cast_value(value)
return value if value.blank?
return value if form_options.is_a? Proc
return field_options[:cast].call(value) if field_options[:cast].is_a? Proc
case form_options[:as]
when :bs_datetimepicker
if value.is_a? String
DateTime.parse(value)
elsif value.is_a? Date
value.to_time
else
value
end
when :bs_datepicker
if value.is_a? String
DateTime.parse(value).to_date
elsif value.is_a? DateTime
value.to_date
else
value
end
else
value
end
end
|
ruby
|
{
"resource": ""
}
|
q5326
|
Resync.Client.get
|
train
|
def get(uri)
uri = Resync::XML.to_uri(uri)
@helper.fetch(uri: uri)
end
|
ruby
|
{
"resource": ""
}
|
q5327
|
Resync.Client.download_to_temp_file
|
train
|
def download_to_temp_file(uri)
uri = Resync::XML.to_uri(uri)
@helper.fetch_to_file(uri: uri)
end
|
ruby
|
{
"resource": ""
}
|
q5328
|
Resync.Client.download_to_file
|
train
|
def download_to_file(uri:, path:)
uri = Resync::XML.to_uri(uri)
@helper.fetch_to_file(path: path, uri: uri)
end
|
ruby
|
{
"resource": ""
}
|
q5329
|
LatoCore.Interface::Modules.core__get_modules_list
|
train
|
def core__get_modules_list
all_gems = core__get_application_gems.keys
lato_gems = []
# check every gem
all_gems.each do |name|
lato_gems.push(name) if name.start_with? 'lato'
end
# return result
lato_gems
end
|
ruby
|
{
"resource": ""
}
|
q5330
|
LatoCore.Interface::Modules.core__get_module_languages
|
train
|
def core__get_module_languages(module_name)
default_languages = core__get_module_default_languages(module_name)
application_languages = core__get_module_application_languages(module_name)
return default_languages unless application_languages
default_languages.each do |key, value|
application_languages[key] = value unless application_languages[key]
end
application_languages
end
|
ruby
|
{
"resource": ""
}
|
q5331
|
LatoCore.Interface::Modules.core__get_module_configs
|
train
|
def core__get_module_configs module_name
default_config = core__get_module_default_configs(module_name)
application_config = core__get_module_application_configs(module_name)
return default_config unless application_config
default_config.each do |key, value|
application_config[key] = value unless application_config[key]
end
return application_config
end
|
ruby
|
{
"resource": ""
}
|
q5332
|
Lunar.Index.text
|
train
|
def text(att, value)
clear_text_field(att)
Scoring.new(value).scores.each do |word, score|
metaphone = Lunar.metaphone(word)
nest[att][metaphone].zadd(score, id)
metaphones[id][att].sadd(metaphone)
end
fields[TEXT].sadd(att)
end
|
ruby
|
{
"resource": ""
}
|
q5333
|
Lunar.Index.number
|
train
|
def number(att, value, purge = true)
if value.kind_of?(Enumerable)
clear_number_field(att)
value.each { |v| number(att, v, false) } and return
end
clear_number_field(att) if purge
numbers[att].zadd(value, id)
numbers[att][value].zadd(1, id)
numbers[id][att].sadd(value)
fields[NUMBERS].sadd att
end
|
ruby
|
{
"resource": ""
}
|
q5334
|
Lunar.Index.sortable
|
train
|
def sortable(att, value)
sortables[id][att].set(value)
fields[SORTABLES].sadd att
end
|
ruby
|
{
"resource": ""
}
|
q5335
|
Substation.Request.to_request
|
train
|
def to_request(new_input = Undefined)
new_input.equal?(Undefined) ? self : self.class.new(name, env, new_input)
end
|
ruby
|
{
"resource": ""
}
|
q5336
|
LatoCore.Interface::Token.core__encode_token
|
train
|
def core__encode_token exp, payload
exp = 1.day.from_now unless exp
payload[:exp] = exp.to_i
JWT.encode(payload, Rails.application.secrets.secret_key_base, 'HS256')
end
|
ruby
|
{
"resource": ""
}
|
q5337
|
LatoCore.Interface::Token.core__decode_token
|
train
|
def core__decode_token token
begin
body = JWT.decode(token, Rails.application.secrets.secret_key_base,
true, algorithm: 'HS256')[0]
return HashWithIndifferentAccess.new body
rescue => exception
return nil
end
end
|
ruby
|
{
"resource": ""
}
|
q5338
|
MarilynRPC.NativeClient.authenticate
|
train
|
def authenticate(username, password, method = :plain)
execute(MarilynRPC::Service::AUTHENTICATION_PATH,
"authenticate_#{method}".to_sym, [username, password])
end
|
ruby
|
{
"resource": ""
}
|
q5339
|
MarilynRPC.NativeClient.execute
|
train
|
def execute(path, method, args)
thread = Thread.current
tag = "#{Time.now.to_f}:#{thread.object_id}"
@semaphore.synchronize {
# since this client can't multiplex, we set the tag to nil
@socket.write(MarilynRPC::MailFactory.build_call(tag, path, method, args))
# lets write our self to the list of waining threads
@threads[tag] = thread
}
# stop the current thread, the thread will be started after the response
# arrived
Thread.stop
# get mail from responses
mail = thread[MAIL_KEY]
if mail.is_a? MarilynRPC::CallResponseMail
mail.result
else
raise MarilynError.new # raise exception to capture the client backtrace
end
rescue MarilynError => exception
# add local and remote trace together and reraise the original exception
backtrace = []
backtrace += exception.backtrace
backtrace += mail.exception.backtrace
mail.exception.set_backtrace(backtrace)
raise mail.exception
end
|
ruby
|
{
"resource": ""
}
|
q5340
|
BadFruit.Movies.search_by_name
|
train
|
def search_by_name(name, page_limit=1, page=1)
if page_limit > 50
page_limit = MAX_PAGE_LIMIT #current limitation of the rotten tomatos API
end
results_json = @badfruit.search_movies(name, page_limit, page)
if results_json.nil?
return []
else
return @badfruit.parse_movies_array(JSON.parse(results_json))
end
end
|
ruby
|
{
"resource": ""
}
|
q5341
|
BadFruit.Movies.search_by_id
|
train
|
def search_by_id(movie_id)
movie = @badfruit.get_movie_info(movie_id, "main")
raise 'Movie not found' if movie.nil? || movie.empty?
@badfruit.parse_movie_array(JSON.parse(movie))
end
|
ruby
|
{
"resource": ""
}
|
q5342
|
BadFruit.Movies.search_by_alias
|
train
|
def search_by_alias(alias_id, type='imdb')
movie = @badfruit.get_movie_alias_info(alias_id, type)
json = JSON.parse(movie)
raise 'Movie not found' if !json['error'].nil?
@badfruit.parse_movie_array(json)
end
|
ruby
|
{
"resource": ""
}
|
q5343
|
OneSky.Translation.dashify_string_hash
|
train
|
def dashify_string_hash(string_hash)
output = Hash.new
string_hash.each do |key, value|
dashed = key.to_s.gsub("_", "-").to_sym
output[dashed] = value
end
output
end
|
ruby
|
{
"resource": ""
}
|
q5344
|
Sunlight.Legislator.committees
|
train
|
def committees
url = Sunlight::Base.construct_url("committees.allForLegislator", {:bioguide_id => self.bioguide_id})
if (result = Sunlight::Base.get_json_data(url))
committees = []
result["response"]["committees"].each do |committee|
committees << Sunlight::Committee.new(committee["committee"])
end
else
nil # appropriate params not found
end
committees
end
|
ruby
|
{
"resource": ""
}
|
q5345
|
ConsoleTweet.CLI.get_access_token
|
train
|
def get_access_token
@client = TwitterOAuth::Client.new(:consumer_key => ConsumerKey, :consumer_secret => ConsumerSecret)
request_token = @client.request_token
# ask the user to visit the auth url
puts "To authenticate your client, visit the URL: #{request_token.authorize_url}"
open_link request_token.authorize_url
# wait for the user to give us the PIN back
print 'Enter PIN: '
begin
@client.authorize(request_token.token, request_token.secret, :oauth_verifier => self.class.get_input.chomp)
rescue OAuth::Unauthorized
false # Didn't get an access token
end
end
|
ruby
|
{
"resource": ""
}
|
q5346
|
ConsoleTweet.CLI.timeline
|
train
|
def timeline(*args)
load_default_token
return failtown("Unauthorized, re-run setup!") unless @client && @client.authorized?
# Only send since_id to @client if it's not nil
home_timeline = since_id ? @client.home_timeline(:since_id => since_id) : @client.home_timeline
if home_timeline.any?
print_tweets(home_timeline)
# Save the last id as since_id
self.since_id = home_timeline.last['id']
end
end
|
ruby
|
{
"resource": ""
}
|
q5347
|
ConsoleTweet.CLI.tweet
|
train
|
def tweet(*args)
load_default_token
# get it from them directly
tweet_text = args.join(' ').strip
# or let them append / or pipe
tweet_text += (tweet_text.empty? ? '' : ' ') + STDIN.read unless STDIN.tty?
# or let them get prompted for it
if tweet_text.empty?
print 'Tweet (Press return to finish): '
tweet_text = STDIN.gets.strip
end
return failtown("Empty Tweet") if tweet_text.empty?
return failtown("Tweet is too long!") if tweet_text.scan(/./mu).size > 140
return failtown("Unauthorized, re-run setup!") unless @client && @client.authorized?
# actually post it
@client.update(tweet_text)
puts "Tweet Posted!"
end
|
ruby
|
{
"resource": ""
}
|
q5348
|
ConsoleTweet.CLI.show
|
train
|
def show(args)
# If we have no user to get, use the timeline instead
return timeline(args) if args.nil? || args.count == 0
target_user = args[0]
# Get the timeline and print the tweets if we don't get an error
load_default_token # for private tweets
res = @client.user_timeline(:screen_name => target_user)
return failtown("show :: #{res['error']}") if !res || res.include?('error')
print_tweets(res)
end
|
ruby
|
{
"resource": ""
}
|
q5349
|
ConsoleTweet.CLI.status
|
train
|
def status(*args)
load_default_token
return failtown("Unauthorized, re-run setup!") unless @client && @client.authorized?
user = @client.info
status = user['status']
puts "#{user['name']} (at #{status['created_at']}) #{status['text']}" unless status.nil?
end
|
ruby
|
{
"resource": ""
}
|
q5350
|
ConsoleTweet.CLI.setup
|
train
|
def setup(*args)
# Keep trying to get the access token
until @access_token = self.get_access_token
print "Try again? [Y/n] "
return false if self.class.get_input.downcase == 'n'
end
# When we finally get it, record it in a dotfile
tokens = {:default => { :token => @access_token.token, :secret => @access_token.secret }}
save_tokens(tokens)
end
|
ruby
|
{
"resource": ""
}
|
q5351
|
ConsoleTweet.CLI.replies
|
train
|
def replies(*args)
load_default_token
return failtown("Unauthorized, re-run setup!") unless @client && @client.authorized?
# Only send since_id_replies to @client if it's not nil
mentions = since_id_replies ? @client.mentions(:since_id => since_id_replies) : @client.mentions
if mentions.any?
print_tweets(mentions)
# Save the last id as since_id
self.since_id_replies = mentions.last['id']
end
end
|
ruby
|
{
"resource": ""
}
|
q5352
|
ConsoleTweet.CLI.help
|
train
|
def help(*args)
puts "#{NameColor}console-tweet#{DefaultColor} by John Crepezzi <[email protected]>"
puts 'http://github.com/seejohnrun/console-tweet'
puts
puts "#{CommandColor}twitter#{DefaultColor} View your timeline, since last view"
puts "#{CommandColor}twitter setup#{DefaultColor} Setup your account"
puts "#{CommandColor}twitter status#{DefaultColor} Get your most recent status"
puts "#{CommandColor}twitter tweet \"Hello World\"#{DefaultColor} Send out a tweet"
puts "#{CommandColor}twitter show [username]#{DefaultColor} Show the timeline for a user"
puts "#{CommandColor}twitter replies#{DefaultColor} Get the most recent @replies and mentions"
end
|
ruby
|
{
"resource": ""
}
|
q5353
|
Sanscript.Benchmark.detect!
|
train
|
def detect!(time = 2, warmup = 1)
::Benchmark.ips do |x|
x.config(time: time, warmup: warmup)
TEST_STRINGS_FLAT.each do |scheme, string|
x.report("Detect #{scheme}") do
Sanscript::Detect.detect_scheme(string)
end
end
x.compare!
end
true
end
|
ruby
|
{
"resource": ""
}
|
q5354
|
Sanscript.Benchmark.transliterate_roman!
|
train
|
def transliterate_roman!(time = 2, warmup = 1)
::Benchmark.ips do |x|
x.config(time: time, warmup: warmup)
TEST_STRINGS[:roman].to_a.product(TEST_STRINGS_FLAT.keys).each do |(ak, av), bk|
next if ak == bk
x.report("#{ak} => #{bk}") do
Sanscript.transliterate(av, ak, bk)
end
end
x.compare!
end
true
end
|
ruby
|
{
"resource": ""
}
|
q5355
|
Ifdef.LogicProcessor.on_or
|
train
|
def on_or(node)
a, b = node.children.map { |c| @truth.fetch(c, process(c)) }
if a == :true || b == :true
:true
elsif a == :false && b == :false
:false
else
nil
end
end
|
ruby
|
{
"resource": ""
}
|
q5356
|
Ifdef.LogicProcessor.on_send
|
train
|
def on_send(node)
_target, _method, _args = node.children
if _method == :!
case @truth.fetch(_target, process(_target))
when :true
:false
when :false
:true
else
nil
end
else
nil
end
end
|
ruby
|
{
"resource": ""
}
|
q5357
|
Ifdef.LogicProcessor.on_begin
|
train
|
def on_begin(node)
child, other_children = *node.children
# Not sure if this can happen in an `if` statement
raise LogicError if other_children
case @truth.fetch(child, process(child))
when :true
:true
when :false
:false
else
nil
end
end
|
ruby
|
{
"resource": ""
}
|
q5358
|
DeploYML.Environment.remote_shell
|
train
|
def remote_shell(&block)
each_dest.map do |dest|
shell = if dest.scheme == 'file'
LocalShell
else
RemoteShell
end
shell.new(dest,self,&block)
end
end
|
ruby
|
{
"resource": ""
}
|
q5359
|
DeploYML.Environment.exec
|
train
|
def exec(command)
remote_shell do |shell|
shell.cd(shell.uri.path)
shell.exec(command)
end
return true
end
|
ruby
|
{
"resource": ""
}
|
q5360
|
DeploYML.Environment.rake
|
train
|
def rake(task,*arguments)
remote_shell do |shell|
shell.cd(shell.uri.path)
shell.rake(task,*arguments)
end
return true
end
|
ruby
|
{
"resource": ""
}
|
q5361
|
DeploYML.Environment.ssh
|
train
|
def ssh(*arguments)
each_dest do |dest|
RemoteShell.new(dest).ssh(*arguments)
end
return true
end
|
ruby
|
{
"resource": ""
}
|
q5362
|
DeploYML.Environment.setup
|
train
|
def setup(shell)
shell.status "Cloning #{@source} ..."
shell.run 'git', 'clone', '--depth', 1, @source, shell.uri.path
shell.status "Cloned #{@source}."
end
|
ruby
|
{
"resource": ""
}
|
q5363
|
DeploYML.Environment.update
|
train
|
def update(shell)
shell.status "Updating ..."
shell.run 'git', 'reset', '--hard', 'HEAD'
shell.run 'git', 'pull', '-f'
shell.status "Updated."
end
|
ruby
|
{
"resource": ""
}
|
q5364
|
DeploYML.Environment.invoke_task
|
train
|
def invoke_task(task,shell)
unless TASKS.include?(task)
raise("invalid task: #{task}")
end
if @before.has_key?(task)
@before[task].each { |command| shell.exec(command) }
end
send(task,shell) if respond_to?(task)
if @after.has_key?(task)
@after[task].each { |command| shell.exec(command) }
end
end
|
ruby
|
{
"resource": ""
}
|
q5365
|
DeploYML.Environment.invoke
|
train
|
def invoke(tasks)
remote_shell do |shell|
# setup the deployment repository
invoke_task(:setup,shell) if tasks.include?(:setup)
# cd into the deployment repository
shell.cd(shell.uri.path)
# update the deployment repository
invoke_task(:update,shell) if tasks.include?(:update)
# framework tasks
invoke_task(:install,shell) if tasks.include?(:install)
invoke_task(:migrate,shell) if tasks.include?(:migrate)
# server tasks
if tasks.include?(:config)
invoke_task(:config,shell)
elsif tasks.include?(:start)
invoke_task(:start,shell)
elsif tasks.include?(:stop)
invoke_task(:stop,shell)
elsif tasks.include?(:restart)
invoke_task(:restart,shell)
end
end
return true
end
|
ruby
|
{
"resource": ""
}
|
q5366
|
DeploYML.Environment.load_framework!
|
train
|
def load_framework!
if @orm
unless FRAMEWORKS.has_key?(@framework)
raise(UnknownFramework,"Unknown framework #{@framework}",caller)
end
extend FRAMEWORKS[@framework]
initialize_framework if respond_to?(:initialize_framework)
end
end
|
ruby
|
{
"resource": ""
}
|
q5367
|
DeploYML.Environment.load_server!
|
train
|
def load_server!
if @server_name
unless SERVERS.has_key?(@server_name)
raise(UnknownServer,"Unknown server name #{@server_name}",caller)
end
extend SERVERS[@server_name]
initialize_server if respond_to?(:initialize_server)
end
end
|
ruby
|
{
"resource": ""
}
|
q5368
|
LatoCore.Interface::Authentication.core__create_superuser_session
|
train
|
def core__create_superuser_session(superuser, lifetime)
token = core__encode_token(lifetime, superuser_id: superuser.id)
session[:lato_core__superuser_session_token] = token
end
|
ruby
|
{
"resource": ""
}
|
q5369
|
LatoCore.Interface::Authentication.core__manage_superuser_session
|
train
|
def core__manage_superuser_session(permission = nil)
decoded_token = core__decode_token(session[:lato_core__superuser_session_token])
if decoded_token
@core__current_superuser = LatoCore::Superuser.find_by(id: decoded_token[:superuser_id])
unless @core__current_superuser
core__destroy_superuser_session
redirect_to lato_core.login_path
end
if permission && @core__current_superuser.permission < permission
flash[:danger] = 'PERMISSION ERROR'
redirect_to lato_core.root_path
end
else
redirect_to lato_core.login_path
end
end
|
ruby
|
{
"resource": ""
}
|
q5370
|
MongoDoc.Matchers.matcher
|
train
|
def matcher(key, value)
if value.is_a?(Hash)
name = "Mongoid::Matchers::#{value.keys.first.gsub("$", "").camelize}"
return name.constantize.new(send(key))
end
Mongoid::Matchers::Default.new(send(key))
end
|
ruby
|
{
"resource": ""
}
|
q5371
|
Chatrix.User.process_power_level
|
train
|
def process_power_level(room, level)
membership = (@memberships[room] ||= {})
membership[:power] = level
broadcast(:power_level, self, room, level)
end
|
ruby
|
{
"resource": ""
}
|
q5372
|
Chatrix.User.process_invite
|
train
|
def process_invite(room, sender, event)
# Return early if we're already part of this room
membership = (@memberships[room] ||= {})
return if membership[:type] == :join
process_member_event room, event
broadcast(:invited, self, room, sender)
end
|
ruby
|
{
"resource": ""
}
|
q5373
|
Chatrix.User.update
|
train
|
def update(data)
update_avatar(data['avatar_url']) if data.key? 'avatar_url'
update_displayname(data['displayname']) if data.key? 'displayname'
end
|
ruby
|
{
"resource": ""
}
|
q5374
|
Algebra.AlgebraCreator.wedge
|
train
|
def wedge(otype) # =:= tensor
if superior?(otype)
self
elsif otype.respond_to?(:superior?) && otype.superior?(self)
otype
else
raise "wedge: unknown pair (#{self}) .wedge (#{otype})"
end
end
|
ruby
|
{
"resource": ""
}
|
q5375
|
QnAMaker.Client.delete_kb
|
train
|
def delete_kb
response = @http.delete(
"#{BASE_URL}/#{knowledgebase_id}"
)
case response.code
when 204
nil
when 400
raise BadArgumentError, response.parse['error']['message'].join(' ')
when 401
raise UnauthorizedError, response.parse['error']['message']
when 403
raise ForbiddenError, response.parse['error']['message']
when 404
raise NotFoundError, response.parse['error']['message']
when 409
raise ConflictError, response.parse['error']['message']
else
raise UnknownError, "Oh no! (#{response.code})"
end
end
|
ruby
|
{
"resource": ""
}
|
q5376
|
SpanManager.Tracer.start_span
|
train
|
def start_span(operation_name, child_of: active_span, **args)
span = @tracer.start_span(operation_name, child_of: child_of, **args)
@managed_span_source.make_active(span)
end
|
ruby
|
{
"resource": ""
}
|
q5377
|
OAuthActiveResource.Connection.handle_response
|
train
|
def handle_response(response)
return super(response)
rescue ActiveResource::ClientError => exc
begin
# ugly code to insert the error_message into response
error_message = "#{format.decode response.body}"
if not error_message.nil? or error_message == ""
exc.response.instance_eval do ||
@message = error_message
end
end
ensure
raise exc
end
end
|
ruby
|
{
"resource": ""
}
|
q5378
|
Auth::Concerns::Shopping::ProductConcern.ClassMethods.add_to_previous_rolling_n_minutes
|
train
|
def add_to_previous_rolling_n_minutes(minutes,origin_epoch,cycle_to_add)
## get all the minutes less than that.
rolling_n_minutes_less_than_that = minutes.keys.select{|c| c < origin_epoch}
end_min = rolling_n_minutes_less_than_that.size < Auth.configuration.rolling_minutes ? rolling_n_minutes_less_than_that.size : Auth.configuration.rolling_minutes
end_min = end_min - 1
end_min = end_min > 0 ? end_min : 0
rolling_n_minutes_less_than_that[0..end_min].each do |epoch|
minutes[epoch].cycles << cycle_to_add
end
end
|
ruby
|
{
"resource": ""
}
|
q5379
|
Delorean.Engine.parse_check_defined_node
|
train
|
def parse_check_defined_node(name, flag)
isdef = node_defined?(name)
if isdef != flag
isdef ? err(RedefinedError, "#{name} already defined") :
err(UndefinedError, "#{name} not defined yet")
end
end
|
ruby
|
{
"resource": ""
}
|
q5380
|
Delorean.Engine.parse_call_attr
|
train
|
def parse_call_attr(node_name, attr_name)
return [] if comp_set.member?(attr_name)
# get the class associated with node
klass = @pm.module_eval(node_name)
# puts attr_name, "#{attr_name}#{POST}".to_sym, klass.methods.inspect
begin
klass.send("#{attr_name}#{POST}".to_sym, [])
rescue NoMethodError
err(UndefinedError, "'#{attr_name}' not defined in #{node_name}")
end
end
|
ruby
|
{
"resource": ""
}
|
q5381
|
Delorean.Engine.parse_define_attr
|
train
|
def parse_define_attr(name, spec)
err(ParseError, "Can't define '#{name}' outside a node") unless
@last_node
err(RedefinedError, "Can't redefine '#{name}' in node #{@last_node}") if
@node_attrs[@last_node].member? name
@node_attrs[@last_node] << name
checks = spec.map do |a|
n = a.index('.') ? a : "#{@last_node}.#{a}"
"_x.member?('#{n}') ? raise('#{n}') : #{a}#{POST}(_x + ['#{n}'])"
end.join(';')
code =
"class #{@last_node}; def self.#{name}#{POST}(_x); #{checks}; end; end"
# pp code
@pm.module_eval(code)
begin
parse_call_attr(@last_node, name)
rescue RuntimeError
err(RecursionError, "'#{name}' is recursive")
end
end
|
ruby
|
{
"resource": ""
}
|
q5382
|
Delorean.Engine.enumerate_params_by_node
|
train
|
def enumerate_params_by_node(node)
attrs = enumerate_attrs_by_node(node)
Set.new(attrs.select { |a| @param_set.include?(a) })
end
|
ruby
|
{
"resource": ""
}
|
q5383
|
Instrumentable.ClassMethods.class_instrument_method
|
train
|
def class_instrument_method(klass, method_to_instrument, event_name, payload={})
class << klass; self; end.class_eval do
Instrumentality.begin(self, method_to_instrument, event_name, payload)
end
end
|
ruby
|
{
"resource": ""
}
|
q5384
|
Effective.Region.snippet_objects
|
train
|
def snippet_objects(locals = {})
locals = {} unless locals.kind_of?(Hash)
@snippet_objects ||= snippets.map do |key, snippet| # Key here is 'snippet_1'
if snippet['class_name']
klass = "Effective::Snippets::#{snippet['class_name'].classify}".safe_constantize
klass.new(snippet.merge!(locals).merge!(:region => self, :id => key)) if klass
end
end.compact
end
|
ruby
|
{
"resource": ""
}
|
q5385
|
Biopsy.Distribution.draw
|
train
|
def draw
r = @dist.rng.to_i
raise "drawn number must be an integer" unless r.is_a? Integer
# keep the value inside the allowed range
r = 0 - r if r < 0
if r >= @range.size
diff = 1 + r - @range.size
r = @range.size - diff
end
@range[r]
end
|
ruby
|
{
"resource": ""
}
|
q5386
|
Biopsy.Hood.generate_neighbour
|
train
|
def generate_neighbour
n = 0
begin
if n >= 100
# taking too long to generate a neighbour,
# loosen the neighbourhood structure so we explore further
# debug("loosening distributions")
@distributions.each do |param, dist|
dist.loosen
end
end
# preform the probabilistic step move for each parameter
neighbour = Hash[@distributions.map { |param, dist| [param, dist.draw] }]
n += 1
end while self.is_tabu?(neighbour)
@tabu << neighbour
@members << neighbour
end
|
ruby
|
{
"resource": ""
}
|
q5387
|
Biopsy.TabuSearch.update_neighbourhood_structure
|
train
|
def update_neighbourhood_structure
self.update_recent_scores
best = self.backtrack_or_continue
unless @distributions.empty?
@standard_deviations = Hash[@distributions.map { |k, d| [k, d.sd] }]
end
best[:parameters].each_pair do |param, value|
self.update_distribution(param, value)
end
end
|
ruby
|
{
"resource": ""
}
|
q5388
|
Biopsy.TabuSearch.backtrack_or_continue
|
train
|
def backtrack_or_continue
best = nil
if (@iterations_since_best / @backtracks) >= @backtrack_cutoff * @max_hood_size
self.backtrack
best = @best
else
best = @current_hood.best
self.adjust_distributions_using_gradient
end
if best[:parameters].nil?
# this should never happen!
best = @best
end
best
end
|
ruby
|
{
"resource": ""
}
|
q5389
|
Biopsy.TabuSearch.adjust_distributions_using_gradient
|
train
|
def adjust_distributions_using_gradient
return if @recent_scores.length < 3
vx = (1..@recent_scores.length).to_a.to_numeric
vy = @recent_scores.reverse.to_numeric
r = Statsample::Regression::Simple.new_from_vectors(vx,vy)
slope = r.b
if slope > 0
@distributions.each_pair { |k, d| d.tighten slope }
elsif slope < 0
@distributions.each_pair { |k, d| d.loosen slope }
end
end
|
ruby
|
{
"resource": ""
}
|
q5390
|
Biopsy.TabuSearch.finished?
|
train
|
def finished?
return false unless @threads.all? do |t|
t.recent_scores.size == @jump_cutoff
end
probabilities = self.recent_scores_combination_test
n_significant = 0
probabilities.each do |mann_u, levene|
if mann_u <= @adjusted_alpha && levene <= @convergence_alpha
n_significant += 1
end
end
finish = n_significant >= probabilities.size * 0.5
end
|
ruby
|
{
"resource": ""
}
|
q5391
|
SweetNotifications.Railtie.initialize_rails
|
train
|
def initialize_rails(name, log_subscriber, controller_runtime)
log_subscriber.attach_to name.to_sym
ActiveSupport.on_load(:action_controller) do
include controller_runtime
end
end
|
ruby
|
{
"resource": ""
}
|
q5392
|
SweetNotifications.Railtie.railtie
|
train
|
def railtie(name, log_subscriber, controller_runtime)
Class.new(Rails::Railtie) do
railtie_name name
initializer "#{name}.notifications" do
SweetNotifications::Railtie.initialize_rails(name,
log_subscriber,
controller_runtime)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5393
|
Lunar.ResultSet.sort
|
train
|
def sort(opts = {})
return [] if not distkey
opts[:by] = sortables[opts[:by]] if opts[:by]
if opts[:start] && opts[:limit]
opts[:limit] = [opts[:start], opts[:limit]]
end
objects(distkey.sort(opts))
end
|
ruby
|
{
"resource": ""
}
|
q5394
|
CryptBufferConcern.Padding.padding
|
train
|
def padding
last = bytes.last
subset = subset_padding
if subset.all?{|e| e == last }
self.class.new(subset)
else
self.class.new([])
end
end
|
ruby
|
{
"resource": ""
}
|
q5395
|
CryptBufferConcern.Padding.strip_padding
|
train
|
def strip_padding
subset = bytes
if padding?
pad = padding
len = pad.length
subset = bytes[0,bytes.length - len]
end
self.class.new(subset)
end
|
ruby
|
{
"resource": ""
}
|
q5396
|
Configurable.Conversions.to_parser
|
train
|
def to_parser(*args, &block)
parser = ConfigParser.new(*args, &block)
traverse do |nesting, config|
next if config[:hidden] == true || nesting.any? {|nest| nest[:hidden] == true }
nest_keys = nesting.collect {|nest| nest.key }
long, short = nesting.collect {|nest| nest.name }.push(config.name).join(':'), nil
long, short = short, long if long.length == 1
guess_attrs = {
:long => long,
:short => short
}
config_attrs = {
:key => config.key,
:nest_keys => nest_keys,
:default => config.default,
:callback => lambda {|value| config.type.cast(value) }
}
attrs = guess_attrs.merge(config.metadata).merge(config_attrs)
parser.on(attrs)
end
parser.sort_opts!
parser
end
|
ruby
|
{
"resource": ""
}
|
q5397
|
Configurable.Conversions.to_default
|
train
|
def to_default
default = {}
each_pair do |key, config|
default[key] = config.default
end
default
end
|
ruby
|
{
"resource": ""
}
|
q5398
|
Configurable.Conversions.traverse
|
train
|
def traverse(nesting=[], &block)
each_value do |config|
if config.type.kind_of?(NestType)
nesting.push config
configs = config.type.configurable.class.configs
configs.traverse(nesting, &block)
nesting.pop
else
yield(nesting, config)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5399
|
KonoUtils.TmpFile.clean_tmpdir
|
train
|
def clean_tmpdir
self.root_dir.each do |d|
if d != '..' and d!='.'
if d.to_i < Time.now.to_i-TIME_LIMIT
FileUtils.rm_rf(File.join(self.root_dir.path, d))
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.