_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q22500 | ZBar.Image.convert | train | def convert(format)
ptr = ZBar.zbar_image_convert(@img, format)
if ptr.null?
raise ArgumentError, "conversion failed"
else
Image.new(ptr)
end
end | ruby | {
"resource": ""
} |
q22501 | Metamagic.Renderer.transform_hash | train | def transform_hash(hash, path = "")
hash.each_with_object({}) do |(k, v), ret|
key = path + k.to_s
if v.is_a?(Hash)
ret.merge! transform_hash(v, "#{key}:")
else
ret[key] = v
end
end
end | ruby | {
"resource": ""
} |
q22502 | Blockchain.Wallet.parse_json | train | def parse_json(response)
json_response = JSON.parse(response)
error = json_response['error']
if !error.nil? then raise APIException.new(error) end
return json_response
end | ruby | {
"resource": ""
} |
q22503 | Numo.Gnuplot.stats | train | def stats(filename,*args)
fn = OptArg.quote(filename)
opt = OptArg.parse(*args)
puts send_cmd "stats #{fn} #{opt}"
end | ruby | {
"resource": ""
} |
q22504 | HTML2Markdown.Converter.parse_element | train | def parse_element(ele)
if ele.is_a? Nokogiri::XML::Text
return "#{ele.text}\n"
else
if (children = ele.children).count > 0
return wrap_node(ele,children.map {|ele| parse_element(ele)}.join )
else
return wrap_node(ele,ele.text)
end
end
end | ruby | {
"resource": ""
} |
q22505 | HTML2Markdown.Converter.wrap_node | train | def wrap_node(node,contents=nil)
result = ''
contents.strip! unless contents==nil
# check if there is a custom parse exist
if respond_to? "parse_#{node.name}"
return self.send("parse_#{node.name}",node,contents)
end
# skip hidden node
return '' if node['style'] and node['style'] =~ /display:\s*none/
# default parse
case node.name.downcase
when 'i'
when 'script'
when 'style'
when 'li'
result << "* #{contents}\n"
when 'blockquote'
contents.split('\n').each do |part|
result << ">#{contents}\n"
end
when 'p'
result << "\n#{contents}\n"
when 'strong'
result << "**#{contents}**\n"
when 'h1'
result << "# #{contents}\n"
when 'h2'
result << "## #{contents}\n"
when 'h3'
result << "### #{contents}\n"
when 'h4'
result << "#### #{contents}\n"
when 'h5'
result << "##### #{contents}\n"
when 'h6'
result << "###### #{contents}\n"
when 'hr'
result << "****\n"
when 'br'
result << "\n"
when 'img'
result << "![#{node['alt']}](#{node['src']})"
when 'a'
result << "[#{contents}](#{node['href']})"
else
result << contents unless contents == nil
end
result
end | ruby | {
"resource": ""
} |
q22506 | HTML2Markdown.Converter.method_missing | train | def method_missing(name,*args,&block)
self.class.send :define_method,"parse_#{name}" do |node,contents|
block.call node,contents
end
end | ruby | {
"resource": ""
} |
q22507 | Asciidoctor::Rouge.CalloutsSubstitutor.convert_line | train | def convert_line(line_num)
return '' unless @callouts.key? line_num
@callouts[line_num]
.map { |num| convert_callout(num) }
.join(' ')
end | ruby | {
"resource": ""
} |
q22508 | Asciidoctor::Rouge.HtmlFormatter.stream_lines | train | def stream_lines(tokens, line_num)
yield line_start(line_num)
tokens.each do |token, value|
yield @inner.span(token, value)
end
yield line_end(line_num)
end | ruby | {
"resource": ""
} |
q22509 | Text.Table.to_s | train | def to_s
rendered_rows = [separator] + text_table_rows.map(&:to_s) + [separator]
rendered_rows.unshift [separator, text_table_head.to_s] if head
rendered_rows << [text_table_foot.to_s, separator] if foot
rendered_rows.join
end | ruby | {
"resource": ""
} |
q22510 | Text.Table.align_column | train | def align_column(column_number, alignment)
set_alignment = Proc.new do |row, column_number_block, alignment_block|
cell = row.find do |cell_row|
row[0...row.index(cell_row)].map {|c| c.is_a?(Hash) ? c[:colspan] || 1 : 1}.inject(0, &:+) == column_number_block - 1
end
row[row.index(cell)] = hashify(cell, {:align => alignment_block}) if cell and not(cell.is_a?(Hash) && cell[:colspan].to_i > 0)
end
rows.each do |row|
next if row == :separator
set_alignment.call(row, column_number, alignment)
end
set_alignment.call(foot, column_number, alignment) if foot
return self
end | ruby | {
"resource": ""
} |
q22511 | Asciidoctor::Rouge.PassthroughsSubstitutor.restore | train | def restore(text)
return text if @node.passthroughs.empty?
# Fix passthrough placeholders that got caught up in syntax highlighting.
text = text.gsub(PASS_SLOT_RX, "#{PASS_START_MARK}\\1#{PASS_END_MARK}")
# Restore converted passthroughs.
@node.restore_passthroughs(text)
end | ruby | {
"resource": ""
} |
q22512 | Crafty.Tools.element! | train | def element!(name, content = nil, attributes = nil)
build! do
if content or block_given?
@_crafted << "<#{name}#{Tools.format_attributes(attributes)}>"
if block_given?
value = yield
content = value if !@_appended or value.kind_of? String
end
content = content.to_s
@_crafted << Tools.escape(content) if content != ""
@_crafted << "</#{name}>"
else
@_crafted << "<#{name}#{Tools.format_attributes(attributes)}/>"
end
end
end | ruby | {
"resource": ""
} |
q22513 | Scorm.Package.extract! | train | def extract!(force = false)
return if @options[:dry_run] && !force
# If opening an already extracted package; do nothing.
if not package?
return
end
# Create the path to the course
FileUtils.mkdir_p(@path)
Zip::ZipFile::foreach(@package) do |entry|
entry_path = File.join(@path, entry.name)
entry_dir = File.dirname(entry_path)
FileUtils.mkdir_p(entry_dir) unless File.exists?(entry_dir)
entry.extract(entry_path)
end
end | ruby | {
"resource": ""
} |
q22514 | Scorm.Package.path_to | train | def path_to(relative_filename, relative = false)
if relative
File.join(@name, relative_filename)
else
File.join(@path, relative_filename)
end
end | ruby | {
"resource": ""
} |
q22515 | Svelte.SwaggerBuilder.make_resource | train | def make_resource
resource = Module.new
paths.each do |path|
new_module = PathBuilder.build(path: path, module_constant: resource)
path.operations.each do |operation|
OperationBuilder.build(operation: operation,
module_constant: new_module,
configuration: configuration)
end
end
Service.const_set(module_name, resource)
end | ruby | {
"resource": ""
} |
q22516 | Svelte.ModelFactory.define_models | train | def define_models(json)
return unless json
models = {}
model_definitions = json['definitions']
model_definitions.each do |model_name, parameters|
attributes = parameters['properties'].keys
model = Class.new do
attr_reader(*attributes.map(&:to_sym))
parameters['properties'].each do |attribute, options|
define_method("#{attribute}=", lambda do |value|
if public_send(attribute).nil? || !public_send(attribute).present?
permitted_values = options.fetch('enum', [])
required = parameters.fetch('required', []).include?(attribute)
instance_variable_set(
"@#{attribute}",
Parameter.new(options['type'],
permitted_values: permitted_values,
required: required)
)
end
instance_variable_get("@#{attribute}").value = value
end)
end
end
define_initialize_on(model: model)
define_attributes_on(model: model)
define_required_attributes_on(model: model)
define_json_for_model_on(model: model)
define_nested_models_on(model: model)
define_as_json_on(model: model)
define_to_json_on(model: model)
define_validate_on(model: model)
define_valid_on(model: model)
model.instance_variable_set('@json_for_model', parameters.freeze)
constant_name_for_model = StringManipulator.constant_name_for(model_name)
models[constant_name_for_model] = model
end
models.each do |model_name, model|
const_set(model_name, model)
end
end | ruby | {
"resource": ""
} |
q22517 | Googl.OAuth2.server | train | def server(client_id, client_secret, redirect_uri)
Googl::OAuth2::Server.new(client_id, client_secret, redirect_uri)
end | ruby | {
"resource": ""
} |
q22518 | Cryptor.Encoding.decode | train | def decode(string)
padding_size = string.bytesize % 4
padded_string = padding_size > 0 ? string + '=' * (4 - padding_size) : string
Base64.urlsafe_decode64(padded_string)
end | ruby | {
"resource": ""
} |
q22519 | Svelte.Path.operations | train | def operations
validate_operations
@operations ||= @raw_operations.map do |operation, properties|
Operation.new(verb: operation, properties: properties, path: self)
end
end | ruby | {
"resource": ""
} |
q22520 | Harvesting.Client.create | train | def create(entity)
url = "#{DEFAULT_HOST}/#{entity.path}"
uri = URI(url)
response = http_response(:post, uri, body: entity.to_hash)
entity.attributes = JSON.parse(response.body)
entity
end | ruby | {
"resource": ""
} |
q22521 | Harvesting.Client.delete | train | def delete(entity)
url = "#{DEFAULT_HOST}/#{entity.path}"
uri = URI(url)
response = http_response(:delete, uri)
raise UnprocessableRequest(response.to_s) unless response.code.to_i == 200
JSON.parse(response.body)
end | ruby | {
"resource": ""
} |
q22522 | Harvesting.Client.get | train | def get(path, opts = {})
url = "#{DEFAULT_HOST}/#{path}"
url += "?#{opts.map {|k, v| "#{k}=#{v}"}.join("&")}" if opts.any?
uri = URI(url)
response = http_response(:get, uri)
JSON.parse(response.body)
end | ruby | {
"resource": ""
} |
q22523 | JobInterview.Knapsack.knapsack | train | def knapsack(items, capacity, algorithm = :dynamic)
if algorithm == :memoize
knapsack_memoize(items, capacity)
elsif algorithm == :dynamic
knapsack_dynamic_programming(items, capacity)
end
end | ruby | {
"resource": ""
} |
q22524 | NetAddr.IPv4Net.prev_sib | train | def prev_sib()
if (self.network.addr == 0)
return nil
end
shift = 32 - self.netmask.prefix_len
addr = ((self.network.addr>>shift) - 1) << shift
return IPv4Net.new(IPv4.new(addr), self.netmask)
end | ruby | {
"resource": ""
} |
q22525 | NetAddr.IPv4Net.summ | train | def summ(other)
if (!other.kind_of?(IPv4Net))
raise ArgumentError, "Expected an IPv4Net object for 'other' but got a #{other.class}."
end
# netmasks must be identical
if (self.netmask.prefix_len != other.netmask.prefix_len)
return nil
end
# merge-able networks will be identical if you right shift them by the number of bits in the hostmask + 1
shift = 32 - self.netmask.prefix_len + 1
addr = self.network.addr >> shift
otherAddr = other.network.addr >> shift
if (addr != otherAddr)
return nil
end
return self.resize(self.netmask.prefix_len - 1)
end | ruby | {
"resource": ""
} |
q22526 | NetAddr.IPv6Net.contains | train | def contains(ip)
if (!ip.kind_of?(IPv6))
raise ArgumentError, "Expected an IPv6 object for 'ip' but got a #{ip.class}."
end
if (@base.addr == ip.addr & @m128.mask)
return true
end
return false
end | ruby | {
"resource": ""
} |
q22527 | NetAddr.EUI64.bytes | train | def bytes()
return [
(@addr >> 56 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 48 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 40 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 32 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 24 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 16 & 0xff).to_s(16).rjust(2, "0"),
(@addr >> 8 & 0xff).to_s(16).rjust(2, "0"),
(@addr & 0xff).to_s(16).rjust(2, "0"),
]
end | ruby | {
"resource": ""
} |
q22528 | TTY.Config.set | train | def set(*keys, value: nil, &block)
assert_either_value_or_block(value, block)
keys = convert_to_keys(keys)
key = flatten_keys(keys)
value_to_eval = block || value
if validators.key?(key)
if callable_without_params?(value_to_eval)
value_to_eval = delay_validation(key, value_to_eval)
else
assert_valid(key, value)
end
end
deepest_setting = deep_set(@settings, *keys[0...-1])
deepest_setting[keys.last] = value_to_eval
deepest_setting[keys.last]
end | ruby | {
"resource": ""
} |
q22529 | TTY.Config.set_if_empty | train | def set_if_empty(*keys, value: nil, &block)
return unless deep_find(@settings, keys.last.to_s).nil?
block ? set(*keys, &block) : set(*keys, value: value)
end | ruby | {
"resource": ""
} |
q22530 | TTY.Config.set_from_env | train | def set_from_env(*keys, &block)
assert_keys_with_block(convert_to_keys(keys), block)
key = flatten_keys(keys)
env_key = block.nil? ? key : block.()
env_key = to_env_key(env_key)
@envs[key.to_s.downcase] = env_key
end | ruby | {
"resource": ""
} |
q22531 | TTY.Config.fetch | train | def fetch(*keys, default: nil, &block)
# check alias
real_key = @aliases[flatten_keys(keys)]
keys = real_key.split(key_delim) if real_key
keys = convert_to_keys(keys)
env_key = autoload_env? ? to_env_key(keys[0]) : @envs[flatten_keys(keys)]
# first try settings
value = deep_fetch(@settings, *keys)
# then try ENV var
if value.nil? && env_key
value = ENV[env_key]
end
# then try default
value = block || default if value.nil?
while callable_without_params?(value)
value = value.call
end
value
end | ruby | {
"resource": ""
} |
q22532 | TTY.Config.append | train | def append(*values, to: nil)
keys = Array(to)
set(*keys, value: Array(fetch(*keys)) + values)
end | ruby | {
"resource": ""
} |
q22533 | TTY.Config.remove | train | def remove(*values, from: nil)
keys = Array(from)
set(*keys, value: Array(fetch(*keys)) - values)
end | ruby | {
"resource": ""
} |
q22534 | TTY.Config.alias_setting | train | def alias_setting(*keys, to: nil)
flat_setting = flatten_keys(keys)
alias_keys = Array(to)
alias_key = flatten_keys(alias_keys)
if alias_key == flat_setting
raise ArgumentError, 'Alias matches setting key'
end
if fetch(alias_key)
raise ArgumentError, 'Setting already exists with an alias ' \
"'#{alias_keys.map(&:inspect).join(', ')}'"
end
@aliases[alias_key] = flat_setting
end | ruby | {
"resource": ""
} |
q22535 | TTY.Config.validate | train | def validate(*keys, &validator)
key = flatten_keys(keys)
values = validators[key] || []
values << validator
validators[key] = values
end | ruby | {
"resource": ""
} |
q22536 | TTY.Config.read | train | def read(file = find_file, format: :auto)
if file.nil?
raise ReadError, 'No file found to read configuration from!'
elsif !::File.exist?(file)
raise ReadError, "Configuration file `#{file}` does not exist!"
end
merge(unmarshal(file, format: format))
end | ruby | {
"resource": ""
} |
q22537 | TTY.Config.write | train | def write(file = find_file, force: false, format: :auto)
if file && ::File.exist?(file)
if !force
raise WriteError, "File `#{file}` already exists. " \
'Use :force option to overwrite.'
elsif !::File.writable?(file)
raise WriteError, "Cannot write to #{file}."
end
end
if file.nil?
dir = @location_paths.empty? ? Dir.pwd : @location_paths.first
file = ::File.join(dir, "#{filename}#{@extname}")
end
content = marshal(file, @settings, format: format)
::File.write(file, content)
end | ruby | {
"resource": ""
} |
q22538 | TTY.Config.assert_either_value_or_block | train | def assert_either_value_or_block(value, block)
if value.nil? && block.nil?
raise ArgumentError, 'Need to set either value or block'
elsif !(value.nil? || block.nil?)
raise ArgumentError, "Can't set both value and block"
end
end | ruby | {
"resource": ""
} |
q22539 | TTY.Config.assert_valid | train | def assert_valid(key, value)
validators[key].each do |validator|
validator.call(key, value)
end
end | ruby | {
"resource": ""
} |
q22540 | TTY.Config.deep_set | train | def deep_set(settings, *keys)
return settings if keys.empty?
key, *rest = *keys
value = settings[key]
if value.nil? && rest.empty?
settings[key] = {}
elsif value.nil? && !rest.empty?
settings[key] = {}
deep_set(settings[key], *rest)
else # nested hash value present
settings[key] = value
deep_set(settings[key], *rest)
end
end | ruby | {
"resource": ""
} |
q22541 | TTY.Config.deep_fetch | train | def deep_fetch(settings, *keys)
key, *rest = keys
value = settings.fetch(key.to_s, settings[key.to_sym])
if value.nil? || rest.empty?
value
else
deep_fetch(value, *rest)
end
end | ruby | {
"resource": ""
} |
q22542 | TTY.Config.marshal | train | def marshal(file, data, format: :auto)
file_ext = ::File.extname(file)
ext = (format == :auto ? file_ext : ".#{format}")
self.extname = file_ext
self.filename = ::File.basename(file, file_ext)
case ext
when *EXTENSIONS[:yaml]
load_write_dep('yaml', ext)
YAML.dump(self.class.normalize_hash(data, :to_s))
when *EXTENSIONS[:json]
load_write_dep('json', ext)
JSON.pretty_generate(data)
when *EXTENSIONS[:toml]
load_write_dep('toml', ext)
TOML::Generator.new(data).body
when *EXTENSIONS[:ini]
Config.generate(data)
else
raise WriteError, "Config file format `#{ext}` is not supported."
end
end | ruby | {
"resource": ""
} |
q22543 | AcmePlugin.CertGenerator.save_certificate | train | def save_certificate(certificate)
return unless certificate
return HerokuOutput.new(common_domain_name, certificate).output unless ENV['DYNO'].nil?
output_dir = File.join(Rails.root, @options[:output_cert_dir])
return FileOutput.new(common_domain_name, certificate, output_dir).output if File.directory?(output_dir)
Rails.logger.error("Output directory: '#{output_dir}' does not exist!")
end | ruby | {
"resource": ""
} |
q22544 | JDBCHelper.TableWrapper.count | train | def count *where
sql, *binds = SQLHelper.count :table => name, :where => @query_where + where, :prepared => true
pstmt = prepare :count, sql
pstmt.query(*binds).to_a[0][0].to_i
end | ruby | {
"resource": ""
} |
q22545 | JDBCHelper.TableWrapper.insert_ignore | train | def insert_ignore data_hash = {}
sql, *binds = SQLHelper.insert_ignore :table => name,
:data => @query_default.merge(data_hash),
:prepared => true
pstmt = prepare :insert, sql
pstmt.set_fetch_size @fetch_size if @fetch_size
pstmt.send @update_method, *binds
end | ruby | {
"resource": ""
} |
q22546 | JDBCHelper.TableWrapper.replace | train | def replace data_hash = {}
sql, *binds = SQLHelper.replace :table => name,
:data => @query_default.merge(data_hash),
:prepared => true
pstmt = prepare :insert, sql
pstmt.send @update_method, *binds
end | ruby | {
"resource": ""
} |
q22547 | JDBCHelper.TableWrapper.delete | train | def delete *where
sql, *binds = SQLHelper.delete(:table => name, :where => @query_where + where, :prepared => true)
pstmt = prepare :delete, sql
pstmt.send @update_method, *binds
end | ruby | {
"resource": ""
} |
q22548 | JDBCHelper.TableWrapper.select | train | def select *fields, &block
obj = self.dup
obj.instance_variable_set :@query_select, fields unless fields.empty?
ret obj, &block
end | ruby | {
"resource": ""
} |
q22549 | JDBCHelper.TableWrapper.where | train | def where *conditions, &block
raise ArgumentError.new("Wrong number of arguments") if conditions.empty?
obj = self.dup
obj.instance_variable_set :@query_where, @query_where + conditions
ret obj, &block
end | ruby | {
"resource": ""
} |
q22550 | JDBCHelper.TableWrapper.order | train | def order *criteria, &block
raise ArgumentError.new("Wrong number of arguments") if criteria.empty?
obj = self.dup
obj.instance_variable_set :@query_order, criteria
ret obj, &block
end | ruby | {
"resource": ""
} |
q22551 | JDBCHelper.TableWrapper.default | train | def default data_hash, &block
raise ArgumentError.new("Hash required") unless data_hash.kind_of? Hash
obj = self.dup
obj.instance_variable_set :@query_default, @query_default.merge(data_hash)
ret obj, &block
end | ruby | {
"resource": ""
} |
q22552 | JDBCHelper.TableWrapper.fetch_size | train | def fetch_size fsz, &block
obj = self.dup
obj.instance_variable_set :@fetch_size, fsz
ret obj, &block
end | ruby | {
"resource": ""
} |
q22553 | JDBCHelper.TableWrapper.each | train | def each &block
sql, *binds = SQLHelper.select(
:prepared => true,
:table => name,
:project => @query_select,
:where => @query_where,
:order => @query_order,
:limit => @query_limit)
pstmt = prepare :select, sql
pstmt.enumerate(*binds, &block)
end | ruby | {
"resource": ""
} |
q22554 | JDBCHelper.TableWrapper.clear_batch | train | def clear_batch *types
types = [:insert, :update, :delete] if types.empty?
types.each do |type|
raise ArgumentError.new("Invalid type: #{type}") unless @pstmts.has_key?(type)
@pstmts[type].values.each(&:clear_batch)
end
nil
end | ruby | {
"resource": ""
} |
q22555 | JDBCHelper.TableWrapper.close | train | def close
@pstmts.each do |typ, hash|
hash.each do |sql, pstmt|
pstmt.close if pstmt
end
@pstmts[typ] = {}
end
end | ruby | {
"resource": ""
} |
q22556 | JDBCHelper.FunctionWrapper.call | train | def call(*args)
pstmt = @connection.prepare("select #{name}(#{args.map{'?'}.join ','})#{@suffix}")
begin
pstmt.query(*args).to_a[0][0]
ensure
pstmt.close
end
end | ruby | {
"resource": ""
} |
q22557 | JDBCHelper.ProcedureWrapper.call | train | def call(*args)
params = build_params args
cstmt = @connection.prepare_call "{call #{name}(#{Array.new(@cols.length){'?'}.join ', '})}"
begin
process_result( args, cstmt.call(*params) )
ensure
cstmt.close
end
end | ruby | {
"resource": ""
} |
q22558 | Fernet.BitPacking.unpack_int64_bigendian | train | def unpack_int64_bigendian(bytes)
bytes.each_byte.to_a.reverse.each_with_index.
reduce(0) { |val, (byte, index)| val | (byte << (index * 8)) }
end | ruby | {
"resource": ""
} |
q22559 | JDBCHelper.Connection.transaction | train | def transaction
check_closed
raise ArgumentError.new("Transaction block not given") unless block_given?
tx = Transaction.send :new, @conn
ac = @conn.get_auto_commit
status = :unknown
begin
@conn.set_auto_commit false
yield tx
@conn.commit
status = :committed
rescue Transaction::Commit
status = :committed
rescue Transaction::Rollback
status = :rolledback
ensure
@conn.rollback if status == :unknown && @conn.get_auto_commit == false
@conn.set_auto_commit ac
end
status == :committed
end | ruby | {
"resource": ""
} |
q22560 | JDBCHelper.Connection.execute | train | def execute(qstr)
check_closed
stmt = @spool.take
begin
if stmt.execute(qstr)
ResultSet.send(:new, stmt.getResultSet) { @spool.give stmt }
else
rset = stmt.getUpdateCount
@spool.give stmt
rset
end
rescue Exception => e
@spool.give stmt
raise
end
end | ruby | {
"resource": ""
} |
q22561 | JDBCHelper.Connection.query | train | def query(qstr, &blk)
check_closed
stmt = @spool.take
begin
rset = stmt.execute_query(qstr)
rescue Exception => e
@spool.give stmt
raise
end
enum = ResultSet.send(:new, rset) { @spool.give stmt }
if block_given?
enum.each do |row|
yield row
end
else
enum
end
end | ruby | {
"resource": ""
} |
q22562 | JDBCHelper.Connection.execute_batch | train | def execute_batch
check_closed
cnt = 0
if @bstmt
cnt += @bstmt.execute_batch.inject(:+) || 0
@spool.give @bstmt
@bstmt = nil
end
@pstmts.each do |pstmt|
cnt += pstmt.execute_batch
end
cnt
end | ruby | {
"resource": ""
} |
q22563 | JDBCHelper.Connection.table | train | def table table_name
table = JDBCHelper::TableWrapper.new(self, table_name)
table = table.fetch_size(@fetch_size) if @fetch_size
@table_wrappers[table_name] ||= table
end | ruby | {
"resource": ""
} |
q22564 | Chargify.Subscription.save | train | def save
self.attributes.stringify_keys!
self.attributes.delete('customer')
self.attributes.delete('product')
self.attributes.delete('credit_card')
self.attributes.delete('bank_account')
self.attributes.delete('paypal_account')
self.attributes, options = extract_uniqueness_token(attributes)
self.prefix_options.merge!(options)
super
end | ruby | {
"resource": ""
} |
q22565 | Oxcelix.Workbook.unpack | train | def unpack(filename)
@destination = Dir.mktmpdir
Zip::File.open(filename){ |zip_file|
zip_file.each{ |f|
f_path=File.join(@destination, f.name)
FileUtils.mkdir_p(File.dirname(f_path))
zip_file.extract(f, f_path) unless File.exists?(f_path)
}
}
end | ruby | {
"resource": ""
} |
q22566 | Oxcelix.Workbook.parse | train | def parse(options={})
@sheets.each do |x|
if !options[:paginate].nil?
lines = options[:paginate][0]; page = options[:paginate][1]
sheet = PagSheet.new(lines, page)
elsif !options[:cellrange].nil?
range = options[:cellrange]
sheet = Cellrange.new(range)
else
sheet = Xlsheet.new()
end
File.open(@destination+"/xl/#{x[:filename]}", 'r') do |f|
Ox.sax_parse(sheet, f)
end
comments = mkcomments(x[:comments])
sheet.cellarray.each do |sh|
sh.numformat = @styles.styleary[sh.style.to_i]
if sh.type=="s"
sh.value = @sharedstrings[sh.value.to_i]
end
if !comments.nil?
comm=comments.select {|c| c[:ref]==(sh.xlcoords)}
if comm.size > 0
sh.comment=comm[0][:comment]
end
comments.delete_if{|c| c[:ref]==(sh.xlcoords)}
end
end
x[:cells] = sheet.cellarray
x[:mergedcells] = sheet.mergedcells
end
matrixto options
end | ruby | {
"resource": ""
} |
q22567 | Oxcelix.Workbook.commentsrel | train | def commentsrel
unless Dir[@destination + '/xl/worksheets/_rels'].empty?
Find.find(@destination + '/xl/worksheets/_rels') do |path|
if File.basename(path).split(".").last=='rels'
a=IO.read(path)
f=Ox::load(a)
f.locate("Relationships/*").each do |x|
if x[:Target].include?"comments"
@sheets.each do |s|
if "worksheets/" + File.basename(path,".rels")==s[:filename]
s[:comments]=x[:Target]
end
end
end
end
end
end
else
@sheets.each do |s|
s[:comments]=nil
end
end
end | ruby | {
"resource": ""
} |
q22568 | Oxcelix.Workbook.shstrings | train | def shstrings
strings = Sharedstrings.new()
File.open(@destination + '/xl/sharedStrings.xml', 'r') do |f|
Ox.sax_parse(strings, f)
end
@sharedstrings=strings.stringarray
end | ruby | {
"resource": ""
} |
q22569 | Oxcelix.Workbook.mkcomments | train | def mkcomments(commentfile)
unless commentfile.nil?
comms = Comments.new()
File.open(@destination + '/xl/'+commentfile.gsub('../', ''), 'r') do |f|
Ox.sax_parse(comms, f)
end
return comms.commarray
end
end | ruby | {
"resource": ""
} |
q22570 | Oxcelix.Workbook.mergevalues | train | def mergevalues(m, col, row, valuecell)
if valuecell != nil
valuecell.xlcoords=(col.col_name)+(row+1).to_s
m[row, col]=valuecell
return m, valuecell
else
valuecell=Cell.new
valuecell.xlcoords=(col.col_name)+(row+1).to_s
m[row, col]=valuecell
return m, valuecell
end
end | ruby | {
"resource": ""
} |
q22571 | Oxcelix.Numformats.datetime | train | def datetime formatcode
deminutified = formatcode.downcase.gsub(/(?<hrs>H|h)(?<div>.)m/, '\k<hrs>\k<div>i')
.gsub(/im/, 'ii')
.gsub(/m(?<div>.)(?<secs>s)/, 'i\k<div>\k<secs>')
.gsub(/mi/, 'ii')
return deminutified.gsub(/[yMmDdHhSsi]*/, Dtmap)
end | ruby | {
"resource": ""
} |
q22572 | Oxcelix.Numberhelper.to_ru | train | def to_ru
if !@value.numeric? || Numformats::Formatarray[@numformat.to_i][:xl] == nil || Numformats::Formatarray[@numformat.to_i][:xl].downcase == "general"
return @value
end
if Numformats::Formatarray[@numformat.to_i][:cls] == 'date'
return DateTime.new(1899, 12, 30) + (eval @value)
elsif Numformats::Formatarray[@numformat.to_i][:cls] == 'numeric' || Numformats::Formatarray[@numformat.to_i][:cls] == 'rational'
return eval @value rescue @value
end
end | ruby | {
"resource": ""
} |
q22573 | Oxcelix.Numberhelper.to_fmt | train | def to_fmt
begin
if Numformats::Formatarray[@numformat.to_i][:cls] == 'date'
self.to_ru.strftime(Numformats::Formatarray[@numformat][:ostring]) rescue @value
elsif Numformats::Formatarray[@numformat.to_i][:cls] == 'numeric' || Numformats::Formatarray[@numformat.to_i][:cls] == 'rational'
sprintf(Numformats::Formatarray[@numformat][:ostring], self.to_ru) rescue @value
else
return @value
end
end
end | ruby | {
"resource": ""
} |
q22574 | Oxcelix.Sheet.to_m | train | def to_m(*attrs)
m=Matrix.build(self.row_size, self.column_size){nil}
self.each_with_index do |x, row, col|
if attrs.size == 0 || attrs.nil?
m[row, col] = x.value
end
end
return m
end | ruby | {
"resource": ""
} |
q22575 | LolSoap.Envelope.body | train | def body(klass = Builder)
builder = klass.new(body_content, input_body_content_type)
yield builder if block_given?
builder
end | ruby | {
"resource": ""
} |
q22576 | LolSoap.Envelope.header | train | def header(klass = Builder)
builder = klass.new(header_content, input_header_content_type)
yield builder if block_given?
builder
end | ruby | {
"resource": ""
} |
q22577 | GhInspector.Inspector.search_exception | train | def search_exception(exception, delegate = nil)
query = ExceptionHound.new(exception).query
search_query(query, delegate)
end | ruby | {
"resource": ""
} |
q22578 | GhInspector.Inspector.search_query | train | def search_query(query, delegate = nil)
delegate ||= Evidence.new
sidekick.search(query, delegate)
end | ruby | {
"resource": ""
} |
q22579 | LolSoap.WSDL.type | train | def type(namespace, name)
if @allow_abstract_types
@types.fetch([namespace, name]) { abstract_type(namespace, name) }
else
@types.fetch([namespace, name]) { NullType.new }
end
end | ruby | {
"resource": ""
} |
q22580 | LolSoap.Response.fault | train | def fault
@fault ||= begin
node = doc.at_xpath('/soap:Envelope/soap:Body/soap:Fault', 'soap' => soap_namespace)
Fault.new(request, node) if node
end
end | ruby | {
"resource": ""
} |
q22581 | GhInspector.Sidekick.search | train | def search(query, delegate)
validate_delegate(delegate)
delegate.inspector_started_query(query, inspector)
url = url_for_request query
begin
results = get_api_results(url)
rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e
delegate.inspector_could_not_create_report(e, query, inspector)
return
end
report = parse_results query, results
# TODO: progress callback
if report.issues.any?
if self.using_deprecated_method
delegate.inspector_successfully_recieved_report(report, inspector)
else
delegate.inspector_successfully_received_report(report, inspector)
end
else
# rubocop:disable Style/IfInsideElse
if self.using_deprecated_method
delegate.inspector_recieved_empty_report(report, inspector)
else
delegate.inspector_received_empty_report(report, inspector)
end
# rubocop:enable Style/IfInsideElse
end
report
end | ruby | {
"resource": ""
} |
q22582 | GhInspector.Sidekick.url_for_request | train | def url_for_request(query, sort_by: nil, order: nil)
url = "https://api.github.com/search/issues?q="
url += ERB::Util.url_encode(query)
url += "+repo:#{repo_owner}/#{repo_name}"
url += "&sort=#{sort_by}" if sort_by
url += "&order=#{order}" if order
url
end | ruby | {
"resource": ""
} |
q22583 | GhInspector.Sidekick.get_api_results | train | def get_api_results(url)
uri = URI.parse(url)
puts "URL: #{url}" if self.verbose
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
JSON.parse(response.body)
end | ruby | {
"resource": ""
} |
q22584 | GhInspector.Sidekick.parse_results | train | def parse_results(query, results)
report = InspectionReport.new
report.url = "https://github.com/#{repo_owner}/#{repo_name}/search?q=#{ERB::Util.url_encode(query)}&type=Issues&utf8=✓"
report.query = query
report.total_results = results['total_count']
report.issues = results['items'].map { |item| Issue.new(item) }
report
end | ruby | {
"resource": ""
} |
q22585 | Blogit.CommentsHelper.name_for_comment | train | def name_for_comment(comment)
if comment.website?
link_to(comment.name, comment.website, class: "blogit_comment__name_link")
else
comment.name
end + " " + t('wrote', scope: "blogit.comments")
end | ruby | {
"resource": ""
} |
q22586 | StateMachines.Machine.draw | train | def draw(graph_options = {})
name = graph_options.delete(:name) || "#{owner_class.name}_#{self.name}"
draw_options = {:human_name => false}
draw_options[:human_name] = graph_options.delete(:human_names) if graph_options.include?(:human_names)
graph = Graph.new(name, graph_options)
# Add nodes / edges
states.by_priority.each { |state| state.draw(graph, draw_options) }
events.each { |event| event.draw(graph, self, draw_options) }
# Output result
graph.output
graph
end | ruby | {
"resource": ""
} |
q22587 | Blogit.ApplicationHelper.div_tag_with_default_class | train | def div_tag_with_default_class(default_class, content_or_options, options, &block)
if block_given?
options = content_or_options
content = capture(&block)
else
content = content_or_options
end
options[:class] = Array(options[:class]) + [default_class]
content_tag(:div, content, options)
end | ruby | {
"resource": ""
} |
q22588 | Payu.Pos.validate_options! | train | def validate_options!
raise PosInvalid.new('Missing pos_id parameter') if pos_id.nil? || pos_id == 0
raise PosInvalid.new('Missing pos_auth_key parameter') if pos_auth_key.nil? || pos_auth_key == ''
raise PosInvalid.new('Missing key1 parameter') if key1.nil? || key1 == ''
raise PosInvalid.new('Missing key2 parameter') if key2.nil? || key2 == ''
raise PosInvalid.new("Invalid variant parameter, expected one of these: #{TYPES.join(', ')}") unless TYPES.include?(variant)
raise PosInvalid.new("Invalid encoding parameter, expected one of these: #{ENCODINGS.join(', ')}") unless ENCODINGS.include?(encoding)
end | ruby | {
"resource": ""
} |
q22589 | Payu.Pos.new_transaction | train | def new_transaction(options = {})
options = options.dup
options.merge!({
:pos_id => @pos_id,
:pos_auth_key => @pos_auth_key,
:gateway_url => options[:gateway_url] || @gateway_url,
:key1 => @key1,
:encoding => encoding,
:variant => variant
})
if !options.has_key?(:add_signature)
options[:add_signature] = add_signature?
end
if !options.has_key?(:pay_type)
options[:pay_type] = test_payment? ? 't' : nil
end
Transaction.new(options)
end | ruby | {
"resource": ""
} |
q22590 | Payu.Helpers.payu_hidden_fields | train | def payu_hidden_fields(transaction)
html = ""
%w(pos_id pos_auth_key pay_type session_id amount amount_netto desc
order_id desc2 trsDesc first_name last_name street street_hn
street_an city post_code country email phone language client_ip
js payback_login sig ts
).each do |field|
value = transaction.send(field)
html << hidden_field_tag(field, value) unless value.blank?
end
html.html_safe
end | ruby | {
"resource": ""
} |
q22591 | Payu.Helpers.payu_verify_params | train | def payu_verify_params(params)
pos_id = params['pos_id']
pos = Payu[pos_id]
Signature.verify!(
params['sig'],
params['pos_id'],
params['session_id'],
params['ts'],
pos.key2
)
end | ruby | {
"resource": ""
} |
q22592 | Smartsheet.GeneralRequest.request | train | def request(method:, url_path:, body: nil, params: {}, header_overrides: {})
spec = body.nil? ? {} : {body_type: :json}
endpoint_spec = Smartsheet::API::EndpointSpec.new(method, [url_path], **spec)
request_spec = Smartsheet::API::RequestSpec.new(
header_overrides: header_overrides,
body: body,
params: params
)
client.make_request(endpoint_spec, request_spec)
end | ruby | {
"resource": ""
} |
q22593 | Smartsheet.GeneralRequest.request_with_file | train | def request_with_file(
method:,
url_path:,
file:,
file_length:,
filename:,
content_type: '',
params: {},
header_overrides: {}
)
endpoint_spec = Smartsheet::API::EndpointSpec.new(method, [url_path], body_type: :file)
request_spec = Smartsheet::API::RequestSpec.new(
header_overrides: header_overrides,
params: params,
file_spec: Smartsheet::API::ObjectFileSpec.new(file, filename, file_length, content_type)
)
client.make_request(endpoint_spec, request_spec)
end | ruby | {
"resource": ""
} |
q22594 | Smartsheet.GeneralRequest.request_with_file_from_path | train | def request_with_file_from_path(
method:,
url_path:,
path:,
filename: nil,
content_type: '',
params: {},
header_overrides: {}
)
endpoint_spec = Smartsheet::API::EndpointSpec.new(method, [url_path], body_type: :file)
request_spec = Smartsheet::API::RequestSpec.new(
header_overrides: header_overrides,
params: params,
file_spec: Smartsheet::API::PathFileSpec.new(path, filename, content_type)
)
client.make_request(endpoint_spec, request_spec)
end | ruby | {
"resource": ""
} |
q22595 | Octopress.Ink.list | train | def list(options={})
site = Octopress.site(options)
Plugins.register
options = {'minimal'=>true} if options.empty?
message = "Octopress Ink - v#{VERSION}\n"
if plugins.size > 0
plugins.each do |plugin|
message += plugin.list(options)
end
else
message += "You have no plugins installed."
end
puts message
end | ruby | {
"resource": ""
} |
q22596 | Octopress.Ink.copy_doc | train | def copy_doc(source, dest, permalink=nil)
contents = File.open(source).read
# Convert H1 to title and add permalink in YAML front-matter
#
contents.sub!(/^# (.*)$/, "#{doc_yaml('\1', permalink).strip}")
FileUtils.mkdir_p File.dirname(dest)
File.open(dest, 'w') {|f| f.write(contents) }
puts "Updated #{dest} from #{source}"
end | ruby | {
"resource": ""
} |
q22597 | PusherClient.Socket.connect | train | def connect(async = false)
@connection_thread = Thread.new do
@connection = TestConnection.new
@global_channel.dispatch('pusher:connection_established', JSON.dump({'socket_id' => '123abc'}))
end
@connection_thread.run
@connection_thread.join unless async
return self
end | ruby | {
"resource": ""
} |
q22598 | PusherClient.Socket.authorize | train | def authorize(channel, callback)
if is_private_channel(channel.name)
auth_data = get_private_auth(channel)
elsif is_presence_channel(channel.name)
auth_data = get_presence_auth(channel)
end
# could both be nil if didn't require auth
callback.call(channel, auth_data, channel.user_data)
end | ruby | {
"resource": ""
} |
q22599 | OneviewSDK.Cli.console | train | def console
client_setup({}, true, true)
puts "Console Connected to #{@client.url}"
puts "HINT: The @client object is available to you\n\n"
rescue
puts "WARNING: Couldn't connect to #{@options['url'] || ENV['ONEVIEWSDK_URL']}\n\n"
ensure
require 'pry'
Pry.config.prompt = proc { '> ' }
Pry.plugins['stack_explorer'] && Pry.plugins['stack_explorer'].disable!
Pry.plugins['byebug'] && Pry.plugins['byebug'].disable!
Pry.start(OneviewSDK::Console.new(@client))
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.