_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q9800 | LatoBlog.Back::TagsController.edit | train | def edit
core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:tags_edit])
@tag = LatoBlog::Tag.find_by(id: params[:id])
return unless check_tag_presence
if @tag.meta_language != cookies[:lato_blog__current_language]
set_current_language @tag.meta_language
end
end | ruby | {
"resource": ""
} |
q9801 | LatoBlog.Back::TagsController.update | train | def update
@tag = LatoBlog::Tag.find_by(id: params[:id])
return unless check_tag_presence
if !@tag.update(edit_tag_params)
flash[:danger] = @tag.errors.full_messages.to_sentence
redirect_to lato_blog.edit_tag_path(@tag.id)
return
end
flash[:success] = LANGUAGES[:lato_blog][:flashes][:tag_update_success]
redirect_to lato_blog.tag_path(@tag.id)
end | ruby | {
"resource": ""
} |
q9802 | LatoBlog.Back::TagsController.destroy | train | def destroy
@tag = LatoBlog::Tag.find_by(id: params[:id])
return unless check_tag_presence
if !@tag.destroy
flash[:danger] = @tag.tag_parent.errors.full_messages.to_sentence
redirect_to lato_blog.edit_tag_path(@tag.id)
return
end
flash[:success] = LANGUAGES[:lato_blog][:flashes][:tag_destroy_success]
redirect_to lato_blog.categories_path(status: 'deleted')
end | ruby | {
"resource": ""
} |
q9803 | Hokkaido.GemModifier.parse_gem | train | def parse_gem(init_lib)
# puts "Processing: #{init_lib}"
# don't ask
init_path = init_lib
init_file = File.read(init_lib)
current_file = ""
init_file.each_line do |line|
if line.strip =~ /^require/
parser = RubyParser.new
sexp = parser.parse(line)
call = sexp[2]
unless call == :require
# WEIRD SHIT IS HAPPENING
current_file += line
next
end
require_type = sexp[3][1][0]
library = sexp[3][1][1]
#p library
if require_type == :str && library.match(@gem_name)
# fold in
full_rb_path = File.join([@lib_folder, "#{library}.rb"])
unless @require_libs.include?(full_rb_path)
file_index = @require_libs.index(init_lib)
insert_index = file_index
@require_libs.insert insert_index, full_rb_path
parse_gem(full_rb_path)
end
else
current_file += "# FIXME: #require is not supported in RubyMotion\n"
current_file += "# #{line}"
next
end
# comment it out
current_file += "# #{line}"
next
elsif line.strip =~ /^autoload/
# same as require
parser = RubyParser.new
sexp = parser.parse(line)
call = sexp[2]
unless call == :autoload
# WEIRD SHIT IS HAPPENING
current_file += line
next
end
require_type = sexp[3][2][0]
library = sexp[3][2][1]
full_rb_path = File.join([@lib_folder, "#{library}.rb"])
unless @require_libs.include?(full_rb_path)
file_index = @require_libs.index(init_lib)
insert_index = file_index
@require_libs.insert insert_index, full_rb_path
parse_gem(full_rb_path)
end
# comment it out
current_file += "# #{line}"
next
elsif line.strip =~ /^eval/
# reprint as a block
# parser = RubyParser.new
# sexp = parser.parse(line)
# code_str = sexp[3][1][1]
# new_eval = "eval do\n #{code_str}\nend\n"
# current_file += "#{new_eval}"
# next
# produce a fixme
current_file += "# FIXME: Cannot eval strings in RubyMotion. \n"
current_file += "# Rewrite to use a block.. inbuilt hack will run \n"
current_file += "# Change this: \n"
current_file += "# eval %Q{ \n"
current_file += '# def #{c}(string = nil) ' + "\n"
current_file += "# To this \n"
current_file += "# eval do \n"
current_file += "# define_method(c) do |string| \n"
current_file += "#{line}"
next
elsif line.strip =~ /^binding/
current_file += "# FIXME: binding is not supported in RubyMotion.\n"
current_file += "#{line}"
next
end
# dont intefere
current_file += line
end
# replace file
File.open(init_lib, 'w') {|f| f.write(current_file) } #unless TEST_MODE
end | ruby | {
"resource": ""
} |
q9804 | Consumers.Base.start | train | def start
channel.prefetch(10)
queue.subscribe(manual_ack: true, exclusive: false) do |delivery_info, metadata, payload|
begin
body = JSON.parse(payload).with_indifferent_access
status = run(body)
rescue => e
status = :error
end
if status == :ok
channel.ack(delivery_info.delivery_tag)
elsif status == :retry
channel.reject(delivery_info.delivery_tag, true)
else # :error, nil etc
channel.reject(delivery_info.delivery_tag, false)
end
end
wait_for_threads
end | ruby | {
"resource": ""
} |
q9805 | DAF.Configurable.process_options | train | def process_options(options)
options.each do |key, value|
key = key.to_s
fail OptionException, "No Option #{key}" unless self.class.options[key]
opt = send("#{key}")
opt.value = value
fail OptionException, "Bad value for option #{key}" unless opt.valid?
end
validate_required_options
end | ruby | {
"resource": ""
} |
q9806 | PauseOutput.OutputPager.write | train | def write(str)
while !str.empty?
pre,mid,str = str.partition("\n")
write_str(pre) unless pre.empty?
writeln unless mid.empty?
end
end | ruby | {
"resource": ""
} |
q9807 | PauseOutput.OutputPager.write_str | train | def write_str(str)
loop do
len = str.length
if @chars + len < chars_per_line
$pause_output_out.write(str)
@chars += len
return
else
tipping_point = chars_per_line - @chars
$pause_output_out.write(str[0, tipping_point])
count_lines
str = (str[tipping_point..-1])
end
end
end | ruby | {
"resource": ""
} |
q9808 | PauseOutput.OutputPager.pause | train | def pause
msg = pause_message
$pause_output_out.write(msg)
MiniTerm.raw do |term|
result = term.get_raw_char
term.flush
result
end
ensure
$pause_output_out.write("\r" + " " * msg.length + "\r")
end | ruby | {
"resource": ""
} |
q9809 | Internode.Account.concurrent_map | train | def concurrent_map
threads = services.map{|s| Thread.new{ yield s } }
threads.each(&:join)
threads.map(&:value)
end | ruby | {
"resource": ""
} |
q9810 | NetworkExecutive.ProgramSchedule.occurrence_at | train | def occurrence_at( time )
real_duration = duration - 1
range = [ time - real_duration, time ]
start_time = proxy.occurrences_between( range[0], range[1] ).first
end_time = start_time + real_duration
Occurrence.new start_time, real_duration, end_time
end | ruby | {
"resource": ""
} |
q9811 | NauktisUtils.Duplicate.files_in | train | def files_in(directories)
files = []
Find.find(*directories) do |path|
unless File.directory?(path) or File.symlink?(path)
files << File.expand_path(path)
end
end
files.uniq
end | ruby | {
"resource": ""
} |
q9812 | NauktisUtils.Duplicate.size_of | train | def size_of(directories)
size = 0
files_in(directories).each do |f|
size += File.size(f)
end
size
end | ruby | {
"resource": ""
} |
q9813 | VirtualMonkey.Mysql.setup_dns | train | def setup_dns(domain)
# TODO should we just use the ID instead of the full href?
owner=@deployment.href
@dns = SharedDns.new(domain)
raise "Unable to reserve DNS" unless @dns.reserve_dns(owner)
@dns.set_dns_inputs(@deployment)
end | ruby | {
"resource": ""
} |
q9814 | Pvcglue.Cloud.find_minion_by_name | train | def find_minion_by_name(minion_name, raise_error = true)
# raise(Thor::Error, "Node not specified.") if node_name.nil? || node_name.empty?
raise('Minion not specified.') if minion_name.nil? || minion_name.empty?
return {minion_name => minions_filtered[minion_name]} if minions[minion_name]
minions.each do |key, value|
return {key => value} if key.start_with?(minion_name)
end
raise("Not found: #{minion_name} in #{stage_name}.") if raise_error
# raise(Thor::Error, "Not found: #{node_name} in #{stage_name}.")
nil
end | ruby | {
"resource": ""
} |
q9815 | Kharon.Validator.method_missing | train | def method_missing(name, *arguments, &block)
if respond_to? name
if arguments.count == 1
processors[name].process(arguments[0])
elsif arguments.count == 2
processors[name].process(arguments[0], arguments[1])
end
else
super
end
end | ruby | {
"resource": ""
} |
q9816 | Raca.HttpClient.cloud_request | train | def cloud_request(request, &block)
Net::HTTP.start(@hostname, 443, use_ssl: true, read_timeout: 120) do |http|
request['X-Auth-Token'] = @account.auth_token
request['User-Agent'] = "raca 0.4.4 (http://rubygems.org/gems/raca)"
response = http.request(request, &block)
if response.is_a?(Net::HTTPSuccess)
response
else
raise_on_error(request, response)
end
end
end | ruby | {
"resource": ""
} |
q9817 | GromNative.UrlRequest.method_missing | train | def method_missing(method, *params, &block)
@endpoint_parts << method.to_s
@endpoint_parts << params
@endpoint_parts = @endpoint_parts.flatten!
block&.call
self || super
end | ruby | {
"resource": ""
} |
q9818 | Traject.SequelWriter.output_value_to_column_value | train | def output_value_to_column_value(v)
if v.kind_of?(Array)
if v.length == 0
nil
elsif v.length == 1
v.first
elsif v.first.kind_of?(String)
v.join(@internal_delimiter)
else
# Not a string? Um, raise for now?
raise ArgumentError.new("Traject::SequelWriter, multiple non-String values provided: #{v}")
end
else
v
end
end | ruby | {
"resource": ""
} |
q9819 | Conify.Command.run | train | def run(klass, method)
# Get the command info for this method on this klass
command_info_module = klass::CommandInfo.const_get(camelize(method))
# If seeking help for this command with --help or -h
if seeking_command_help?(@current_args)
puts "\nPurpose: #{command_description(command_info_module)}\n"
# respond with command-specific help
respond_with_command_help(command_info_module)
return
end
# get the valid arguments defined for this comand
valid_args = command_valid_args(command_info_module)
if !valid_args?(valid_args)
handle_invalid_args(command_info_module)
return
end
klass.new(@current_args.dup).send(method)
end | ruby | {
"resource": ""
} |
q9820 | Conify.Command.valid_args? | train | def valid_args?(accepted_arg_formats)
valid_args = false
accepted_arg_formats.each { |format|
# if no arguments exist, and no arguments is an accepted format, args are valid.
if format.empty? && @current_args.empty?
valid_args = true
else
passed_in_args = @current_args.clone
format.each_with_index { |arg, i|
passed_in_args[i] = arg if CMD_BLACKLIST.include?(arg)
}
@invalid_args = passed_in_args - format - [nil]
valid_args = true if passed_in_args == format
end
}
valid_args
end | ruby | {
"resource": ""
} |
q9821 | Conify.Command.handle_invalid_args | train | def handle_invalid_args(command_info_module)
if !@invalid_args.empty?
message = 'Invalid argument'
message += 's' if @invalid_args.length > 1
args = @invalid_args.map { |arg| "\"#{arg}\"" }.join(', ')
puts " ! #{message}: #{args}"
else
puts " ! Invalid command usage"
end
respond_with_command_help(command_info_module)
end | ruby | {
"resource": ""
} |
q9822 | Conify.Command.create_commands_map | train | def create_commands_map
# Require all the ruby command files
command_file_paths.each do |file|
require file
# Get basename for the file without the extension
basename = get_basename_from_file(file)
# Camelcase the basename to be the klass name
klass_name = camelize(basename)
# return the command klass for this klass_name
command_klass = Conify::Command.const_get(klass_name)
# For each of the user-defined methods inside this class, create a command for it
manually_added_methods(command_klass).each { |method|
register_command(basename, method.to_s, command_klass, global: basename == 'global')
}
end
end | ruby | {
"resource": ""
} |
q9823 | Conify.Command.usage_info | train | def usage_info(map)
keys = map.keys
commands_column_width = keys.max_by(&:length).length + 1
commands_column_width += 2 if commands_column_width < 12
# iterate through each of the commands, create an array
# of strings in a `<command> # <description>` format. Sort
# them alphabetically, and then join them with new lines.
keys.map { |key|
command = " #{key}"
command += (' ' * (commands_column_width - key.length + 1))
command += "# #{map[key][:description]}"
command
}.sort_by{ |k| k.downcase }.join("\n")
end | ruby | {
"resource": ""
} |
q9824 | Conify.Command.get_basename_from_file | train | def get_basename_from_file(file)
basename = Pathname.new(file).basename.to_s
basename[0..(basename.rindex('.') - 1)]
end | ruby | {
"resource": ""
} |
q9825 | Conify.Command.command_file_paths | train | def command_file_paths
abstract_file = File.join(File.dirname(__FILE__), 'command', 'abstract_command.rb')
Dir[File.join(File.dirname(__FILE__), 'command', '*.rb')] - [abstract_file]
end | ruby | {
"resource": ""
} |
q9826 | Conify.Command.register_command | train | def register_command(basename, action, command_class, global: false)
command = global ? action : (action == 'index' ? basename : "#{basename}:#{action}")
command_info_module = command_class::CommandInfo.const_get(camelize(action))
commands[command] = { description: command_description(command_info_module) }
end | ruby | {
"resource": ""
} |
q9827 | Prezio.SyntaxHighlighter.tableize_code | train | def tableize_code (str, lang = '')
table = '<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers">'
code = ''
str.lines.each_with_index do |line,index|
table += "<span class='line-number'>#{index+1}</span>\n"
code += "<span class='line'>#{line}</span>"
end
table += "</pre></td><td class='code'><pre><code class='#{lang}'>#{code}</code></pre></td></tr></table></div>"
end | ruby | {
"resource": ""
} |
q9828 | Atlas.Box.save | train | def save
validate!
body = { box: to_hash }
# versions are saved seperately
body[:box].delete(:versions)
# update or create the box
begin
response = Atlas.client.put(url_builder.box_url, body: body)
rescue Atlas::Errors::NotFoundError
body[:box].replace_key!(:private, :is_private)
response = Atlas.client.post("/boxes", body: body)
end
# trigger the same on versions
versions.each(&:save) if versions
update_with_response(response, [:versions])
end | ruby | {
"resource": ""
} |
q9829 | BitwiseAttribute.ClassMethods.build_mapping | train | def build_mapping(values)
{}.tap do |hash|
values.each_with_index { |key, index| hash[key] = (0b1 << index) }
end
end | ruby | {
"resource": ""
} |
q9830 | Firefly.Client.shorten | train | def shorten(input)
if input.is_a?(String)
return create_url(input)
elsif input.is_a?(Array)
result = {}
input.each do |inp|
result[inp] = create_url(inp)
end
return result
else
raise ArgumentError.new('Shorten requires either a url or an array of urls')
end
end | ruby | {
"resource": ""
} |
q9831 | Firefly.Client.create_url | train | def create_url(long_url)
begin
options = { :query => { :url => long_url, :api_key => @api_key } }
result = HTTParty.post(@firefly_url + '/api/add', options)
if result =~ /Permission denied/i
raise "Permission denied. Is your API Key set correctly?" if result.status = 401
else
return result
end
end
end | ruby | {
"resource": ""
} |
q9832 | JSONAPIHelpers.KeyTransform.camel | train | def camel(value)
case value
when Hash then value.deep_transform_keys! { |key| camel(key) }
when Symbol then camel(value.to_s).to_sym
when String then StringSupport.camel(value)
else value
end
end | ruby | {
"resource": ""
} |
q9833 | JSONAPIHelpers.KeyTransform.camel_lower | train | def camel_lower(value)
case value
when Hash then value.deep_transform_keys! { |key| camel_lower(key) }
when Symbol then camel_lower(value.to_s).to_sym
when String then StringSupport.camel_lower(value)
else value
end
end | ruby | {
"resource": ""
} |
q9834 | JSONAPIHelpers.KeyTransform.dash | train | def dash(value)
case value
when Hash then value.deep_transform_keys! { |key| dash(key) }
when Symbol then dash(value.to_s).to_sym
when String then StringSupport.dash(value)
else value
end
end | ruby | {
"resource": ""
} |
q9835 | JSONAPIHelpers.KeyTransform.underscore | train | def underscore(value)
case value
when Hash then value.deep_transform_keys! { |key| underscore(key) }
when Symbol then underscore(value.to_s).to_sym
when String then StringSupport.underscore(value)
else value
end
end | ruby | {
"resource": ""
} |
q9836 | Swissforecast.Client.find_by | train | def find_by(param)
if param.key?(:city)
perform(param[:city].sub(' ', '-'))
elsif param.key?(:lat) && param.key?(:lng)
perform("lat=#{param[:lat]}lng=#{param[:lng]}")
end
end | ruby | {
"resource": ""
} |
q9837 | FakeService.Server.right_header? | train | def right_header?(expected, actual)
expected.inject(true) do |memo, (k, v)|
memo && v == actual[k]
end
end | ruby | {
"resource": ""
} |
q9838 | TodoLint.Options.parse | train | def parse(args)
@options = { :report => false }
OptionParser.new do |parser|
parser.banner = "Usage: todo_lint [options] [files]"
add_config_options parser
exclude_file_options parser
include_extension_options parser
report_version parser
report_report_options parser
end.parse!(args)
# Any remaining arguments are assumed to be files
options[:files] = args
options
end | ruby | {
"resource": ""
} |
q9839 | TodoLint.Options.exclude_file_options | train | def exclude_file_options(parser)
parser.on("-e", "--exclude file1,...", Array,
"List of file names to exclude") do |files_list|
options[:excluded_files] = []
files_list.each do |short_file|
options[:excluded_files] << File.expand_path(short_file)
end
end
end | ruby | {
"resource": ""
} |
q9840 | CanTango.Category.has_any? | train | def has_any? subject, &block
found = subjects.include? subject
yield if found && block
found
end | ruby | {
"resource": ""
} |
q9841 | Scat.Field.input_attributes | train | def input_attributes(value)
params = {:id => input_id, :type => type, :name => name, :value => value }
if type == 'checkbox' then
params[:value] ||= self.value
params[:checked] = true if default
end
params
end | ruby | {
"resource": ""
} |
q9842 | Sem4r.GeoLocationAccountExtension.geo_location | train | def geo_location(c1, c2 = nil , c3 = nil)
if c1.class != GeoLocationSelector
# TODO: raise wrong number of arguments if c2 or c3 are nil
selector = GeoLocationSelector.new
selector.address do
address c1
city c2
country c3
end
else
selector = c1
end
soap_message = service.geo_location.get(credentials, selector.to_xml)
add_counters(soap_message.counters)
end | ruby | {
"resource": ""
} |
q9843 | ActiveRecord.Relation.update_all | train | def update_all(updates, conditions = nil, options = {})
IdentityMap.repository[symbolized_base_class].clear if IdentityMap.enabled?
if conditions || options.present?
where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates)
else
stmt = Arel::UpdateManager.new(arel.engine)
stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates))
stmt.table(table)
stmt.key = table[primary_key]
if joins_values.any?
@klass.connection.join_to_update(stmt, arel)
else
stmt.take(arel.limit)
stmt.order(*arel.orders)
stmt.wheres = arel.constraints
end
@klass.connection.update stmt, 'SQL', bind_values
end
end | ruby | {
"resource": ""
} |
q9844 | Rexport.DataFields.export | train | def export(*methods)
methods.flatten.map do |method|
case value = (eval("self.#{method}", binding) rescue nil)
when Date, Time
value.strftime("%m/%d/%y")
when TrueClass
'Y'
when FalseClass
'N'
else value.to_s
end
end
end | ruby | {
"resource": ""
} |
q9845 | Machined.Environment.reload | train | def reload
# Make sure we have a fresh cache after we reload
config.cache.clear if config.cache.respond_to?(:clear)
# Reload dependencies as well, if necessary
ActiveSupport::Dependencies.clear if defined?(ActiveSupport::Dependencies)
# Use current configuration, but skip bundle and autoloading initializers
current_config = config.marshal_dump.dup
current_config.merge! :skip_bundle => true#, :skip_autoloading => true)
initialize current_config
end | ruby | {
"resource": ""
} |
q9846 | Machined.Environment.remove_sprocket | train | def remove_sprocket(name)
if sprocket = get_sprocket(name)
sprockets.delete sprocket
set_sprocket(name, nil)
end
end | ruby | {
"resource": ""
} |
q9847 | Machined.Environment.append_path | train | def append_path(sprocket, path) # :nodoc:
path = Pathname.new(path).expand_path(root)
sprocket.append_path(path) if path.exist?
end | ruby | {
"resource": ""
} |
q9848 | Machined.Environment.append_paths | train | def append_paths(sprocket, paths) # :nodoc:
paths or return
paths.each do |path|
append_path sprocket, path
end
end | ruby | {
"resource": ""
} |
q9849 | Machined.Environment.js_compressor | train | def js_compressor # :nodoc:
case config.js_compressor
when Crush::Engine
config.js_compressor
when Symbol, String
JS_COMPRESSORS[config.js_compressor.to_sym]
else
Crush.register_js
Tilt['js']
end
end | ruby | {
"resource": ""
} |
q9850 | Machined.Environment.css_compressor | train | def css_compressor # :nodoc:
case config.css_compressor
when Crush::Engine
config.css_compressor
when Symbol, String
CSS_COMPRESSORS[config.css_compressor.to_sym]
else
Crush.register_css
Tilt['css']
end
end | ruby | {
"resource": ""
} |
q9851 | NSIVideoGranulate.Client.granulate | train | def granulate(options = {})
@request_data = Hash.new
if options[:video_link]
insert_download_data options
elsif options[:sam_uid] && options[:filename]
file_data = {:video_uid => options[:sam_uid], :filename => options[:filename]}
@request_data.merge! file_data
elsif options[:file] && options[:filename]
file_data = {:video => options[:file], :filename => options[:filename]}
@request_data.merge! file_data
else
raise NSIVideoGranulate::Errors::Client::MissingParametersError
end
insert_callback_data options
request = prepare_request :POST, @request_data.to_json
execute_request(request)
end | ruby | {
"resource": ""
} |
q9852 | NSIVideoGranulate.Client.grains_keys_for | train | def grains_keys_for(video_key)
request = prepare_request :GET, {:video_key => video_key, :grains => true}.to_json
execute_request(request).select { |key| ['images', 'videos'].include? key }
end | ruby | {
"resource": ""
} |
q9853 | SimpleCommander.CLI.set_exec_path | train | def set_exec_path(path)
yml = YAML.load_file(@config_file)
yml[:exec_path] = File.expand_path(path)
File.open(@config_file, 'w+'){|f| f.write(yml.to_yaml)}
end | ruby | {
"resource": ""
} |
q9854 | Aker::Rack.SessionTimer.call | train | def call(env)
now = Time.now.to_i
session = env['rack.session']
window_size = window_size(env)
previous_timeout = session['aker.last_request_at']
return @app.call(env) unless window_size > 0
env['aker.timeout_at'] = now + window_size
session['aker.last_request_at'] = now
return @app.call(env) unless previous_timeout
if now >= previous_timeout + window_size
env['aker.session_expired'] = true
env['warden'].logout
end
@app.call(env)
end | ruby | {
"resource": ""
} |
q9855 | Conflow.Future.build_promise | train | def build_promise(depending_job, param_key)
Promise.new.tap do |promise|
promise.assign_attributes(job_id: job.id, hash_field: param_key, result_key: result_key)
depending_job.promise_ids << promise.id
end
end | ruby | {
"resource": ""
} |
q9856 | StorageRoom.Accessors.to_hash | train | def to_hash(args = {}) # :nodoc:
args ||= {}
hash = {}
self.attributes.each do |name, value|
hash[name] = if value.is_a?(::Array)
value.map {|x| x.respond_to?(:to_hash) ? call_method_with_optional_parameters(x, :to_hash, :nested => true) : x}
elsif value.respond_to?(:to_hash)
call_method_with_optional_parameters(value, :to_hash, :nested => true)
elsif value.respond_to?(:as_json)
value.as_json(:nested => true)
else
value
end
end
hash
end | ruby | {
"resource": ""
} |
q9857 | StorageRoom.Accessors.call_method_with_optional_parameters | train | def call_method_with_optional_parameters(object, method_name, parameters)
if object.respond_to?(method_name)
if object.method(method_name).arity == -1
object.send(method_name, parameters)
else
object.send(method_name)
end
end
end | ruby | {
"resource": ""
} |
q9858 | StorageRoom.Accessors.initialize_from_response_data | train | def initialize_from_response_data # :nodoc:
run_callbacks :initialize_from_response_data do
self.class.attribute_options_including_superclasses.each do |name, options|
value = if options[:type] == :key
self[name].blank? ? options[:default] : self[name]
elsif options[:type] == :one
hash = self[name.to_s]
hash && hash['@type'] ? self.class.new_from_response_data(hash) : nil
elsif options[:type] == :many
response_data[name] && response_data[name].map{|hash| self.class.new_from_response_data(hash)} || []
else
raise "Invalid type: #{options[:type]}"
end
send("#{name}=", value)
end
end
end | ruby | {
"resource": ""
} |
q9859 | Duxml.History.xml | train | def xml
h = Element.new('history')
events.each do |event| h << event.xml end
h
end | ruby | {
"resource": ""
} |
q9860 | Truty.General.general | train | def general(input, convert = [:all])
output = input
output = ellipsis(output) if (convert.include?(:all) || convert.include?(:ellipsis))
output = multicharacters(output) if (convert.include? (:all) || convert.include?(:characters))
output = brackets_whitespace(output) if (convert.include?(:all) || convert.include?(:brackets))
output = emdash(output) if (convert.include?(:all) || convert.include?(:dashes))
output = endash(output) if (convert.include?(:all) || convert.include?(:dashes))
output = name_abbreviations(output) if (convert.include?(:all) || convert.include?(:abbreviations))
output = multiplication_sign(output) if (convert.include?(:all) || convert.include?(:multiplication))
output = space_between_numbers(output) if (convert.include?(:all) || convert.include?(:numbers))
output = units(output) if (convert.include?(:all) || convert.include?(:units))
output = widows(output) if (convert.include?(:all) || convert.include?(:widows))
output
end | ruby | {
"resource": ""
} |
q9861 | Truty.General.brackets_whitespace | train | def brackets_whitespace(input)
output = input.gsub(/([\(\[\{])\s*/, '\1')
output = output.gsub(/\s*([\]\)\}])/, '\1')
output = output.gsub(/\s+([\(\[\{])\s*/, ' \1')
output = output.gsub(/\s*([\]\)\}])\s+/, '\1 ')
end | ruby | {
"resource": ""
} |
q9862 | Organismo.Element.create | train | def create
if text.match(/\_QUOTE/)
require 'organismo/element/quote'
Organismo::Element::Quote.new(text, location)
elsif text.match(/\_SRC/)
require 'organismo/element/code'
Organismo::Element::Code.new(text, location)
elsif text.match(/\_EXAMPLE/)
require 'organismo/element/example'
Organismo::Element::Example.new(text, location)
elsif text.match(/\*/)
require 'organismo/element/header'
Organismo::Element::Header.new(text, location)
elsif text.match(/\[\[\S*(\.png)|(\jpg)|(\.jpeg)\]\]/)
require 'organismo/element/image'
Organismo::Element::Image.new(text, location)
elsif text.match(/\[\[\S*\]\]/)
require 'organismo/element/link'
Organismo::Element::Link.new(text, location)
elsif text.match(/\-/)
require 'organismo/element/plain_list'
Organismo::Element::PlainList.new(text, location)
else
require 'organismo/element/text'
Organismo::Element::Text.new(text, location)
end
end | ruby | {
"resource": ""
} |
q9863 | Octo.Email.send | train | def send(email, subject, opts = {})
if email.nil? or subject.nil?
raise ArgumentError, 'Email Address or Subject is missing'
else
message = {
from_name: Octo.get_config(:email_sender).fetch(:name),
from_email: Octo.get_config(:email_sender).fetch(:email),
subject: subject,
text: opts.fetch('text', nil),
html: opts.fetch('html', nil),
to: [{
email: email,
name: opts.fetch('name', nil)
}]
}
# Pass the message to resque only when mandrill key is present
_mandrill_config = ENV['MANDRILL_API_KEY'] || Octo.get_config(:mandrill_api_key)
if _mandrill_config and !_mandrill_config.empty?
enqueue_msg(message)
end
end
end | ruby | {
"resource": ""
} |
q9864 | Debeasy.Package.parse_control_file | train | def parse_control_file
@control_file_contents.scan(/^([\w-]+?): (.*?)\n(?! )/m).each do |entry|
field, value = entry
@fields[field.gsub("-", "_").downcase] = value
end
@fields["installed_size"] = @fields["installed_size"].to_i * 1024 unless @fields["installed_size"].nil?
end | ruby | {
"resource": ""
} |
q9865 | ElasticQueue.Query.method_missing | train | def method_missing(method, *args, &block)
if @queue.respond_to?(method)
proc = @queue.scopes[method]
instance_exec *args, &proc
end
end | ruby | {
"resource": ""
} |
q9866 | LooseLeaf.CollaborationChannel.document | train | def document(data)
document = collaborative_model.find_by_collaborative_key(data['id'])
@documents ||= []
@documents << document
send_attribute_versions(document)
stream_from "loose_leaf.documents.#{document.id}.operations"
end | ruby | {
"resource": ""
} |
q9867 | LooseLeaf.CollaborationChannel.send_attribute_versions | train | def send_attribute_versions(document)
collaborative_model.collaborative_attributes.each do |attribute_name|
attribute = document.collaborative_attribute(attribute_name)
transmit(
document_id: document.id,
action: 'attribute',
attribute: attribute_name,
version: attribute.version
)
end
end | ruby | {
"resource": ""
} |
q9868 | TodoLint.Cli.load_files | train | def load_files(file_finder)
if file_finder.options.fetch(:files).empty?
file_finder.list(*options[:extensions])
else
file_finder.options.fetch(:files) { [] }
end
end | ruby | {
"resource": ""
} |
q9869 | TodoLint.Cli.print_report | train | def print_report
todos = []
finder = FileFinder.new(path, options)
files = load_files(finder)
files.each do |file|
todos += Todo.within(File.open(file), :config => @options)
end
todos.sort.each.with_index do |todo, num|
due_date = if todo.due_date
tag_context = " via #{todo.tag}" if todo.tag?
Rainbow(" (due #{todo.due_date.to_date}#{tag_context})")
.public_send(todo.due_date.overdue? ? :red : :blue)
else
Rainbow(" (no due date)").red
end
puts "#{num + 1}. #{todo.task}#{due_date} " +
Rainbow(
"(#{todo.relative_path}:#{todo.line_number}:" \
"#{todo.character_number})"
).yellow
end
exit 0
end | ruby | {
"resource": ""
} |
q9870 | Redhead.HeaderSet.[]= | train | def []=(key, value)
h = self[key]
if h
h.value = value
else
new_header = Redhead::Header.new(key, TO_RAW[key], value)
self << new_header
end
end | ruby | {
"resource": ""
} |
q9871 | Redhead.HeaderSet.delete | train | def delete(key)
header = self[key]
@headers.reject! { |header| header.key == key } ? header : nil
end | ruby | {
"resource": ""
} |
q9872 | ActsAsReferred.Controller._supply_model_hook | train | def _supply_model_hook
# 3.2.1 -> adwords auto-tagging - (show hint to manual tag adwords):
# ?gclid=xxxx
# 3.2.2 -> manual tagging
# ?utm_source=google&utm_medium=cpc&utm_term=my_keyword&utm_campaign=my_summerdeal
# 3.2.3 -> manual url-tagging specific for piwik
# ?pk_campaign=my_summerdeal&pk_kwd=my_keyword
# cookie / session persisted:
# e.g.: "req=http://foo/baz?utm_campaign=plonk|ref=http://google.com/search|count=0"
tmp = session[:__reqref]
_struct = nil
if tmp
arr = tmp.split('|')
_struct = OpenStruct.new(
request_url: arr[0].split('=',2)[1],
referrer_url: minlength_or_nil(arr[1].split('=',2)[1]),
visit_count: arr[2].split('=',2)[1].to_i
)
end
ActiveRecord::Base.send(
:define_method,
'_get_reqref',
proc{ _struct }
)
end | ruby | {
"resource": ""
} |
q9873 | QueueToTheFuture.Coordinator.shutdown | train | def shutdown(force = false)
@workforce.mu_synchronize do
Thread.pass until @job_queue.empty? unless force
while worker = @workforce.shift; worker.terminate; end
end
nil
end | ruby | {
"resource": ""
} |
q9874 | Coach4rb.Coach.authenticate | train | def authenticate(username, password)
begin
options = {authorization: basic_auth_encryption(username, password)}
url = url_for_path('/authenticateduser/')
client.get(url, options) do |response|
if response.code == 200
a_hash = parse response
Resource::User.from_coach a_hash
else
false
end
end
rescue
raise 'Error: Could not authenticate user!'
end
end | ruby | {
"resource": ""
} |
q9875 | Coach4rb.Coach.user_exists? | train | def user_exists?(username)
begin
url = url_for_path(user_path(username))
client.get(url) { |response| response.code == 200 }
rescue
raise 'Error: Could not test user existence!'
end
end | ruby | {
"resource": ""
} |
q9876 | Coach4rb.Coach.create_user | train | def create_user(options={}, &block)
builder = Builder::User.new(public_visible: Privacy::Public)
block.call(builder)
url = url_for_path(user_path(builder.username))
begin
client.put(url, builder.to_xml, options) do |response|
a_hash = parse response
Resource::User.from_coach a_hash
end
rescue =>e
raise e if debug
false
end
end | ruby | {
"resource": ""
} |
q9877 | Coach4rb.Coach.delete_user | train | def delete_user(user, options={})
raise 'Error: Param user is nil!' if user.nil?
url = if user.is_a?(Resource::User)
url_for_resource(user)
elsif user.is_a?(String)
url_for_path(user_path(user))
else
raise 'Error: Invalid parameters!'
end
begin
client.delete(url, options) do |response|
response.code == 200
end
rescue => e
raise e if debug
end
end | ruby | {
"resource": ""
} |
q9878 | Coach4rb.Coach.create_partnership | train | def create_partnership(first_user, second_user, options={}, &block)
raise 'Error: Param first_user is nil!' if first_user.nil?
raise 'Error: Param second_user is nil!' if second_user.nil?
path = if first_user.is_a?(Resource::User) && second_user.is_a?(Resource::User)
partnership_path(first_user.username, second_user.username)
elsif first_user.is_a?(String) && second_user.is_a?(String)
partnership_path(first_user, second_user)
else
raise 'Error: Invalid parameters!'
end
url = url_for_path(path)
builder = Builder::Partnership.new(public_visible: Privacy::Public)
block.call(builder) if block_given?
begin
client.put(url, builder.to_xml, options) do |response|
a_hash = parse response
Resource::Partnership.from_coach a_hash
end
rescue => e
raise e if debug
false
end
end | ruby | {
"resource": ""
} |
q9879 | Coach4rb.Coach.delete_partnership | train | def delete_partnership(partnership, options={})
raise 'Error: Param partnership is nil!' if partnership.nil?
url = url_for_resource(partnership)
begin
client.delete(url, options) do |response|
response.code == 200
end
rescue => e
raise e if debug
false
end
end | ruby | {
"resource": ""
} |
q9880 | Coach4rb.Coach.breakup_between | train | def breakup_between(first_user, second_user, options={})
raise 'Error: Param first_user is nil!' if first_user.nil?
raise 'Error: Param second_user is nil!' if second_user.nil?
path = if first_user.is_a?(Resource::User) && second_user.is_a?(Resource::User)
partnership_path(first_user.username, second_user.username)
elsif first_user.is_a?(String) && second_user.is_a?(String)
partnership_path(first_user, second_user)
else
raise 'Error: Invalid parameters!'
end
url = url_for_path(path)
begin
client.delete(url, options) do |response|
response.code == 200
end
rescue => e
raise e if debug
false
end
end | ruby | {
"resource": ""
} |
q9881 | Coach4rb.Coach.create_subscription | train | def create_subscription(user_partnership, sport, options={}, &block)
raise 'Error: Param user_partnership is nil!' if user_partnership.nil?
raise 'Error: Param sport is nil!' if sport.nil?
url = if user_partnership.is_a?(Resource::User)
url_for_path(subscription_user_path(user_partnership.username, sport))
elsif user_partnership.is_a?(Resource::Partnership)
first_username = user_partnership.first_user.username
second_username = user_partnership.second_user.username
url_for_path(subscription_partnership_path(first_username, second_username, sport))
elsif user_partnership.is_a?(String)
url_for_uri(user_partnership)
else
raise 'Error: Invalid parameter!'
end
builder = Builder::Subscription.new(public_visible: Privacy::Public)
block.call(builder) if block_given?
begin
client.put(url, builder.to_xml, options) do |response|
a_hash = parse response
Resource::Subscription.from_coach a_hash
end
rescue => e
raise e if debug
false
end
end | ruby | {
"resource": ""
} |
q9882 | Coach4rb.Coach.create_entry | train | def create_entry(user_partnership, sport, options={}, &block)
raise 'Error: Param user_partnership is nil!' if user_partnership.nil?
raise 'Error: Param sport is nil!' if sport.nil?
entry_type = sport.downcase.to_sym
builder = Builder::Entry.builder(entry_type)
url = if user_partnership.is_a?(Resource::Entity)
url_for_resource(user_partnership) + sport.to_s
elsif user_partnership.is_a?(String)
url_for_uri(user_partnership) + sport.to_s
else
raise 'Error: Invalid parameter!'
end
block.call(builder) if block_given?
begin
client.post(url, builder.to_xml, options) do |response|
if uri = response.headers[:location]
entry_by_uri(uri, options)
else
false
end
end
rescue => e
raise e if debug
false
end
end | ruby | {
"resource": ""
} |
q9883 | Coach4rb.Coach.update_entry | train | def update_entry(entry, options={}, &block)
raise 'Error: Param entry is nil!' if entry.nil?
url, entry_type = if entry.is_a?(Resource::Entry)
[url_for_resource(entry), entry.type]
else
*, type, id = url_for_uri(entry).split('/')
type = type.downcase.to_sym
[url_for_uri(entry), type]
end
builder = Builder::Entry.builder(entry_type)
block.call(builder)
begin
client.put(url, builder.to_xml, options) do |response|
a_hash = parse(response)
Resource::Entry.from_coach a_hash
end
rescue => e
raise e if debug
false
end
end | ruby | {
"resource": ""
} |
q9884 | Coach4rb.Coach.delete_entry | train | def delete_entry(entry, options={})
raise 'Error: Param entry is nil!' if entry.nil?
url = if entry.is_a?(Resource::Entry)
url_for_resource(entry)
elsif entry.is_a?(String)
url_for_uri(entry)
else
raise 'Error: Invalid parameter!'
end
begin
client.delete(url, options) do |response|
response.code == 200
end
rescue => e
raise e if debug
false
end
end | ruby | {
"resource": ""
} |
q9885 | Coach4rb.Coach.user | train | def user(user, options={})
raise 'Error: Param user is nil!' if user.nil?
url = if user.is_a?(Resource::User)
url_for_resource(user)
elsif user.is_a?(String)
url_for_path(user_path(user))
else
raise 'Error: Invalid parameter!'
end
url = append_query_params(url, options)
client.get(url, options) do |response|
a_hash = parse(response)
Resource::User.from_coach a_hash
end
end | ruby | {
"resource": ""
} |
q9886 | Coach4rb.Coach.user_by_uri | train | def user_by_uri(uri, options={})
raise 'Error: Param uri is nil!' if uri.nil?
url = url_for_uri(uri)
url = append_query_params(url, options)
client.get(url, options) do |response|
a_hash = parse(response)
Resource::User.from_coach a_hash
end
end | ruby | {
"resource": ""
} |
q9887 | Coach4rb.Coach.users | train | def users(options={query: {}})
url = url_for_path(user_path)
url = append_query_params(url, options)
client.get(url, options) do |response|
a_hash = parse(response)
Resource::Page.from_coach a_hash, Resource::User
end
end | ruby | {
"resource": ""
} |
q9888 | Coach4rb.Coach.partnership_by_uri | train | def partnership_by_uri(uri, options={})
raise 'Error: Param uri is nil!' if uri.nil?
url = url_for_uri(uri)
url = append_query_params(url, options)
client.get(url, options) do |response|
a_hash = parse(response)
Resource::Partnership.from_coach a_hash
end
end | ruby | {
"resource": ""
} |
q9889 | Coach4rb.Coach.partnership | train | def partnership(first_username, second_username, options={})
raise 'Error: Param first_username is nil!' if first_username.nil?
raise 'Error: Param second_username is nil!' if second_username.nil?
url = url_for_path(partnership_path(first_username, second_username))
url = append_query_params(url, options)
client.get(url, options) do |response|
a_hash = parse(response)
Resource::Partnership.from_coach a_hash
end
end | ruby | {
"resource": ""
} |
q9890 | Coach4rb.Coach.partnerships | train | def partnerships(options={query: {}})
url = url_for_path(partnership_path)
url = append_query_params(url, options)
client.get(url, options) do |response|
a_hash = parse(response)
Resource::Page.from_coach a_hash, Resource::Partnership
end
end | ruby | {
"resource": ""
} |
q9891 | Aker::Form::Middleware.LogoutResponder.call | train | def call(env)
if env['REQUEST_METHOD'] == 'GET' && env['PATH_INFO'] == logout_path(env)
::Rack::Response.new(login_html(env, :logged_out => true)) do |resp|
resp['Content-Type'] = 'text/html'
end.finish
else
@app.call(env)
end
end | ruby | {
"resource": ""
} |
q9892 | RenderSuper.InstanceMethods.render_with_super | train | def render_with_super(*args, &block)
if args.first == :super
last_view = view_stack.last || {:view => instance_variable_get(:@virtual_path).split('/').last}
options = args[1] || {}
options[:locals] ||= {}
options[:locals].reverse_merge!(last_view[:locals] || {})
if last_view[:templates].nil?
last_view[:templates] = lookup_context.find_all_templates(last_view[:view], last_view[:partial], options[:locals].keys)
last_view[:templates].shift
end
options[:template] = last_view[:templates].shift
view_stack << last_view
result = render_without_super options
view_stack.pop
result
else
options = args.first
if options.is_a?(Hash)
current_view = {:view => options[:partial], :partial => true} if options[:partial]
current_view = {:view => options[:template], :partial => false} if current_view.nil? && options[:template]
current_view[:locals] = options[:locals] if !current_view.nil? && options[:locals]
view_stack << current_view if current_view.present?
end
result = render_without_super(*args, &block)
view_stack.pop if current_view.present?
result
end
end | ruby | {
"resource": ""
} |
q9893 | PhpFpmDocker.Pool.bind_mounts | train | def bind_mounts
ret_val = @launcher.bind_mounts
ret_val << File.dirname(@config['listen'])
ret_val += valid_web_paths
ret_val.uniq
end | ruby | {
"resource": ""
} |
q9894 | PhpFpmDocker.Pool.spawn_command | train | def spawn_command
[
@launcher.spawn_cmd_path,
'-s', @config['listen'],
'-U', listen_uid.to_s,
'-G', listen_gid.to_s,
'-M', '0660',
'-u', uid.to_s,
'-g', gid.to_s,
'-C', '4',
'-n'
]
end | ruby | {
"resource": ""
} |
q9895 | ActiveScraper.CachedRequest.to_uri | train | def to_uri
h = self.attributes.symbolize_keys.slice(:scheme, :host, :path)
h[:query] = self.unobfuscated_query || self.query
return Addressable::URI.new(h)
end | ruby | {
"resource": ""
} |
q9896 | Zaypay.PriceSetting.locale_string_for_ip | train | def locale_string_for_ip(ip)
get "/#{ip}/pay/#{price_setting_id}/locale_for_ip" do |data|
parts = data[:locale].split('-')
Zaypay::Util.stringify_locale_hash({:country => parts[1], :language => parts[0]})
end
end | ruby | {
"resource": ""
} |
q9897 | Zaypay.PriceSetting.country_has_been_configured_for_ip | train | def country_has_been_configured_for_ip(ip, options={})
# options can take a :amount key
locale = locale_for_ip(ip)
country = list_countries(options).select{ |c| c.has_value? locale[:country] }.first
{:country => country, :locale => locale} if country
end | ruby | {
"resource": ""
} |
q9898 | Zaypay.PriceSetting.list_payment_methods | train | def list_payment_methods(options={})
raise Zaypay::Error.new(:locale_not_set, "locale was not set for your price setting") if @locale.nil?
get "/#{options[:amount]}/#{@locale}/pay/#{price_setting_id}/payments/new" do |data|
Zaypay::Util.arrayify_if_not_an_array(data[:payment_methods][:payment_method])
end
end | ruby | {
"resource": ""
} |
q9899 | Zaypay.PriceSetting.create_payment | train | def create_payment(options={})
raise Zaypay::Error.new(:locale_not_set, "locale was not set for your price setting") if @locale.nil?
raise Zaypay::Error.new(:payment_method_id_not_set, "payment_method_id was not set for your price setting") if @payment_method_id.nil?
query = {:payment_method_id => payment_method_id}
query.merge!(options)
amount = query.delete(:amount)
post "/#{amount}/#{@locale}/pay/#{price_setting_id}/payments", query do |data|
payment_hash data
end
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.