_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q6700
|
Kajiki.Runner.stop
|
train
|
def stop(&block)
block.call('stop') unless block.nil?
pid = read_pid
fail 'No valid PID file.' unless pid && pid > 0
Process.kill('TERM', pid)
delete_pid
puts 'Process terminated.'
end
|
ruby
|
{
"resource": ""
}
|
q6701
|
RForce.SoapPullable.local
|
train
|
def local(tag)
first, second = tag.split ':'
return first if second.nil?
@namespaces.include?(first) ? second : tag
end
|
ruby
|
{
"resource": ""
}
|
q6702
|
Sp2db.BaseTable.to_csv
|
train
|
def to_csv data
attributes = data.first&.keys || []
CSV.generate(headers: true) do |csv|
csv << attributes
data.each do |row|
csv << attributes.map do |att|
row[att]
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6703
|
Sp2db.BaseTable.standardize_cell_val
|
train
|
def standardize_cell_val v
v = ((float = Float(v)) && (float % 1.0 == 0) ? float.to_i : float) rescue v
v = v.force_encoding("UTF-8") if v.is_a?(String)
v
end
|
ruby
|
{
"resource": ""
}
|
q6704
|
Sp2db.BaseTable.raw_filter
|
train
|
def raw_filter raw_data, opts={}
raw_header = raw_data[header_row].map.with_index do |h, idx|
is_valid = valid_header?(h)
{
idx: idx,
is_remove: !is_valid,
is_required: require_header?(h),
name: is_valid && h.gsub(/\s*/, '').gsub(/!/, '').downcase
}
end
rows = raw_data[(header_row + 1)..-1].map.with_index do |raw, rdx|
row = {}.with_indifferent_access
raw_header.each do |h|
val = raw[h[:idx]]
next if h[:is_remove]
if h[:is_required] && val.blank?
row = {}
break
end
row[h[:name]] = standardize_cell_val val
end
next if row.values.all?(&:blank?)
row[:id] = rdx + 1 if find_columns.include?(:id) && row[:id].blank?
row
end.compact
.reject(&:blank?)
rows = rows.select do |row|
if required_columns.present?
required_columns.all? {|col| row[col].present? }
else
true
end
end
rows
end
|
ruby
|
{
"resource": ""
}
|
q6705
|
FriendlyAttributes.ClassMethods.friendly_details
|
train
|
def friendly_details(*args, &block)
klass = args.shift
options = args.extract_options!
attributes = args.extract_options!
if attributes.empty?
attributes = options
options = {}
end
DetailsDelegator.new(klass, self, attributes, options, &block).tap do |dd|
dd.setup_delegated_attributes
dd.instance_eval(&block) if block_given?
end
end
|
ruby
|
{
"resource": ""
}
|
q6706
|
Bebox.Cli.inside_project?
|
train
|
def inside_project?
project_found = false
cwd = Pathname(Dir.pwd)
home_directory = File.expand_path('~')
cwd.ascend do |current_path|
project_found = File.file?("#{current_path.to_s}/.bebox")
self.project_root = current_path.to_s if project_found
break if project_found || (current_path.to_s == home_directory)
end
project_found
end
|
ruby
|
{
"resource": ""
}
|
q6707
|
BibSonomy.API.get_post
|
train
|
def get_post(user_name, intra_hash)
response = @conn.get @url_post.expand({
:user_name => user_name,
:intra_hash => intra_hash,
:format => @format
})
if @parse
attributes = JSON.parse(response.body)
return Post.new(attributes["post"])
end
return response.body
end
|
ruby
|
{
"resource": ""
}
|
q6708
|
BibSonomy.API.get_posts_for_user
|
train
|
def get_posts_for_user(user_name, resource_type, tags = nil, start = 0, endc = $MAX_POSTS_PER_REQUEST)
return get_posts("user", user_name, resource_type, tags, start, endc)
end
|
ruby
|
{
"resource": ""
}
|
q6709
|
BibSonomy.API.get_posts_for_group
|
train
|
def get_posts_for_group(group_name, resource_type, tags = nil, start = 0, endc = $MAX_POSTS_PER_REQUEST)
return get_posts("group", group_name, resource_type, tags, start, endc)
end
|
ruby
|
{
"resource": ""
}
|
q6710
|
BibSonomy.API.get_posts
|
train
|
def get_posts(grouping, name, resource_type, tags = nil, start = 0, endc = $MAX_POSTS_PER_REQUEST)
url = @url_posts.partial_expand({
:format => @format,
:resourcetype => get_resource_type(resource_type),
:start => start,
:end => endc
})
# decide what to get
if grouping == "user"
url = url.partial_expand({:user => name})
elsif grouping == "group"
url = url.partial_expand({:group => name})
end
# add tags, if requested
if tags != nil
url = url.partial_expand({:tags => tags.join(" ")})
end
response = @conn.get url.expand({})
if @parse
posts = JSON.parse(response.body)["posts"]["post"]
return posts.map { |attributes| Post.new(attributes) }
end
return response.body
end
|
ruby
|
{
"resource": ""
}
|
q6711
|
BibSonomy.API.get_document
|
train
|
def get_document(user_name, intra_hash, file_name)
response = @conn.get get_document_href(user_name, intra_hash, file_name)
if response.status == 200
return [response.body, response.headers['content-type']]
end
return nil, nil
end
|
ruby
|
{
"resource": ""
}
|
q6712
|
BibSonomy.API.get_document_preview
|
train
|
def get_document_preview(user_name, intra_hash, file_name, size)
response = @conn.get get_document_href(user_name, intra_hash, file_name), { :preview => size }
if response.status == 200
return [response.body, 'image/jpeg']
end
return nil, nil
end
|
ruby
|
{
"resource": ""
}
|
q6713
|
BibSonomy.API.get_resource_type
|
train
|
def get_resource_type(resource_type)
if $resource_types_bookmark.include? resource_type.downcase()
return "bookmark"
end
if $resource_types_bibtex.include? resource_type.downcase()
return "bibtex"
end
raise ArgumentError.new("Unknown resource type: #{resource_type}. Supported resource types are ")
end
|
ruby
|
{
"resource": ""
}
|
q6714
|
TableRenamable.DeprecatedTable.get_current_table_name
|
train
|
def get_current_table_name
[self.old_name, self.new_name].each do |name|
return name.to_s if self.table_exists?(name)
end
# raise exception if we don't have a valid table
self.raise_no_table_error
end
|
ruby
|
{
"resource": ""
}
|
q6715
|
TableRenamable.DeprecatedTable.set_table_name
|
train
|
def set_table_name
[self.old_name, self.new_name].each do |name|
# make sure this table exists
if self.table_exists?(name)
# return true if we are already using this table
return true if self.klass.table_name == name.to_s
# otherwise we can change the table name
self.klass.table_name = name
return true
end
end
self.raise_no_table_error
end
|
ruby
|
{
"resource": ""
}
|
q6716
|
PhilipsHue.Light.set
|
train
|
def set(options)
json_body = options.to_json
request_uri = "#{base_request_uri}/state"
HTTParty.put(request_uri, :body => json_body)
end
|
ruby
|
{
"resource": ""
}
|
q6717
|
PhilipsHue.Light.rename
|
train
|
def rename(new_name)
json_body = { :name => new_name }.to_json
HTTParty.put(base_request_uri, :body => json_body)
@name = new_name
end
|
ruby
|
{
"resource": ""
}
|
q6718
|
PhilipsHue.Light.to_s
|
train
|
def to_s
pretty_name = @name.to_s.split(/_/).map(&:capitalize).join(" ")
on_or_off = on? ? "on" : "off"
reachable = reachable? ? "reachable" : "unreachable"
"#{pretty_name} is #{on_or_off} and #{reachable}"
end
|
ruby
|
{
"resource": ""
}
|
q6719
|
Roroacms.Admin::PagesController.edit
|
train
|
def edit
@edit = true
@record = Post.find(params[:id])
# add breadcrumb and set title
add_breadcrumb I18n.t("controllers.admin.pages.edit.breadcrumb")
set_title(I18n.t("controllers.admin.pages.edit.title", post_title: @record.post_title))
@action = 'update'
end
|
ruby
|
{
"resource": ""
}
|
q6720
|
Roroacms.Admin::PagesController.destroy
|
train
|
def destroy
Post.disable_post(params[:id])
respond_to do |format|
format.html { redirect_to admin_pages_path, notice: I18n.t("controllers.admin.pages.destroy.flash.success") }
end
end
|
ruby
|
{
"resource": ""
}
|
q6721
|
NillyVanilly.Inspect.results
|
train
|
def results
ActiveRecord::Base.connection.tables.each do |table|
model = table.classify.constantize rescue next
model.columns.each do |column|
present = model.respond_to?(:nillify_attributes) && model.nillify_attributes.include?(column.name.to_sym)
@results << [present, model.name, column.name] if include_column(column)
end
end
@results
end
|
ruby
|
{
"resource": ""
}
|
q6722
|
Chap.Config.load_json
|
train
|
def load_json(key)
path = if yaml[key] =~ %r{^/} # root path given
yaml[key]
else # relative path
dirname = File.dirname(options[:config])
"#{dirname}/#{yaml[key]}"
end
if File.exist?(path)
Mash.from_hash(JSON.parse(IO.read(path)))
else
puts "ERROR: #{key}.json config does not exist at: #{path}"
exit 1
end
end
|
ruby
|
{
"resource": ""
}
|
q6723
|
Mimi.Config.load
|
train
|
def load(manifest_filename, opts = {})
opts = self.class.module_options.deep_merge(opts)
manifest_filename = Pathname.new(manifest_filename).expand_path
load_manifest(manifest_filename, opts)
load_params(opts)
if opts[:raise_on_missing_params] && !missing_params.empty?
raise "Missing required configurable parameters: #{missing_params.join(', ')}"
end
self
end
|
ruby
|
{
"resource": ""
}
|
q6724
|
Mimi.Config.missing_params
|
train
|
def missing_params
required_params = manifest.select { |p| p[:required] }.map { |p| p[:name] }
required_params - @params.keys
end
|
ruby
|
{
"resource": ""
}
|
q6725
|
Mimi.Config.manifest
|
train
|
def manifest
@manifest.map do |k, v|
{
name: k,
desc: v[:desc],
required: !v.key?(:default),
const: v[:const],
default: v[:default]
}
end
end
|
ruby
|
{
"resource": ""
}
|
q6726
|
Mimi.Config.load_params
|
train
|
def load_params(opts = {})
Dotenv.load if opts[:use_dotenv]
manifest.each do |p|
env_name = p[:name].to_s
if p[:const]
# const
@params[p[:name]] = p[:default]
elsif p[:required]
# required configurable
@params[p[:name]] = ENV[env_name] if ENV.key?(env_name)
else
# optional configurable
@params[p[:name]] = ENV.key?(env_name) ? ENV[env_name] : p[:default]
end
end
@params
end
|
ruby
|
{
"resource": ""
}
|
q6727
|
Myreplicator.Parallelizer.run
|
train
|
def run
@done = false
@manager_running = false
reaper = nil
while @queue.size > 0
if @threads.size <= @max_threads
@threads << Thread.new(@queue.pop) do |proc|
Thread.current[:thread_state] = "running"
@klass.new.instance_exec(proc[:params], &proc[:block])
Thread.current[:thread_state] = "done"
end
else
unless @manager_running
reaper = manage_threads
@manager_running = true
end
sleep 1
end
end
# Run manager if thread size never reached max
reaper = manage_threads unless @manager_running
# Waits until all threads are completed
# Before exiting
reaper.join
end
|
ruby
|
{
"resource": ""
}
|
q6728
|
Myreplicator.Parallelizer.manage_threads
|
train
|
def manage_threads
Thread.new do
while(@threads.size > 0)
done = []
@threads.each do |t|
done << t if t[:thread_state] == "done" || !t.status
# puts t.object_id.to_s + "--" + t.status.to_s + "--" + t.to_s
# raise "Nil Thread State" if t[:thread_state].nil?
end
done.each{|d| @threads.delete(d)} # Clear dead threads
# If no more jobs are left, mark done
if done?
@done = true
else
puts "Sleeping for 2"
sleep 2 # Wait for more threads to spawn
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6729
|
MMETools.Debug.print_debug
|
train
|
def print_debug(stck_lvls, *vars)
@mutex ||= Mutex.new # instance mutex created the first time it is called
referers = caller[0...stck_lvls] if stck_lvls > 0
@mutex.synchronize do
referers.each { |r| puts "#{r}:"}
vars.each { |v| pp v } if vars
end
end
|
ruby
|
{
"resource": ""
}
|
q6730
|
FriendlyAttributes.InstanceMethods.friendly_instance_for_attribute
|
train
|
def friendly_instance_for_attribute(attr)
klass = friendly_attributes_configuration.model_for_attribute(attr)
send DetailsDelegator.friendly_model_reader(klass)
end
|
ruby
|
{
"resource": ""
}
|
q6731
|
FriendlyAttributes.InstanceMethods.friendly_instance_present?
|
train
|
def friendly_instance_present?(friendly_model)
friendly_model_ivar = DetailsDelegator.friendly_model_ivar(friendly_model)
val = instance_variable_get(friendly_model_ivar)
val.present?
end
|
ruby
|
{
"resource": ""
}
|
q6732
|
Shibbolite.ShibbolethController.load_session
|
train
|
def load_session
unless logged_in?
session[Shibbolite.pid] = request.env[Shibbolite.pid.to_s]
current_user.update(get_attributes) if registered_user?
end
end
|
ruby
|
{
"resource": ""
}
|
q6733
|
Rack.Plastic.create_node
|
train
|
def create_node(doc, node_name, content=nil) #:doc:
node = Nokogiri::XML::Node.new(node_name, doc)
node.content = content if content
node
end
|
ruby
|
{
"resource": ""
}
|
q6734
|
RComp.Process.run
|
train
|
def run
begin
@process.start
rescue ChildProcess::LaunchError => e
raise StandardError.new(e.message)
end
begin
@process.poll_for_exit(@timeout)
rescue ChildProcess::TimeoutError
@timedout = true
@process.stop(@timeout)
end
end
|
ruby
|
{
"resource": ""
}
|
q6735
|
Roroacms.GeneralHelper.rewrite_theme_helper
|
train
|
def rewrite_theme_helper
if File.exists?("#{Rails.root}/app/views/themes/#{current_theme}/theme_helper.rb")
# get the theme helper from the theme folder
file = File.open("#{Rails.root}/app/views/themes/#{current_theme}/theme_helper.rb", "rb")
contents = file.read
# check if the first line starts with the module name or not
parts = contents.split(/[\r\n]+/)
if parts[0] != 'module ThemeHelper'
contents = "module ThemeHelper\n\n" + contents + "\n\nend"
end
# write the contents to the actual file file
File.open("#{Rails.root}/app/helpers/theme_helper.rb", 'w') { |file| file.write(contents) }
else
contents = "module ThemeHelper\n\nend"
File.open("#{Rails.root}/app/helpers/theme_helper.rb", 'w') { |file| file.write(contents) }
end
load("#{Rails.root}/app/helpers/theme_helper.rb")
end
|
ruby
|
{
"resource": ""
}
|
q6736
|
Factom.Client.address_to_pubkey
|
train
|
def address_to_pubkey(addr)
return unless addr.size == 52
prefix = ADDRESS_PREFIX[addr[0,2]]
return unless prefix
v = Bitcoin.decode_base58(addr)
return if v[0,4] != prefix
bytes = [v[0, 68]].pack('H*')
return if v[68, 8] != sha256d(bytes)[0, 8]
v[4, 64]
end
|
ruby
|
{
"resource": ""
}
|
q6737
|
Bebox.VagrantHelper.prepare_vagrant
|
train
|
def prepare_vagrant(node)
project_name = Bebox::Project.name_from_file(node.project_root)
vagrant_box_base = Bebox::Project.vagrant_box_base_from_file(node.project_root)
configure_local_hosts(project_name, node)
add_vagrant_node(project_name, vagrant_box_base, node)
end
|
ruby
|
{
"resource": ""
}
|
q6738
|
ActiveWindowX.Window.prop
|
train
|
def prop atom
val, format, nitems = prop_raw atom
case format
when 32; val.unpack("l!#{nitems}")
when 16; val.unpack("s#{nitems}")
when 8; val[0, nitems]
when 0; nil
end
end
|
ruby
|
{
"resource": ""
}
|
q6739
|
ActionCommand.InputOutput.validate_input
|
train
|
def validate_input(dest, args)
return true unless should_validate(dest)
@input.each do |p|
val = args[p[:symbol]]
# if the argument has a value, no need to test whether it is optional.
next unless !val || val == '*' || val == ''
opts = p[:opts]
unless opts[:optional]
raise ArgumentError, "You must specify the required input #{p[:symbol]}"
end
end
return true
end
|
ruby
|
{
"resource": ""
}
|
q6740
|
ActionCommand.InputOutput.process_input
|
train
|
def process_input(dest, args)
# pass down predefined attributes.
dest.parent = args[:parent]
dest.test = args[:test]
return unless validate_input(dest, args)
@input.each do |param|
sym = param[:symbol]
if args.key? sym
sym_assign = "#{sym}=".to_sym
dest.send(sym_assign, args[sym])
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6741
|
ActionCommand.InputOutput.process_output
|
train
|
def process_output(dest, result)
return unless result.ok? && should_validate(dest)
@output.each do |param|
sym = param[:symbol]
unless result.key?(sym)
opts = param[:opts]
raise ArgumentError, "Missing required value #{sym} in output" unless opts[:optional]
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6742
|
ActionCommand.InputOutput.rake_input
|
train
|
def rake_input(rake_arg)
params = {}
rake_arg.each do |key, val|
params[key] = val
end
# by default, use human logging if a logger is enabled.
params[:logger] = Logger.new(STDOUT) unless params.key?(:logger)
params[:log_format] = :human unless params.key?(:log_format)
return params
end
|
ruby
|
{
"resource": ""
}
|
q6743
|
Watir.Element.refresh_until_present
|
train
|
def refresh_until_present(timeout = 30)
message = "waiting for #{@selector.inspect} to become present"
Watir::WaitWithRefresh.refresh_until(browser, timeout, message) { present? }
end
|
ruby
|
{
"resource": ""
}
|
q6744
|
Watir.Element.refresh_while_present
|
train
|
def refresh_while_present(timeout = 30)
message = "waiting for #{@selector.inspect} to disappear"
Watir::WaitWithRefresh.refresh_while(browser, timeout, message) { present? }
end
|
ruby
|
{
"resource": ""
}
|
q6745
|
Watir.Element.when_present_after_refresh
|
train
|
def when_present_after_refresh(timeout = 30)
message = "waiting for #{@selector.inspect} to become present"
if block_given?
Watir::WaitWithRefresh.refresh_until(browser, timeout, message) { present? }
yield self
else
WhenPresentAfterRefreshDecorator.new(self, timeout, message)
end
end
|
ruby
|
{
"resource": ""
}
|
q6746
|
Mutagem.Lockfile.locked?
|
train
|
def locked?
return false unless File.exists?(lockfile)
result = false
open(lockfile, 'w') do |f|
# exclusive non-blocking lock
result = !lock(f, File::LOCK_EX | File::LOCK_NB)
end
result
end
|
ruby
|
{
"resource": ""
}
|
q6747
|
BasicCache.Cache.[]
|
train
|
def [](key = nil)
key ||= BasicCache.caller_name
raise KeyError, 'Key not cached' unless include? key.to_sym
@store[key.to_sym]
end
|
ruby
|
{
"resource": ""
}
|
q6748
|
BROpenData::Chamber.Service.setup_propositions
|
train
|
def setup_propositions(params)
self.params = {
sigla: params[:sigla], numero: params[:numero], ano: params[:ano], datApresentacaoIni: params[:datApresentacaoIni],
generoAutor: params[:generoAutor], datApresentacaoFim: params[:datApresentacaoFim], parteNomeAutor: params[:parteNomeAutor],
idTipoAutor: params[:idTipoAutor], siglaUFAutor: params[:siglaUFAutor], codEstado: params[:codEstado],
codOrgaoEstado: params[:codOrgaoEstado], emTramitacao: params[:emTramitacao], siglaPartidoAutor: params[:siglaPartidoAutor]
}
end
|
ruby
|
{
"resource": ""
}
|
q6749
|
Incline::Extensions.JbuilderTemplate.api_errors!
|
train
|
def api_errors!(model_name, model_errors)
base_error = model_errors[:base]
field_errors = model_errors.reject{ |k,_| k == :base }
unless base_error.blank?
set! 'error', "#{model_name.humanize} #{base_error.map{|e| h(e.to_s)}.join("<br>\n#{model_name.humanize} ")}"
end
unless field_errors.blank?
set! 'fieldErrors' do
array! field_errors do |k,v|
set! 'name', "#{model_name}.#{k}"
set! 'status', v.is_a?(::Array) ?
"#{k.to_s.humanize} #{v.map{|e| h(e.to_s)}.join("<br>\n#{k.to_s.humanize} ")}" :
"#{k.to_s.humanize} #{h v.to_s}"
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6750
|
Hornetseye.RGB_.assign
|
train
|
def assign(value)
value = value.simplify
if @value.r.respond_to? :assign
@value.r.assign value.get.r
else
@value.r = value.get.r
end
if @value.g.respond_to? :assign
@value.g.assign value.get.g
else
@value.g = value.get.g
end
if @value.b.respond_to? :assign
@value.b.assign value.get.b
else
@value.b = value.get.b
end
value
end
|
ruby
|
{
"resource": ""
}
|
q6751
|
Hornetseye.Node.r_with_decompose
|
train
|
def r_with_decompose
if typecode == OBJECT or is_a?(Variable) or Thread.current[:lazy]
r_without_decompose
elsif typecode < RGB_
decompose 0
else
self
end
end
|
ruby
|
{
"resource": ""
}
|
q6752
|
Hornetseye.Node.g_with_decompose
|
train
|
def g_with_decompose
if typecode == OBJECT or is_a?(Variable) or Thread.current[:lazy]
g_without_decompose
elsif typecode < RGB_
decompose 1
else
self
end
end
|
ruby
|
{
"resource": ""
}
|
q6753
|
Hornetseye.Node.b_with_decompose
|
train
|
def b_with_decompose
if typecode == OBJECT or is_a?(Variable) or Thread.current[:lazy]
b_without_decompose
elsif typecode < RGB_
decompose 2
else
self
end
end
|
ruby
|
{
"resource": ""
}
|
q6754
|
Hornetseye.Node.b=
|
train
|
def b=(value)
if typecode < RGB_
decompose( 2 )[] = value
elsif typecode == OBJECT
self[] = Hornetseye::lazy do
r * RGB.new( 1, 0, 0 ) + g * RGB.new( 0, 1, 0 ) + value * RGB.new( 0, 0, 1 )
end
else
raise "Cannot assign blue channel to elements of type #{typecode.inspect}"
end
end
|
ruby
|
{
"resource": ""
}
|
q6755
|
Hornetseye.Node.histogram_with_rgb
|
train
|
def histogram_with_rgb( *ret_shape )
if typecode < RGB_
[ r, g, b ].histogram *ret_shape
else
histogram_without_rgb *ret_shape
end
end
|
ruby
|
{
"resource": ""
}
|
q6756
|
Hornetseye.Node.lut_with_rgb
|
train
|
def lut_with_rgb( table, options = {} )
if typecode < RGB_
[ r, g, b ].lut table, options
else
lut_without_rgb table, options
end
end
|
ruby
|
{
"resource": ""
}
|
q6757
|
Incline::Extensions.FormBuilder.currency_field
|
train
|
def currency_field(method, options = {})
# get the symbol for the field.
sym = options.delete(:currency_symbol) || '$'
# get the value
if (val = object.send(method))
options[:value] = number_with_precision val, precision: 2, delimiter: ','
end
# build the field
fld = text_field(method, options)
# return the value.
"<div class=\"input-symbol\"><span>#{CGI::escape_html sym}</span>#{fld}</div>".html_safe
end
|
ruby
|
{
"resource": ""
}
|
q6758
|
Incline::Extensions.FormBuilder.text_form_group
|
train
|
def text_form_group(method, options = {})
gopt, lopt, fopt = split_form_group_options(options)
lbl = label_w_small(method, lopt)
fld = gopt[:wrap].call(text_field(method, fopt))
form_group lbl, fld, gopt
end
|
ruby
|
{
"resource": ""
}
|
q6759
|
Incline::Extensions.FormBuilder.password_form_group
|
train
|
def password_form_group(method, options = {})
gopt, lopt, fopt = split_form_group_options(options)
lbl = label_w_small(method, lopt)
fld = gopt[:wrap].call(password_field(method, fopt))
form_group lbl, fld, gopt
end
|
ruby
|
{
"resource": ""
}
|
q6760
|
Incline::Extensions.FormBuilder.textarea_form_group
|
train
|
def textarea_form_group(method, options = {})
gopt, lopt, fopt = split_form_group_options(options)
lbl = label_w_small method, lopt
fld = gopt[:wrap].call(text_area(method, fopt))
form_group lbl, fld, gopt
end
|
ruby
|
{
"resource": ""
}
|
q6761
|
Incline::Extensions.FormBuilder.currency_form_group
|
train
|
def currency_form_group(method, options = {})
gopt, lopt, fopt = split_form_group_options(options)
lbl = label_w_small(method, lopt)
fld = gopt[:wrap].call(currency_field(method, fopt))
form_group lbl, fld, gopt
end
|
ruby
|
{
"resource": ""
}
|
q6762
|
Incline::Extensions.FormBuilder.static_form_group
|
train
|
def static_form_group(method, options = {})
gopt, lopt, fopt = split_form_group_options(options)
lbl = label_w_small(method, lopt)
fld = gopt[:wrap].call("<input type=\"text\" class=\"form-control disabled\" readonly=\"readonly\" value=\"#{CGI::escape_html(fopt[:value] || object.send(method))}\">")
form_group lbl, fld, gopt
end
|
ruby
|
{
"resource": ""
}
|
q6763
|
Incline::Extensions.FormBuilder.datepicker_form_group
|
train
|
def datepicker_form_group(method, options = {})
gopt, lopt, fopt = split_form_group_options(options)
lbl = label_w_small(method, lopt)
fld = gopt[:wrap].call(date_picker(method, fopt))
form_group lbl, fld, gopt
end
|
ruby
|
{
"resource": ""
}
|
q6764
|
Incline::Extensions.FormBuilder.multi_input_form_group
|
train
|
def multi_input_form_group(methods, options = {})
gopt, lopt, fopt = split_form_group_options(options)
lopt[:text] ||= gopt[:label]
if lopt[:text].blank?
lopt[:text] = methods.map {|k,_| k.to_s.humanize }.join(', ')
end
lbl = label_w_small(methods.map{|k,_| k}.first, lopt)
fld = gopt[:wrap].call(multi_input(methods, fopt))
form_group lbl, fld, gopt
end
|
ruby
|
{
"resource": ""
}
|
q6765
|
Incline::Extensions.FormBuilder.check_box_form_group
|
train
|
def check_box_form_group(method, options = {})
gopt, lopt, fopt = split_form_group_options({ class: 'checkbox', field_class: ''}.merge(options))
if gopt[:h_align]
gopt[:class] = gopt[:class].blank? ?
"col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}" :
"#{gopt[:class]} col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}"
end
lbl = label method do
check_box(method, fopt) +
CGI::escape_html(lopt[:text] || method.to_s.humanize) +
(lopt[:small_text] ? " <small>(#{CGI::escape_html lopt[:small_text]})</small>" : '').html_safe
end
"<div class=\"#{gopt[:h_align] ? 'row' : 'form-group'}\"><div class=\"#{gopt[:class]}\">#{lbl}</div></div>".html_safe
end
|
ruby
|
{
"resource": ""
}
|
q6766
|
Incline::Extensions.FormBuilder.recaptcha
|
train
|
def recaptcha(method, options = {})
Incline::Recaptcha::Tag.new(@object_name, method, @template, options).render
end
|
ruby
|
{
"resource": ""
}
|
q6767
|
Cmdlib.App.addopt
|
train
|
def addopt ( opt )
raise TypeError, 'Incorrectly types for option object.' unless
opt.instance_of? Cmdlib::Option
@options[opt.longname.to_sym] = opt
end
|
ruby
|
{
"resource": ""
}
|
q6768
|
Cmdlib.App.display_commands
|
train
|
def display_commands( cmdlist )
maxlen = 0
cmdlist.each do |cmd|
maxlen = cmd.name.length if cmd.name.length > maxlen
end
cmdlist.each do |cmd|
print ' ' + cmd.name
print "#{' ' * (maxlen - cmd.name.length)} # "
puts cmd.brief
end
end
|
ruby
|
{
"resource": ""
}
|
q6769
|
Cmdlib.App.display_options
|
train
|
def display_options( optlist )
maxlen = 0
listout = []
optlist.each_value do |opt|
optnames = ''
if opt.shortname.length == 0
optnames += ' '
else
optnames += OPTION_PREFIX_SHORT + opt.shortname
end
optnames += ','
optnames += OPTION_PREFIX_LONG + opt.longname if opt.longname.length != 0
optnames += '=[...]' if opt.param == true
listout << { :n => optnames, :b => opt.brief }
maxlen = optnames.length if optnames.length > maxlen
end
listout.each do |opt|
print ' ' + opt[:n]
print "#{' ' * (maxlen - opt[:n].length)} # "
puts opt[:b]
end
end
|
ruby
|
{
"resource": ""
}
|
q6770
|
Cmdlib.App.run
|
train
|
def run
option_parser @options
# Check on include version request.
if @options[:version].value then
puts "#{@name}, version #{@version}"
exit
end
# Check on include help request.
if ARGV[0] == 'help' or ARGV[0] == '--help' or ARGV[0] == '-h' then
# Help arguments apsent, well then display information about application.
if ARGV.size == 1 then
puts
puts "*** #{@name} ***".center(80)
# Display about info.
if @about.size > 0 then
puts '** ABOUT:'
@about.each do |line|
puts " #{line}"
end
end
# Display usage info.
if @usage.size > 0 then
puts
puts '** USAGE:'
@usage.each do |line|
puts " #{line}"
end
end
# Display options info.
puts
puts '** OPTIONS:'
display_options @options
# Display commands info
if @commands.size > 0 then
@commands.each do |c| c.init end
puts
puts '** COMMANDS:'
display_commands @commands
puts
puts "For details, type: help [COMMAND]"
end
puts
# Help arguments exist, find command in application command list.
else
ARGV.delete_at( 0 )
cmd = command_select
if ARGV.size != 0 then
puts "fatal error: unknown command '#{ARGV[0]}'"
exit
end
# Display describe information on command.
puts
puts Cmdlib::Describe.outtitle( cmd.name )
puts " #{cmd.brief}"
if cmd.details.size > 0 then
puts
puts '** DETAILS:'
cmd.details.each do |e|
puts " #{e}"
end
end
if cmd.example.size > 0 then
puts
puts '** EXAMPLE:'
cmd.example.each do |e|
puts " #{e}"
end
end
# Display options info.
if cmd.options.size > 0 then
puts
puts '** OPTIONS:'
display_options cmd.options
end
# Display commands info.
if cmd.subcmd.size > 0 then
cmd.subcmd.each do |c| c.init end
puts
puts '** SUBCOMMANDS:'
display_commands cmd.subcmd
puts
puts "For details, type: help #{cmd.name} [SUBCOMMAND]"
end
puts
end
exit
end
# Handling default command (if exist her).
if @default != nil then
option_excess
if ARGV.size < @default.argnum then
puts "fatal error: to few arguments for programm, use <help>."
else
@default.handler( @options, ARGV )
end
exit
end
# Handling commands.
cmd = command_select
if cmd == nil then
puts "fatal error: unknown command or command miss, use <help>."
exit
end
if ARGV.size < cmd.argnum then
puts "fatal error: to few arguments for command, use: <help> <command name>."
exit
end
# Scaning options fir this command
option_parser cmd.options
option_excess
#cmd.init
cmd.handler( @options, ARGV )
exit
end
|
ruby
|
{
"resource": ""
}
|
q6771
|
Cmdlib.App.command_select
|
train
|
def command_select
command = command_search( @commands, ARGV[0] )
if command != nil then
# remove command name from ARGV and search next.
ARGV.delete_at( 0 )
ARGV.each do |arg|
cmd = command_search( command.subcmd, arg )
break if cmd == nil
ARGV.delete_at( 0 )
command = cmd
end
end
return command
end
|
ruby
|
{
"resource": ""
}
|
q6772
|
Cmdlib.App.option_excess
|
train
|
def option_excess
ARGV.each do |opt|
o = getopt( opt )
if o[:n] != '' then
puts "fatal error: unknown option '#{o[:t]}#{o[:n]}'"
exit
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6773
|
Cmdlib.App.option_parser
|
train
|
def option_parser( optlist )
return if optlist.size == 0
deletelist = []
# search option in argument list.
ARGV.each_with_index do |opt,i|
o = getopt( opt )
if o[:n] != '' and o[:n] != 'h' and o[:n] != 'help'
o[:i] = i
# Search in application list
result = option_search( o, optlist )
if result != nil then
deletelist << opt
result = option_set( o, optlist[result] )
deletelist << result if result != ''
end
end
end
# delete option from ARGV.
deletelist.each do |n|
ARGV.delete( n )
end
end
|
ruby
|
{
"resource": ""
}
|
q6774
|
Dbtap.Tapper.run
|
train
|
def run
puts (1..tests.length).to_s
tests.each_with_index do |test, i|
begin
if test.is_ok?
ok(test, i)
else
not_ok(test, i)
end
rescue Sequel::DatabaseError
puts $!.sql
raise $!
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6775
|
Dbtap.Tapper.ok
|
train
|
def ok(test, i)
message = "ok #{i + 1}"
message += ' - ' + test.name if test.name
puts message
end
|
ruby
|
{
"resource": ""
}
|
q6776
|
Dbtap.Tapper.not_ok
|
train
|
def not_ok(test, i)
message = "not ok #{i + 1}"
message += ' - ' + test.name if test.name
message += "\n " + test.errors.join("\n ") if test.errors
puts message
end
|
ruby
|
{
"resource": ""
}
|
q6777
|
NRSER.Decorate.resolve_method
|
train
|
def resolve_method name:, default_type: nil
name_string = name.to_s # .gsub( /\A\@\@/, '.' ).gsub( /\A\@/, '#' )
case name_string
when Meta::Names::Method::Bare
bare_name = Meta::Names::Method::Bare.new name_string
case default_type&.to_sym
when nil
raise NRSER::ArgumentError.new \
"When `default_type:` param is `nil` `name:` must start with '.'",
"or '#'",
name: name
when :singleton, :class
method bare_name
when :instance
instance_method bare_name
else
raise NRSER::ArgumentError.new \
"`default_type:` param must be `nil`, `:instance`, `:singleton` or",
"`:class`, found", default_type.inspect,
name: name,
default_type: default_type
end
when Meta::Names::Method::Singleton
method Meta::Names::Method::Singleton.new( name_string ).bare_name
when Meta::Names::Method::Instance
instance_method Meta::Names::Method::Instance.new( name_string ).bare_name
else
raise NRSER::ArgumentError.new \
"`name:` does not look like a method name:", name.inspect
end
end
|
ruby
|
{
"resource": ""
}
|
q6778
|
Snapshotify.Url.parse_uri
|
train
|
def parse_uri
self.uri = URI.parse(raw_url)
uri.path = "/" if uri.path.empty?
uri.fragment = nil
# if this fails, mark the URL as invalid
rescue
self.valid = false
end
|
ruby
|
{
"resource": ""
}
|
q6779
|
BBLib.FamilyTree.descendants
|
train
|
def descendants(include_singletons = false)
return _inherited_by.map { |c| [c, c.descendants] }.flatten.uniq if BBLib.in_opal?
ObjectSpace.each_object(Class).select do |c|
(include_singletons || !c.singleton_class?) && c < self
end
end
|
ruby
|
{
"resource": ""
}
|
q6780
|
BBLib.FamilyTree.direct_descendants
|
train
|
def direct_descendants(include_singletons = false)
return _inherited_by if BBLib.in_opal?
ObjectSpace.each_object(Class).select do |c|
(include_singletons || !c.singleton_class?) && c.ancestors[1..-1].find { |k| k.is_a?(Class) } == self
end
end
|
ruby
|
{
"resource": ""
}
|
q6781
|
BBLib.FamilyTree.instances
|
train
|
def instances(descendants = true)
inst = ObjectSpace.each_object(self).to_a
descendants ? inst : inst.select { |i| i.class == self }
end
|
ruby
|
{
"resource": ""
}
|
q6782
|
HtmlMockup::Release::Scm.Git.find_git_dir
|
train
|
def find_git_dir(path)
path = Pathname.new(path).realpath
while path.parent != path && !(path + ".git").directory?
path = path.parent
end
path = path + ".git"
raise "Could not find suitable .git dir in #{path}" if !path.directory?
path
end
|
ruby
|
{
"resource": ""
}
|
q6783
|
Gearbox.RDFCollection.has_key?
|
train
|
def has_key?(key, opts={})
key = normalize_key(key) if opts.fetch(:normalize, true)
@source.has_key?(key)
end
|
ruby
|
{
"resource": ""
}
|
q6784
|
Jinx.Importer.const_missing
|
train
|
def const_missing(sym)
# Load the class definitions in the source directory, if necessary.
# If a load is performed as a result of referencing the given symbol,
# then dereference the class constant again after the load, since the class
# might have been loaded or referenced during the load.
unless defined? @introspected then
configure_importer
load_definitions
return const_get(sym)
end
# Append the symbol to the package to make the Java class name.
logger.debug { "Detecting whether #{sym} is a #{self} Java class..." }
klass = @packages.detect_value do |pkg|
begin
java_import "#{pkg}.#{sym}"
rescue NameError
nil
end
end
if klass then
logger.debug { "Added #{klass} to the #{self} module." }
else
# Not a Java class; print a log message and pass along the error.
logger.debug { "#{sym} is not recognized as a #{self} Java class." }
super
end
# Introspect the Java class meta-data, if necessary.
unless introspected?(klass) then
add_metadata(klass)
# Print the class meta-data.
logger.info(klass.pp_s)
end
klass
end
|
ruby
|
{
"resource": ""
}
|
q6785
|
Jinx.Importer.configure_importer
|
train
|
def configure_importer
# The default package conforms to the JRuby convention for mapping a package name
# to a module name.
@packages ||= [name.split('::').map { |n| n.downcase }.join('.')]
@packages.each do |pkg|
begin
eval "java_package Java::#{pkg}"
rescue Exception => e
raise ArgumentError.new("#{self} Java package #{pkg} not found - #{$!}")
end
end
# The introspected classes.
@introspected = Set.new
# The name => file hash for file definitions that are not in the packages.
@unresolved_defs = {}
end
|
ruby
|
{
"resource": ""
}
|
q6786
|
Jinx.Importer.load_dir
|
train
|
def load_dir(dir)
logger.debug { "Loading the class definitions in #{dir}..." }
# Import the classes.
srcs = sources(dir)
# Introspect and load the classes in reverse class order, i.e. superclass before subclass.
klasses = srcs.keys.transitive_closure { |k| [k.superclass] }.select { |k| srcs[k] }.reverse
# Introspect the classes as necessary.
klasses.each { |klass| add_metadata(klass) unless introspected?(klass) }
# Load the classes.
klasses.each do |klass|
file = srcs[klass]
load_definition(klass, file)
end
logger.debug { "Loaded the class definitions in #{dir}." }
end
|
ruby
|
{
"resource": ""
}
|
q6787
|
Jinx.Importer.add_metadata
|
train
|
def add_metadata(klass)
logger.debug("Adding #{self}::#{klass.qp} metadata...")
# Mark the class as introspected. Do this first to preclude a recursive loop back
# into this method when the references are introspected below.
@introspected << klass
# Add the superclass meta-data if necessary.
add_superclass_metadata(klass)
# Include this resource module into the class, unless this has already occurred.
unless klass < self then
m = self
klass.class_eval { include m }
end
# Import the class into this resource module, unless this has already occurred.
name = klass.name.demodulize
unless const_defined?(name) then
java_import(klass.java_class.name)
end
# Add introspection capability to the class.
md_mod = @metadata_module || Metadata
logger.debug { "Extending #{self}::#{klass.qp} with #{md_mod.name}..." }
klass.extend(md_mod)
# Set the class domain module.
klass.domain_module = self
# Introspect the Java properties.
klass.introspect
# Add the {attribute => value} initializer.
klass.add_attribute_value_initializer if Class === klass
# Add referenced domain class metadata as necessary.
klass.each_property do |prop|
ref = prop.type
if ref.nil? then raise MetadataError.new("#{self} #{prop} domain type is unknown.") end
if introspectible?(ref) then
logger.debug { "Introspecting the #{klass.qp} #{prop} reference type #{ref.qp}..." }
add_metadata(ref)
end
end
# If the class has a definition file but does not resolve to a standard package, then
# load it now based on the demodulized class name match.
file = @unresolved_defs[name]
load_definition(klass, file) if file
logger.debug("#{self}::#{klass.qp} metadata added.")
end
|
ruby
|
{
"resource": ""
}
|
q6788
|
Ruta.Route.get
|
train
|
def get params=nil
path = if params
paramaterize params.dup
else
@url
end
{
path: path,
title: self.flags.fetch(:title){nil},
params: params_hash(params),
route: self
}
end
|
ruby
|
{
"resource": ""
}
|
q6789
|
Ruta.Route.match
|
train
|
def match(path)
if match = @regexp.match(path)
params = {}
@named.each_with_index { |name, i| params[name] = match[i + 1] } if @type == :handlers
{
path: path,
title: self.flags.fetch(:title){nil},
params: params,
route: self
}
else
false
end
end
|
ruby
|
{
"resource": ""
}
|
q6790
|
Ruta.Route.execute_handler
|
train
|
def execute_handler params={},path=nil
case @type
when :handlers
@handlers.each do |handler_ident|
handler = @context_ref.handlers.fetch(handler_ident) {raise "handler #{handler_ident} doesn't exist in context #{@context_ref.ref}"}
component = handler.(params,path||@url,&:call)
Context.current_context = @context_ref.ref
if component.class == Proc
component.call
else
Context.renderer.call(component,handler_ident)
end
Context.current_context = :no_context
end
when :context
Context.wipe
Context.render handlers
History.push(@context_ref.ref,"",[],@context_ref.ref)
end
end
|
ruby
|
{
"resource": ""
}
|
q6791
|
DependentRestrict.ClassMethods.has_one
|
train
|
def has_one(*args, &extension)
options = args.extract_options! || {}
if VALID_DEPENDENTS.include?(options[:dependent].try(:to_sym))
reflection = if active_record_4?
association_id, scope = *args
restrict_create_reflection(:has_one, association_id, scope || {}, options, self)
else
association_id = args[0]
create_reflection(:has_one, association_id, options, self)
end
add_dependency_callback!(reflection, options)
end
args << options
super(*args, &extension)
end
|
ruby
|
{
"resource": ""
}
|
q6792
|
Mutagem.Task.run
|
train
|
def run
pipe = IO.popen(@cmd + " 2>&1")
@pid = pipe.pid
begin
@output = pipe.readlines
pipe.close
@exitstatus = $?.exitstatus
rescue => e
@exception = e
end
end
|
ruby
|
{
"resource": ""
}
|
q6793
|
Sinatra.Ratpack.link_to
|
train
|
def link_to(content,href=nil,options={})
href ||= content
options.update :href => url_for(href)
content_tag :a, content, options
end
|
ruby
|
{
"resource": ""
}
|
q6794
|
Aerogel.Reloader.check!
|
train
|
def check!
return unless @files
@file_list = file_list( @files )
new_signature = signature( @file_list )
if @signature != new_signature
# reload file list
puts "* Aerogel::Reloader reloading: #{@file_list}, group: #{@group}"
if @group
# invoke :before group actions
Aerogel::Reloader.reloaders.select{|r| r.group == @group && r.opts[:before] }.each do |r|
r.action.call @file_list
end
end
@action.call @file_list
@signature = new_signature
if @group
# invoke :after group actions
Aerogel::Reloader.reloaders.select{|r| r.group == @group && r.opts[:after] }.each do |r|
r.action.call @file_list
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6795
|
Aerogel.Reloader.file_list
|
train
|
def file_list( files )
case files
when String
[files]
when Array
files
when Proc
files.call # result should respond to #each
else
[]
end
end
|
ruby
|
{
"resource": ""
}
|
q6796
|
Remi.Dsl.dsl_eval
|
train
|
def dsl_eval(dsl, fallback_dsl, *args, &block)
exec_in_proxy_context(dsl, fallback_dsl, Docile::FallbackContextProxy, *args, &block)
dsl
end
|
ruby
|
{
"resource": ""
}
|
q6797
|
EquitracUtilities.UserActions.user_modify
|
train
|
def user_modify(attribs)
defaults = {user_name: "!", min_bal: "!",
email: "!", dept_name: "!", pimary_pin: "!",
secondary_pin: "!", quota: "!", alternate_pin: "!",
home_server: "!", locked: "!", location: "!",
default_bc: "!", additional_info: "!", home_folder: "!"}
attribs = defaults.merge(attribs)
attribs = check_atrribs(attribs)
"modify ur #{attribs[:user_id]} \"#{attribs[:user_name]}\"" +
" #{attribs[:min_bal]} #{attribs[:email]} #{attribs[:dept_name]}" +
" #{attribs[:primary_pin]} #{attribs[:secondary_pin]}" +
" #{attribs[:quota]} #{attribs[:alternate_pin]}" +
" #{attribs[:home_server]} #{attribs[:locked]}" +
" #{attribs[:location]} #{attribs[:default_bc]}" +
" #{attribs[:additional_info]} #{attribs[:home_folder]}"
end
|
ruby
|
{
"resource": ""
}
|
q6798
|
EquitracUtilities.UserActions.user_adjust_set
|
train
|
def user_adjust_set(attribs)
defaults = {new_bal: 0.0, description: nil}
attribs = defaults.merge(attribs)
attribs = check_atrribs(attribs)
"adjust ur #{attribs[:user_id]} set #{attribs[:new_bal]} #{attribs[:description]}"
end
|
ruby
|
{
"resource": ""
}
|
q6799
|
Kalindar.Event.start_time_f
|
train
|
def start_time_f day
#puts "start #{start_time} : #{start_time.class} #{start_time.to_date} #{day}"
if dtstart.class == Date
# whole day
""
elsif start_time.to_date == day.to_date
start_time.strftime('%H:%M')
else
"..."
end
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.