_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q24700 | RWebSpec.Driver.attach_browser | train | def attach_browser(how, what, options = {})
options.merge!(:browser => is_firefox? ? "Firefox" : "IE") unless options[:browser]
begin
options.merge!(:base_url => browser.context.base_url)
rescue => e
puts "failed to set base_url, ignore : #{e}"
end
WebBrowser.attach_browser(how, what, options)
end | ruby | {
"resource": ""
} |
q24701 | RWebSpec.Driver.enter_text_with_id | train | def enter_text_with_id(textfield_id, value, opts = {})
# For IE10, it seems unable to identify HTML5 elements
#
# However for IE10, the '.' is omitted.
if opts.nil? || opts.empty?
# for Watir, default is clear
opts[:appending] = false
end
perform_operation {
begin
text_field(:id, textfield_id).set(value)
rescue => e
# However, this approach is not reliable with Watir (IE)
# for example, for entering email, the dot cannot be entered, try ["a@b", :decimal, "com"]
the_elem = element(:xpath, "//input[@id='#{textfield_id}']")
the_elem.send_keys(:clear) unless opts[:appending]
the_elem.send_keys(value)
end
}
end | ruby | {
"resource": ""
} |
q24702 | RWebSpec.Driver.absolutize_page | train | def absolutize_page(content, base_url, current_url_parent)
modified_content = ""
content.each_line do |line|
if line =~ /<script\s+.*src=["'']?(.*)["'].*/i then
script_src = $1
substitute_relative_path_in_src_line(line, script_src, base_url, current_url_parent)
elsif line =~ /<link\s+.*href=["'']?(.*)["'].*/i then
link_href = $1
substitute_relative_path_in_src_line(line, link_href, base_url, current_url_parent)
elsif line =~ /<img\s+.*src=["'']?(.*)["'].*/i then
img_src = $1
substitute_relative_path_in_src_line(line, img_src, base_url, current_url_parent)
end
modified_content += line
end
return modified_content
end | ruby | {
"resource": ""
} |
q24703 | RWebSpec.Driver.absolutize_page_hpricot | train | def absolutize_page_hpricot(content, base_url, parent_url)
return absolutize_page(content, base_url, parent_url) if RUBY_PLATFORM == 'java'
begin
require 'hpricot'
doc = Hpricot(content)
base_url.slice!(-1) if ends_with?(base_url, "/")
(doc/'link').each { |e| e['href'] = absolutify_url(e['href'], base_url, parent_url) || "" }
(doc/'img').each { |e| e['src'] = absolutify_url(e['src'], base_url, parent_url) || "" }
(doc/'script').each { |e| e['src'] = absolutify_url(e['src'], base_url, parent_url) || "" }
return doc.to_html
rescue => e
absolutize_page(content, base_url, parent_url)
end
end | ruby | {
"resource": ""
} |
q24704 | RWebSpec.Driver.wait_for_element | train | def wait_for_element(element_id, timeout = $testwise_polling_timeout, interval = $testwise_polling_interval)
start_time = Time.now
#TODO might not work with Firefox
until @web_browser.element_by_id(element_id) do
sleep(interval)
if (Time.now - start_time) > timeout
raise RuntimeError, "failed to find element: #{element_id} for max #{timeout}"
end
end
end | ruby | {
"resource": ""
} |
q24705 | RWebSpec.Driver.clear_popup | train | def clear_popup(popup_win_title, seconds = 10, yes = true)
# commonly "Security Alert", "Security Information"
if is_windows?
sleep 1
autoit = WIN32OLE.new('AutoItX3.Control')
# Look for window with given title. Give up after 1 second.
ret = autoit.WinWait(popup_win_title, '', seconds)
#
# If window found, send appropriate keystroke (e.g. {enter}, {Y}, {N}).
if ret == 1 then
puts "about to send click Yes" if debugging?
button_id = yes ? "Button1" : "Button2" # Yes or No
autoit.ControlClick(popup_win_title, '', button_id)
end
sleep(0.5)
else
raise "Currently supported only on Windows"
end
end | ruby | {
"resource": ""
} |
q24706 | RWebSpec.Driver.basic_authentication_ie | train | def basic_authentication_ie(title, username, password, options = {})
default_options = {:textctrl_username => "Edit2",
:textctrl_password => "Edit3",
:button_ok => 'Button1'
}
options = default_options.merge(options)
title ||= ""
if title =~ /^Connect\sto/
full_title = title
else
full_title = "Connect to #{title}"
end
require 'rformspec'
login_win = RFormSpec::Window.new(full_title)
login_win.send_control_text(options[:textctrl_username], username)
login_win.send_control_text(options[:textctrl_password], password)
login_win.click_button("OK")
end | ruby | {
"resource": ""
} |
q24707 | MetaPresenter.Helpers.presenter | train | def presenter
@presenter ||= begin
controller = self
klass = MetaPresenter::Builder.new(controller, action_name).presenter_class
klass.new(controller)
end
end | ruby | {
"resource": ""
} |
q24708 | DataSift.AccountIdentityToken.create | train | def create(identity_id = '', service = '', token = '')
fail BadParametersError, 'identity_id is required' if identity_id.empty?
fail BadParametersError, 'service is required' if service.empty?
fail BadParametersError, 'token is required' if token.empty?
params = {
service: service,
token: token
}
DataSift.request(:POST, "account/identity/#{identity_id}/token", @config, params)
end | ruby | {
"resource": ""
} |
q24709 | DataSift.AccountIdentityToken.list | train | def list(identity_id = '', per_page = '', page = '')
params = { identity_id: identity_id }
requires params
params.merge!(per_page: per_page) unless per_page.empty?
params.merge!(page: page) unless page.empty?
DataSift.request(:GET, "account/identity/#{identity_id}/token", @config, params)
end | ruby | {
"resource": ""
} |
q24710 | BuildrIzPack.Pack.emitIzPackXML | train | def emitIzPackXML(xm)
# raise "xm must be an Builder::XmlMarkup object, but is #{xm.class}" if xm.class != Builder::XmlMarkup
xm.pack(@attributes) {
xm.description(@description)
@files.each{ |src, dest| xm.singlefile('src'=> src, 'target' =>dest) }
}
end | ruby | {
"resource": ""
} |
q24711 | BuildrIzPack.IzPackTask.create_from | train | def create_from(file_map)
@izpackVersion ||= '4.3.5'
@appName ||= project.id
@izpackBaseDir = File.dirname(@output) if !@izpackBaseDir
@installerType ||= 'standard'
@inheritAll ||= 'true'
@compression ||= 'deflate'
@compressionLevel ||= '9'
@locales ||= ['eng']
@panels ||= ['TargetPanel', 'InstallPanel']
@packs ||=
raise "You must include at least one file to create an izPack installer" if file_map.size == 0 and !File.exists?(@input)
izPackArtifact = Buildr.artifact( "org.codehaus.izpack:izpack-standalone-compiler:jar:#{@izpackVersion}")
doc = nil
if !File.exists?(@input)
genInstaller(Builder::XmlMarkup.new(:target=>File.open(@input, 'w+'), :indent => 2), file_map)
# genInstaller(Builder::XmlMarkup.new(:target=>$stdout, :indent => 2), file_map)
# genInstaller(Builder::XmlMarkup.new(:target=>File.open('/home/niklaus/tmp2.xml', 'w+'), :indent => 2), file_map)
end
Buildr.ant('izpack-ant') do |x|
izPackArtifact.invoke
msg = "Generating izpack aus #{File.expand_path(@input)}"
trace msg
if properties
properties.each{ |name, value|
puts "Need added property #{name} with value #{value}"
x.property(:name => name, :value => value)
}
end
x.echo(:message =>msg)
x.taskdef :name=>'izpack',
:classname=>'com.izforge.izpack.ant.IzPackTask',
:classpath=>izPackArtifact.to_s
x.izpack :input=> @input,
:output => @output,
:basedir => @izpackBaseDir,
:installerType=> @installerType,
:inheritAll=> @inheritAll,
:compression => @compression,
:compressionLevel => @compressionLevel do
end
end
end | ruby | {
"resource": ""
} |
q24712 | Tenon.ApplicationHelper.first_image | train | def first_image(obj, options = {})
opts = {
collection: :images,
method: :image,
style: :thumbnail,
default: image_path('noimage.jpg')
}.merge(options.symbolize_keys!)
image = obj.send(opts[:collection]).first
image ? image.send(opts[:method]).url(opts[:style]) : opts[:default]
end | ruby | {
"resource": ""
} |
q24713 | Tenon.ApplicationHelper.human | train | def human(object)
if object.is_a?(Date)
object.strftime('%B %d, %Y')
elsif object.is_a?(Time)
object.strftime('%B %d, %Y at %I:%M %p')
elsif object.is_a?(String)
object.humanize
else
object
end
end | ruby | {
"resource": ""
} |
q24714 | TeaLeaves.ExponentialSmoothingForecast.mean_squared_error | train | def mean_squared_error
return @mean_squared_error if @mean_squared_error
numerator = errors.drop(@seasonality_strategy.start_index).map {|i| i ** 2 }.inject(&:+)
@mean_squared_error = numerator / (errors.size - @seasonality_strategy.start_index).to_f
end | ruby | {
"resource": ""
} |
q24715 | DataSift.ManagedSourceResource.add | train | def add(id, resources, validate = 'true')
params = {
id: id,
resources: resources,
validate: validate
}
requires params
DataSift.request(:PUT, 'source/resource/add', @config, params)
end | ruby | {
"resource": ""
} |
q24716 | DataSift.ManagedSourceResource.remove | train | def remove(id, resource_ids)
params = {
id: id,
resource_ids: resource_ids
}
requires params
DataSift.request(:PUT, 'source/resource/remove', @config, params)
end | ruby | {
"resource": ""
} |
q24717 | DataSift.ManagedSourceAuth.add | train | def add(id, auth, validate = 'true')
params = {
id: id,
auth: auth,
validate: validate
}
requires params
DataSift.request(:PUT, 'source/auth/add', @config, params)
end | ruby | {
"resource": ""
} |
q24718 | DataSift.ManagedSourceAuth.remove | train | def remove(id, auth_ids)
params = {
id: id,
auth_ids: auth_ids
}
requires params
DataSift.request(:PUT, 'source/auth/remove', @config, params)
end | ruby | {
"resource": ""
} |
q24719 | MediaWiki.Auth.login | train | def login(username, password)
# Save the assertion value while trying to log in, because otherwise the assertion will prevent us from logging in
assertion_value = @assertion.clone
@assertion = nil
params = {
action: 'login',
lgname: username,
lgpassword: password,
lgtoken: get_token('login')
}
response = post(params)
@assertion = assertion_value
result = response['login']['result']
if result == 'Success'
@name = response['login']['lgusername']
@logged_in = true
return true
end
raise MediaWiki::Butt::AuthenticationError.new(result)
end | ruby | {
"resource": ""
} |
q24720 | MediaWiki.Auth.create_account | train | def create_account(username, password, language = 'en', reason = nil)
params = {
name: username,
password: password,
language: language,
token: get_token('createaccount')
}
params[:reason] = reason unless reason.nil?
result = post(params)
unless result['error'].nil?
raise MediaWiki::Butt::AuthenticationError.new(result['error']['code'])
end
result['createaccount']['result'] == 'Success'
end | ruby | {
"resource": ""
} |
q24721 | MediaWiki.Auth.create_account_email | train | def create_account_email(username, email, language = 'en', reason = nil)
params = {
name: username,
email: email,
mailpassword: 'value',
language: language,
token: get_token('createaccount')
}
params[:reason] = reason unless reason.nil?
result = post(params)
unless result['error'].nil?
raise MediaWiki::Butt::AuthenticationError.new(result['error']['code'])
end
result['createaccount']['result'] == 'Success'
end | ruby | {
"resource": ""
} |
q24722 | RWebSpec.Driver.save_current_page | train | def save_current_page(options = {})
default_options = {:replacement => true}
options = default_options.merge(options)
to_dir = options[:dir] || default_dump_dir
if options[:filename]
file_name = options[:filename]
else
file_name = Time.now.strftime("%m%d%H%M%S") + ".html"
end
Dir.mkdir(to_dir) unless File.exists?(to_dir)
file = File.join(to_dir, file_name)
content = page_source
base_url = @web_browser.context.base_url
current_url = @web_browser.url
current_url =~ /(.*\/).*$/
current_url_parent = $1
if options[:replacement] && base_url =~ /^http:/
File.new(file, "w").puts absolutize_page_hpricot(content, base_url, current_url_parent)
else
File.new(file, "w").puts content
end
end | ruby | {
"resource": ""
} |
q24723 | RWebSpec.Driver.wait_until | train | def wait_until(timeout = $testwise_polling_timeout || 30, polling_interval = $testwise_polling_interval || 1, & block)
end_time = ::Time.now + timeout
until ::Time.now > end_time
result = nil
begin
result = yield(self)
return result if result
rescue => e
end
sleep polling_interval
end
raise TimeoutError, "timed out after #{timeout} seconds"
end | ruby | {
"resource": ""
} |
q24724 | MediaWiki.Administration.block | train | def block(user, expiry = '2 weeks', reason = nil, nocreate = true)
params = {
action: 'block',
user: user,
expiry: expiry
}
token = get_token
params[:reason] = reason if reason
params[:nocreate] = '1' if nocreate
params[:token] = token
response = post(params)
if response.key?('error')
raise MediaWiki::Butt::BlockError.new(response.dig('error', 'code') || 'Unknown error code')
end
response['id'].to_i
end | ruby | {
"resource": ""
} |
q24725 | MediaWiki.Administration.unblock | train | def unblock(user, reason = nil)
params = {
action: 'unblock',
user: user
}
token = get_token
params[:reason] = reason if reason
params[:token] = token
response = post(params)
if response.key?('error')
raise MediaWiki::Butt::BlockError.new(response.dig('error', 'code') || 'Unknown error code')
end
response['id'].to_i
end | ruby | {
"resource": ""
} |
q24726 | Argos.Ds.parse_message | train | def parse_message(contact)
header = contact[0]
body = contact[1,contact.count]
items = process_item_body(body)
combine_header_with_transmission(items, header)
end | ruby | {
"resource": ""
} |
q24727 | Argos.Ds.merge | train | def merge(ds, measurement, cardinality)
m = ds.select {|k,v| k != :measurements and k != :errors and k != :warn }
m = m.merge(measurement)
m = m.merge ({ technology: "argos",
type: type,
cardinality: cardinality
#file: "file://"+filename,
#source: sha1
})
# if not ds[:errors].nil? and ds[:errors].any?
# m[:errors] = ds[:errors].clone
# end
#
# if not ds[:warn].nil? and ds[:warn].any?
# m[:warn] = ds[:warn].clone
# end
#
# if not m[:sensor_data].nil? and m[:sensor_data].size != ds[:sensors]
# if m[:warn].nil?
# m[:warn] = []
# end
# m[:warn] << "sensors-count-mismatch"
# end
# Create id as SHA1 hash of measurement minus stuff that may vary (like filename)
#
# Possible improvement for is to base id on a static list of keys
# :program,
# :platform,
# :lines,
# :sensors,
# :satellite,
# :lc,
# :positioned,
# :latitude,
# :longitude,
# :altitude,
# :headers,
# :measured,
# :identical,
# :sensor_data,
# :technology,
# :type,
# :source
idbase = m.clone
idbase.delete :errors
idbase.delete :file
idbase.delete :warn
id = Digest::SHA1.hexdigest(idbase.to_json)
#m[:parser] = Argos.library_version
m[:id] = id
#m[:bundle] = bundle
m
end | ruby | {
"resource": ""
} |
q24728 | DataSift.AccountIdentityLimit.create | train | def create(identity_id = '', service = '', total_allowance = nil, analyze_queries = nil)
fail BadParametersError, 'identity_id is required' if identity_id.empty?
fail BadParametersError, 'service is required' if service.empty?
fail BadParametersError, 'Must set total_allowance or analyze_queries' if
total_allowance.nil? && analyze_queries.nil?
params = { service: service }
params[:total_allowance] = total_allowance unless total_allowance.nil?
params[:analyze_queries] = analyze_queries unless analyze_queries.nil?
DataSift.request(:POST, "account/identity/#{identity_id}/limit", @config, params)
end | ruby | {
"resource": ""
} |
q24729 | DataSift.AccountIdentityLimit.get | train | def get(identity_id = '', service = '')
fail BadParametersError, 'identity_id is required' if identity_id.empty?
fail BadParametersError, 'service is required' if service.empty?
DataSift.request(:GET, "account/identity/#{identity_id}/limit/#{service}", @config)
end | ruby | {
"resource": ""
} |
q24730 | DataSift.AccountIdentityLimit.list | train | def list(service = '', per_page = '', page = '')
fail BadParametersError, 'service is required' if service.empty?
params = {}
params[:per_page] = per_page unless per_page.empty?
params[:page] = page unless page.empty?
DataSift.request(:GET, "account/identity/limit/#{service}", @config, params)
end | ruby | {
"resource": ""
} |
q24731 | DataSift.AccountIdentityLimit.delete | train | def delete(identity_id = '', service = '')
fail BadParametersError, 'identity_id is required' if identity_id.empty?
fail BadParametersError, 'service is required' if service.empty?
DataSift.request(:DELETE, "account/identity/#{identity_id}/limit/#{service}", @config)
end | ruby | {
"resource": ""
} |
q24732 | EcsCompose.JsonGenerator.generate | train | def generate
if @yaml.has_key?("version")
@yaml = @yaml.fetch("services")
end
# Generate JSON for our containers.
containers = @yaml.map do |name, fields|
# Skip this service if we've been given a list to emit, and
# this service isn't on the list.
begin
mount_points = (fields["volumes"] || []).map do |v|
host, container, ro = v.split(':')
{
"sourceVolume" => path_to_vol_name(host),
"containerPath" => container,
"readOnly" => (ro == "ro")
}
end
json = {
"name" => name,
"image" => fields.fetch("image"),
# Default to a tiny guaranteed CPU share. Currently, 2 is the
# smallest meaningful value, and various ECS tools will round
# smaller numbers up.
"cpu" => fields["cpu_shares"] || 2,
"memory" => mem_limit_to_mb(fields.fetch("mem_limit")),
"links" => fields["links"] || [],
"portMappings" =>
(fields["ports"] || []).map {|pm| port_mapping(pm) },
"essential" => true,
"environment" => environment(fields["environment"] || {}),
"mountPoints" => mount_points,
"volumesFrom" => [],
"dockerLabels" => fields.fetch("labels", {}),
}
if fields.has_key?("entrypoint")
json["entryPoint"] = command_line(fields.fetch("entrypoint"))
end
if fields.has_key?("command")
json["command"] = command_line(fields.fetch("command"))
end
if fields.has_key?("privileged")
json["privileged"] = fields.fetch("privileged")
end
if fields.has_key?("ulimits")
json["ulimits"] = fields.fetch("ulimits").map do |name, limits|
case limits
when Hash
softLimit = limits.fetch("soft")
hardLimit = limits.fetch("hard")
else
softLimit = limits
hardLimit = limits
end
{ "name" => name,
"softLimit" => softLimit,
"hardLimit" => hardLimit }
end
end
json
rescue KeyError => e
# This makes it a lot easier to localize errors a bit.
raise ContainerKeyError.new("#{e.message} processing container \"#{name}\"")
end
end
# Generate our top-level volume declarations.
volumes = @yaml.map do |name, fields|
(fields["volumes"] || []).map {|v| v.split(':')[0] }
end.flatten.sort.uniq.map do |host_path|
{
"name" => path_to_vol_name(host_path),
"host" => { "sourcePath" => host_path }
}
end
# Return our final JSON.
{
"family" => @family,
"containerDefinitions" => containers,
"volumes" => volumes
}
end | ruby | {
"resource": ""
} |
q24733 | EcsCompose.JsonGenerator.mem_limit_to_mb | train | def mem_limit_to_mb(mem_limit)
unless mem_limit.downcase =~ /\A(\d+)([bkmg])\z/
raise "Cannot parse docker memory limit: #{mem_limit}"
end
val = $1.to_i
case $2
when "b" then (val / (1024.0 * 1024.0)).ceil
when "k" then (val / 1024.0).ceil
when "m" then (val * 1.0).ceil
when "g" then (val * 1024.0).ceil
else raise "Can't convert #{mem_limit} to megabytes"
end
end | ruby | {
"resource": ""
} |
q24734 | EcsCompose.JsonGenerator.port_mapping | train | def port_mapping(port)
case port.to_s
when /\A(\d+)(?:\/([a-z]+))?\z/
port = $1.to_i
{
"hostPort" => port,
"containerPort" => port,
"protocol" => $2 || "tcp"
}
when /\A(\d+):(\d+)(?:\/([a-z]+))?\z/
{
"hostPort" => $1.to_i,
"containerPort" => $2.to_i,
"protocol" => $3 || "tcp"
}
else
raise "Cannot parse port specification: #{port}"
end
end | ruby | {
"resource": ""
} |
q24735 | SemiSemantic.VersionSegment.increment | train | def increment(index=-1)
value = @components[index]
raise TypeError.new "'#{value}' is not an integer" unless value.is_a? Integer
copy = Array.new @components
copy[index] = value + 1
while index < copy.size && index != -1
index += 1
value = copy[index]
if value.is_a? Integer
copy[index] = 0
end
end
self.class.new copy
end | ruby | {
"resource": ""
} |
q24736 | SemiSemantic.VersionSegment.decrement | train | def decrement(index=-1)
value = @components[index]
raise TypeError.new "'#{value}' is not an integer" unless value.is_a? Integer
raise RangeError.new "'#{value}' is zero or less" unless value > 0
copy = Array.new @components
copy[index] = value - 1
self.class.new copy
end | ruby | {
"resource": ""
} |
q24737 | SemiSemantic.VersionSegment.compare_arrays | train | def compare_arrays(a, b)
a.each_with_index do |v1, i|
v2 = b[i]
if v1.is_a?(String) && v2.is_a?(Integer)
return 1
elsif v1.is_a?(Integer) && v2.is_a?(String)
return -1
end
comparison = v1 <=> v2
unless comparison == 0
return comparison
end
end
0
end | ruby | {
"resource": ""
} |
q24738 | DataSift.ManagedSource.create | train | def create(source_type, name, parameters = {}, resources = [], auth = [], options = {})
fail BadParametersError, 'source_type and name are required' if source_type.nil? || name.nil?
params = {
:source_type => source_type,
:name => name
}
params.merge!(options) unless options.empty?
params.merge!(
{ :auth => auth.is_a?(String) ? auth : MultiJson.dump(auth) }
) unless auth.empty?
params.merge!(
{ :parameters => parameters.is_a?(String) ? parameters : MultiJson.dump(parameters) }
) unless parameters.empty?
params.merge!(
{ :resources => resources.is_a?(String) ? resources : MultiJson.dump(resources) }
) if resources.length > 0
DataSift.request(:POST, 'source/create', @config, params)
end | ruby | {
"resource": ""
} |
q24739 | DataSift.ManagedSource.update | train | def update(id, source_type, name, parameters = {}, resources = [], auth = [], options = {})
fail BadParametersError, 'ID, source_type and name are required' if id.nil? || source_type.nil? || name.nil?
params = {
:id => id,
:source_type => source_type,
:name => name
}
params.merge!(options) unless options.empty?
params.merge!({:auth => MultiJson.dump(auth)}) if !auth.empty?
params.merge!({:parameters => MultiJson.dump(parameters)}) if !parameters.empty?
params.merge!({:resources => MultiJson.dump(resources)}) if resources.length > 0
DataSift.request(:POST, 'source/update', @config, params)
end | ruby | {
"resource": ""
} |
q24740 | DataSift.ManagedSource.get | train | def get(id = nil, source_type = nil, page = 1, per_page = 20)
params = { :page => page, :per_page => per_page }
params.merge!({ :id => id }) if !id.nil?
params.merge!({ :source_type => source_type }) if !source_type.nil?
DataSift.request(:GET, 'source/get', @config, params)
end | ruby | {
"resource": ""
} |
q24741 | DataSift.ManagedSource.log | train | def log(id, page = 1, per_page = 20)
fail BadParametersError, 'ID is required' if id.nil?
DataSift.request(:POST, 'source/log', @config, { :id => id, :page => page, :per_page => per_page })
end | ruby | {
"resource": ""
} |
q24742 | Guard.Less.compile | train | def compile(lessfile, cssfile)
import_paths = options[:import_paths].unshift(File.dirname(lessfile))
parser = ::Less::Parser.new paths: import_paths, filename: lessfile
File.open(lessfile, 'r') do |infile|
File.open(cssfile, 'w') do |outfile|
tree = parser.parse(infile.read)
outfile << tree.to_css(compress: options[:compress], yuicompress: options[:yuicompress])
end
end
true
rescue StandardError => e
Compat::UI.info "Guard::Less: Compiling #{lessfile} failed with message: #{e.message}"
false
end | ruby | {
"resource": ""
} |
q24743 | DataSift.Pylon.tags | train | def tags(hash = '', id = '', service = 'facebook')
fail BadParametersError, 'hash or id is required' if hash.empty? && id.empty?
fail BadParametersError, 'service is required' if service.empty?
params = {}
params.merge!(hash: hash) unless hash.empty?
params.merge!(id: id) unless id.empty?
DataSift.request(:GET, build_path(service, 'pylon/tags', @config), @config, params)
end | ruby | {
"resource": ""
} |
q24744 | DataSift.Pylon.sample | train | def sample(hash = '', count = nil, start_time = nil, end_time = nil, filter = '', id = '', service = 'facebook')
fail BadParametersError, 'hash or id is required' if hash.empty? && id.empty?
fail BadParametersError, 'service is required' if service.empty?
params = {}
params.merge!(hash: hash) unless hash.empty?
params.merge!(id: id) unless id.empty?
params.merge!(count: count) unless count.nil?
params.merge!(start_time: start_time) unless start_time.nil?
params.merge!(end_time: end_time) unless end_time.nil?
if filter.empty?
DataSift.request(:GET, build_path(service, 'pylon/sample', @config), @config, params)
else
params.merge!(filter: filter)
DataSift.request(:POST, build_path(service, 'pylon/sample', @config), @config, params)
end
end | ruby | {
"resource": ""
} |
q24745 | DataSift.Pylon.reference | train | def reference(service:, slug: '', **opts)
params = {}
params[:per_page] = opts[:per_page] if opts.key?(:per_page)
params[:page] = opts[:page] if opts.key?(:page)
DataSift.request(:GET, "pylon/#{service}/reference/#{slug}", @config, params)
end | ruby | {
"resource": ""
} |
q24746 | TeaLeaves.Forecast.errors | train | def errors
@errors ||= @time_series.zip(one_step_ahead_forecasts).map do |(observation, forecast)|
forecast - observation if forecast && observation
end
end | ruby | {
"resource": ""
} |
q24747 | Tenon.TenonHelper.action_link | train | def action_link(title, link, icon, options = {})
icon_tag = content_tag(:i, '', class: "fa fa-#{icon} fa-fw")
default_options = { title: title, data: { tooltip: title } }
link_to icon_tag, link, default_options.deep_merge(options)
end | ruby | {
"resource": ""
} |
q24748 | Tenon.TenonHelper.toggle_link | train | def toggle_link(object, field, link, true_values, false_values)
state = object.send(field)
icon = state ? true_values[0] : false_values[0]
tooltip = state ? true_values[1] : false_values[1]
data = {
trueicon: true_values[0],
falseicon: false_values[0],
truetooltip: true_values[1],
falsetooltip: false_values[1]
}
action_link tooltip, link, icon, class: "toggle #{field} #{state}", data: data
end | ruby | {
"resource": ""
} |
q24749 | Tenon.TenonHelper.edit_link | train | def edit_link(obj, options = {})
if policy(obj).edit?
url = polymorphic_url([:edit] + Array(obj))
action_link('Edit', url, 'pencil', options)
end
end | ruby | {
"resource": ""
} |
q24750 | Tenon.TenonHelper.delete_link | train | def delete_link(obj, options = {})
if policy(obj).destroy?
default_options = { data: {
confirm: 'Are you sure? There is no undo for this!',
tooltip: 'Delete',
method: 'Delete',
remote: 'true'
} }
url = polymorphic_url(obj)
action_link('Delete', url, 'trash-o', default_options.deep_merge(options))
end
end | ruby | {
"resource": ""
} |
q24751 | Argos.Soap._call_xml_operation | train | def _call_xml_operation(op_sym, body, extract=nil)
@operation = _operation(op_sym)
@operation.body = body
@response = operation.call
# Check for http errors?
# Handle faults (before extracting data)
_envelope.xpath("soap:Body/soap:Fault", namespaces).each do | fault |
raise Exception, fault.to_s
end
# Extract data
if extract.respond_to?(:call)
@xml = extract.call(response)
else
@xml = response.raw
end
# Handle errors
ng = Nokogiri.XML(xml)
ng.xpath("/data/errors/error").each do | error |
if error.key?("code")
case error["code"].to_i
when 4
raise NodataException
end
#<error code="2">max response reached</error>
#<error code="3">authentification error</error>
#<error code="9">start date upper than end date</error>
else
raise Exception, error
end
end
# Validation - only :getXml
if [:getXml].include? op_sym
# Validation against getXSD schema does not work: ["Element 'data': No matching global declaration available for the validation root."]
# See https://github.com/npolar/argos-ruby/commit/219e4b3761e5265f8f9e8b924bcfc23607902428 for the fix
schema = Nokogiri::XML::Schema(File.read("#{__dir__}/_xsd/argos-data.xsd"))
v = schema.validate(ng)
if v.any?
log.debug "#{v.size} errors: #{v.map{|v|v.to_s}.uniq.to_json}"
end
end
# Convert XML to Hash
nori = Nori.new
nori.parse(xml)
end | ruby | {
"resource": ""
} |
q24752 | Argos.Soap._extract_motm | train | def _extract_motm
lambda {|response|
# Scan for MOTM signature --uuid:*
if response.raw =~ (/^(--[\w:-]+)--$/)
# Get the last message, which is -2 because of the trailing --
xml = response.raw.split($1)[-2].strip
# Get rid of HTTP headers
if xml =~ /\r\n\r\n[<]/
xml = xml.split(/\r\n\r\n/)[-1]
end
else
raise "Cannot parse MOTM"
end
}
end | ruby | {
"resource": ""
} |
q24753 | AssLauncher.Api.ole | train | def ole(type, requiremet = '>= 0')
AssLauncher::Enterprise::Ole.ole_client(type).new(requiremet)
end | ruby | {
"resource": ""
} |
q24754 | RWebSpec.Popup.check_for_security_alerts | train | def check_for_security_alerts
autoit = WIN32OLE.new('AutoItX3.Control')
loop do
["Security Alert", "Security Information"].each do |win_title|
ret = autoit.WinWait(win_title, '', 1)
if (ret==1) then
autoit.Send('{Y}')
end
end
sleep(3)
end
end | ruby | {
"resource": ""
} |
q24755 | RWebSpec.Popup.start_checking_js_dialog | train | def start_checking_js_dialog(button = "OK", wait_time = 3)
w = WinClicker.new
longName = File.expand_path(File.dirname(__FILE__)).gsub("/", "\\" )
shortName = w.getShortFileName(longName)
c = "start ruby #{shortName}\\clickJSDialog.rb #{button} #{wait_time} "
w.winsystem(c)
w = nil
end | ruby | {
"resource": ""
} |
q24756 | MediaWiki.Butt.query | train | def query(params, base_return = [])
params[:action] = 'query'
params[:continue] = ''
loop do
result = post(params)
yield(base_return, result['query']) if result.key?('query')
break unless @use_continuation
break unless result.key?('continue')
continue = result['continue']
continue.each do |key, val|
params[key.to_sym] = val
end
end
base_return
end | ruby | {
"resource": ""
} |
q24757 | MediaWiki.Butt.query_ary_irrelevant_keys | train | def query_ary_irrelevant_keys(params, base_response_key, property_key)
query(params) do |return_val, query|
return_val.concat(query[base_response_key].values.collect { |obj| obj[property_key] })
end
end | ruby | {
"resource": ""
} |
q24758 | MediaWiki.Butt.query_ary | train | def query_ary(params, base_response_key, property_key)
query(params) do |return_val, query|
return_val.concat(query[base_response_key].collect { |obj| obj[property_key] })
end
end | ruby | {
"resource": ""
} |
q24759 | MediaWiki.Butt.get_limited | train | def get_limited(integer, max_user = 500, max_bot = 5000)
if integer.is_a?(String)
return integer if integer == 'max'
return 500
end
return integer if integer <= max_user
if user_bot?
integer > max_bot ? max_bot : integer
else
max_user
end
end | ruby | {
"resource": ""
} |
q24760 | MetaPresenter.Builder.ancestors_until | train | def ancestors_until(until_class)
# trim down the list
ancestors_list = all_ancestors[0..all_ancestors.index(until_class)]
# map to the fully qualified class name
ancestors_list.map { |klass| yield(klass) }
end | ruby | {
"resource": ""
} |
q24761 | RailsRateLimiter.ClassMethods.rate_limit | train | def rate_limit(options = {}, &block)
raise Error, 'Handling block was not provided' unless block_given?
# Separate out options related only to rate limiting
strategy = (options.delete(:strategy) || 'sliding_window_log').to_s
limit = options.delete(:limit) || 100
per = options.delete(:per) || 3600
pattern = options.delete(:pattern)
client = options.delete(:client)
before_action(options) do
check_rate_limits(strategy, limit, per, pattern, client, block)
end
end | ruby | {
"resource": ""
} |
q24762 | DataSift.Historics.prepare | train | def prepare(hash, start, end_time, name, sources = '', sample = 100)
params = {
:hash => hash,
:start => start,
:end => end_time,
:name => name,
:sources => sources,
:sample => sample
}
requires params
DataSift.request(:POST, 'historics/prepare', @config, params)
end | ruby | {
"resource": ""
} |
q24763 | DataSift.Historics.pause | train | def pause(id, reason = '')
params = { :id => id }
requires params
params[:reason] = reason
DataSift.request(:PUT, 'historics/pause', @config, params)
end | ruby | {
"resource": ""
} |
q24764 | DataSift.Historics.stop | train | def stop(id, reason = '')
params = { :id => id }
requires params
params[:reason] = reason
DataSift.request(:POST, 'historics/stop', @config, params)
end | ruby | {
"resource": ""
} |
q24765 | DataSift.Historics.status | train | def status(start, end_time, sources = '')
params = { :start => start, :end => end_time, :sources => sources }
requires params
DataSift.request(:GET, 'historics/status', @config, params)
end | ruby | {
"resource": ""
} |
q24766 | DataSift.Historics.update | train | def update(id, name)
params = { :id => id, :name => name }
requires params
DataSift.request(:POST, 'historics/update', @config, params)
end | ruby | {
"resource": ""
} |
q24767 | DataSift.Historics.get_by_id | train | def get_by_id(id, with_estimate = 1)
params = { :id => id, :with_estimate => with_estimate }
requires params
DataSift.request(:GET, 'historics/get', @config, params)
end | ruby | {
"resource": ""
} |
q24768 | DataSift.Historics.get | train | def get(max = 20, page = 1, with_estimate = 1)
params = { :max => max, :page => page, :with_estimate => with_estimate }
requires params
DataSift.request(:GET, 'historics/get', @config, params)
end | ruby | {
"resource": ""
} |
q24769 | Bech32.SegwitAddr.to_script_pubkey | train | def to_script_pubkey
v = ver == 0 ? ver : ver + 0x50
([v, prog.length].pack("CC") + prog.map{|p|[p].pack("C")}.join).unpack('H*').first
end | ruby | {
"resource": ""
} |
q24770 | Bech32.SegwitAddr.script_pubkey= | train | def script_pubkey=(script_pubkey)
values = [script_pubkey].pack('H*').unpack("C*")
@ver = values[0] == 0 ? values[0] : values[0] - 0x50
@prog = values[2..-1]
end | ruby | {
"resource": ""
} |
q24771 | Youtrack.Issue.add_work_item_to | train | def add_work_item_to(issue_id, attributes={})
attributes = attributes.to_hash
attributes.symbolize_keys!
attributes[:date] ||= Date.current.iso8601
epoc_date = Date.parse(attributes[:date]).to_time.to_i * 1000
attributes[:user] ||= self.service.login
work_items = REXML::Element.new('workItems')
work_item = work_items.add_element('workItem')
work_item.add_element('author').add_attribute('login', attributes[:user])
work_item.add_element('date').add_text(epoc_date.to_s)
work_item.add_element('duration').add_text(attributes[:duration].to_s)
work_item.add_element('description').add_text(attributes[:description])
put("import/issue/#{issue_id}/workitems", body: work_items.to_s, :headers => {'Content-type' => 'text/xml'} )
response
end | ruby | {
"resource": ""
} |
q24772 | Songkickr.Setlist.parse_setlist_items | train | def parse_setlist_items(setlist_item_array = nil)
return [] unless setlist_item_array
setlist_item_array.inject([]) do |setlist_items, item|
setlist_items << Songkickr::SetlistItem.new(item)
end
end | ruby | {
"resource": ""
} |
q24773 | Epp.Server.get_frame | train | def get_frame
raise SocketError.new("Connection closed by remote server") if !@socket or @socket.eof?
header = @socket.read(4)
raise SocketError.new("Error reading frame from remote server") if header.nil?
length = header_size(header)
raise SocketError.new("Got bad frame header length of #{length} bytes from the server") if length < 5
return @socket.read(length - 4)
end | ruby | {
"resource": ""
} |
q24774 | Epp.Server.login | train | def login
raise SocketError, "Socket must be opened before logging in" if !@socket or @socket.closed?
xml = new_epp_request
xml.root << command = Node.new("command")
command << login = Node.new("login")
login << Node.new("clID", tag)
login << Node.new("pw", password)
login << options = Node.new("options")
options << Node.new("version", version)
options << Node.new("lang", lang)
login << services = Node.new("svcs")
services << Node.new("objURI", "urn:ietf:params:xml:ns:domain-1.0")
services << Node.new("objURI", "urn:ietf:params:xml:ns:contact-1.0")
services << Node.new("objURI", "urn:ietf:params:xml:ns:host-1.0")
services << extensions_container = Node.new("svcExtension") unless extensions.empty?
for uri in extensions
extensions_container << Node.new("extURI", uri)
end
command << Node.new("clTRID", UUIDTools::UUID.timestamp_create.to_s)
response = Hpricot::XML(send_request(xml.to_s))
handle_response(response)
end | ruby | {
"resource": ""
} |
q24775 | Epp.Server.logout | train | def logout
raise SocketError, "Socket must be opened before logging out" if !@socket or @socket.closed?
xml = new_epp_request
xml.root << command = Node.new("command")
command << login = Node.new("logout")
command << Node.new("clTRID", UUIDTools::UUID.timestamp_create.to_s)
response = Hpricot::XML(send_request(xml.to_s))
handle_response(response, 1500)
end | ruby | {
"resource": ""
} |
q24776 | ZenPush.Zendesk.find_category | train | def find_category(category_name, options = {})
categories = self.categories
if categories.is_a?(Array)
categories.detect { |c| c['name'] == category_name }
else
raise "Could not retrieve categories: #{categories}"
end
end | ruby | {
"resource": ""
} |
q24777 | ZenPush.Zendesk.find_forum | train | def find_forum(category_name, forum_name, options = {})
category = self.find_category(category_name, options)
if category
self.forums.detect {|f| f['category_id'] == category['id'] && f['name'] == forum_name }
end
end | ruby | {
"resource": ""
} |
q24778 | ZenPush.Zendesk.find_or_create_forum | train | def find_or_create_forum(category_name, forum_name, options={ })
category = self.find_or_create_category(category_name, options)
if category
self.forums.detect { |f| f['category_id'] == category['id'] && f['name'] == forum_name } || post_forum(category['id'], forum_name)
end
end | ruby | {
"resource": ""
} |
q24779 | ZenPush.Zendesk.find_topic | train | def find_topic(category_name, forum_name, topic_title, options = {})
forum = self.find_forum(category_name, forum_name, options)
if forum
self.topics(forum['id'], options).detect {|t| t['title'] == topic_title}
end
end | ruby | {
"resource": ""
} |
q24780 | ZenPush.Zendesk.post_forum | train | def post_forum(category_id, forum_name, options={ })
self.post('/forums.json',
options.merge(
:body => { :forum => {
:name => forum_name,
:category_id => category_id
} }.to_json
)
)['forum']
end | ruby | {
"resource": ""
} |
q24781 | ZenPush.Zendesk.post_topic | train | def post_topic(forum_id, title, body, options = { })
self.post("/topics.json",
options.merge(
:body => { :topic => {
:forum_id => forum_id, :title => title, :body => body
} }.to_json
)
)['topic']
end | ruby | {
"resource": ""
} |
q24782 | Tenon.PieceHelper.responsive_image_tag | train | def responsive_image_tag(piece, options = {}, breakpoints)
srcset = generate_srcset(piece)
sizes = generate_sizes(piece, breakpoints)
# Let's just use an plain image_tag if responsive styles haven't been
# generated. We'll test for :x2000 to determine if that's the case
if piece.image.attachment.exists?(computed_style(piece, 'x2000'))
image_tag(piece.image.url(default_style(piece, breakpoints)), options.merge(srcset: srcset, sizes: sizes))
else
image_tag(piece.image.url(:_medium), options)
end
end | ruby | {
"resource": ""
} |
q24783 | RWebSpec.Assert.assert | train | def assert test, msg = nil
msg ||= "Failed assertion, no message given."
# comment out self.assertions += 1 to counting assertions
unless test then
msg = msg.call if Proc === msg
raise RWebSpec::Assertion, msg
end
true
end | ruby | {
"resource": ""
} |
q24784 | RWebSpec.Assert.assert_link_present_with_text | train | def assert_link_present_with_text(link_text)
@web_browser.links.each { |link|
return if link.text.include?(link_text)
}
fail( "can't find the link containing text: #{link_text}")
end | ruby | {
"resource": ""
} |
q24785 | RWebSpec.Assert.assert_radio_option_not_present | train | def assert_radio_option_not_present(radio_group, radio_option)
@web_browser.radios.each { |radio|
the_element_name = element_name(radio)
if (the_element_name == radio_group) then
perform_assertion { assert(!(radio_option == element_value(radio) ), "unexpected radio option: " + radio_option + " found") }
end
}
end | ruby | {
"resource": ""
} |
q24786 | JedisRb.Pool.yield_connection | train | def yield_connection
response = begin
resource = @connection_pool.resource
yield resource
ensure
resource.close if resource
end
if @convert_objects
convert(response)
else
response
end
end | ruby | {
"resource": ""
} |
q24787 | JedisRb.Pool.convert | train | def convert(value)
case value
when java.util.List then value.to_a
when java.util.Set then value.to_set
when java.util.Map then value.to_hash
else value
end
end | ruby | {
"resource": ""
} |
q24788 | DataSift.HistoricsPreview.create | train | def create(hash, sources, parameters, start, end_time = nil)
params = {
:hash => hash,
:sources => sources,
:parameters => parameters,
:start => start
}
requires params
params.merge!(:end => end_time) unless end_time.nil?
DataSift.request(:POST, 'preview/create', @config, params)
end | ruby | {
"resource": ""
} |
q24789 | Youtrack.Client.connect! | train | def connect!
@connection = HTTParty.post(File.join(url, "rest/user/login"), body: credentials_hash )
@cookies['Cookie'] = @connection.headers['set-cookie']
@connection.code
end | ruby | {
"resource": ""
} |
q24790 | Tenon.ProxyAttachment.url | train | def url(style = :original, *args)
if style.to_sym == :original
original_url(*args)
else
named_url(style, *args)
end
end | ruby | {
"resource": ""
} |
q24791 | Hero.Observer.log_step | train | def log_step(id, step, context, options, error=nil)
return unless Hero.logger
if error
Hero.logger.error "HERO #{id.to_s.ljust(6)} #{formula_name} -> #{step.first} Context: #{context.inspect} Options: #{options.inspect} Error: #{error.message}"
else
Hero.logger.info "HERO #{id.to_s.ljust(6)} #{formula_name} -> #{step.first} Context: #{context.inspect} Options: #{options.inspect}"
end
end | ruby | {
"resource": ""
} |
q24792 | DataSift.Task.create | train | def create(service:, type:, subscription_id:, name:, parameters:)
DataSift.request(:POST, "pylon/#{service}/task", @config, {
type: type,
subscription_id: subscription_id,
name: name,
parameters: parameters
})
end | ruby | {
"resource": ""
} |
q24793 | DataSift.Task.list | train | def list(service:, type: 'analysis', **opts)
params = {}
params[:per_page] = opts[:per_page] if opts.key?(:per_page)
params[:page] = opts[:page] if opts.key?(:page)
params[:status] = opts[:status] if opts.key?(:status)
DataSift.request(:GET, "pylon/#{service}/task/#{type}", @config, params)
end | ruby | {
"resource": ""
} |
q24794 | EcsCompose.TaskDefinition.update | train | def update(cluster)
deployed = primary_deployment(cluster)
Ecs.update_service(cluster.name, name, register(deployed))
name
end | ruby | {
"resource": ""
} |
q24795 | EcsCompose.TaskDefinition.scale | train | def scale(cluster, count)
Ecs.update_service_desired_count(cluster.name, name, count)
name
end | ruby | {
"resource": ""
} |
q24796 | EcsCompose.TaskDefinition.run | train | def run(cluster, started_by: nil, **args)
overrides_json = json_generator.generate_override_json(**args)
info = Ecs.run_task(cluster.name, register,
started_by: started_by,
overrides_json: overrides_json)
info.fetch("tasks")[0].fetch("taskArn")
end | ruby | {
"resource": ""
} |
q24797 | ClientVariable.TiltHandlebars.evaluate | train | def evaluate(scope, locals, &block)
binding.pry
template = data.dup
template.gsub!(/"/, '\\"')
template.gsub!(/\r?\n/, '\\n')
template.gsub!(/\t/, '\\t')
return 'console.log(1223);'
end | ruby | {
"resource": ""
} |
q24798 | TeaLeaves.ArrayMethods.moving_average | train | def moving_average(average_specifier)
if average_specifier.kind_of?(Array)
avg = MovingAverage.weighted(average_specifier)
elsif average_specifier.kind_of?(Integer)
avg = MovingAverage.simple(average_specifier)
else
raise ArgumentError.new("Unknown weights")
end
avg.calculate(self)
end | ruby | {
"resource": ""
} |
q24799 | TeaLeaves.MovingAverage.calculate | train | def calculate(array)
return [] if @span > array.length
array.each_cons(@span).map do |window|
window.zip(weights).map {|(a,b)| a * b }.inject(&:+)
end
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.