_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q19900 | BaseCRM.DealUnqualifiedReasonsService.update | train | def update(deal_unqualified_reason)
validate_type!(deal_unqualified_reason)
params = extract_params!(deal_unqualified_reason, :id)
id = params[:id]
attributes = sanitize(deal_unqualified_reason)
_, _, root = @client.put("/deal_unqualified_reasons/#{id}", attributes)
DealUnqualified... | ruby | {
"resource": ""
} |
q19901 | ISO8601.Date.+ | train | def +(other)
other = other.to_days if other.respond_to?(:to_days)
ISO8601::Date.new((@date + other).iso8601)
end | ruby | {
"resource": ""
} |
q19902 | ISO8601.Date.atomize | train | def atomize(input)
week_date = parse_weekdate(input)
return atomize_week_date(input, week_date[2], week_date[1]) unless week_date.nil?
_, sign, year, separator, day = parse_ordinal(input)
return atomize_ordinal(year, day, separator, sign) unless year.nil?
_, year, separator, month, day =... | ruby | {
"resource": ""
} |
q19903 | ISO8601.Duration.months_to_seconds | train | def months_to_seconds(base)
month_base = base.nil? ? nil : base + years.to_seconds(base)
months.to_seconds(month_base)
end | ruby | {
"resource": ""
} |
q19904 | ISO8601.Duration.atomize | train | def atomize(input)
duration = parse(input) || raise(ISO8601::Errors::UnknownPattern, input)
valid_pattern?(duration)
@sign = sign_to_i(duration[:sign])
components = parse_tokens(duration)
components.delete(:time) # clean time capture
valid_fractions?(components.values)
com... | ruby | {
"resource": ""
} |
q19905 | ISO8601.Duration.fetch_seconds | train | def fetch_seconds(other, base = nil)
case other
when ISO8601::Duration
other.to_seconds(base)
when Numeric
other.to_f
else
raise(ISO8601::Errors::TypeError, other)
end
end | ruby | {
"resource": ""
} |
q19906 | ISO8601.Years.to_seconds | train | def to_seconds(base = nil)
valid_base?(base)
return factor(base) * atom if base.nil?
target = ::Time.new(base.year + atom.to_i, base.month, base.day, base.hour, base.minute, base.second, base.zone)
target - base.to_time
end | ruby | {
"resource": ""
} |
q19907 | ISO8601.TimeInterval.include? | train | def include?(other)
raise(ISO8601::Errors::TypeError, "The parameter must respond_to #to_time") \
unless other.respond_to?(:to_time)
(first.to_time <= other.to_time &&
last.to_time >= other.to_time)
end | ruby | {
"resource": ""
} |
q19908 | ISO8601.TimeInterval.subset? | train | def subset?(other)
raise(ISO8601::Errors::TypeError, "The parameter must be an instance of #{self.class}") \
unless other.is_a?(self.class)
other.include?(first) && other.include?(last)
end | ruby | {
"resource": ""
} |
q19909 | ISO8601.TimeInterval.intersection | train | def intersection(other)
raise(ISO8601::Errors::IntervalError, "The intervals are disjoint") \
if disjoint?(other) && other.disjoint?(self)
return self if subset?(other)
return other if other.subset?(self)
a, b = sort_pair(self, other)
self.class.from_datetimes(b.first, a.last)
... | ruby | {
"resource": ""
} |
q19910 | ISO8601.TimeInterval.parse_subpattern | train | def parse_subpattern(pattern)
return ISO8601::Duration.new(pattern) if pattern.start_with?('P')
ISO8601::DateTime.new(pattern)
end | ruby | {
"resource": ""
} |
q19911 | ISO8601.DateTime.parse | train | def parse(date_time)
raise(ISO8601::Errors::UnknownPattern, date_time) if date_time.empty?
date, time = date_time.split('T')
date_atoms = parse_date(date)
time_atoms = Array(time && parse_time(time))
separators = [date_atoms.pop, time_atoms.pop]
raise(ISO8601::Errors::UnknownPatte... | ruby | {
"resource": ""
} |
q19912 | ISO8601.DateTime.parse_date | train | def parse_date(input)
today = ::Date.today
return [today.year, today.month, today.day, :ignore] if input.empty?
date = ISO8601::Date.new(input)
date.atoms << date.separator
end | ruby | {
"resource": ""
} |
q19913 | ISO8601.DateTime.valid_representation? | train | def valid_representation?(date, time)
year, month, day = date
hour = time.first
date.nil? || !(!year.nil? && (month.nil? || day.nil?) && !hour.nil?)
end | ruby | {
"resource": ""
} |
q19914 | SpecHelper.TemporaryRepos.repo_make | train | def repo_make(name)
path = repo_path(name)
path.mkpath
Dir.chdir(path) do
`git init`
repo_make_readme_change(name, 'Added')
`git add .`
`git commit -m "Initialized."`
end
path
end | ruby | {
"resource": ""
} |
q19915 | AsciiBinder.Engine.local_branches | train | def local_branches
@local_branches ||= begin
branches = []
if not git.branches.local.empty?
branches << git.branches.local.select{ |b| b.current }[0].name
branches << git.branches.local.select{ |b| not b.current }.map{ |b| b.name }
end
branches.flatten
end... | ruby | {
"resource": ""
} |
q19916 | ISO8583.Message.[] | train | def [](key)
bmp_def = _get_definition key
bmp = @values[bmp_def.bmp]
bmp ? bmp.value : nil
end | ruby | {
"resource": ""
} |
q19917 | ISO8583.Message.to_s | train | def to_s
_mti_name = _get_mti_definition(mti)[1]
str = "MTI:#{mti} (#{_mti_name})\n\n"
_max = @values.values.max {|a,b|
a.name.length <=> b.name.length
}
_max_name = _max.name.length
@values.keys.sort.each{|bmp_num|
_bmp = @values[bmp_num]
str += ("%03d %#{_m... | ruby | {
"resource": ""
} |
q19918 | ISO8583.Bitmap.[]= | train | def []=(i, value)
if i > 128
raise ISO8583Exception.new("Bits > 128 are not permitted.")
elsif i < 2
raise ISO8583Exception.new("Bits < 2 are not permitted (continutation bit is set automatically)")
end
@bmp[i-1] = (value == true)
end | ruby | {
"resource": ""
} |
q19919 | ISO8583.Bitmap.to_bytes | train | def to_bytes
# Convert binary to hex, by slicing the binary in 4 bytes chuncks
bitmap_hex = ""
str = ""
self.to_s.chars.reverse.each_with_index do |ch, i|
str << ch
next if i == 0
if (i+1) % 4 == 0
bitmap_hex << str.reverse.to_i(2).to_s(16)
str = ""
... | ruby | {
"resource": ""
} |
q19920 | DaFunk.Helper.try_user | train | def try_user(timeout = Device::IO.timeout, options = nil, &block)
time = timeout != 0 ? Time.now + timeout / 1000 : Time.now
processing = Hash.new(keep: true)
interation = 0
files = options[:bmps][:attach_loop] if options && options[:bmps].is_a?(Hash)
max = (files.size - 1) if ... | ruby | {
"resource": ""
} |
q19921 | DaFunk.Helper.menu | train | def menu(title, selection, options = {})
return nil if selection.empty?
options[:number] = true if options[:number].nil?
options[:timeout] ||= Device::IO.timeout
key, selected = pagination(title, options, selection) do |collection, line_zero|
collection.each_with_index do |value,i|
... | ruby | {
"resource": ""
} |
q19922 | Looksee.Editor.edit | train | def edit(object, method_name)
method = LookupPath.new(object).find(method_name.to_s) or
raise NoMethodError, "no method `#{method_name}' in lookup path of #{object.class} instance"
file, line = method.source_location
if !file
raise NoSourceLocationError, "no source location for #{metho... | ruby | {
"resource": ""
} |
q19923 | Looksee.Editor.command_for | train | def command_for(file, line)
line = line.to_s
words = Shellwords.shellwords(command)
words.map! do |word|
word.gsub!(/%f/, file)
word.gsub!(/%l/, line)
word.gsub!(/%%/, '%')
word
end
end | ruby | {
"resource": ""
} |
q19924 | Looksee.Inspector.edit | train | def edit(name)
Editor.new(Looksee.editor).edit(lookup_path.object, name)
end | ruby | {
"resource": ""
} |
q19925 | Watirsome.Regions.has_one | train | def has_one(region_name, **opts, &block)
within = opts[:in] || opts[:within]
region_class = opts[:class] || opts[:region_class]
define_region_accessor(region_name, within: within, region_class: region_class, &block)
end | ruby | {
"resource": ""
} |
q19926 | Watirsome.Regions.has_many | train | def has_many(region_name, **opts, &block)
region_class = opts[:class] || opts[:region_class]
collection_class = opts[:through] || opts[:collection_class]
each = opts[:each] || raise(ArgumentError, '"has_many" method requires "each" param')
within = opts[:in] || opts[:within]
define_region_... | ruby | {
"resource": ""
} |
q19927 | Gecko.Client.authorize_from_refresh_token | train | def authorize_from_refresh_token(refresh_token)
@access_token = oauth_client.get_token({
client_id: oauth_client.id,
client_secret: oauth_client.secret,
refresh_token: refresh_token,
grant_type: 'refresh_token'
})
end | ruby | {
"resource": ""
} |
q19928 | CQM.Measure.as_hqmf_model | train | def as_hqmf_model
json = {
'id' => hqmf_id,
'title' => title,
'description' => description,
'population_criteria' => population_criteria,
'data_criteria' => data_criteria,
'source_data_criteria' => source_data_criteria,
'measure_period' => measure_period,
... | ruby | {
"resource": ""
} |
q19929 | QDM.DataElement.code_system_pairs | train | def code_system_pairs
codes.collect do |code|
{ code: code.code, system: code.codeSystem }
end
end | ruby | {
"resource": ""
} |
q19930 | QDM.DataElement.shift_dates | train | def shift_dates(seconds)
# Iterate over fields
fields.keys.each do |field|
# Check if field is a DateTime
if send(field).is_a? DateTime
send(field + '=', (send(field).to_time + seconds.seconds).to_datetime)
end
# Check if field is an Interval
if (send(field)... | ruby | {
"resource": ""
} |
q19931 | QDM.Interval.shift_dates | train | def shift_dates(seconds)
if (@low.is_a? DateTime) || (@low.is_a? Time)
@low = (@low.utc.to_time + seconds.seconds).to_datetime.new_offset(0)
end
if (@high.is_a? DateTime) || (@high.is_a? Time)
@high = (@high.utc.to_time + seconds.seconds).to_datetime.new_offset(0)
@high = @high... | ruby | {
"resource": ""
} |
q19932 | QDM.Patient.shift_dates | train | def shift_dates(seconds)
self.birthDatetime = (birthDatetime.utc.to_time + seconds.seconds).to_datetime
dataElements.each { |element| element.shift_dates(seconds) }
end | ruby | {
"resource": ""
} |
q19933 | GovukElementsFormBuilder.FormBuilder.fields_for | train | def fields_for record_name, record_object = nil, fields_options = {}, &block
super record_name, record_object, fields_options.merge(builder: self.class), &block
end | ruby | {
"resource": ""
} |
q19934 | GovukElementsFormBuilder.FormBuilder.merge_attributes | train | def merge_attributes attributes, default:
hash = attributes || {}
hash.merge(default) { |_key, oldval, newval| Array(newval) + Array(oldval) }
end | ruby | {
"resource": ""
} |
q19935 | VagrantCloud.Box.update | train | def update(args = {})
# hash arguments kept for backwards compatibility
return @data if args.empty?
org = args[:organization] || account.username
box_name = args[:name] || @name
data = @client.request('put', box_path(org, box_name), box: args)
# Update was called on *this* object,... | ruby | {
"resource": ""
} |
q19936 | VagrantCloud.Search.search | train | def search(query = nil, provider = nil, sort = nil, order = nil, limit = nil, page = nil)
params = {
q: query,
provider: provider,
sort: sort,
order: order,
limit: limit,
page: page
}.delete_if { |_, v| v.nil? }
@client.request('get', '/search', params)... | ruby | {
"resource": ""
} |
q19937 | Paru.Filter.filter | train | def filter(&block)
@selectors = Hash.new
@filtered_nodes = []
@document = read_document
@metadata = PandocFilter::Metadata.new @document.meta
nodes_to_filter = Enumerator.new do |node_list|
@document.each_depth_first do |node|
... | ruby | {
"resource": ""
} |
q19938 | Paru.Filter.with | train | def with(selector)
@selectors[selector] = Selector.new selector unless @selectors.has_key? selector
yield @current_node if @selectors[selector].matches? @current_node, @filtered_nodes
end | ruby | {
"resource": ""
} |
q19939 | Paru.Selector.matches? | train | def matches? node, filtered_nodes
node.type == @type and
@classes.all? {|c| node.has_class? c } and
@relations.all? {|r| r.matches? node, filtered_nodes}
end | ruby | {
"resource": ""
} |
q19940 | Riemann.Event.[] | train | def [](k)
if RESERVED_FIELDS.include? k.to_sym
super
else
r = attributes.find {|a| a.key.to_s == k.to_s }.value
end
end | ruby | {
"resource": ""
} |
q19941 | Riemann.AutoState.once | train | def once(opts)
o = @state.merge opts
o[:time] = Time.now.to_i
o[:tags] = ((o[:tags] | ["once"]) rescue ["once"])
@client << o
end | ruby | {
"resource": ""
} |
q19942 | Slimmer.Headers.set_slimmer_headers | train | def set_slimmer_headers(hash)
raise InvalidHeader if (hash.keys - SLIMMER_HEADER_MAPPING.keys).any?
SLIMMER_HEADER_MAPPING.each do |hash_key, header_suffix|
value = hash[hash_key]
headers["#{HEADER_PREFIX}-#{header_suffix}"] = value.to_s if value
end
end | ruby | {
"resource": ""
} |
q19943 | PryDebugger.Breakpoints.add | train | def add(file, line, expression = nil)
real_file = (file != Pry.eval_path)
raise ArgumentError, 'Invalid file!' if real_file && !File.exist?(file)
validate_expression expression
Pry.processor.debugging = true
path = (real_file ? File.expand_path(file) : file)
Debugger.add_breakpoint... | ruby | {
"resource": ""
} |
q19944 | PryDebugger.Breakpoints.change | train | def change(id, expression = nil)
validate_expression expression
breakpoint = find_by_id(id)
breakpoint.expr = expression
breakpoint
end | ruby | {
"resource": ""
} |
q19945 | PryDebugger.Breakpoints.delete | train | def delete(id)
unless Debugger.started? && Debugger.remove_breakpoint(id)
raise ArgumentError, "No breakpoint ##{id}"
end
Pry.processor.debugging = false if to_a.empty?
end | ruby | {
"resource": ""
} |
q19946 | PryDebugger.Breakpoints.clear | train | def clear
Debugger.breakpoints.clear if Debugger.started?
Pry.processor.debugging = false
end | ruby | {
"resource": ""
} |
q19947 | PryDebugger.Processor.stop | train | def stop
Debugger.stop if !@always_enabled && Debugger.started?
if PryDebugger.current_remote_server # Cleanup DRb remote if running
PryDebugger.current_remote_server.teardown
end
end | ruby | {
"resource": ""
} |
q19948 | Fudge.TaskDSL.task | train | def task(name, *args)
klass = Fudge::Tasks.discover(name)
task = klass.new(*args)
current_scope.tasks << task
with_scope(task) { yield if block_given? }
end | ruby | {
"resource": ""
} |
q19949 | Fudge.TaskDSL.method_missing | train | def method_missing(meth, *args, &block)
task meth, *args, &block
rescue Fudge::Exceptions::TaskNotFound
super
end | ruby | {
"resource": ""
} |
q19950 | Fudge.FileFinder.generate_command | train | def generate_command(name, tty_options)
cmd = []
cmd << name
cmd += tty_options
cmd << "`#{find_filters.join(' | ')}`"
cmd.join(' ')
end | ruby | {
"resource": ""
} |
q19951 | Fudge.Cli.init | train | def init
generator = Fudge::Generator.new(Dir.pwd)
msg = generator.write_fudgefile
shell.say msg
end | ruby | {
"resource": ""
} |
q19952 | Fudge.Cli.build | train | def build(build_name='default')
description = Fudge::Parser.new.parse('Fudgefile')
Fudge::Runner.new(description).run_build(build_name, options)
end | ruby | {
"resource": ""
} |
q19953 | Fudge.Description.build | train | def build(name, options={})
@builds[name] = build = Build.new(options)
with_scope(build) { yield }
end | ruby | {
"resource": ""
} |
q19954 | Fudge.Description.task_group | train | def task_group(name, *args, &block)
if block
@task_groups[name] = block
else
find_task_group(name).call(*args)
end
end | ruby | {
"resource": ""
} |
q19955 | Fudge.Description.find_task_group | train | def find_task_group(name)
@task_groups[name].tap do |block|
raise Exceptions::TaskGroupNotFound.new(name) unless block
end
end | ruby | {
"resource": ""
} |
q19956 | Fudge.Runner.run_build | train | def run_build(which_build='default', options={})
formatter = options[:formatter] || Fudge::Formatters::Simple.new
output_start(which_build, formatter)
status = run(which_build, options)
output_status(status, formatter)
end | ruby | {
"resource": ""
} |
q19957 | Libhoney.Event.with_timer | train | def with_timer(name)
start = Time.now
yield
duration = Time.now - start
# report in ms
add_field(name, duration * 1000)
self
end | ruby | {
"resource": ""
} |
q19958 | Yoti.Configuration.validate_required_all | train | def validate_required_all(required_configs)
required_configs.each do |config|
unless config_set?(config)
message = "Configuration value `#{config}` is required."
raise ConfigurationError, message
end
end
end | ruby | {
"resource": ""
} |
q19959 | Yoti.Configuration.validate_required_any | train | def validate_required_any(required_configs)
valid = required_configs.select { |config| config_set?(config) }
return if valid.any?
config_list = required_configs.map { |conf| '`' + conf + '`' }.join(', ')
message = "At least one of the configuration values has to be set: #{config_list}."
... | ruby | {
"resource": ""
} |
q19960 | Yoti.Configuration.validate_value | train | def validate_value(config, allowed_values)
value = instance_variable_get("@#{config}")
return unless invalid_value?(value, allowed_values)
message = "Configuration value `#{value}` is not allowed for `#{config}`."
raise ConfigurationError, message
end | ruby | {
"resource": ""
} |
q19961 | Libhoney.LogTransmissionClient.add | train | def add(event)
if @verbose
metadata = "Honeycomb dataset '#{event.dataset}' | #{event.timestamp.iso8601}"
metadata << " (sample rate: #{event.sample_rate})" if event.sample_rate != 1
@output.print("#{metadata} | ")
end
@output.puts(event.data.to_json)
end | ruby | {
"resource": ""
} |
q19962 | Libhoney.Client.send_event | train | def send_event(event)
@lock.synchronize do
transmission_client_params = {
max_batch_size: @max_batch_size,
send_frequency: @send_frequency,
max_concurrent_batches: @max_concurrent_batches,
pending_work_capacity: @pending_work_capacity,
responses: @response... | ruby | {
"resource": ""
} |
q19963 | Yoti.Request.body | train | def body
raise RequestError, 'The request requires a HTTP method.' unless @http_method
raise RequestError, 'The payload needs to be a hash.' unless @payload.to_s.empty? || @payload.is_a?(Hash)
res = Net::HTTP.start(uri.hostname, Yoti.configuration.api_port, use_ssl: https_uri?) do |http|
sign... | ruby | {
"resource": ""
} |
q19964 | BookingSync::API.Response.process_data | train | def process_data(hash)
Array(hash).map do |hash|
Resource.new(client, hash, resource_relations, resources_key)
end
end | ruby | {
"resource": ""
} |
q19965 | BookingSync::API.Client.request | train | def request(method, path, data = nil, options = nil)
instrument("request.bookingsync_api", method: method, path: path) do
response = call(method, path, data, options)
response.respond_to?(:resources) ? response.resources : response
end
end | ruby | {
"resource": ""
} |
q19966 | BookingSync::API.Client.paginate | train | def paginate(path, options = {}, &block)
instrument("paginate.bookingsync_api", path: path) do
request_settings = {
auto_paginate: options.delete(:auto_paginate),
request_method: options.delete(:request_method) || :get
}
if block_given?
data = fetch_with_bloc... | ruby | {
"resource": ""
} |
q19967 | BookingSync::API.Client.call | train | def call(method, path, data = nil, options = nil)
instrument("call.bookingsync_api", method: method, path: path) do
if [:get, :head].include?(method)
options = data
data = {}
end
options ||= {}
options[:headers] ||= {}
options[:headers]["Authorization"] ... | ruby | {
"resource": ""
} |
q19968 | BookingSync::API.Client.with_headers | train | def with_headers(extra_headers = {}, &block)
original_headers = @conn.headers.dup
@conn.headers.merge!(extra_headers)
result = yield self
@conn.headers = original_headers
result
end | ruby | {
"resource": ""
} |
q19969 | BookingSync::API.Client.handle_response | train | def handle_response(faraday_response)
@last_response = response = Response.new(self, faraday_response)
case response.status
when 204; nil # destroy/cancel
when 200..299; response
when 401; raise Unauthorized.new(response)
when 403; raise Forbidden.new(response)
when 404; raise ... | ruby | {
"resource": ""
} |
q19970 | BookingSync::API.Relation.call | train | def call(data = {}, options = {})
m = options.delete(:method)
client.call m || method, href_template, data, options
end | ruby | {
"resource": ""
} |
q19971 | Brainstem.ControllerMethods.brainstem_present | train | def brainstem_present(name, options = {}, &block)
Brainstem.presenter_collection(options[:namespace]).presenting(name, options.reverse_merge(:params => params), &block)
end | ruby | {
"resource": ""
} |
q19972 | Brainstem.Preloader.preload_method | train | def preload_method
@preload_method ||= begin
if Gem.loaded_specs['activerecord'].version >= Gem::Version.create('4.1')
ActiveRecord::Associations::Preloader.new.method(:preload)
else
Proc.new do |models, association_names|
ActiveRecord::Associations::Preloader.new(m... | ruby | {
"resource": ""
} |
q19973 | Brainstem.Presenter.apply_ordering_to_scope | train | def apply_ordering_to_scope(scope, user_params)
sort_name, direction = calculate_sort_name_and_direction(user_params)
order = configuration[:sort_orders].fetch(sort_name, {})[:value]
ordered_scope = case order
when Proc
fresh_helper_instance.instance_exec(scope, direction, &order)
... | ruby | {
"resource": ""
} |
q19974 | Brainstem.Presenter.calculate_sort_name_and_direction | train | def calculate_sort_name_and_direction(user_params = {})
default_column, default_direction = (configuration[:default_sort_order] || "updated_at:desc").split(":")
sort_name, direction = user_params['order'].to_s.split(":")
unless sort_name.present? && configuration[:sort_orders][sort_name]
sort_... | ruby | {
"resource": ""
} |
q19975 | Brainstem.Cli.call | train | def call
if requested_command && commands.has_key?(requested_command)
self.command_method = commands[requested_command].method(:call)
end
command_method.call(_args.drop(1))
self
end | ruby | {
"resource": ""
} |
q19976 | Openwsman.ClientOptions.properties= | train | def properties= value
value.each do |k,v|
self.add_property k.to_s, v
end
end | ruby | {
"resource": ""
} |
q19977 | Openwsman.ClientOptions.selectors= | train | def selectors= value
value.each do |k,v|
self.add_selector k.to_s, v
end
end | ruby | {
"resource": ""
} |
q19978 | RDoc.Swig_Parser.handle_class_module | train | def handle_class_module(class_mod, class_name, options = {})
# puts "handle_class_module(#{class_mod}, #{class_name})"
progress(class_mod[0, 1])
parent = options[:parent]
parent_name = @known_classes[parent] || parent
if @@module_name
enclosure = @top_level.find_module_named(@@modu... | ruby | {
"resource": ""
} |
q19979 | Pocketsphinx.SpeechRecognizer.recognize | train | def recognize(max_samples = 2048, &b)
unless ALGORITHMS.include?(algorithm)
raise NotImplementedError, "Unknown speech recognition algorithm: #{algorithm}"
end
start unless recognizing?
FFI::MemoryPointer.new(:int16, max_samples) do |buffer|
loop do
send("recognize_#{... | ruby | {
"resource": ""
} |
q19980 | Pocketsphinx.SpeechRecognizer.recognize_continuous | train | def recognize_continuous(max_samples, buffer)
process_audio(buffer, max_samples).tap do
if hypothesis = decoder.hypothesis
decoder.end_utterance
yield hypothesis
decoder.start_utterance
end
end
end | ruby | {
"resource": ""
} |
q19981 | Pocketsphinx.Decoder.decode | train | def decode(audio_path_or_file, max_samples = 2048)
case audio_path_or_file
when String
File.open(audio_path_or_file, 'rb') { |f| decode_raw(f, max_samples) }
else
decode_raw(audio_path_or_file, max_samples)
end
end | ruby | {
"resource": ""
} |
q19982 | Pocketsphinx.Decoder.decode_raw | train | def decode_raw(audio_file, max_samples = 2048)
start_utterance
FFI::MemoryPointer.new(:int16, max_samples) do |buffer|
while data = audio_file.read(max_samples * 2)
buffer.write_string(data)
process_raw(buffer, data.length / 2)
end
end
end_utterance
end | ruby | {
"resource": ""
} |
q19983 | Pocketsphinx.Decoder.process_raw | train | def process_raw(buffer, size, no_search = false, full_utt = false)
api_call :ps_process_raw, ps_decoder, buffer, size, no_search ? 1 : 0, full_utt ? 1 : 0
end | ruby | {
"resource": ""
} |
q19984 | Pocketsphinx.Decoder.log_prob_to_linear | train | def log_prob_to_linear(log_prob)
logmath = ps_api.ps_get_logmath(ps_decoder)
ps_api.logmath_exp(logmath, log_prob)
end | ruby | {
"resource": ""
} |
q19985 | Pocketsphinx.Microphone.read_audio | train | def read_audio(buffer, max_samples = 2048)
samples = ps_api.ad_read(@ps_audio_device, buffer, max_samples)
samples if samples >= 0
end | ruby | {
"resource": ""
} |
q19986 | Pocketsphinx.AudioFile.read_audio | train | def read_audio(buffer, max_samples = 2048)
if file.nil?
raise "Can't read audio: use AudioFile#start_recording to open the file first"
end
if data = file.read(max_samples * 2)
buffer.write_string(data)
data.length / 2
end
end | ruby | {
"resource": ""
} |
q19987 | ZK.Threadpool.on_threadpool? | train | def on_threadpool?
tp = nil
@mutex.synchronize do
return false unless @threadpool # you can't dup nil
tp = @threadpool.dup
end
tp.respond_to?(:include?) and tp.include?(Thread.current)
end | ruby | {
"resource": ""
} |
q19988 | ZK.EventHandler.process | train | def process(event, watch_type = nil)
@zk.raw_event_handler(event)
logger.debug { "EventHandler#process dispatching event for #{watch_type.inspect}: #{event.inspect}" }# unless event.type == -1
event.zk = @zk
cb_keys =
if event.node_event?
[event.path, ALL_NODE_EVENTS_KEY]
... | ruby | {
"resource": ""
} |
q19989 | ZK.EventHandler.restricting_new_watches_for? | train | def restricting_new_watches_for?(watch_type, path)
synchronize do
if set = @outstanding_watches[watch_type]
return set.include?(path)
end
end
false
end | ruby | {
"resource": ""
} |
q19990 | ZK.MessageQueue.delete_message | train | def delete_message(message_title)
full_path = "#{full_queue_path}/#{message_title}"
locker = @zk.locker("#{full_queue_path}/#{message_title}")
if locker.lock!
begin
@zk.delete(full_path)
return true
ensure
locker.unlock!
end
else
retu... | ruby | {
"resource": ""
} |
q19991 | ZK.MessageQueue.destroy! | train | def destroy!
unsubscribe # first thing, make sure we don't get any callbacks related to this
children = @zk.children(full_queue_path)
locks = []
children.each do |path|
lock = @zk.locker("#{full_queue_path}/#{path}")
lock.lock! # XXX(slyphon): should this be a blocking lock?
... | ruby | {
"resource": ""
} |
q19992 | ZK.ThreadedCallback.shutdown | train | def shutdown(timeout=5)
# logger.debug { "#{self.class}##{__method__}" }
@mutex.lock
begin
return true if @state == :shutdown
@state = :shutdown
@cond.broadcast
ensure
@mutex.unlock rescue nil
end
return true unless @thread
unless @thread.jo... | ruby | {
"resource": ""
} |
q19993 | ZK.NodeDeletionWatcher.wait_until_blocked | train | def wait_until_blocked(timeout=nil)
@mutex.synchronize do
return true unless @blocked == NOT_YET
start = Time.now
time_to_stop = timeout ? (start + timeout) : nil
logger.debug { "#{__method__} @blocked: #{@blocked.inspect} about to wait" }
@cond.wait(timeout)
if ... | ruby | {
"resource": ""
} |
q19994 | ZK.NodeDeletionWatcher.wait_for_result | train | def wait_for_result(timeout)
# do the deadline maths
time_to_stop = timeout ? (Time.now + timeout) : nil # slight time slippage between here
#
until @result #
if timeout ... | ruby | {
"resource": ""
} |
q19995 | ZK.NodeDeletionWatcher.watch_appropriate_nodes | train | def watch_appropriate_nodes
remaining_paths.last( threshold + 1 ).reverse_each do |path|
next if watched_paths.include? path
watched_paths << path
finish_node(path) unless zk.exists?(path, :watch => true)
end
end | ruby | {
"resource": ""
} |
q19996 | Fog.ServicesMixin.require_service_provider_library | train | def require_service_provider_library(service, provider)
require "fog/#{provider}/#{service}"
rescue LoadError # Try to require the service provider in an alternate location
Fog::Logger.deprecation("Unable to require fog/#{provider}/#{service}")
Fog::Logger.deprecation(
format(E_SERVICE_PR... | ruby | {
"resource": ""
} |
q19997 | Boxen.Flags.apply | train | def apply(config)
config.debug = debug?
config.fde = fde? if config.fde?
config.homedir = homedir if homedir
config.logfile = logfile if logfile
config.login = login if login
config.token = token if token
config.pretend ... | ruby | {
"resource": ""
} |
q19998 | Instamojo.CommonObject.construct_hash | train | def construct_hash
vars = instance_variables.reject { |x| [:@client, :@original].include? x }
Hash[vars.map { |key| [key.to_s[1..key.length], instance_variable_get(key)] }]
end | ruby | {
"resource": ""
} |
q19999 | Fitgem.Client.create_subscription | train | def create_subscription(opts)
resp = raw_post make_subscription_url(opts.merge({:use_subscription_id => true})), EMPTY_BODY, make_headers(opts)
[resp.status, extract_response_body(resp)]
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.