_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q8700 | HtmlGrid.Component.escape_symbols | train | def escape_symbols(txt)
esc = ''
txt.to_s.each_byte { |byte|
esc << if(entity = @@symbol_entities[byte])
'&' << entity << ';'
else
byte
end
}
esc
end | ruby | {
"resource": ""
} |
q8701 | Nacho.Helper.nacho_select_tag | train | def nacho_select_tag(name, choices = nil, options = {}, html_options = {})
nacho_options = build_options(name, choices, options, html_options)
select_element = select_tag(name, options_for_select(nacho_options[:choices]), nacho_options[:options], nacho_options[:html_options])
select_element += nacho_options[:button] if nacho_options[:html_options][:multiple]
select_element
end | ruby | {
"resource": ""
} |
q8702 | Checkdin.CustomActivities.create_custom_activity | train | def create_custom_activity(options={})
response = connection.post do |req|
req.url "custom_activities", options
end
return_error_or_body(response)
end | ruby | {
"resource": ""
} |
q8703 | Mailgun.Domain.list | train | def list(domain=nil)
if domain
@mailgun.response = Mailgun::Base.fire(:get, @mailgun.api_url + "/domains/#{domain}")
else
@mailgun.response = Mailgun::Base.fire(:get, @mailgun.api_url + "/domains")["items"] || []
end
end | ruby | {
"resource": ""
} |
q8704 | Kanpachi.ResponseList.add | train | def add(response)
if @list.key? response.name
raise DuplicateResponse, "A response named #{response.name} already exists"
end
@list[response.name] = response
end | ruby | {
"resource": ""
} |
q8705 | Drafter.Apply.restore_attrs | train | def restore_attrs
draftable_columns.each do |key|
self.send "#{key}=", self.draft.data[key] if self.respond_to?(key)
end
self
end | ruby | {
"resource": ""
} |
q8706 | Drafter.Apply.restore_files | train | def restore_files
draft.draft_uploads.each do |draft_upload|
uploader = draft_upload.draftable_mount_column
self.send(uploader + "=", draft_upload.file_data)
end
end | ruby | {
"resource": ""
} |
q8707 | RailsViewHelpers.HtmlHelper.body_tag | train | def body_tag(options={}, &block)
options = canonicalize_options(options)
options.delete(:class) if options[:class].blank?
options[:data] ||= {}
options[:data][:controller] = controller.controller_name
options[:data][:action] = controller.action_name
content_tag(:body, options) do
yield
end
end | ruby | {
"resource": ""
} |
q8708 | PageRecord.Validations.errors | train | def errors
found_errors = @record.all('[data-error-for]')
error_list = ActiveModel::Errors.new(self)
found_errors.each do | error |
attribute = error['data-error-for']
message = error.text
error_list.add(attribute, message)
end
error_list
end | ruby | {
"resource": ""
} |
q8709 | KalturaFu.ViewHelpers.kaltura_player_embed | train | def kaltura_player_embed(entry_id,options={})
player_conf_parameter = "/ui_conf_id/"
options[:div_id] ||= "kplayer"
options[:size] ||= []
options[:use_url] ||= false
width = PLAYER_WIDTH
height = PLAYER_HEIGHT
source_type = "entryId"
unless options[:size].empty?
width = options[:size].first
height = options[:size].last
end
if options[:use_url] == true
source_type = "url"
end
unless options[:player_conf_id].nil?
player_conf_parameter += "#{options[:player_conf_id]}"
else
unless KalturaFu.config.player_conf_id.nil?
player_conf_parameter += "#{KalturaFu.config.player_conf_id}"
else
player_conf_parameter += "#{DEFAULT_KPLAYER}"
end
end
"<div id=\"#{options[:div_id]}\"></div>
<script type=\"text/javascript\">
var params= {
allowscriptaccess: \"always\",
allownetworking: \"all\",
allowfullscreen: \"true\",
wmode: \"opaque\",
bgcolor: \"#000000\"
};
var flashVars = {};
flashVars.sourceType = \"#{source_type}\";
flashVars.entryId = \"#{entry_id}\";
flashVars.emptyF = \"onKdpEmpty\";
flashVars.readyF = \"onKdpReady\";
var attributes = {
id: \"#{options[:div_id]}\",
name: \"#{options[:div_id]}\"
};
swfobject.embedSWF(\"#{KalturaFu.config.service_url}/kwidget/wid/_#{KalturaFu.config.partner_id}" + player_conf_parameter + "\",\"#{options[:div_id]}\",\"#{width}\",\"#{height}\",\"10.0.0\",\"http://ttv.mit.edu/swfs/expressinstall.swf\",flashVars,params,attributes);
</script>"
end | ruby | {
"resource": ""
} |
q8710 | KalturaFu.ViewHelpers.kaltura_seek_link | train | def kaltura_seek_link(content,seek_time,options={})
options[:div_id] ||= "kplayer"
options[:onclick] = "$(#{options[:div_id]}).get(0).sendNotification('doSeek',#{seek_time});window.scrollTo(0,0);return false;"
options.delete(:div_id)
link_to(content,"#", options)
end | ruby | {
"resource": ""
} |
q8711 | HMS.Duration.op | train | def op(sym, o)
case o
when Duration
Duration.new(@seconds.send(sym, o.to_i))
when Numeric
Duration.new(@seconds.send(sym, o))
else
a, b = o.coerce(self)
a.send(sym, b)
end
end | ruby | {
"resource": ""
} |
q8712 | Kelp.Navigation.follow | train | def follow(link, scope={})
in_scope(scope) do
begin
click_link(link)
rescue Capybara::ElementNotFound
raise Kelp::MissingLink,
"No link with title, id or text '#{link}' found"
end
end
end | ruby | {
"resource": ""
} |
q8713 | Kelp.Navigation.press | train | def press(button, scope={})
in_scope(scope) do
begin
click_button(button)
rescue Capybara::ElementNotFound
raise Kelp::MissingButton,
"No button with value, id or text '#{button}' found"
end
end
end | ruby | {
"resource": ""
} |
q8714 | Kelp.Navigation.click_link_in_row | train | def click_link_in_row(link, text)
begin
row = find(:xpath, xpath_row_containing([link, text]))
rescue Capybara::ElementNotFound
raise Kelp::MissingRow,
"No table row found containing '#{link}' and '#{text}'"
end
begin
row.click_link(link)
rescue Capybara::ElementNotFound
raise Kelp::MissingLink,
"No link with title, id or text '#{link}' found in the same row as '#{text}'"
end
end | ruby | {
"resource": ""
} |
q8715 | Kelp.Navigation.should_be_on_page | train | def should_be_on_page(page_name_or_path)
# Use the path_to translator function if it's defined
# (normally in features/support/paths.rb)
if defined? path_to
expect_path = path_to(page_name_or_path)
# Otherwise, expect a raw path string
else
expect_path = page_name_or_path
end
actual_path = URI.parse(current_url).path
if actual_path != expect_path
raise Kelp::Unexpected,
"Expected to be on page: '#{expect_path}'" + \
"\nActually on page: '#{actual_path}'"
end
end | ruby | {
"resource": ""
} |
q8716 | Kelp.Navigation.should_have_query | train | def should_have_query(params)
query = URI.parse(current_url).query
actual_params = query ? CGI.parse(query) : {}
expected_params = {}
params.each_pair do |k,v|
expected_params[k] = v.split(',')
end
if actual_params != expected_params
raise Kelp::Unexpected,
"Expected query params: '#{expected_params.inspect}'" + \
"\nActual query params: '#{actual_params.inspect}'"
end
end | ruby | {
"resource": ""
} |
q8717 | Machined.StaticCompiler.compile | train | def compile
compiled_assets = {}
machined.sprockets.each do |sprocket|
next unless sprocket.compile?
sprocket.each_logical_path do |logical_path|
url = File.join(sprocket.config.url, logical_path)
next unless compiled_assets[url].nil? && compile?(url)
if asset = sprocket.find_asset(logical_path)
compiled_assets[url] = write_asset(sprocket, asset)
end
end
end
compiled_assets
end | ruby | {
"resource": ""
} |
q8718 | Machined.StaticCompiler.write_asset | train | def write_asset(environment, asset)
filename = path_for(environment, asset)
FileUtils.mkdir_p File.dirname(filename)
asset.write_to filename
asset.write_to "#{filename}.gz" if gzip?(filename)
asset.digest
end | ruby | {
"resource": ""
} |
q8719 | Machined.StaticCompiler.path_for | train | def path_for(environment, asset) # :nodoc:
path = digest?(environment, asset) ? asset.digest_path : asset.logical_path
File.join(machined.output_path, environment.config.url, path)
end | ruby | {
"resource": ""
} |
q8720 | Kawaii.RouteHandler.call | train | def call(env)
@request = Rack::Request.new(env)
@params = @path_params.merge(@request.params.symbolize_keys)
process_response(instance_exec(self, params, request, &@block))
end | ruby | {
"resource": ""
} |
q8721 | ActiveRecord::Associations::Builder.HasAndBelongsToMany.join_table_name | train | def join_table_name(first_table_name, second_table_name)
if first_table_name < second_table_name
join_table = "#{first_table_name}_#{second_table_name}"
else
join_table = "#{second_table_name}_#{first_table_name}"
end
model.table_name_prefix + join_table + model.table_name_suffix
end | ruby | {
"resource": ""
} |
q8722 | InColumns.Columnizer.row_counts | train | def row_counts(number_of_columns)
per_column = (number_of_elements / number_of_columns).floor
counts = [per_column] * number_of_columns
left_overs = number_of_elements % number_of_columns
left_overs.times { |n|
counts[n] = counts[n] + 1
}
counts
end | ruby | {
"resource": ""
} |
q8723 | SimpleCataloger.CatOnSqlite.require_models | train | def require_models
model_dir = File.join(File.dirname(__FILE__), %w{ model })
unless Dir.exist? model_dir
raise "model directory '#{model_dir}' not exists"
end
Dir[File.join(model_dir, '*.rb')].each do |f|
# puts f
require f
end
end | ruby | {
"resource": ""
} |
q8724 | Solrizer::Fedora.Solrizer.solrize_objects | train | def solrize_objects(opts={})
# retrieve a list of all the pids in the fedora repository
num_docs = 1000000 # modify this number to guarantee that all the objects are retrieved from the repository
puts "WARNING: You have turned off indexing of Full Text content. Be sure to re-run indexer with @@index_full_text set to true in main.rb" if index_full_text == false
if @@index_list == false
solrize_from_fedora_search(opts)
else
solrize_from_csv
end
end | ruby | {
"resource": ""
} |
q8725 | Farmstead.Project.generate_files | train | def generate_files
ip = local_ip
version = Farmstead::VERSION
scaffold_path = "#{File.dirname __FILE__}/scaffold"
scaffold = Dir.glob("#{scaffold_path}/**/*.erb", File::FNM_DOTMATCH)
scaffold.each do |file|
basename = File.basename(file)
folderstruct = file.match("#{scaffold_path}/(.*)")[1]
if basename != folderstruct
foldername = File.dirname(folderstruct)
create_recursive("#{@name}/#{foldername}")
end
projectpath = "#{@name}/#{folderstruct}".chomp(".erb")
template = File.read(file)
results = ERB.new(template).result(binding)
copy_to_directory(results, projectpath)
end
end | ruby | {
"resource": ""
} |
q8726 | ActsAsReferred.ClassMethods.acts_as_referred | train | def acts_as_referred(options = {})
has_one :referee, as: :referable, dependent: :destroy, class_name: 'Referee'
after_create :create_referrer
include ActsAsReferred::InstanceMethods
end | ruby | {
"resource": ""
} |
q8727 | DCI.Role.add_role_reader_for! | train | def add_role_reader_for!(rolekey)
return if private_method_defined?(rolekey)
define_method(rolekey) {__context.send(rolekey)}
private rolekey
end | ruby | {
"resource": ""
} |
q8728 | Railslider.Image.render | train | def render
@result_html = ''
@result_html += "<div class=\"rs-container #{self.class.name}\" id=\"#{@id}\">"
@result_html += render_controls.gsub("<option value=\"rs-#{@effect}\">",
"<option value=\"rs-#{@effect}\" selected=\"selected\">")
@result_html += "<div class=\"rs-wrapper\">"
@result_html += "<div class=\"rs-shadow\"></div>"
@result_html += '<div class="rs-images">'
@images_urls.each do |url|
@result_html += "<img src=\"#{url}\"/>"
end
@result_html += '</div>'
@result_html += '<div class="rs-cover">'
@result_html += '<a class="rs-animation-command rs-pause" href="javascript:void(0)">Play/Pause</a>'
@result_html += "<img src=\"#{@images_urls.first}\"/>"
@result_html += '</div>'
@result_html += '<div class="rs-transition">'
@result_html += render_flips
@result_html += render_multi_flips
@result_html += render_cubes
@result_html += render_unfolds
@result_html += '</div>'
@result_html += '</div>'
@result_html += render_bullets
@result_html += '</div>'
@result_html.html_safe
end | ruby | {
"resource": ""
} |
q8729 | Gricer.Config.admin_menu | train | def admin_menu
@admin_menu ||= [
['overview', :dashboard, {controller: 'gricer/dashboard', action: 'overview'}],
['visitors', :menu, [
['entry_pages', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'entry_path'}],
['referers', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'referer_host'}],
['search_engines', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'search_engine'}],
['search_terms', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'search_query'}],
['countries', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'country'}],
['domains', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'domain'}],
['locales', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'requested_locale_major'}]
] ],
['pages', :menu, [
['views', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'path'}],
['hosts', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'host'}],
['methods', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'method'}],
['protocols', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'protocol'}],
] ],
['browsers', :menu, [
['browsers', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'agent.name'}],
['operating_systems', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'agent.os'}],
['engines', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'agent.engine_name'}],
['javascript', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'javascript'}],
['java', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'java'}],
['silverlight', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'silverlight_major_version'}],
['flash', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'flash_major_version'}],
['screen_sizes', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'screen_size'}],
['color_depths', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'screen_depth'}]
] ]
]
end | ruby | {
"resource": ""
} |
q8730 | StixSchemaSpy.HasChildren.process_field | train | def process_field(child)
if ['complexContent', 'simpleContent', 'sequence', 'group', 'choice', 'extension', 'restriction'].include?(child.name)
child.elements.each {|grandchild| process_field(grandchild)}
elsif child.name == 'element'
element = Element.new(child, self.schema, self)
@elements[element.name] = element
elsif child.name == 'attribute'
attribute = Attribute.new(child, self.schema, self)
@attributes[attribute.name] = attribute
elsif child.name == 'complexType'
type = ComplexType.build(child, self.schema)
@types[type.name] = type
elsif child.name == 'simpleType'
type = SimpleType.build(child, self.schema)
@types[type.name] = type
elsif child.name == 'anyAttribute'
@special_fields << SpecialField.new("##anyAttribute")
elsif child.name == 'anyElement'
@special_fields << SpecialField.new("##anyElement")
elsif child.name == 'attributeGroup'
# The only special case here...essentially we'll' transparently roll attribute groups into parent nodes,
# while at the schema level global attribute groups get created as a type
if self.kind_of?(Schema)
type = ComplexType.build(child, self.schema)
@types[type.name] = type
else
Type.find(child.attributes['ref'].value, nil, stix_version).attributes.each {|attrib| @attributes[attrib.name] = attrib}
end
else
$logger.debug "Skipping: #{child.name}" if defined?($logger)
end
end | ruby | {
"resource": ""
} |
q8731 | SimpleCommander.Runner.helper_exist? | train | def helper_exist?(helper)
Object.const_defined?(helper) &&
Object.const_get(helper).instance_of?(::Module)
end | ruby | {
"resource": ""
} |
q8732 | ActiveRecord.Explain.logging_query_plan | train | def logging_query_plan # :nodoc:
return yield unless logger
threshold = auto_explain_threshold_in_seconds
current = Thread.current
if threshold && current[:available_queries_for_explain].nil?
begin
queries = current[:available_queries_for_explain] = []
start = Time.now
result = yield
logger.warn(exec_explain(queries)) if Time.now - start > threshold
result
ensure
current[:available_queries_for_explain] = nil
end
else
yield
end
end | ruby | {
"resource": ""
} |
q8733 | ActiveRecord.Explain.silence_auto_explain | train | def silence_auto_explain
current = Thread.current
original, current[:available_queries_for_explain] = current[:available_queries_for_explain], false
yield
ensure
current[:available_queries_for_explain] = original
end | ruby | {
"resource": ""
} |
q8734 | OpenSSL::X509.SPKI.validate_spki | train | def validate_spki
unless @spki.is_a?(OpenSSL::ASN1::Sequence)
raise SPKIError,
"SPKI data is not an ASN1 sequence (got a #{@spki.class})"
end
if @spki.value.length != 2
raise SPKIError,
"SPKI top-level sequence must have two elements (length is #{@spki.value.length})"
end
alg_id, key_data = @spki.value
unless alg_id.is_a?(OpenSSL::ASN1::Sequence)
raise SPKIError,
"SPKI algorithm_identifier must be a sequence (got a #{alg_id.class})"
end
unless (1..2) === alg_id.value.length
raise SPKIError,
"SPKI algorithm sequence must have one or two elements (got #{alg_id.value.length} elements)"
end
unless alg_id.value.first.is_a?(OpenSSL::ASN1::ObjectId)
raise SPKIError,
"SPKI algorithm identifier does not contain an object ID (got #{alg_id.value.first.class})"
end
unless key_data.is_a?(OpenSSL::ASN1::BitString)
raise SPKIError,
"SPKI publicKeyInfo field must be a BitString (got a #{@spki.value.last.class})"
end
end | ruby | {
"resource": ""
} |
q8735 | XS.CommonSocketBehavior.setsockopt | train | def setsockopt name, value, length = nil
if 1 == @option_lookup[name]
length = 8
pointer = LibC.malloc length
pointer.write_long_long value
elsif 0 == @option_lookup[name]
length = 4
pointer = LibC.malloc length
pointer.write_int value
elsif 2 == @option_lookup[name]
length ||= value.size
# note: not checking errno for failed memory allocations :(
pointer = LibC.malloc length
pointer.write_string value
end
rc = LibXS.xs_setsockopt @socket, name, pointer, length
LibC.free(pointer) unless pointer.nil? || pointer.null?
rc
end | ruby | {
"resource": ""
} |
q8736 | XS.CommonSocketBehavior.more_parts? | train | def more_parts?
rc = getsockopt XS::RCVMORE, @more_parts_array
Util.resultcode_ok?(rc) ? @more_parts_array.at(0) : false
end | ruby | {
"resource": ""
} |
q8737 | XS.CommonSocketBehavior.send_strings | train | def send_strings parts, flag = 0
return -1 if !parts || parts.empty?
flag = NonBlocking if dontwait?(flag)
parts[0..-2].each do |part|
rc = send_string part, (flag | XS::SNDMORE)
return rc unless Util.resultcode_ok?(rc)
end
send_string parts[-1], flag
end | ruby | {
"resource": ""
} |
q8738 | XS.CommonSocketBehavior.send_and_close | train | def send_and_close message, flag = 0
rc = sendmsg message, flag
message.close
rc
end | ruby | {
"resource": ""
} |
q8739 | XS.CommonSocketBehavior.recv_strings | train | def recv_strings list, flag = 0
array = []
rc = recvmsgs array, flag
if Util.resultcode_ok?(rc)
array.each do |message|
list << message.copy_out_string
message.close
end
end
rc
end | ruby | {
"resource": ""
} |
q8740 | XS.CommonSocketBehavior.recv_multipart | train | def recv_multipart list, routing_envelope, flag = 0
parts = []
rc = recvmsgs parts, flag
if Util.resultcode_ok?(rc)
routing = true
parts.each do |part|
if routing
routing_envelope << part
routing = part.size > 0
else
list << part
end
end
end
rc
end | ruby | {
"resource": ""
} |
q8741 | XS.CommonSocketBehavior.sockopt_buffers | train | def sockopt_buffers option_type
if 1 == option_type
# int64_t or uint64_t
unless @longlong_cache
length = FFI::MemoryPointer.new :size_t
length.write_int 8
@longlong_cache = [FFI::MemoryPointer.new(:int64), length]
end
@longlong_cache
elsif 0 == option_type
# int, Crossroads assumes int is 4-bytes
unless @int_cache
length = FFI::MemoryPointer.new :size_t
length.write_int 4
@int_cache = [FFI::MemoryPointer.new(:int32), length]
end
@int_cache
elsif 2 == option_type
length = FFI::MemoryPointer.new :size_t
# could be a string of up to 255 bytes
length.write_int 255
[FFI::MemoryPointer.new(255), length]
else
# uh oh, someone passed in an unknown option; use a slop buffer
unless @int_cache
length = FFI::MemoryPointer.new :size_t
length.write_int 4
@int_cache = [FFI::MemoryPointer.new(:int32), length]
end
@int_cache
end
end | ruby | {
"resource": ""
} |
q8742 | XS.Socket.getsockopt | train | def getsockopt name, array
rc = __getsockopt__ name, array
if Util.resultcode_ok?(rc) && (RCVMORE == name)
# convert to boolean
array[0] = 1 == array[0]
end
rc
end | ruby | {
"resource": ""
} |
q8743 | Roles::Generic::User.Implementation.role= | train | def role= role
raise ArgumentError, '#add_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array)
self.roles = role
end | ruby | {
"resource": ""
} |
q8744 | Roles::Generic::User.Implementation.add_role | train | def add_role role
raise ArgumentError, '#add_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array)
add_roles role
end | ruby | {
"resource": ""
} |
q8745 | Roles::Generic::User.Implementation.remove_role | train | def remove_role role
raise ArgumentError, '#remove_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array)
remove_roles role
end | ruby | {
"resource": ""
} |
q8746 | Handlebarer.Compiler.v8_context | train | def v8_context
V8::C::Locker() do
context = V8::Context.new
context.eval(source)
yield context
end
end | ruby | {
"resource": ""
} |
q8747 | Handlebarer.Compiler.compile | train | def compile(template)
v8_context do |context|
template = template.read if template.respond_to?(:read)
compiled_handlebars = context.eval("Handlebars.precompile(#{template.to_json})")
"Handlebars.template(#{compiled_handlebars});"
end
end | ruby | {
"resource": ""
} |
q8748 | Handlebarer.Compiler.render | train | def render(template, vars = {})
v8_context do |context|
unless Handlebarer.configuration.nil?
helpers = handlebars_helpers
context.eval(helpers.join("\n")) if helpers.any?
end
context.eval("var fn = Handlebars.compile(#{template.to_json})")
context.eval("fn(#{vars.to_hbs.to_json})")
end
end | ruby | {
"resource": ""
} |
q8749 | SengiriYaml.Writer.divide | train | def divide(src_file, dst_dir)
FileUtils.mkdir_p(dst_dir) unless File.exist?(dst_dir)
src_content = YAML.load_file(src_file)
filenames = []
case src_content
when Hash
src_content.each do |key, value|
filename = "#{dst_dir}/#{key}.yml"
File.open(filename, "wb") do |f|
f.write({key => value}.to_yaml)
end
filenames << filename
end
when Array
src_content.each_with_index do |element, index|
filename = "#{dst_dir}/#{index}.yml"
File.open(filename, "wb") do |f|
f.write([element].to_yaml)
end
filenames << filename
end
else
raise "Unknown type"
end
filenames
end | ruby | {
"resource": ""
} |
q8750 | DCI.Context.players_unplay_role! | train | def players_unplay_role!(extending_ticker)
roles.keys.each do |rolekey|
::DCI::Multiplayer(@_players[rolekey]).each do |roleplayer|
# puts " Context: #{self} - un-assigning role #{rolekey} to #{roleplayer}"
roleplayer.__unplay_last_role! if extending_ticker["#{roleplayer.object_id}_#{rolekey}"]
end
# 'instance_variable_set(:"@#{rolekey}", nil)
end
end | ruby | {
"resource": ""
} |
q8751 | Ichiban.Watcher.on_change | train | def on_change(modified, added, deleted)
# Modifications and additions are treated the same.
(modified + added).uniq.each do |path|
if file = Ichiban::ProjectFile.from_abs(path)
begin
@loader.change(file) # Tell the Loader that this file has changed
file.update
rescue Exception => exc
Ichiban.logger.exception(exc)
end
end
end
# Deletions are handled specially.
deleted.each do |path|
Ichiban::Deleter.new.delete_dest(path)
end
# Finally, propagate this change to any dependent files.
(modified + added + deleted).uniq.each do |path|
begin
Ichiban::Dependencies.propagate(path)
rescue => exc
Ichiban.logger.exception(exc)
end
end
end | ruby | {
"resource": ""
} |
q8752 | BrownPaperTickets.Event.all | train | def all
events = Event.get("/eventlist", :query =>{"id" => @@id , "account" => @@account })
event_sales = Event.get("/eventsales", :query =>{"id" => @@id , "account" => @@account })
parsed_event = []
events.parsed_response["document"]["event"].each do |event|
parsed_event << Event.new(@id,@account, event)
end
return parsed_event
end | ruby | {
"resource": ""
} |
q8753 | BrownPaperTickets.Event.find | train | def find(event_id)
event = Event.get("/eventlist",:query =>{"id" => @@id , "account" => @@account, "event_id" => event_id })
event_sales=Event.get("/eventsales",:query =>{"id" => @@id , "account" => @@account, "event_id" => event_id })
@attributes = event.parsed_response["document"]["event"]
return self
end | ruby | {
"resource": ""
} |
q8754 | Blocktrain.Lookups.init! | train | def init!
@lookups ||= {}
@aliases ||= {}
# Get unique list of keys from ES
r = Aggregations::TermsAggregation.new(from: '2015-09-01 00:00:00Z', to: '2015-09-02 00:00:00Z', term: "memoryAddress").results
addresses = r.map {|x| x["key"]}
# Get a memory location for each key
addresses.each do |address|
r = Query.new(from: '2015-09-01 10:00:00Z', to: '2015-09-30 11:00:00Z', memory_addresses: address, limit: 1).results
signal_name = remove_cruft(r.first["_source"]["signalName"].to_s)
@lookups[signal_name] = address
end
# Read aliases from file
aliases = OpenStruct.new fetch_yaml 'signal_aliases'
aliases.each_pair do |key, value|
@aliases[key.to_s] = @lookups[value]
@lookups[key.to_s] = @lookups[value]
end
end | ruby | {
"resource": ""
} |
q8755 | Blocktrain.Lookups.remove_cruft | train | def remove_cruft(signal)
parts = signal.split(".")
[
parts[0..-3].join('.'),
parts.pop
].join('.')
end | ruby | {
"resource": ""
} |
q8756 | ActiveCopy.ViewHelper.render_copy | train | def render_copy from_source_path
source_path = "#{ActiveCopy.content_path}/#{from_source_path}.md"
if File.exists? source_path
raw_source = IO.read source_path
source = raw_source.split("---\n")[2]
template = ActiveCopy::Markdown.new
template.render(source).html_safe
else
raise ArgumentError.new "#{source_path} does not exist."
end
end | ruby | {
"resource": ""
} |
q8757 | Capistrano.DSL.sudo! | train | def sudo!(*args)
on roles(:all) do |host|
key = "#{host.user}@#{host.hostname}"
SSHKit::Sudo.password_cache[key] = "#{fetch(:password)}\n" # \n is enter
end
sudo(*args)
end | ruby | {
"resource": ""
} |
q8758 | FakeService.Middleware.define_actions | train | def define_actions
unless @action_defined
hash = YAML.load(File.read(@file_path))
hash.each do |k, v|
v.each do |key, value|
@app.class.define_action!(value["request"], value["response"])
end
end
@action_defined = true
end
end | ruby | {
"resource": ""
} |
q8759 | Insulin.Event.save | train | def save mongo_handle
# See above
date_collection = self["date"]
if self["time"] < @@cut_off_time
date_collection = (Time.parse(self["date"]) - 86400).strftime "%F"
end
# Save to each of these collections
clxns = [
"events",
self["type"],
self["subtype"],
date_collection
]
clxns.each do |c|
if c
mongo_handle.db.collection(c).update(
{
"serial" => self["serial"]
},
self,
{
# Upsert: update if exists, otherwise insert
:upsert => true
}
)
end
end
end | ruby | {
"resource": ""
} |
q8760 | ZTK.Logger.shift | train | def shift(severity, shift=0, &block)
severity = ZTK::Logger.const_get(severity.to_s.upcase)
add(severity, nil, nil, shift, &block)
end | ruby | {
"resource": ""
} |
q8761 | ZTK.Logger.add | train | def add(severity, message=nil, progname=nil, shift=0, &block)
return if (@level > severity)
message = block.call if message.nil? && block_given?
return if message.nil?
called_by = parse_caller(caller[1+shift])
message = [message.chomp, progname].flatten.compact.join(": ")
message = "%19s.%06d|%05d|%5s|%s%s\n" % [Time.now.utc.strftime("%Y-%m-%d|%H:%M:%S"), Time.now.utc.usec, Process.pid, SEVERITIES[severity], called_by, message]
@logdev.write(ZTK::ANSI.uncolor(message))
@logdev.respond_to?(:flush) and @logdev.flush
true
end | ruby | {
"resource": ""
} |
q8762 | ZTK.Logger.set_log_level | train | def set_log_level(level=nil)
defined?(Rails) and (default = (Rails.env.production? ? "INFO" : "DEBUG")) or (default = "INFO")
log_level = (ENV['LOG_LEVEL'] || level || default)
self.level = ZTK::Logger.const_get(log_level.to_s.upcase)
end | ruby | {
"resource": ""
} |
q8763 | Redstruct.List.pop | train | def pop(size = 1, timeout: nil)
raise ArgumentError, 'size must be positive' unless size.positive?
if timeout.nil?
return self.connection.rpop(@key) if size == 1
return shift_pop_script(keys: @key, argv: [-size, -1, 1])
else
raise ArgumentError, 'timeout is only supported if size == 1' unless size == 1
return self.connection.brpop(@key, timeout: timeout)&.last
end
end | ruby | {
"resource": ""
} |
q8764 | Redstruct.List.shift | train | def shift(size = 1, timeout: nil)
raise ArgumentError, 'size must be positive' unless size.positive?
if timeout.nil?
return self.connection.lpop(@key) if size == 1
return shift_pop_script(keys: @key, argv: [0, size - 1, 0])
else
raise ArgumentError, 'timeout is only supported if size == 1' unless size == 1
return self.connection.blpop(@key, timeout: timeout)&.last
end
end | ruby | {
"resource": ""
} |
q8765 | Redstruct.List.popshift | train | def popshift(list, timeout: nil)
raise ArgumentError, 'list must respond to #key' unless list.respond_to?(:key)
if timeout.nil?
return self.connection.rpoplpush(@key, list.key)
else
return self.connection.brpoplpush(@key, list.key, timeout: timeout)
end
end | ruby | {
"resource": ""
} |
q8766 | EZMQ.Socket.connect | train | def connect(transport: :tcp, address: '127.0.0.1', port: 5555)
endpoint = "#{ transport }://#{ address }"
endpoint << ":#{ port }" if %i(tcp pgm epgm).include? transport
@socket.method(__callee__).call(endpoint) == 0
end | ruby | {
"resource": ""
} |
q8767 | MultiOpQueue.Queue.pop | train | def pop(non_block=false)
handle_interrupt do
@mutex.synchronize do
while true
if @que.empty?
if non_block
raise ThreadError, "queue empty"
else
begin
@num_waiting += 1
@cond.wait @mutex
ensure
@num_waiting -= 1
end
end
else
return @que.shift
end
end
end
end
end | ruby | {
"resource": ""
} |
q8768 | MultiOpQueue.Queue.pop_up_to | train | def pop_up_to(num_to_pop = 1, opts = {})
case opts
when TrueClass, FalseClass
non_bock = opts
when Hash
timeout = opts.fetch(:timeout, nil)
non_block = opts.fetch(:non_block, false)
end
handle_interrupt do
@mutex.synchronize do
while true
if @que.empty?
if non_block
raise ThreadError, "queue empty"
else
begin
@num_waiting += 1
@cond.wait(@mutex, timeout)
return nil if @que.empty?
ensure
@num_waiting -= 1
end
end
else
return @que.shift(num_to_pop)
end
end
end
end
end | ruby | {
"resource": ""
} |
q8769 | Confo.OptionsManager.raw_get | train | def raw_get(option)
value = options_storage[option]
Confo.callable_without_arguments?(value) ? value.call : value
end | ruby | {
"resource": ""
} |
q8770 | Confo.OptionsManager.public_set | train | def public_set(option, value)
# TODO Prevent subconfigs here
method = "#{option}="
respond_to?(method) ? send(method, value) : raw_set(option, value)
end | ruby | {
"resource": ""
} |
q8771 | Confo.OptionsManager.set? | train | def set?(arg, *rest_args)
if arg.kind_of?(Hash)
arg.each { |k, v| set(k, v) unless set?(k) }
nil
elsif rest_args.size > 0
set(arg, rest_args.first) unless set?(arg)
true
else
options_storage.has_key?(arg)
end
end | ruby | {
"resource": ""
} |
q8772 | PageParts.Extension.find_or_build_page_part | train | def find_or_build_page_part(attr_name)
key = normalize_page_part_key(attr_name)
page_parts.detect { |record| record.key.to_s == key } || page_parts.build(key: key)
end | ruby | {
"resource": ""
} |
q8773 | IMDB.Movie.poster | train | def poster
src = doc.at("#img_primary img")["src"] rescue nil
unless src.nil?
if src.match(/\._V1/)
return src.match(/(.*)\._V1.*(.jpg)/)[1, 2].join
else
return src
end
end
src
end | ruby | {
"resource": ""
} |
q8774 | IMDB.Movie.title | train | def title
doc.at("//head/meta[@name='title']")["content"].split(/\(.*\)/)[0].strip! ||
doc.at("h1.header").children.first.text.strip
end | ruby | {
"resource": ""
} |
q8775 | IMDB.Movie.director_person | train | def director_person
begin
link=doc.xpath("//h4[contains(., 'Director')]/..").at('a[@href^="/name/nm"]')
profile = link['href'].match(/\/name\/nm([0-9]+)/)[1] rescue nil
IMDB::Person.new(profile) unless profile.nil?
rescue
nil
end
end | ruby | {
"resource": ""
} |
q8776 | CiscoMSE.Stub.stub! | train | def stub!
CiscoMSE::Endpoints::Location.any_instance.stub(:clients).and_return( Stub::Data::Location::CLIENTS )
end | ruby | {
"resource": ""
} |
q8777 | LatoBlog.Interface::Posts.blog__clean_post_parents | train | def blog__clean_post_parents
post_parents = LatoBlog::PostParent.all
post_parents.map { |pp| pp.destroy if pp.posts.empty? }
end | ruby | {
"resource": ""
} |
q8778 | LatoBlog.Interface::Posts.blog__get_posts | train | def blog__get_posts(
order: nil,
language: nil,
category_permalink: nil,
category_permalink_AND: false,
category_id: nil,
category_id_AND: false,
tag_permalink: nil,
tag_permalink_AND: false,
tag_id: nil,
tag_id_AND: false,
search: nil,
page: nil,
per_page: nil
)
posts = LatoBlog::Post.published.joins(:post_parent).where('lato_blog_post_parents.publication_datetime <= ?', DateTime.now)
# apply filters
order = order && order == 'ASC' ? 'ASC' : 'DESC'
posts = _posts_filter_by_order(posts, order)
posts = _posts_filter_by_language(posts, language)
if category_permalink || category_id
posts = posts.joins(:categories)
posts = _posts_filter_by_category_permalink(posts, category_permalink, category_permalink_AND)
posts = _posts_filter_category_id(posts, category_id, category_id_AND)
end
if tag_permalink || tag_id
posts = posts.joins(:tags)
posts = _posts_filter_by_tag_permalink(posts, tag_permalink, tag_permalink_AND)
posts = _posts_filter_tag_id(posts, tag_id, tag_id_AND)
end
posts = _posts_filter_search(posts, search)
# take posts uniqueness
posts = posts.uniq(&:id)
# save total posts
total = posts.length
# manage pagination
page = page&.to_i || 1
per_page = per_page&.to_i || 20
posts = core__paginate_array(posts, per_page, page)
# return result
{
posts: posts && !posts.empty? ? posts.map(&:serialize) : [],
page: page,
per_page: per_page,
order: order,
total: total
}
end | ruby | {
"resource": ""
} |
q8779 | LatoBlog.Interface::Posts.blog__get_post | train | def blog__get_post(id: nil, permalink: nil)
return {} unless id || permalink
if id
post = LatoBlog::Post.find_by(id: id.to_i, meta_status: 'published')
else
post = LatoBlog::Post.find_by(meta_permalink: permalink, meta_status: 'published')
end
post.serialize
end | ruby | {
"resource": ""
} |
q8780 | Trahald.RedisClient.commit! | train | def commit!(message)
date = Time.now
@status_add.each{|name, body|
json = Article.new(name, body, date).to_json
zcard = @redis.zcard name
@redis.zadd name, zcard+1, json
@redis.sadd KEY_SET, name
@summary_redis.update MarkdownBody.new(name, body, date).summary
}
@remove_add.each{|name, latest_rank|
@redis.zremrange(name, 0, latest_rank)
}
@redis.set MODIFIED_DATE, date.to_s
end | ruby | {
"resource": ""
} |
q8781 | Slack.Request.make_query_string | train | def make_query_string(params)
clean_params(params).collect do |k, v|
CGI.escape(k) + '=' + CGI.escape(v)
end.join('&')
end | ruby | {
"resource": ""
} |
q8782 | Slack.Request.do_http | train | def do_http(uri, request)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
# Let then know about us
request['User-Agent'] = 'SlackRubyAPIWrapper'
begin
http.request(request)
rescue OpenSSL::SSL::SSLError => e
raise Slack::Error, 'SSL error connecting to Slack.'
end
end | ruby | {
"resource": ""
} |
q8783 | ESS.ESS.find_coming | train | def find_coming n=10, start_time=nil
start_time = Time.now if start_time.nil?
feeds = []
channel.feed_list.each do |feed|
feed.dates.item_list.each do |item|
if item.type_attr == "standalone"
feeds << { :time => Time.parse(item.start.text!), :feed => feed }
elsif item.type_attr == "recurrent"
moments = parse_recurrent_date_item(item, n, start_time)
moments.each do |moment|
feeds << { :time => moment, :feed => feed }
end
elsif item.type_attr == "permanent"
start = Time.parse(item.start.text!)
if start > start_time
feeds << { :time => start, :feed => feed }
else
feeds << { :time => start_time, :feed => feed }
end
else
raise DTD::InvalidValueError, "the \"#{item.type_attr}\" is not valid for a date item type attribute"
end
end
end
feeds = feeds.delete_if { |x| x[:time] < start_time }
feeds.sort! { |x, y| x[:time] <=> y[:time] }
return feeds[0..n-1]
end | ruby | {
"resource": ""
} |
q8784 | ESS.ESS.find_between | train | def find_between start_time, end_time
feeds = []
channel.feed_list.each do |feed|
feed.dates.item_list.each do |item|
if item.type_attr == "standalone"
feed_start_time = Time.parse(item.start.text!)
if feed_start_time.between?(start_time, end_time)
feeds << { :time => feed_start_time, :feed => feed }
end
elsif item.type_attr == "recurrent"
moments = parse_recurrent_date_item(item, end_time, start_time)
moments.each do |moment|
if moment.between?(start_time, end_time)
feeds << { :time => moment, :feed => feed }
end
end
elsif item.type_attr == "permanent"
start = Time.parse(item.start.text!)
unless start > end_time
if start > start_time
feeds << { :time => start, :feed => feed }
else
feeds << { :time => start_time, :feed => feed }
end
end
else
raise DTD::InvalidValueError, "the \"#{item.type_attr}\" is not valid for a date item type attribute"
end
end
end
feeds.sort! { |x, y| x[:time] <=> y[:time] }
end | ruby | {
"resource": ""
} |
q8785 | FlexibleAccessibility.Filters.check_permission_to_route | train | def check_permission_to_route
route_provider = RouteProvider.new(self.class)
if route_provider.verifiable_routes_list.include?(current_action)
if logged_user.nil?
raise UserNotLoggedInException.new(current_route, nil)
end
is_permitted = AccessProvider.action_permitted_for_user?(
current_route, logged_user
)
is_permitted ? allow_route : deny_route
elsif route_provider.non_verifiable_routes_list.include?(current_action)
allow_route
else
deny_route
end
end | ruby | {
"resource": ""
} |
q8786 | Fetch.Base.fetch | train | def fetch
requests = instantiate_modules.select(&:fetch?).map(&:requests).flatten
total, done = requests.size, 0
update_progress(total, done)
before_fetch
backend.new(requests).run do
update_progress(total, done += 1)
end
after_fetch
true
rescue => e
error(e)
raise e
end | ruby | {
"resource": ""
} |
q8787 | Fetch.Base.instantiate_modules | train | def instantiate_modules
mods = Array(modules)
mods = load!(mods) if callback?(:load)
Array(mods).map do |klass|
init!(klass) || klass.new(fetchable)
end
end | ruby | {
"resource": ""
} |
q8788 | Fetch.Base.update_progress | train | def update_progress(total, done)
percentage = total.zero? ? 100 : ((done.to_f / total) * 100).to_i
progress(percentage)
end | ruby | {
"resource": ""
} |
q8789 | KalturaFu.Session.generate_session_key | train | def generate_session_key
self.check_for_client_session
raise "Missing Administrator Secret" unless KalturaFu.config.administrator_secret
@@session_key = @@client.session_service.start(KalturaFu.config.administrator_secret,'',Kaltura::Constants::SessionType::ADMIN)
@@client.ks = @@session_key
rescue Kaltura::APIError => e
puts e.message
end | ruby | {
"resource": ""
} |
q8790 | OxMlk.Attr.from_xml | train | def from_xml(data)
procs.inject(XML::Node.from(data)[tag]) {|d,p| p.call(d) rescue d}
end | ruby | {
"resource": ""
} |
q8791 | Bini.OptionParser.mash | train | def mash(h)
h.merge! @options
@options.clear
h.each {|k,v| self[k] = v}
end | ruby | {
"resource": ""
} |
q8792 | ContentDriven.Routes.content_for | train | def content_for route
parts = route.split("/").delete_if &:empty?
content = parts.inject(self) do |page, part|
page.children[part.to_sym] if page
end
content
end | ruby | {
"resource": ""
} |
q8793 | Checkdin.WonRewards.won_rewards | train | def won_rewards(options={})
response = connection.get do |req|
req.url "won_rewards", options
end
return_error_or_body(response)
end | ruby | {
"resource": ""
} |
q8794 | Octo.Authorization.generate_password | train | def generate_password
if(self.password.nil?)
self.password = Digest::SHA1.hexdigest(self.username + self.enterprise_id)
else
self.password = Digest::SHA1.hexdigest(self.password + self.enterprise_id)
end
end | ruby | {
"resource": ""
} |
q8795 | Octo.Authorization.kong_requests | train | def kong_requests
kong_config = Octo.get_config :kong
if kong_config[:enabled]
url = '/consumers/'
payload = {
username: self.username,
custom_id: self.enterprise_id
}
process_kong_request(url, :PUT, payload)
create_keyauth( self.username, self.apikey)
end
end | ruby | {
"resource": ""
} |
q8796 | NsOptions::Proxy.ProxyMethods.option | train | def option(name, *args, &block)
__proxy_options__.option(name, *args, &block)
NsOptions::ProxyMethod.new(self, name, 'an option').define($stdout, caller)
end | ruby | {
"resource": ""
} |
q8797 | NsOptions::Proxy.ProxyMethods.method_missing | train | def method_missing(meth, *args, &block)
if (po = __proxy_options__) && po.respond_to?(meth.to_s)
po.send(meth.to_s, *args, &block)
else
super
end
end | ruby | {
"resource": ""
} |
q8798 | Sequoia.Configurable.configure | train | def configure(env=:default, &block)
environment = config_attributes[env.to_sym]
Builder.new(environment, &block)
end | ruby | {
"resource": ""
} |
q8799 | Sequoia.Configurable.build_configuration | train | def build_configuration(env=nil)
result = config_attributes[:default]
result.deep_merge!(config_attributes[env.to_sym]) if env
Entity.create(result)
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.