_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q6300 | Mutter.Mutterer.unstyle | train | def unstyle msg
styles.map do |_,v|
v[:match]
end.flatten.inject(msg) do |m, tag|
m.gsub(tag, '')
end
end | ruby | {
"resource": ""
} |
q6301 | Mutter.Mutterer.write | train | def write str
self.class.stream.tap do |stream|
stream.write str
stream.flush
end ; nil
end | ruby | {
"resource": ""
} |
q6302 | Mutter.Mutterer.stylize | train | def stylize string, styles = []
[styles].flatten.inject(string) do |str, style|
style = style.to_sym
if ANSI[:transforms].include? style
esc str, *ANSI[:transforms][style]
elsif ANSI[:colors].include? style
esc str, ANSI[:colors][style], ANSI[:colors][:reset]
else
stylize(str, @styles[style][:style])
end
end
end | ruby | {
"resource": ""
} |
q6303 | Seiten.Page.parent_of? | train | def parent_of?(child)
page = self
if child
if page.id == child.parent_id
true
else
child.parent.nil? ? false : page.parent_of?(child.parent)
end
end
end | ruby | {
"resource": ""
} |
q6304 | Seiten.Page.active? | train | def active?(current_page)
if current_page
if id == current_page.id
true
elsif parent_of?(current_page)
true
else
false
end
end
end | ruby | {
"resource": ""
} |
q6305 | Sequel.LoadDataInfile.load_infile_sql | train | def load_infile_sql(path, columns, options={})
replacement = opts[:insert_ignore] ? :ignore : :replace
options = {:update => replacement}.merge(options)
LoadDataInfileExpression.new(path,
opts[:from].first,
columns,
options).
to_sql(db)
end | ruby | {
"resource": ""
} |
q6306 | Features.SessionHelpers.sign_in_as | train | def sign_in_as(group)
FactoryGirl.create(:user, umbcusername: 'test_user', group: group)
page.driver.browser.process_and_follow_redirects(:get, '/shibbolite/login', {}, {'umbcusername' => 'test_user'})
end | ruby | {
"resource": ""
} |
q6307 | Poster.Site.connect | train | def connect uri
Faraday.new(:url => "#{uri.scheme}://#{uri.host}") do |faraday|
faraday.request :multipart
faraday.request :url_encoded
# faraday.use FaradayMiddleware::FollowRedirects, limit: 3
faraday.use :cookie_jar
faraday.response :logger # log requests to STDOUT
faraday.adapter Faraday.default_adapter # make requests with Net::HTTP
end
end | ruby | {
"resource": ""
} |
q6308 | Coinstack.Printer.pretty_print_user_list | train | def pretty_print_user_list(list)
total = 0
data = []
# Header row
data.push('Asset', 'Total Value', 'Change % (Week)')
list.user_pairs.each do |user_pair|
data.push(user_pair.symbol)
data.push(user_pair.valuation.format)
data.push(user_pair.perchant_change_week.to_s)
total += user_pair.valuation
end
data.push('', '', '')
data.push('TOTAL:', total.format, '')
data.push('', '', '')
print_arrays(data, 3)
end | ruby | {
"resource": ""
} |
q6309 | Coinstack.Printer.print_arrays | train | def print_arrays(data, cols)
formatted_list = cli.list(data, :uneven_columns_across, cols)
cli.say(formatted_list)
end | ruby | {
"resource": ""
} |
q6310 | Coinstack.Printer.array_char_length | train | def array_char_length(input_array)
length = 0
input_array.each do |a|
length += a.to_s.length
end
length
end | ruby | {
"resource": ""
} |
q6311 | ContextFilters::Filters.Filters.select_filters | train | def select_filters(target, options)
found = filters_store.fetch(options, [])
if
Hash === options || options.nil?
then
options ||={}
options.merge!(:target => target)
found +=
# can not @filters.fetch(options, []) to allow filters provide custom ==()
filters_store.select do |filter_options, filters|
options == filter_options
end.map(&:last).flatten
end
found
end | ruby | {
"resource": ""
} |
q6312 | Parse.Object.save_eventually | train | def save_eventually
block = block_given? ? Proc.new : nil
_self = self
Parse::Stack::Async.run do
begin
result = true
_self.save!
rescue => e
result = false
puts "[SaveEventually] Failed for object #{_self.parse_class}##{_self.id}: #{e}"
ensure
block.call(result) if block
block = nil
_self = nil
end # begin
end # do
end | ruby | {
"resource": ""
} |
q6313 | Parse.Object.destroy_eventually | train | def destroy_eventually
block = block_given? ? Proc.new : nil
_self = self
Parse::Stack::Async.run do
begin
result = true
_self.destroy
rescue => e
result = false
puts "[DestroyEventually] Failed for object #{_self.parse_class}##{_self.id}: #{e}"
ensure
block.call(result) if block
block = nil
_self = nil
end # begin
end # do
end | ruby | {
"resource": ""
} |
q6314 | Myreplicator.MysqlExporter.export_table | train | def export_table export_obj
@export_obj = export_obj
ExportMetadata.record(:table => @export_obj.table_name,
:database => @export_obj.source_schema,
:export_to => load_to,
:export_id => @export_obj.id,
:filepath => filepath,
:store_in => @export_obj.s3_path,
:incremental_col => @export_obj.incremental_column) do |metadata|
prepare metadata
if (@export_obj.export_type? == :new && load_to == "mysql") || load_to == "mysql"
on_failure_state_trans(metadata, "new") # If failed, go back to new
on_export_success(metadata)
initial_export metadata
elsif @export_obj.export_type? == :incremental || load_to == "vertica"
on_failure_state_trans(metadata, "failed") # Set state trans on failure
on_export_success(metadata)
incremental_export_into_outfile metadata
end
end # metadata
end | ruby | {
"resource": ""
} |
q6315 | Myreplicator.MysqlExporter.initial_export | train | def initial_export metadata
metadata.export_type = "initial"
max_value = @export_obj.max_value if @export_obj.incremental_export?
cmd = initial_mysqldump_cmd
exporting_state_trans # mark exporting
puts "Exporting..."
result = execute_export(cmd, metadata)
check_result(result, 0)
@export_obj.update_max_val(max_value) if @export_obj.incremental_export?
end | ruby | {
"resource": ""
} |
q6316 | Myreplicator.MysqlExporter.incremental_export_into_outfile | train | def incremental_export_into_outfile metadata
unless @export_obj.is_running?
if @export_obj.export_type == "incremental"
max_value = @export_obj.max_value
metadata.export_type = "incremental"
@export_obj.update_max_val if @export_obj.max_incremental_value.blank?
end
if (@export_obj.export_type == "all" && @export_obj.export_to == "vertica")
metadata.export_type = "incremental"
end
options = {
:db => @export_obj.source_schema,
:source_schema => @export_obj.source_schema,
:table => @export_obj.table_name,
:filepath => filepath,
:destination_schema => @export_obj.destination_schema,
:enclosed_by => Myreplicator.configs[@export_obj.source_schema]["enclosed_by"],
:export_id => @export_obj.id
}
schema_status = Myreplicator::MysqlExporter.schema_changed?(options)
Kernel.p "===== schema_status ====="
Kernel.p schema_status
if schema_status[:changed] # && new?
metadata.export_type = "initial"
else
options[:incremental_col] = @export_obj.incremental_column
options[:incremental_col_type] = @export_obj.incremental_column_type
options[:export_type] = @export_obj.export_type
options[:incremental_val] = [@export_obj.destination_max_incremental_value, @export_obj.max_incremental_value].min
#options[:incremental_val] = @export_obj.max_incremental_value
end
#Kernel.p "===== incremental_export_into_outfile OPTIONS ====="
#Kernel.p options
cmd = SqlCommands.mysql_export_outfile(options)
#Kernel.p "===== incremental_export_into_outfile CMD ====="
#puts cmd
exporting_state_trans
puts "Exporting..."
result = execute_export(cmd, metadata)
check_result(result, 0)
if @export_obj.export_type == "incremental"
metadata.incremental_val = max_value # store max val in metadata
@export_obj.update_max_val(max_value) # update max value if export was successful
end
end
return false
end | ruby | {
"resource": ""
} |
q6317 | Myreplicator.MysqlExporter.check_result | train | def check_result result, size
unless result.nil?
raise Exceptions::ExportError.new("Export Error\n#{result}") if result.length > 0
end
end | ruby | {
"resource": ""
} |
q6318 | Myreplicator.MysqlExporter.zipfile | train | def zipfile metadata
cmd = "cd #{Myreplicator.configs[@export_obj.source_schema]["ssh_tmp_dir"]}; gzip #{@export_obj.filename}"
puts cmd
zip_result = metadata.ssh.exec!(cmd)
unless zip_result.nil?
raise Exceptions::ExportError.new("Export Error\n#{zip_result}") if zip_result.length > 0
end
metadata.zipped = true
return zip_result
end | ruby | {
"resource": ""
} |
q6319 | Thermometer.Configuration.load_time_ranges | train | def load_time_ranges
@time_ranges = ActiveSupport::HashWithIndifferentAccess.new
time_ranges = @config['time']
time_ranges.each do |t,r|
time_range = ActiveSupport::HashWithIndifferentAccess.new
src_ranges ||= r
src_ranges.map { |k,v| time_range[k.to_sym] = rangify_time_boundaries(v) }
@time_ranges[t.to_sym] = time_range
end
end | ruby | {
"resource": ""
} |
q6320 | Thermometer.Configuration.rangify_time_boundaries | train | def rangify_time_boundaries(src)
src.split("..").inject{ |s,e| s.split(".").inject{|n,m| n.to_i.send(m)}..e.split(".").inject{|n,m| n.to_i.send(m) }}
end | ruby | {
"resource": ""
} |
q6321 | APPI.HandlesResources.klass_for_type | train | def klass_for_type(type, singular=false)
type = type.singularize unless singular
type.classify.constantize
end | ruby | {
"resource": ""
} |
q6322 | APPI.HandlesResources.resource_params | train | def resource_params
attributes = find_in_params(:attributes).try(:permit, permitted_attributes) || {}
relationships = {}
# Build Relationships Data
relationships_in_payload = find_in_params(:relationships)
if relationships_in_payload
raw_relationships = relationships_in_payload.clone
raw_relationships.each_key do |key|
data = raw_relationships.delete(key)[:data]
if permitted_relationships.include?(key.to_sym) && data
if data.kind_of?(Array)
relationships["#{key.singularize}_ids"] = extract_ids data
else
relationships["#{key}_id"] = extract_id data
end
end
end
end
attributes.merge relationships
end | ruby | {
"resource": ""
} |
q6323 | Lightstreamer.StreamConnectionHeader.process_line | train | def process_line(line)
@lines << line
return process_success if @lines.first == 'OK'
return process_error if @lines.first == 'ERROR'
return process_end if @lines.first == 'END'
return process_sync_error if @lines.first == 'SYNC ERROR'
process_unrecognized
end | ruby | {
"resource": ""
} |
q6324 | Xpay.TransactionQuery.create_request | train | def create_request
raise AttributeMissing.new "(2500) TransactionReference or OrderReference need to be present." if (transaction_reference.nil? && order_reference.nil?)
raise AttributeMissing.new "(2500) SiteReference must be present." if (site_reference.nil? && (REXML::XPath.first(@request_xml, "//SiteReference").text.blank? rescue true))
REXML::XPath.first(@request_xml, "//Request").attributes["Type"] = "TRANSACTIONQUERY"
ops = REXML::XPath.first(@request_xml, "//Operation")
["TermUrl", "MerchantName", "Currency", "SettlementDay"].each { |e| ops.delete_element e }
(ops.elements["SiteReference"] || ops.add_element("SiteReference")).text = self.site_reference if self.site_reference
(ops.elements["TransactionReference"] || ops.add_element("TransactionReference")).text = self.transaction_reference if self.transaction_reference
order = REXML::XPath.first(@request_xml, "//Operation")
(order.elements["OrderReference"] || order.add_element("OrderReference")).text = self.order_reference if self.order_reference
root = @request_xml.root
(root.elements["Certificate"] || root.add_element("Certificate")).text = self.site_alias if self.site_alias
end | ruby | {
"resource": ""
} |
q6325 | Cashboard.TimeEntry.toggle_timer | train | def toggle_timer
options = self.class.merge_options()
options.merge!({:body => self.to_xml})
response = self.class.put(self.links[:toggle_timer], options)
# Raise special errors if not a success
self.class.check_status_code(response)
# Re-initialize ourselves with information from response
initialize(response.parsed_response)
if self.stopped_timer
stopped_timer = Cashboard::Struct.new(self.stopped_timer)
end
stopped_timer || nil
end | ruby | {
"resource": ""
} |
q6326 | Ducktrap.Error.dump | train | def dump(output)
output.name(self)
output.attribute(:input, input)
output.nest(:context, context)
end | ruby | {
"resource": ""
} |
q6327 | AgileZen.Stories.project_story | train | def project_story(project_id, story_id, options={})
response_body = nil
begin
response = connection.get do |req|
req.url "/api/v1/projects/#{project_id}/story/#{story_id}", options
end
response_body = response.body
rescue MultiJson::DecodeError => e
#p 'Unable to parse JSON.'
end
response_body
end | ruby | {
"resource": ""
} |
q6328 | DatabaseCachedAttribute.ClassMethods.database_cached_attribute | train | def database_cached_attribute(*attrs)
attrs.each do |attr|
define_method("invalidate_#{attr}") do |arg=nil| # default arg to allow before_blah callbacks
invalidate_cache attr.to_sym
end
define_method("only_#{attr}_changed?") do
only_change? attr.to_sym
end
define_method("cache_#{attr}") do
update_cache attr.to_sym
end
end
end | ruby | {
"resource": ""
} |
q6329 | NameableRecord.Name.to_s | train | def to_s( pattern='%l, %f' )
if pattern.is_a?( Symbol )
return conversational if pattern == :conversational
return sortable if pattern == :sortable
pattern = PREDEFINED_PATTERNS[pattern]
end
PATTERN_MAP.inject( pattern ) do |name, mapping|
name = name.gsub( mapping.first,
(send( mapping.last ) || '') )
end
end | ruby | {
"resource": ""
} |
q6330 | NameableRecord.Name.sortable | train | def sortable
[
last,
[
prefix,
first,
middle,
suffix
].reject( &:blank? ).
join( ' ' )
].reject( &:blank? ).
join( ', ' )
end | ruby | {
"resource": ""
} |
q6331 | Varnish.Client.vcl | train | def vcl(op, *params)
response = cmd("vcl.#{op}", *params)
case op
when :list
response.split("\n").map do |line|
a = line.split(/\s+/, 3)
[a[0], a[1].to_i, a[2]]
end
else
response
end
end | ruby | {
"resource": ""
} |
q6332 | Varnish.Client.purge | train | def purge(*args)
c = 'purge'
c << ".#{args.shift}" if [:url, :hash, :list].include?(args.first)
response = cmd(c, *args)
case c
when 'purge.list'
response.split("\n").map do |line|
a = line.split("\t")
[a[0].to_i, a[1]]
end
else
bool response
end
end | ruby | {
"resource": ""
} |
q6333 | Varnish.Client.stats | train | def stats
result = cmd("stats")
Hash[*result.split("\n").map { |line|
stat = line.strip!.split(/\s+/, 2)
[stat[1], stat[0].to_i]
}.flatten
]
end | ruby | {
"resource": ""
} |
q6334 | BarkestCore.PdfTableBuilder.last_column | train | def last_column
max = 0
@data.each do |row|
max = row.length if max < row.length
end
max - 1
end | ruby | {
"resource": ""
} |
q6335 | BarkestCore.PdfTableBuilder.build_column | train | def build_column(start_column = nil)
if block_given?
raise StandardError.new('build_column block called within row block') if @in_row
raise StandardError.new('build_column called without valid argument') unless start_column.is_a?(Numeric)
backup_col_start = @col_start
backup_col_offset = @col_offset
backup_row_offset = @row_offset
@col_start = start_column.to_i
@col_offset = @col_start
@row_offset = 0
yield
@col_start = backup_col_start
@col_offset = backup_col_offset
@row_offset = backup_row_offset
end
@col_start
end | ruby | {
"resource": ""
} |
q6336 | BarkestCore.PdfTableBuilder.row | train | def row(options = {}, &block)
raise StandardError.new('row called within row block') if @in_row
@in_row = true
@col_offset = @col_start
options = change_row(options || {})
@row_cell_options = @base_cell_options.merge(options)
fill_cells(@row_offset, @col_offset)
# skip placeholders when starting a new row.
if @data[@row_offset]
while @data[@row_offset][@col_offset] == :span_placeholder
@col_offset += 1
end
end
yield if block_given?
@in_row = false
@row_offset += 1
@row_cell_options = nil
end | ruby | {
"resource": ""
} |
q6337 | BarkestCore.PdfTableBuilder.subtable | train | def subtable(cell_options = {}, options = {}, &block)
raise StandardError.new('subtable called outside of row block') unless @in_row
cell cell_options || {} do
PdfTableBuilder.new(@doc, options || {}, &block).to_table
end
end | ruby | {
"resource": ""
} |
q6338 | BarkestCore.PdfTableBuilder.cells | train | def cells(options = {}, &block)
cell_regex = /^cell_([0-9]+)_/
options ||= { }
result = block_given? ? yield : (options[:values] || [''])
cell_options = result.map { {} }
common_options = {}
options.each do |k,v|
# if the option starts with 'cell_#_' then apply it accordingly.
if (m = cell_regex.match(k.to_s))
k = k.to_s[m[0].length..-1].to_sym
cell_options[m[1].to_i - 1][k] = v
# the 'column' option applies only to the first cell.
elsif k == :column
cell_options[0][k] = v
# everything else applies to all cells, unless overridden explicitly.
elsif k != :values
common_options[k] = v
end
end
cell_options.each_with_index do |opt,idx|
cell common_options.merge(opt).merge( { value: result[idx] } )
end
end | ruby | {
"resource": ""
} |
q6339 | BarkestCore.PdfTableBuilder.cell | train | def cell(options = {}, &block)
raise StandardError.new('cell called outside of row block') unless @in_row
options = @row_cell_options.merge(options || {})
options = change_col(options)
result = block_given? ? yield : (options[:value] || '')
options.except!(:value)
set_cell(result, nil, nil, options)
end | ruby | {
"resource": ""
} |
q6340 | BarkestCore.PdfTableBuilder.fix_row_widths | train | def fix_row_widths
fill_cells(@row_offset - 1, 0)
max = 0
@data.each_with_index do |row|
max = row.length unless max >= row.length
end
@data.each_with_index do |row,idx|
if row.length < max
row = row + [ @base_cell_options.merge({content: ''}) ] * (max - row.length)
@data[idx] = row
end
end
end | ruby | {
"resource": ""
} |
q6341 | TicTacToe.Board.empty_positions | train | def empty_positions(&block)
positions = []
each_position do |row, column|
next if get_cell(row, column)
yield(row, column) if block_given?
positions << [row, column]
end
positions
end | ruby | {
"resource": ""
} |
q6342 | TicTacToe.Board.solved? | train | def solved?
letter = won_across?
return letter if letter
letter = won_up_and_down?
return letter if letter
letter = won_diagonally?
return letter if letter
false
end | ruby | {
"resource": ""
} |
q6343 | Buzztools.Config.read | train | def read(aSource,&aBlock)
default_values.each do |k,v|
done = false
if block_given? && ((newv = yield(k,v,aSource && aSource[k])) != nil)
self[k] = newv
done = true
end
copy_item(aSource,k) if !done && aSource && !aSource[k].nil?
end
self
end | ruby | {
"resource": ""
} |
q6344 | Buzztools.Config.reset | train | def reset
self.clear
me = self
@default_values.each {|n,v| me[n] = v.is_a?(Class) ? nil : v}
end | ruby | {
"resource": ""
} |
q6345 | Snapshotify.Writer.ensure_directory | train | def ensure_directory
dir = File.dirname(full_filename)
unless File.directory?(dir)
FileUtils.mkdir_p(dir)
end
end | ruby | {
"resource": ""
} |
q6346 | Snapshotify.Writer.filename | train | def filename
# Based on the path of the file
path = resource.url.uri.path
# It's either an index.html file
# if the path ends with a slash
if path.end_with?('/')
return path + 'index.html'
# Or it's also an index.html if it ends
# without a slah yet is not a file with an
# extension
elsif !path.split('/').last.include?(".")
return path + '/index.html'
end
# Alternative, the filename is the path as described
path
end | ruby | {
"resource": ""
} |
q6347 | Jinx.Hasher.assoc_values | train | def assoc_values(*others)
all_keys = keys
others.each { |hash| all_keys.concat(hash.keys) }
all_keys.to_compact_hash do |k|
others.map { |other| other[k] }.unshift(self[k])
end
end | ruby | {
"resource": ""
} |
q6348 | Jinx.Hasher.enum_keys_with_value | train | def enum_keys_with_value(target_value=nil, &filter) # :yields: value
return enum_keys_with_value { |v| v == target_value } if target_value
filter_on_value(&filter).keys
end | ruby | {
"resource": ""
} |
q6349 | Jinx.Hasher.copy_recursive | train | def copy_recursive
copy = Hash.new
keys.each do |k|
value = self[k]
copy[k] = Hash === value ? value.copy_recursive : value
end
copy
end | ruby | {
"resource": ""
} |
q6350 | RDSBackup.Email.body | train | def body
msg = "Hello.\n\n"
if job.status == 200
msg += "Your backup of database #{job.rds_id} is complete.\n"+
(job.files.empty? ? "" : "Output is at #{job.files.first[:url]}\n")
else
msg += "Your backup is incomplete. (job ID #{job.backup_id})\n"
end
msg += "Job status: #{job.message}"
end | ruby | {
"resource": ""
} |
q6351 | BootstrapsBootstraps.BootstrapFormHelper.bootstrapped_form | train | def bootstrapped_form object, options={}, &block
options[:builder] = BootstrapFormBuilder
form_for object, options, &block
end | ruby | {
"resource": ""
} |
q6352 | Maturate.InstanceMethods.api_version | train | def api_version
version = params[:api_version]
return current_api_version if version == 'current'
api_versions.include?(version) ? version : current_api_version
end | ruby | {
"resource": ""
} |
q6353 | TrackableTasks.Base.allowable_log_level | train | def allowable_log_level(log_level)
log_level = "" if log_level.nil?
log_level = log_level.to_sym unless log_level.is_a?(Symbol)
if !@log_levels.include?(log_level)
log_level = :notice
end
return log_level
end | ruby | {
"resource": ""
} |
q6354 | TrackableTasks.Base.run_task | train | def run_task
begin
run
rescue Exception => e
@task_run.add_error_text(e.class.name + ": " + e.message)
@task_run.add_error_text(e.backtrace.inspect)
@task_run.success = false
end
finally
@task_run.end_time = Time.now
@task_run.save
end | ruby | {
"resource": ""
} |
q6355 | Mobilize.Runner.force_due | train | def force_due
r = self
r.update_attributes(:started_at=>(Time.now.utc - Jobtracker.runner_read_freq - 1.second))
end | ruby | {
"resource": ""
} |
q6356 | TriglavClient.UsersApi.create_user | train | def create_user(user, opts = {})
data, _status_code, _headers = create_user_with_http_info(user, opts)
return data
end | ruby | {
"resource": ""
} |
q6357 | TriglavClient.UsersApi.get_user | train | def get_user(id, opts = {})
data, _status_code, _headers = get_user_with_http_info(id, opts)
return data
end | ruby | {
"resource": ""
} |
q6358 | TriglavClient.UsersApi.update_user | train | def update_user(id, user, opts = {})
data, _status_code, _headers = update_user_with_http_info(id, user, opts)
return data
end | ruby | {
"resource": ""
} |
q6359 | Dater.Resolver.time_for_period | train | def time_for_period(string=nil)
@last_date = case string
when /today/,/now/
now
when /tomorrow/
tomorrow_time
when /yesterday/
yesterday_time
when /sunday/, /monday/, /tuesday/, /wednesday/, /thursday/, /friday/, /saturday/
time_for_weekday(string)
when /next/
now + period_of_time_from_string(string.gsub("next","1"))
when /last/
now - period_of_time_from_string(string.gsub("last","1"))
when /\d[\sa-zA-Z]+\sbefore/
@last_date ||= now
@last_date -= period_of_time_from_string(string)
when /\d[\sa-zA-Z]+\sago/
@last_date ||= now
now - period_of_time_from_string(string)
when /\d[\sa-zA-Z]+\slater/
@last_date ||= now
@last_date += period_of_time_from_string(string)
when /in/,/\d\sminutes?/,/\d\shours?/,/\d\sdays?/, /\d\smonths?/, /\d\sweeks?/, /\d\syears?/
now + period_of_time_from_string(string)
when /\d+.\d+.\d+/
time_from_date(string)
when /rand/,/future/
now + rand(100_000_000)
when /past/
now - rand(100_000_000)
end
return @last_date
end | ruby | {
"resource": ""
} |
q6360 | Dater.Resolver.is_required_day? | train | def is_required_day?(time, day)
day_to_ask = "#{day}?"
result = eval("time.#{day_to_ask}") if time.respond_to? day_to_ask.to_sym
return result
end | ruby | {
"resource": ""
} |
q6361 | Dater.Resolver.multiply_by | train | def multiply_by(string)
return minute_mult(string) || hour_mult(string) || day_mult(string) || week_mult(string) || month_mult(string) || year_mult(string) || 1
end | ruby | {
"resource": ""
} |
q6362 | Dater.Resolver.time_from_date | train | def time_from_date(date)
numbers=date.scan(/\d+/).map!{|i| i.to_i}
day=numbers[2-numbers.index(numbers.max)]
Date.new(numbers.max,numbers[1],day).to_time
end | ruby | {
"resource": ""
} |
q6363 | Dater.Resolver.method_missing | train | def method_missing(meth)
self.class.send :define_method, meth do
string = meth.to_s.gsub("_"," ")
self.for("for('#{string}')")
end
begin
self.send(meth.to_s)
rescue
raise "Method does not exists (#{meth})."
end
end | ruby | {
"resource": ""
} |
q6364 | Incline.ActionSecurity.update_flags | train | def update_flags
self.allow_anon = self.require_anon = self.require_admin = self.unknown_controller = self.non_standard = false
self.unknown_controller = true
klass = ::Incline.get_controller_class(controller_name)
if klass
self.unknown_controller = false
if klass.require_admin_for?(action_name)
self.require_admin = true
elsif klass.require_anon_for?(action_name)
self.require_anon = true
elsif klass.allow_anon_for?(action_name)
self.allow_anon = true
end
# if the authentication methods are overridden, set a flag to alert the user that standard security may not be honored.
unless klass.instance_method(:valid_user?).owner == Incline::Extensions::ActionControllerBase &&
klass.instance_method(:authorize!).owner == Incline::Extensions::ActionControllerBase
self.non_standard = true
end
end
end | ruby | {
"resource": ""
} |
q6365 | Incline.ActionSecurity.permitted | train | def permitted(refresh = false)
@permitted = nil if refresh
@permitted ||=
if require_admin?
'Administrators Only'
elsif require_anon?
'Anonymous Only'
elsif allow_anon?
'Everyone'
elsif groups.any?
names = groups.pluck(:name).map{|v| "\"#{v}\""}
'Members of ' +
if names.count == 1
names.first
elsif names.count == 2
names.join(' or ')
else
names[0...-1].join(', ') + ', or ' + names.last
end
else
'All Users'
end +
if non_standard
' (Non-Standard)'
else
''
end
end | ruby | {
"resource": ""
} |
q6366 | Incline.ActionSecurity.group_ids= | train | def group_ids=(values)
values ||= []
values = [ values ] unless values.is_a?(::Array)
values = values.reject{|v| v.blank?}.map{|v| v.to_i}
self.groups = Incline::AccessGroup.where(id: values).to_a
end | ruby | {
"resource": ""
} |
q6367 | TheViking.Akismet.check_comment | train | def check_comment(options = {})
return false if invalid_options?
message = call_akismet('comment-check', options)
{ :spam => !self.class.valid_responses.include?(message), :message => message }
end | ruby | {
"resource": ""
} |
q6368 | TheViking.Akismet.call_akismet | train | def call_akismet(akismet_function, options = {})
http_post(
Net::HTTP.new([self.options[:api_key], self.class.host].join('.'), options[:proxy_host], options[:proxy_port]),
akismet_function,
options.update(:blog => self.options[:blog]).to_query
)
end | ruby | {
"resource": ""
} |
q6369 | Evvnt.Actions.define_action | train | def define_action(action, &block)
action = action.to_sym
defined_actions << action unless defined_actions.include?(action)
if action.in?(Evvnt::ClassTemplateMethods.instance_methods)
define_class_action(action, &block)
end
if action.in?(Evvnt::InstanceTemplateMethods.instance_methods)
define_instance_action(action, &block)
end
action
end | ruby | {
"resource": ""
} |
q6370 | BROpenData.ParentService.get_request | train | def get_request(hash=true)
resp = RestClient.get get_url
hash ? Hash.from_xml(resp).it_keys_to_sym : resp
end | ruby | {
"resource": ""
} |
q6371 | EcomDev::ChefSpec::Helpers.Platform.filter | train | def filter(*conditions)
latest = !conditions.select {|item| item === true }.empty?
filters = translate_conditions(conditions)
items = list(latest)
unless filters.empty?
items = items.select do |item|
!filters.select {|filter| match_filter(filter, item) }.empty?
end
end
items
end | ruby | {
"resource": ""
} |
q6372 | EcomDev::ChefSpec::Helpers.Platform.is_version | train | def is_version(string)
return false if string === false || string === true || string.nil?
string.to_s.match(/^\d+[\d\.a-zA-Z\-_~]*/)
end | ruby | {
"resource": ""
} |
q6373 | EcomDev::ChefSpec::Helpers.Platform.is_os | train | def is_os(string)
return false if string === false || string === true || string.nil?
@os.key?(string.to_sym)
end | ruby | {
"resource": ""
} |
q6374 | EcomDev::ChefSpec::Helpers.Platform.match_filter | train | def match_filter(filter, item)
filter.each_pair do |key, value|
unless item.key?(key)
return false
end
unless value.is_a?(Array)
return false if value != item[key]
else
return true if value.empty?
return false unless value.include?(item[key])
end
end
true
end | ruby | {
"resource": ""
} |
q6375 | EcomDev::ChefSpec::Helpers.Platform.list | train | def list(latest = false)
result = []
@os.map do |os, versions|
unless latest
versions.each { |version| result << {os: os, version: version}}
else
result << {os: os, version: versions.last} if versions.length > 0
end
end
result
end | ruby | {
"resource": ""
} |
q6376 | StalkClimber.Connection.fetch_and_cache_job | train | def fetch_and_cache_job(job_id)
job = fetch_job(job_id)
self.cached_jobs[job_id] = job unless job.nil?
@min_climbed_job_id = job_id if job_id < @min_climbed_job_id
@max_climbed_job_id = job_id if job_id > @max_climbed_job_id
return job
end | ruby | {
"resource": ""
} |
q6377 | Mycroft.Messages.connect_to_mycroft | train | def connect_to_mycroft
if ARGV.include?("--no-tls")
@client = TCPSocket.open(@host, @port)
else
socket = TCPSocket.new(@host, @port)
ssl_context = OpenSSL::SSL::SSLContext.new
ssl_context.cert = OpenSSL::X509::Certificate.new(File.open(@cert))
ssl_context.key = OpenSSL::PKey::RSA.new(File.open(@key))
@client = OpenSSL::SSL::SSLSocket.new(socket, ssl_context)
begin
@client.connect
rescue
end
end
end | ruby | {
"resource": ""
} |
q6378 | Mycroft.Messages.send_manifest | train | def send_manifest
begin
manifest = JSON.parse(File.read(@manifest))
manifest['instanceId'] = "#{Socket.gethostname}_#{SecureRandom.uuid}" if @generate_instance_ids
@instance_id = manifest['instanceId']
rescue
end
send_message('APP_MANIFEST', manifest)
end | ruby | {
"resource": ""
} |
q6379 | Mycroft.Messages.query | train | def query(capability, action, data, priority = 30, instance_id = nil)
query_message = {
id: SecureRandom.uuid,
capability: capability,
action: action,
data: data,
priority: priority,
instanceId: []
}
query_message[:instanceId] = instance_id unless instance_id.nil?
send_message('MSG_QUERY', query_message)
end | ruby | {
"resource": ""
} |
q6380 | Mycroft.Messages.broadcast | train | def broadcast(content)
message = {
id: SecureRandom.uuid,
content: content
}
send_message('MSG_BROADCAST', message)
end | ruby | {
"resource": ""
} |
q6381 | LitePage.PageInitializers.visit | train | def visit(page_class, query_params = {}, browser = @browser)
page = page_class.new(browser)
url = query_params.empty? ? page.page_url : page.page_url(query_params)
browser.goto(url)
yield page if block_given?
page
end | ruby | {
"resource": ""
} |
q6382 | LitePage.PageInitializers.on | train | def on(page_class, browser = @browser)
page = page_class.new(browser)
yield page if block_given?
page
end | ruby | {
"resource": ""
} |
q6383 | Konfig.Store.load_directory | train | def load_directory(path)
unless File.directory?(path)
raise "Konfig couldn't load because it was unable to access #{ path }. Please make sure the directory exists and has the correct permissions."
end
Dir[File.join(path, "*.yml")].each { |f| load_file(f) }
end | ruby | {
"resource": ""
} |
q6384 | Konfig.Store.load_file | train | def load_file(path)
d = YAML.load_file(path)
if d.is_a?(Hash)
d = HashWithIndifferentAccess.new(d)
e = Evaluator.new(d)
d = process(d, e)
end
@data[File.basename(path, ".yml").downcase] = d
end | ruby | {
"resource": ""
} |
q6385 | Bebox.ProfileCommands.profile_new_command | train | def profile_new_command(profile_command)
profile_command.desc _('cli.profile.new.desc')
profile_command.arg_name "[name]"
profile_command.command :new do |profile_new_command|
profile_new_command.flag :p, :arg_name => 'path', :desc => _('cli.profile.new.path_flag_desc')
profile_new_command.action do |global_options,options,args|
path = options[:p] || ''
help_now!(error(_('cli.profile.new.name_arg_missing'))) if args.count == 0
Bebox::ProfileWizard.new.create_new_profile(project_root, args.first, path)
end
end
end | ruby | {
"resource": ""
} |
q6386 | Bebox.ProfileCommands.profile_remove_command | train | def profile_remove_command(profile_command)
profile_command.desc _('cli.profile.remove.desc')
profile_command.command :remove do |profile_remove_command|
profile_remove_command.action do |global_options,options,args|
Bebox::ProfileWizard.new.remove_profile(project_root)
end
end
end | ruby | {
"resource": ""
} |
q6387 | Bebox.ProfileCommands.profile_list_command | train | def profile_list_command(profile_command)
profile_command.desc _('cli.profile.list.desc')
profile_command.command :list do |profile_list_command|
profile_list_command.action do |global_options,options,args|
profiles = Bebox::ProfileWizard.new.list_profiles(project_root)
title _('cli.profile.list.current_profiles')
profiles.map{|profile| msg(profile)}
warn(_('cli.profile.list.no_profiles')) if profiles.empty?
linebreak
end
end
end | ruby | {
"resource": ""
} |
q6388 | ARK.TextBuilder.wrap | train | def wrap(width: 78, indent: 0, indent_after: false, segments: false)
if segments
text = Text.wrap_segments(@lines[@line], width: width, indent: indent, indent_after: indent_after)
else
text = Text.wrap(@lines[@line], width: width, indent: indent, indent_after: indent_after)
end
@lines.delete_at(@line)
@line -= 1
text.split("\n").each {|line| self.next(line) }
return self
end | ruby | {
"resource": ""
} |
q6389 | Shopsense.API.search | train | def search( search_string = nil, index = 0, num_results = 10)
raise "no search string provieded!" if( search_string === nil)
fts = "fts=" + search_string.split().join( '+').to_s
min = "min=" + index.to_s
count = "count=" + num_results.to_s
args = [fts, min, count].join( '&')
return call_api( __method__, args)
end | ruby | {
"resource": ""
} |
q6390 | Shopsense.API.get_look | train | def get_look( look_id = nil)
raise "no look_id provieded!" if( look_id === nil)
look = "look=" + look_id.to_s
return call_api( __method__, look)
end | ruby | {
"resource": ""
} |
q6391 | Shopsense.API.get_stylebook | train | def get_stylebook( user_name = nil, index = 0, num_results = 10)
raise "no user_name provieded!" if( user_name === nil)
handle = "handle=" + user_name.to_s
min = "min=" + index.to_s
count = "count=" + num_results.to_s
args = [handle, min, count].join( '&')
return call_api( __method__, args)
end | ruby | {
"resource": ""
} |
q6392 | Shopsense.API.get_looks | train | def get_looks( look_type = nil, index = 0, num_results = 10)
raise "invalid filter type must be one of the following: #{self.look_types}" if( !self.look_types.include?( look_type))
type = "type=" + look_type.to_s
min = "min=" + index.to_s
count = "count=" + num_results.to_s
args = [type, min, count].join( '&')
return call_api( __method__, args)
end | ruby | {
"resource": ""
} |
q6393 | Shopsense.API.get_trends | train | def get_trends( category = "", products = 0)
cat = "cat=" + category.to_s
products = "products=" + products.to_s
args = [cat, products].join( '&')
return call_api( __method__, args)
end | ruby | {
"resource": ""
} |
q6394 | Shopsense.API.call_api | train | def call_api( method, args = nil)
method_url = self.api_url + self.send( "#{method}_path")
pid = "pid=" + self.partner_id
format = "format=" + self.format
site = "site=" + self.site
if( args === nil) then
uri = URI.parse( method_url.to_s + [pid, format, site].join('&').to_s)
else
uri = URI.parse( method_url.to_s + [pid, format, site, args].join('&').to_s)
end
return Net::HTTP.get( uri)
end | ruby | {
"resource": ""
} |
q6395 | Numerals.Format::Symbols::Digits.digits_text | train | def digits_text(digit_values, options={})
insignificant_digits = options[:insignificant_digits] || 0
num_digits = digit_values.reduce(0) { |num, digit|
digit.nil? ? num : num + 1
}
num_digits -= insignificant_digits
digit_values.map { |d|
if d.nil?
options[:separator]
else
num_digits -= 1
if num_digits >= 0
digit_symbol(d, options)
else
options[:insignificant_symbol]
end
end
}.join
end | ruby | {
"resource": ""
} |
q6396 | Woro.TaskList.width | train | def width
@width ||= list.map { |t| t.name_with_args ? t.name_with_args.length : 0 }.max || 10
end | ruby | {
"resource": ""
} |
q6397 | Woro.TaskList.print | train | def print
list.each do |entry|
entry.headline ? print_headline(entry) : print_task_description(entry)
end
end | ruby | {
"resource": ""
} |
q6398 | Garcon.Event.wait | train | def wait(timeout = nil)
@mutex.lock
unless @set
remaining = Condition::Result.new(timeout)
while !@set && remaining.can_wait?
remaining = @condition.wait(@mutex, remaining.remaining_time)
end
end
@set
ensure
@mutex.unlock
end | ruby | {
"resource": ""
} |
q6399 | Sumac.RemoteObject.method_missing | train | def method_missing(method_name, *arguments, &block) # TODO: blocks not working yet
arguments << block.to_lambda if block_given?
reqeust = {object: self, method: method_name.to_s, arguments: arguments}
begin
return_value = @object_request_broker.call(reqeust)
rescue ClosedObjectRequestBrokerError
raise StaleObjectError
end
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.