_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q25000 | AdwordsApi.ReportUtils.download_report_as_stream_with_awql | validation | def download_report_as_stream_with_awql(
report_query, format, cid = nil, &block)
return get_report_response_with_awql(report_query, format, cid, &block)
end | ruby | {
"resource": ""
} |
q25001 | AdwordsApi.ReportUtils.get_stream_helper_with_awql | validation | def get_stream_helper_with_awql(report_query, format, cid = nil)
return AdwordsApi::ReportStream.set_up_with_awql(
self, report_query, format, cid)
end | ruby | {
"resource": ""
} |
q25002 | AdwordsApi.ReportUtils.get_report_response | validation | def get_report_response(report_definition, cid, &block)
definition_text = get_report_definition_text(report_definition)
data = '__rdxml=%s' % CGI.escape(definition_text)
return make_adhoc_request(data, cid, &block)
end | ruby | {
"resource": ""
} |
q25003 | AdwordsApi.ReportUtils.get_report_response_with_awql | validation | def get_report_response_with_awql(report_query, format, cid, &block)
data = '__rdquery=%s&__fmt=%s' %
[CGI.escape(report_query), CGI.escape(format)]
return make_adhoc_request(data, cid, &block)
end | ruby | {
"resource": ""
} |
q25004 | AdwordsApi.ReportUtils.make_adhoc_request | validation | def make_adhoc_request(data, cid, &block)
@api.utils_reporter.report_utils_used()
url = @api.api_config.adhoc_report_download_url(@version)
headers = get_report_request_headers(url, cid)
log_request(url, headers, data)
# A given block indicates that we should make a stream request and yield
# the results, rather than return a full response.
if block_given?
AdsCommon::Http.post_stream(url, data, @api.config, headers, &block)
return nil
else
response = AdsCommon::Http.post_response(
url, data, @api.config, headers)
log_headers(response.headers)
check_for_errors(response)
return response
end
end | ruby | {
"resource": ""
} |
q25005 | AdwordsApi.ReportUtils.get_report_request_headers | validation | def get_report_request_headers(url, cid)
@header_handler ||= AdwordsApi::ReportHeaderHandler.new(
@api.credential_handler, @api.get_auth_handler(), @api.config)
return @header_handler.headers(url, cid)
end | ruby | {
"resource": ""
} |
q25006 | AdwordsApi.ReportUtils.save_to_file | validation | def save_to_file(data, path)
open(path, 'wb') { |file| file.write(data) } if path
end | ruby | {
"resource": ""
} |
q25007 | AdwordsApi.ReportUtils.log_headers | validation | def log_headers(headers)
@api.logger.debug('HTTP headers: [%s]' %
(headers.map { |k, v| [k, v].join(': ') }.join(', ')))
end | ruby | {
"resource": ""
} |
q25008 | AdwordsApi.ReportUtils.check_for_errors | validation | def check_for_errors(response)
# Check for error code.
if response.code != 200
# Check for error in body.
report_body = response.body
check_for_xml_error(report_body, response.code)
# No XML error found nor raised, falling back to a default message.
raise AdwordsApi::Errors::ReportError.new(response.code,
'HTTP code: %d, body: %s' % [response.code, response.body])
end
return nil
end | ruby | {
"resource": ""
} |
q25009 | AdwordsApi.ReportUtils.check_for_xml_error | validation | def check_for_xml_error(report_body, response_code)
unless report_body.nil?
error_response = get_nori().parse(report_body)
if error_response.include?(:report_download_error) and
error_response[:report_download_error].include?(:api_error)
api_error = error_response[:report_download_error][:api_error]
raise AdwordsApi::Errors::ReportXmlError.new(response_code,
api_error[:type], api_error[:trigger], api_error[:field_path])
end
end
end | ruby | {
"resource": ""
} |
q25010 | AdwordsApi.ReportUtils.report_definition_to_xml | validation | def report_definition_to_xml(report_definition)
check_report_definition_hash(report_definition)
add_report_definition_hash_order(report_definition)
begin
return Gyoku.xml({:report_definition => report_definition})
rescue ArgumentError => e
if e.message.include?("order!")
unknown_fields =
e.message.slice(e.message.index('['), e.message.length)
raise AdwordsApi::Errors::InvalidReportDefinitionError,
"Unknown report definition field(s): %s" % unknown_fields
end
raise e
end
end | ruby | {
"resource": ""
} |
q25011 | AdwordsApi.ReportUtils.check_report_definition_hash | validation | def check_report_definition_hash(report_definition)
# Minimal set of fields required.
REQUIRED_FIELDS.each do |field|
unless report_definition.include?(field)
raise AdwordsApi::Errors::InvalidReportDefinitionError,
"Required field '%s' is missing in the definition" % field
end
end
# Fields list is also required.
unless report_definition[:selector].include?(:fields)
raise AdwordsApi::Errors::InvalidReportDefinitionError,
'Fields list is required'
end
# 'Fields' must be an Array.
unless report_definition[:selector][:fields].kind_of?(Array)
raise AdwordsApi::Errors::InvalidReportDefinitionError,
'Fields list must be an array'
end
# We should request at least one field.
if report_definition[:selector][:fields].empty?
raise AdwordsApi::Errors::InvalidReportDefinitionError,
'At least one field needs to be requested'
end
end | ruby | {
"resource": ""
} |
q25012 | AdwordsApi.ReportUtils.add_report_definition_hash_order | validation | def add_report_definition_hash_order(node, name = :root)
def_order = REPORT_DEFINITION_ORDER[name]
var_order = def_order.reject { |field| !node.include?(field) }
node.keys.each do |key|
if REPORT_DEFINITION_ORDER.include?(key)
case node[key]
when Hash
add_report_definition_hash_order(node[key], key)
when Array
node[key].each do |item|
add_report_definition_hash_order(item, key)
end
end
end
end
node[:order!] = var_order
return nil
end | ruby | {
"resource": ""
} |
q25013 | AdwordsApi.ReportHeaderHandler.headers | validation | def headers(url, cid)
override = (cid.nil?) ? nil : {:client_customer_id => cid}
credentials = @credential_handler.credentials(override)
headers = {
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => @auth_handler.auth_string(credentials),
'User-Agent' => @credential_handler.generate_user_agent(),
'clientCustomerId' => credentials[:client_customer_id].to_s,
'developerToken' => credentials[:developer_token]
}
skip_report_header = @config.read('library.skip_report_header')
unless skip_report_header.nil?
headers['skipReportHeader'] = skip_report_header.to_s
end
skip_report_summary = @config.read('library.skip_report_summary')
unless skip_report_summary.nil?
headers['skipReportSummary'] = skip_report_summary.to_s
end
skip_column_header = @config.read('library.skip_column_header')
unless skip_column_header.nil?
headers['skipColumnHeader'] = skip_column_header.to_s
end
include_zero_impressions =
@config.read('library.include_zero_impressions')
unless include_zero_impressions.nil?
headers['includeZeroImpressions'] = include_zero_impressions.to_s
end
use_raw_enum_values =
@config.read('library.use_raw_enum_values')
unless use_raw_enum_values.nil?
headers['useRawEnumValues'] = use_raw_enum_values.to_s
end
return headers
end | ruby | {
"resource": ""
} |
q25014 | AdsCommon.CredentialHandler.credentials | validation | def credentials(credentials_override = nil)
credentials = @credentials.dup()
credentials.merge!(credentials_override) unless credentials_override.nil?
return credentials
end | ruby | {
"resource": ""
} |
q25015 | AdsCommon.CredentialHandler.credentials= | validation | def credentials=(new_credentials)
# Find new and changed properties.
diff = new_credentials.inject([]) do |result, (key, value)|
result << [key, value] if value != @credentials[key]
result
end
# Find removed properties.
diff = @credentials.inject(diff) do |result, (key, _)|
result << [key, nil] unless new_credentials.include?(key)
result
end
# Set each property.
diff.each { |entry| set_credential(entry[0], entry[1]) }
return nil
end | ruby | {
"resource": ""
} |
q25016 | AdsCommon.CredentialHandler.generate_user_agent | validation | def generate_user_agent(extra_ids = [], agent_app = nil)
agent_app ||= File.basename($0)
agent_data = extra_ids
agent_data << 'Common-Ruby/%s' % AdsCommon::ApiConfig::CLIENT_LIB_VERSION
agent_data << 'GoogleAdsSavon/%s' % GoogleAdsSavon::VERSION
ruby_engine = defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby'
agent_data << [ruby_engine, RUBY_VERSION].join('/')
agent_data << 'HTTPI/%s' % HTTPI::VERSION
agent_data << HTTPI::Adapter.use.to_s
agent_data += get_extra_user_agents()
return '%s (%s)' % [agent_app, agent_data.join(', ')]
end | ruby | {
"resource": ""
} |
q25017 | AdsCommon.CredentialHandler.get_extra_user_agents | validation | def get_extra_user_agents()
@extra_user_agents_lock.synchronize do
user_agents = @extra_user_agents.collect do |k, v|
v.nil? ? k : '%s/%s' % [k, v]
end
@extra_user_agents.clear
return user_agents
end
end | ruby | {
"resource": ""
} |
q25018 | AdsCommon.ResultsExtractor.extract_header_data | validation | def extract_header_data(response)
header_type = get_full_type_signature(:SoapResponseHeader)
headers = response.header[:response_header].dup
process_attributes(headers, false)
headers = normalize_fields(headers, header_type[:fields])
return headers
end | ruby | {
"resource": ""
} |
q25019 | AdsCommon.ResultsExtractor.extract_exception_data | validation | def extract_exception_data(soap_fault, exception_name)
exception_type = get_full_type_signature(exception_name)
process_attributes(soap_fault, false)
soap_fault = normalize_fields(soap_fault, exception_type[:fields])
return soap_fault
end | ruby | {
"resource": ""
} |
q25020 | AdsCommon.ResultsExtractor.normalize_fields | validation | def normalize_fields(data, fields)
fields.each do |field|
field_name = field[:name]
if data.include?(field_name)
field_data = data[field_name]
field_data = normalize_output_field(field_data, field)
field_data = check_array_collapse(field_data, field)
data[field_name] = field_data unless field_data.nil?
end
end
return data
end | ruby | {
"resource": ""
} |
q25021 | AdsCommon.ResultsExtractor.normalize_output_field | validation | def normalize_output_field(field_data, field_def)
return case field_data
when Array
normalize_array_field(field_data, field_def)
when Hash
normalize_hash_field(field_data, field_def)
else
normalize_item(field_data, field_def)
end
end | ruby | {
"resource": ""
} |
q25022 | AdsCommon.ResultsExtractor.normalize_array_field | validation | def normalize_array_field(data, field_def)
result = data
# Convert a specific structure to a handy hash if detected.
if check_key_value_struct(result)
result = convert_key_value_to_hash(result).inject({}) do |s, (k,v)|
s[k] = normalize_output_field(v, field_def)
s
end
else
result = data.map {|item| normalize_output_field(item, field_def)}
end
return result
end | ruby | {
"resource": ""
} |
q25023 | AdsCommon.ResultsExtractor.normalize_hash_field | validation | def normalize_hash_field(field, field_def)
process_attributes(field, true)
field_type = field_def[:type]
field_def = get_full_type_signature(field_type)
# First checking for xsi:type provided.
xsi_type_override = determine_xsi_type_override(field, field_def)
unless xsi_type_override.nil?
field_def = get_full_type_signature(xsi_type_override)
return (field_def.nil?) ? field :
normalize_fields(field, field_def[:fields])
end
result = field
# Now checking for choice options from wsdl.
choice_type_override = determine_choice_type_override(field, field_def)
unless choice_type_override.nil?
# For overrides we need to process sub-field and than return it
# in the original structure.
field_key = field.keys.first
field_data = field[field_key]
field_def = get_full_type_signature(choice_type_override)
if !field_def.nil? and field_data.kind_of?(Hash)
field_data = normalize_fields(field_data, field_def[:fields])
end
result = {field_key => field_data}
else
# Otherwise using the best we have.
unless field_def.nil?
result = normalize_fields(field, field_def[:fields])
end
end
# Convert a single key-value hash to a proper hash if detected.
if check_key_value_struct(result)
result = convert_key_value_to_hash(result)
end
return result
end | ruby | {
"resource": ""
} |
q25024 | AdsCommon.ResultsExtractor.determine_choice_type_override | validation | def determine_choice_type_override(field_data, field_def)
result = nil
if field_data.kind_of?(Hash) and field_def.include?(:choices)
result = determine_choice(field_data, field_def[:choices])
end
return result
end | ruby | {
"resource": ""
} |
q25025 | AdsCommon.ResultsExtractor.determine_choice | validation | def determine_choice(field_data, field_choices)
result = nil
key_name = field_data.keys.first
unless key_name.nil?
choice = find_named_entry(field_choices, key_name)
result = choice[:type] unless choice.nil?
end
return result
end | ruby | {
"resource": ""
} |
q25026 | AdsCommon.ResultsExtractor.normalize_item | validation | def normalize_item(item, field_def)
return case field_def[:type]
when 'long', 'int' then Integer(item)
when 'double', 'float' then Float(item)
when 'boolean' then item.kind_of?(String) ?
item.casecmp('true') == 0 : item
else item
end
end | ruby | {
"resource": ""
} |
q25027 | AdsCommon.ResultsExtractor.check_array_collapse | validation | def check_array_collapse(data, field_def)
result = data
if !field_def[:min_occurs].nil? &&
(field_def[:max_occurs] == :unbounded ||
(!field_def[:max_occurs].nil? && field_def[:max_occurs] > 1)) &&
!(field_def[:type] =~ /MapEntry$/)
result = arrayize(result)
end
return result
end | ruby | {
"resource": ""
} |
q25028 | AdsCommon.ResultsExtractor.process_attributes | validation | def process_attributes(data, keep_xsi_type = false)
if keep_xsi_type
xsi_type = data.delete(:"@xsi:type")
data[:xsi_type] = xsi_type if xsi_type
end
data.reject! {|key, value| key.to_s.start_with?('@')}
end | ruby | {
"resource": ""
} |
q25029 | AdsCommon.Api.service | validation | def service(name, version = nil)
name = name.to_sym
version = (version.nil?) ? api_config.default_version : version.to_sym
# Check if the combination is available.
validate_service_request(version, name)
# Try to re-use the service for this version if it was requested before.
wrapper = if @wrappers.include?(version) && @wrappers[version][name]
@wrappers[version][name]
else
@wrappers[version] ||= {}
@wrappers[version][name] = prepare_wrapper(version, name)
end
return wrapper
end | ruby | {
"resource": ""
} |
q25030 | AdsCommon.Api.authorize | validation | def authorize(parameters = {}, &block)
parameters.each_pair do |key, value|
@credential_handler.set_credential(key, value)
end
auth_handler = get_auth_handler()
token = auth_handler.get_token()
# If token is invalid ask for a new one.
if token.nil?
begin
credentials = @credential_handler.credentials
token = auth_handler.get_token(credentials)
rescue AdsCommon::Errors::OAuth2VerificationRequired => e
verification_code = (block_given?) ? yield(e.oauth_url) : nil
# Retry with verification code if one provided.
if verification_code
@credential_handler.set_credential(
:oauth2_verification_code, verification_code)
retry
else
raise e
end
end
end
return token
end | ruby | {
"resource": ""
} |
q25031 | AdsCommon.Api.save_oauth2_token | validation | def save_oauth2_token(token)
raise AdsCommon::Errors::Error, "Can't save nil token" if token.nil?
AdsCommon::Utils.save_oauth2_token(
File.join(ENV['HOME'], api_config.default_config_filename), token)
end | ruby | {
"resource": ""
} |
q25032 | AdsCommon.Api.validate_service_request | validation | def validate_service_request(version, service)
# Check if the current config supports the requested version.
unless api_config.has_version(version)
raise AdsCommon::Errors::Error,
"Version '%s' not recognized" % version.to_s
end
# Check if the specified version has the requested service.
unless api_config.version_has_service(version, service)
raise AdsCommon::Errors::Error,
"Version '%s' does not contain service '%s'" %
[version.to_s, service.to_s]
end
end | ruby | {
"resource": ""
} |
q25033 | AdsCommon.Api.create_auth_handler | validation | def create_auth_handler()
auth_method = @config.read('authentication.method', :OAUTH2)
return case auth_method
when :OAUTH
raise AdsCommon::Errors::Error,
'OAuth authorization method is deprecated, use OAuth2 instead.'
when :OAUTH2
AdsCommon::Auth::OAuth2Handler.new(
@config,
api_config.config(:oauth_scope)
)
when :OAUTH2_SERVICE_ACCOUNT
AdsCommon::Auth::OAuth2ServiceAccountHandler.new(
@config,
api_config.config(:oauth_scope)
)
else
raise AdsCommon::Errors::Error,
"Unknown authentication method '%s'" % auth_method
end
end | ruby | {
"resource": ""
} |
q25034 | AdsCommon.Api.prepare_wrapper | validation | def prepare_wrapper(version, service)
api_config.do_require(version, service)
endpoint = api_config.endpoint(version, service)
interface_class_name = api_config.interface_name(version, service)
wrapper = class_for_path(interface_class_name).new(@config, endpoint)
auth_handler = get_auth_handler()
header_ns = api_config.config(:header_ns) + version.to_s
soap_handler = soap_header_handler(auth_handler, version, header_ns,
wrapper.namespace)
wrapper.header_handler = soap_handler
return wrapper
end | ruby | {
"resource": ""
} |
q25035 | AdsCommon.Api.create_default_logger | validation | def create_default_logger()
logger = Logger.new(STDOUT)
logger.level = get_log_level_for_string(
@config.read('library.log_level', 'INFO'))
return logger
end | ruby | {
"resource": ""
} |
q25036 | AdsCommon.Api.load_config | validation | def load_config(provided_config = nil)
@config = (provided_config.nil?) ?
AdsCommon::Config.new(
File.join(ENV['HOME'], api_config.default_config_filename)) :
AdsCommon::Config.new(provided_config)
init_config()
end | ruby | {
"resource": ""
} |
q25037 | AdsCommon.Api.init_config | validation | def init_config()
# Set up logger.
provided_logger = @config.read('library.logger')
self.logger = (provided_logger.nil?) ?
create_default_logger() : provided_logger
# Set up default HTTPI adapter.
provided_adapter = @config.read('connection.adapter')
@config.set('connection.adapter', :httpclient) if provided_adapter.nil?
# Make sure Auth param is a symbol.
symbolize_config_value('authentication.method')
end | ruby | {
"resource": ""
} |
q25038 | AdsCommon.Api.symbolize_config_value | validation | def symbolize_config_value(key)
value_str = @config.read(key).to_s
if !value_str.nil? and !value_str.empty?
value = value_str.upcase.to_sym
@config.set(key, value)
end
end | ruby | {
"resource": ""
} |
q25039 | AdsCommon.Api.class_for_path | validation | def class_for_path(path)
path.split('::').inject(Kernel) do |scope, const_name|
scope.const_get(const_name)
end
end | ruby | {
"resource": ""
} |
q25040 | Zold.Farm.to_json | validation | def to_json
{
threads: @threads.to_json,
pipeline: @pipeline.size,
best: best.map(&:to_mnemo).join(', '),
farmer: @farmer.class.name
}
end | ruby | {
"resource": ""
} |
q25041 | Zold.AsyncEntrance.exists? | validation | def exists?(id, body)
DirItems.new(@dir).fetch.each do |f|
next unless f.start_with?("#{id}-")
return true if safe_read(File.join(@dir, f)) == body
end
false
end | ruby | {
"resource": ""
} |
q25042 | Zold.Tax.exists? | validation | def exists?(details)
!@wallet.txns.find { |t| t.details.start_with?("#{PREFIX} ") && t.details == details }.nil?
end | ruby | {
"resource": ""
} |
q25043 | Zold.SpreadEntrance.push | validation | def push(id, body)
mods = @entrance.push(id, body)
return mods if @remotes.all.empty?
mods.each do |m|
next if @seen.include?(m)
@mutex.synchronize { @seen << m }
@modified.push(m)
@log.debug("Spread-push scheduled for #{m}, queue size is #{@modified.size}")
end
mods
end | ruby | {
"resource": ""
} |
q25044 | Zold.Wallet.init | validation | def init(id, pubkey, overwrite: false, network: 'test')
raise "File '#{path}' already exists" if File.exist?(path) && !overwrite
raise "Invalid network name '#{network}'" unless network =~ /^[a-z]{4,16}$/
FileUtils.mkdir_p(File.dirname(path))
IO.write(path, "#{network}\n#{PROTOCOL}\n#{id}\n#{pubkey.to_pub}\n\n")
@txns.flush
@head.flush
end | ruby | {
"resource": ""
} |
q25045 | Zold.Wallet.balance | validation | def balance
txns.inject(Amount::ZERO) { |sum, t| sum + t.amount }
end | ruby | {
"resource": ""
} |
q25046 | Zold.Wallet.sub | validation | def sub(amount, invoice, pvt, details = '-', time: Time.now)
raise 'The amount has to be of type Amount' unless amount.is_a?(Amount)
raise "The amount can't be negative: #{amount}" if amount.negative?
raise 'The pvt has to be of type Key' unless pvt.is_a?(Key)
prefix, target = invoice.split('@')
tid = max + 1
raise 'Too many transactions already, can\'t add more' if max > 0xffff
txn = Txn.new(
tid,
time,
amount * -1,
prefix,
Id.new(target),
details
)
txn = txn.signed(pvt, id)
raise "Invalid private key for the wallet #{id}" unless Signature.new(network).valid?(key, id, txn)
add(txn)
txn
end | ruby | {
"resource": ""
} |
q25047 | Zold.Wallet.add | validation | def add(txn)
raise 'The txn has to be of type Txn' unless txn.is_a?(Txn)
raise "Wallet #{id} can't pay itself: #{txn}" if txn.bnf == id
raise "The amount can't be zero in #{id}: #{txn}" if txn.amount.zero?
if txn.amount.negative? && includes_negative?(txn.id)
raise "Negative transaction with the same ID #{txn.id} already exists in #{id}"
end
if txn.amount.positive? && includes_positive?(txn.id, txn.bnf)
raise "Positive transaction with the same ID #{txn.id} and BNF #{txn.bnf} already exists in #{id}"
end
raise "The tax payment already exists in #{id}: #{txn}" if Tax.new(self).exists?(txn.details)
File.open(path, 'a') { |f| f.print "#{txn}\n" }
@txns.flush
end | ruby | {
"resource": ""
} |
q25048 | Zold.Wallet.includes_negative? | validation | def includes_negative?(id, bnf = nil)
raise 'The txn ID has to be of type Integer' unless id.is_a?(Integer)
!txns.find { |t| t.id == id && (bnf.nil? || t.bnf == bnf) && t.amount.negative? }.nil?
end | ruby | {
"resource": ""
} |
q25049 | Zold.Wallet.includes_positive? | validation | def includes_positive?(id, bnf)
raise 'The txn ID has to be of type Integer' unless id.is_a?(Integer)
raise 'The bnf has to be of type Id' unless bnf.is_a?(Id)
!txns.find { |t| t.id == id && t.bnf == bnf && !t.amount.negative? }.nil?
end | ruby | {
"resource": ""
} |
q25050 | Zold.Wallet.age | validation | def age
list = txns
list.empty? ? 0 : (Time.now - list.min_by(&:date).date) / (60 * 60)
end | ruby | {
"resource": ""
} |
q25051 | Zold.Wallet.max | validation | def max
negative = txns.select { |t| t.amount.negative? }
negative.empty? ? 0 : negative.max_by(&:id).id
end | ruby | {
"resource": ""
} |
q25052 | Zold.Propagate.propagate | validation | def propagate(id, _)
start = Time.now
modified = []
total = 0
network = @wallets.acq(id, &:network)
@wallets.acq(id, &:txns).select { |t| t.amount.negative? }.each do |t|
total += 1
if t.bnf == id
@log.error("Paying itself in #{id}? #{t}")
next
end
@wallets.acq(t.bnf, exclusive: true) do |target|
unless target.exists?
@log.debug("#{t.amount * -1} from #{id} to #{t.bnf}: wallet is absent")
next
end
unless target.network == network
@log.debug("#{t.amount * -1} to #{t.bnf}: network mismatch, '#{target.network}'!='#{network}'")
next
end
next if target.includes_positive?(t.id, id)
unless target.prefix?(t.prefix)
@log.debug("#{t.amount * -1} from #{id} to #{t.bnf}: wrong prefix \"#{t.prefix}\" in \"#{t}\"")
next
end
target.add(t.inverse(id))
@log.info("#{t.amount * -1} arrived to #{t.bnf}: #{t.details}")
modified << t.bnf
end
end
modified.uniq!
@log.debug("Wallet #{id} propagated successfully, #{total} txns \
in #{Age.new(start, limit: 20 + total * 0.005)}, #{modified.count} wallets affected")
modified.each do |w|
@wallets.acq(w, &:refurbish)
end
modified
end | ruby | {
"resource": ""
} |
q25053 | Zold.Node.exec | validation | def exec(cmd, nohup_log)
start = Time.now
Open3.popen2e({ 'MALLOC_ARENA_MAX' => '2' }, cmd) do |stdin, stdout, thr|
nohup_log.print("Started process ##{thr.pid} from process ##{Process.pid}: #{cmd}\n")
stdin.close
until stdout.eof?
begin
line = stdout.gets
rescue IOError => e
line = Backtrace.new(e).to_s
end
nohup_log.print(line)
end
nohup_log.print("Nothing else left to read from ##{thr.pid}\n")
code = thr.value.to_i
nohup_log.print("Exit code of process ##{thr.pid} is #{code}, was alive for #{Age.new(start)}: #{cmd}\n")
code
end
end | ruby | {
"resource": ""
} |
q25054 | Zold.ThreadPool.add | validation | def add
raise 'Block must be given to start()' unless block_given?
latch = Concurrent::CountDownLatch.new(1)
thread = Thread.start do
Thread.current.name = @title
VerboseThread.new(@log).run do
latch.count_down
yield
end
end
latch.wait
Thread.current.thread_variable_set(
:kids,
(Thread.current.thread_variable_get(:kids) || []) + [thread]
)
@threads << thread
end | ruby | {
"resource": ""
} |
q25055 | Zold.ThreadPool.kill | validation | def kill
if @threads.empty?
@log.debug("Thread pool \"#{@title}\" terminated with no threads")
return
end
@log.debug("Stopping \"#{@title}\" thread pool with #{@threads.count} threads: \
#{@threads.map { |t| "#{t.name}/#{t.status}" }.join(', ')}...")
start = Time.new
begin
join(0.1)
ensure
@threads.each do |t|
(t.thread_variable_get(:kids) || []).each(&:kill)
t.kill
sleep(0.001) while t.alive? # I believe it's a bug in Ruby, this line fixes it
Thread.current.thread_variable_set(
:kids,
(Thread.current.thread_variable_get(:kids) || []) - [t]
)
end
@log.debug("Thread pool \"#{@title}\" terminated all threads in #{Age.new(start)}, \
it was alive for #{Age.new(@start)}: #{@threads.map { |t| "#{t.name}/#{t.status}" }.join(', ')}")
@threads.clear
end
end | ruby | {
"resource": ""
} |
q25056 | Zold.ThreadPool.to_json | validation | def to_json
@threads.map do |t|
{
name: t.name,
status: t.status,
alive: t.alive?,
vars: Hash[t.thread_variables.map { |v| [v.to_s, t.thread_variable_get(v)] }]
}
end
end | ruby | {
"resource": ""
} |
q25057 | Zold.ThreadPool.to_s | validation | def to_s
@threads.map do |t|
[
"#{t.name}: status=#{t.status}; alive=#{t.alive?}",
'Vars: ' + t.thread_variables.map { |v| "#{v}=\"#{t.thread_variable_get(v)}\"" }.join('; '),
t.backtrace.nil? ? 'NO BACKTRACE' : " #{t.backtrace.join("\n ")}"
].join("\n")
end
end | ruby | {
"resource": ""
} |
q25058 | Zold.Patch.legacy | validation | def legacy(wallet, hours: 24)
raise 'You can\'t add legacy to a non-empty patch' unless @id.nil?
wallet.txns.each do |txn|
@txns << txn if txn.amount.negative? && txn.date < Time.now - hours * 60 * 60
end
end | ruby | {
"resource": ""
} |
q25059 | Zold.Patch.save | validation | def save(file, overwrite: false, allow_negative_balance: false)
raise 'You have to join at least one wallet in' if empty?
before = ''
wallet = Wallet.new(file)
before = wallet.digest if wallet.exists?
Tempfile.open([@id, Wallet::EXT]) do |f|
temp = Wallet.new(f.path)
temp.init(@id, @key, overwrite: overwrite, network: @network)
File.open(f.path, 'a') do |t|
@txns.each do |txn|
next if Id::BANNED.include?(txn.bnf.to_s)
t.print "#{txn}\n"
end
end
temp.refurbish
if temp.balance.negative? && !temp.id.root? && !allow_negative_balance
if wallet.exists?
@log.info("The balance is negative, won't merge #{temp.mnemo} on top of #{wallet.mnemo}")
else
@log.info("The balance is negative, won't save #{temp.mnemo}")
end
else
FileUtils.mkdir_p(File.dirname(file))
IO.write(file, IO.read(f.path))
end
end
before != wallet.digest
end | ruby | {
"resource": ""
} |
q25060 | Zold.Copies.clean | validation | def clean(max: 24 * 60 * 60)
Futex.new(file, log: @log).open do
list = load
list.reject! do |s|
if s[:time] >= Time.now - max
false
else
@log.debug("Copy ##{s[:name]}/#{s[:host]}:#{s[:port]} is too old, over #{Age.new(s[:time])}")
true
end
end
save(list)
deleted = 0
files.each do |f|
next unless list.find { |s| s[:name] == File.basename(f, Copies::EXT) }.nil?
file = File.join(@dir, f)
size = File.size(file)
File.delete(file)
@log.debug("Copy at #{f} deleted: #{Size.new(size)}")
deleted += 1
end
list.select! do |s|
cp = File.join(@dir, "#{s[:name]}#{Copies::EXT}")
wallet = Wallet.new(cp)
begin
wallet.refurbish
raise "Invalid protocol #{wallet.protocol} in #{cp}" unless wallet.protocol == Zold::PROTOCOL
true
rescue StandardError => e
FileUtils.rm_rf(cp)
@log.debug("Copy at #{cp} deleted: #{Backtrace.new(e)}")
deleted += 1
false
end
end
save(list)
deleted
end
end | ruby | {
"resource": ""
} |
q25061 | Zold.Copies.add | validation | def add(content, host, port, score, time: Time.now, master: false)
raise "Content can't be empty" if content.empty?
raise 'TCP port must be of type Integer' unless port.is_a?(Integer)
raise "TCP port can't be negative: #{port}" if port.negative?
raise 'Time must be of type Time' unless time.is_a?(Time)
raise "Time must be in the past: #{time}" if time > Time.now
raise 'Score must be Integer' unless score.is_a?(Integer)
raise "Score can't be negative: #{score}" if score.negative?
FileUtils.mkdir_p(@dir)
Futex.new(file, log: @log).open do
list = load
target = list.find do |s|
f = File.join(@dir, "#{s[:name]}#{Copies::EXT}")
digest = OpenSSL::Digest::SHA256.new(content).hexdigest
File.exist?(f) && OpenSSL::Digest::SHA256.file(f).hexdigest == digest
end
if target.nil?
max = DirItems.new(@dir).fetch
.select { |f| File.basename(f, Copies::EXT) =~ /^[0-9]+$/ }
.map(&:to_i)
.max
max = 0 if max.nil?
name = (max + 1).to_s
IO.write(File.join(@dir, "#{name}#{Copies::EXT}"), content)
else
name = target[:name]
end
list.reject! { |s| s[:host] == host && s[:port] == port }
list << {
name: name,
host: host,
port: port,
score: score,
time: time,
master: master
}
save(list)
name
end
end | ruby | {
"resource": ""
} |
q25062 | Zold.Remotes.iterate | validation | def iterate(log, farm: Farm::Empty.new, threads: 1)
raise 'Log can\'t be nil' if log.nil?
raise 'Farm can\'t be nil' if farm.nil?
Hands.exec(threads, all) do |r, idx|
Thread.current.name = "remotes-#{idx}@#{r[:host]}:#{r[:port]}"
start = Time.now
best = farm.best[0]
node = RemoteNode.new(
host: r[:host],
port: r[:port],
score: best.nil? ? Score::ZERO : best,
idx: idx,
master: master?(r[:host], r[:port]),
log: log,
network: @network
)
begin
yield node
raise 'Took too long to execute' if (Time.now - start).round > @timeout
unerror(r[:host], r[:port]) if node.touched
rescue StandardError => e
error(r[:host], r[:port])
if e.is_a?(RemoteNode::CantAssert) || e.is_a?(Fetch::Error)
log.debug("#{Rainbow(node).red}: \"#{e.message.strip}\" in #{Age.new(start)}")
else
log.info("#{Rainbow(node).red}: \"#{e.message.strip}\" in #{Age.new(start)}")
log.debug(Backtrace.new(e).to_s)
end
remove(r[:host], r[:port]) if r[:errors] > TOLERANCE
end
end
end | ruby | {
"resource": ""
} |
q25063 | Thredded.PostCommon.mark_as_unread | validation | def mark_as_unread(user)
if previous_post.nil?
read_state = postable.user_read_states.find_by(user_id: user.id)
read_state.destroy if read_state
else
postable.user_read_states.touch!(user.id, previous_post, overwrite_newer: true)
end
end | ruby | {
"resource": ""
} |
q25064 | Thredded.BaseMailer.find_record | validation | def find_record(klass, id_or_record)
# Check by name because in development the Class might have been reloaded after id was initialized
id_or_record.class.name == klass.name ? id_or_record : klass.find(id_or_record)
end | ruby | {
"resource": ""
} |
q25065 | Thredded.ContentModerationState.moderation_state_visible_to_user? | validation | def moderation_state_visible_to_user?(user)
moderation_state_visible_to_all? ||
(!user.thredded_anonymous? &&
(user_id == user.id || user.thredded_can_moderate_messageboard?(messageboard)))
end | ruby | {
"resource": ""
} |
q25066 | Spreadsheet.Worksheet.protect! | validation | def protect! password = ''
@protected = true
password = password.to_s
if password.size == 0
@password_hash = 0
else
@password_hash = Excel::Password.password_hash password
end
end | ruby | {
"resource": ""
} |
q25067 | Spreadsheet.Worksheet.format_column | validation | def format_column idx, format=nil, opts={}
opts[:worksheet] = self
res = case idx
when Integer
column = nil
if format
column = Column.new(idx, format, opts)
end
@columns[idx] = column
else
idx.collect do |col| format_column col, format, opts end
end
shorten @columns
res
end | ruby | {
"resource": ""
} |
q25068 | Spreadsheet.Worksheet.update_row | validation | def update_row idx, *cells
res = if row = @rows[idx]
row[0, cells.size] = cells
row
else
Row.new self, idx, cells
end
row_updated idx, res
res
end | ruby | {
"resource": ""
} |
q25069 | Spreadsheet.Worksheet.merge_cells | validation | def merge_cells start_row, start_col, end_row, end_col
# FIXME enlarge or dup check
@merged_cells.push [start_row, end_row, start_col, end_col]
end | ruby | {
"resource": ""
} |
q25070 | Spreadsheet.Row.formatted | validation | def formatted
copy = dup
Helpers.rcompact(@formats)
if copy.length < @formats.size
copy.concat Array.new(@formats.size - copy.length)
end
copy
end | ruby | {
"resource": ""
} |
q25071 | Spreadsheet.Workbook.set_custom_color | validation | def set_custom_color idx, red, green, blue
raise 'Invalid format' if [red, green, blue].find { |c| ! (0..255).include?(c) }
@palette[idx] = [red, green, blue]
end | ruby | {
"resource": ""
} |
q25072 | Spreadsheet.Workbook.format | validation | def format idx
case idx
when Integer
@formats[idx] || @default_format || Format.new
when String
@formats.find do |fmt| fmt.name == idx end
end
end | ruby | {
"resource": ""
} |
q25073 | Spreadsheet.Workbook.worksheet | validation | def worksheet idx
case idx
when Integer
@worksheets[idx]
when String
@worksheets.find do |sheet| sheet.name == idx end
end
end | ruby | {
"resource": ""
} |
q25074 | Spreadsheet.Workbook.write | validation | def write io_path_or_writer
if io_path_or_writer.is_a? Writer
io_path_or_writer.write self
else
writer(io_path_or_writer).write(self)
end
end | ruby | {
"resource": ""
} |
q25075 | ZendeskAPI.Sideloading._side_load | validation | def _side_load(name, klass, resources)
associations = klass.associated_with(name)
associations.each do |association|
association.side_load(resources, @included[name])
end
resources.each do |resource|
loaded_associations = resource.loaded_associations
loaded_associations.each do |association|
loaded = resource.send(association[:name])
next unless loaded
_side_load(name, association[:class], to_array(loaded))
end
end
end | ruby | {
"resource": ""
} |
q25076 | ZendeskAPI.Collection.<< | validation | def <<(item)
fetch
if item.is_a?(Resource)
if item.is_a?(@resource_class)
@resources << item
else
raise "this collection is for #{@resource_class}"
end
else
@resources << wrap_resource(item, true)
end
end | ruby | {
"resource": ""
} |
q25077 | ZendeskAPI.Collection.fetch! | validation | def fetch!(reload = false)
if @resources && (!@fetchable || !reload)
return @resources
elsif association && association.options.parent && association.options.parent.new_record?
return (@resources = [])
end
@response = get_response(@query || path)
handle_response(@response.body)
@resources
end | ruby | {
"resource": ""
} |
q25078 | ZendeskAPI.Collection.method_missing | validation | def method_missing(name, *args, &block)
if resource_methods.include?(name)
collection_method(name, *args, &block)
elsif [].respond_to?(name, false)
array_method(name, *args, &block)
else
next_collection(name, *args, &block)
end
end | ruby | {
"resource": ""
} |
q25079 | ZendeskAPI.Association.side_load | validation | def side_load(resources, side_loads)
key = "#{options.name}_id"
plural_key = "#{Inflection.singular options.name.to_s}_ids"
resources.each do |resource|
if resource.key?(plural_key) # Grab associations from child_ids field on resource
side_load_from_child_ids(resource, side_loads, plural_key)
elsif resource.key?(key) || options.singular
side_load_from_child_or_parent_id(resource, side_loads, key)
else # Grab associations from parent_id field from multiple child resources
side_load_from_parent_id(resource, side_loads, key)
end
end
end | ruby | {
"resource": ""
} |
q25080 | ZendeskAPI.Save.save | validation | def save(options = {}, &block)
save!(options, &block)
rescue ZendeskAPI::Error::RecordInvalid => e
@errors = e.errors
false
rescue ZendeskAPI::Error::ClientError
false
end | ruby | {
"resource": ""
} |
q25081 | ZendeskAPI.Save.save_associations | validation | def save_associations
self.class.associations.each do |association_data|
association_name = association_data[:name]
next unless send("#{association_name}_used?") && association = send(association_name)
inline_creation = association_data[:inline] == :create && new_record?
changed = association.is_a?(Collection) || association.changed?
if association.respond_to?(:save) && changed && !inline_creation && association.save
send("#{association_name}=", association) # set id/ids columns
end
if (association_data[:inline] == true || inline_creation) && changed
attributes[association_name] = association.to_param
end
end
end | ruby | {
"resource": ""
} |
q25082 | ZendeskAPI.Read.reload! | validation | def reload!
response = @client.connection.get(path) do |req|
yield req if block_given?
end
handle_response(response)
attributes.clear_changes
self
end | ruby | {
"resource": ""
} |
q25083 | ZendeskAPI.CreateMany.create_many! | validation | def create_many!(client, attributes_array, association = Association.new(:class => self))
response = client.connection.post("#{association.generate_path}/create_many") do |req|
req.body = { resource_name => attributes_array }
yield req if block_given?
end
JobStatus.new_from_response(client, response)
end | ruby | {
"resource": ""
} |
q25084 | ZendeskAPI.CreateOrUpdate.create_or_update! | validation | def create_or_update!(client, attributes, association = Association.new(:class => self))
response = client.connection.post("#{association.generate_path}/create_or_update") do |req|
req.body = { resource_name => attributes }
yield req if block_given?
end
new_from_response(client, response, Array(association.options[:include]))
end | ruby | {
"resource": ""
} |
q25085 | ZendeskAPI.CreateOrUpdateMany.create_or_update_many! | validation | def create_or_update_many!(client, attributes)
association = Association.new(:class => self)
response = client.connection.post("#{association.generate_path}/create_or_update_many") do |req|
req.body = { resource_name => attributes }
yield req if block_given?
end
JobStatus.new_from_response(client, response)
end | ruby | {
"resource": ""
} |
q25086 | ZendeskAPI.Destroy.destroy! | validation | def destroy!
return false if destroyed? || new_record?
@client.connection.delete(url || path) do |req|
yield req if block_given?
end
@destroyed = true
end | ruby | {
"resource": ""
} |
q25087 | ZendeskAPI.DestroyMany.destroy_many! | validation | def destroy_many!(client, ids, association = Association.new(:class => self))
response = client.connection.delete("#{association.generate_path}/destroy_many") do |req|
req.params = { :ids => ids.join(',') }
yield req if block_given?
end
JobStatus.new_from_response(client, response)
end | ruby | {
"resource": ""
} |
q25088 | ZendeskAPI.UpdateMany.update_many! | validation | def update_many!(client, ids_or_attributes, attributes = {})
association = attributes.delete(:association) || Association.new(:class => self)
response = client.connection.put("#{association.generate_path}/update_many") do |req|
if attributes == {}
req.body = { resource_name => ids_or_attributes }
else
req.params = { :ids => ids_or_attributes.join(',') }
req.body = { singular_resource_name => attributes }
end
yield req if block_given?
end
JobStatus.new_from_response(client, response)
end | ruby | {
"resource": ""
} |
q25089 | ZendeskAPI.Macro.apply! | validation | def apply!(ticket = nil)
path = "#{self.path}/apply"
if ticket
path = "#{ticket.path}/#{path}"
end
response = @client.connection.get(path)
SilentMash.new(response.body.fetch("result", {}))
end | ruby | {
"resource": ""
} |
q25090 | ZendeskAPI.Client.method_missing | validation | def method_missing(method, *args, &block)
method = method.to_s
options = args.last.is_a?(Hash) ? args.pop : {}
@resource_cache[method] ||= { :class => nil, :cache => ZendeskAPI::LRUCache.new }
if !options.delete(:reload) && (cached = @resource_cache[method][:cache].read(options.hash))
cached
else
@resource_cache[method][:class] ||= method_as_class(method)
raise "Resource for #{method} does not exist" unless @resource_cache[method][:class]
@resource_cache[method][:cache].write(options.hash, ZendeskAPI::Collection.new(self, @resource_cache[method][:class], options))
end
end | ruby | {
"resource": ""
} |
q25091 | Pliny.Router.version | validation | def version(*versions, &block)
condition = lambda { |env|
versions.include?(env["HTTP_X_API_VERSION"])
}
with_conditions(condition, &block)
end | ruby | {
"resource": ""
} |
q25092 | Vanity.Metric.track_args | validation | def track_args(args)
case args
when Hash
timestamp, identity, values = args.values_at(:timestamp, :identity, :values)
when Array
values = args
when Numeric
values = [args]
end
identity ||= Vanity.context.vanity_identity rescue nil
[timestamp || Time.now, identity, values || [1]]
end | ruby | {
"resource": ""
} |
q25093 | Vanity.Render.render | validation | def render(path_or_options, locals = {})
if path_or_options.respond_to?(:keys)
render_erb(
path_or_options[:file] || path_or_options[:partial],
path_or_options[:locals]
)
else
render_erb(path_or_options, locals)
end
end | ruby | {
"resource": ""
} |
q25094 | Vanity.Render.method_missing | validation | def method_missing(method, *args, &block)
%w(url_for flash).include?(method.to_s) ? ProxyEmpty.new : super
end | ruby | {
"resource": ""
} |
q25095 | Vanity.Render.vanity_simple_format | validation | def vanity_simple_format(text, options={})
open = "<p #{options.map { |k,v| "#{k}=\"#{CGI.escapeHTML v}\"" }.join(" ")}>"
text = open + text.gsub(/\r\n?/, "\n"). # \r\n and \r -> \n
gsub(/\n\n+/, "</p>\n\n#{open}"). # 2+ newline -> paragraph
gsub(/([^\n]\n)(?=[^\n])/, '\1<br />') + # 1 newline -> br
"</p>"
end | ruby | {
"resource": ""
} |
q25096 | Vanity.Playground.experiment | validation | def experiment(name)
id = name.to_s.downcase.gsub(/\W/, "_").to_sym
Vanity.logger.warn("Deprecated: Please call experiment method with experiment identifier (a Ruby symbol)") unless id == name
experiments[id.to_sym] or raise NoExperimentError, "No experiment #{id}"
end | ruby | {
"resource": ""
} |
q25097 | Vanity.Templates.custom_template_path_valid? | validation | def custom_template_path_valid?
Vanity.playground.custom_templates_path &&
File.exist?(Vanity.playground.custom_templates_path) &&
!Dir[File.join(Vanity.playground.custom_templates_path, '*')].empty?
end | ruby | {
"resource": ""
} |
q25098 | BenchmarkDriver.RubyInterface.run | validation | def run
unless @executables.empty?
@config.executables = @executables
end
jobs = @jobs.flat_map do |job|
BenchmarkDriver::JobParser.parse({
type: @config.runner_type,
prelude: @prelude,
loop_count: @loop_count,
}.merge!(job))
end
BenchmarkDriver::Runner.run(jobs, config: @config)
end | ruby | {
"resource": ""
} |
q25099 | Viewpoint::EWS::SOAP.ExchangeUserConfiguration.get_user_configuration | validation | def get_user_configuration(opts)
opts = opts.clone
[:user_config_name, :user_config_props].each do |k|
validate_param(opts, k, true)
end
req = build_soap! do |type, builder|
if(type == :header)
else
builder.nbuild.GetUserConfiguration {|x|
x.parent.default_namespace = @default_ns
builder.user_configuration_name!(opts[:user_config_name])
builder.user_configuration_properties!(opts[:user_config_props])
}
end
end
do_soap_request(req, response_class: EwsSoapAvailabilityResponse)
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.