_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q1900
|
Rackstash.Logger.capture
|
train
|
def capture(buffer_args = {})
raise ArgumentError, 'block required' unless block_given?
buffer_stack.push(buffer_args)
begin
yield
ensure
buffer_stack.flush_and_pop
end
end
|
ruby
|
{
"resource": ""
}
|
q1901
|
Confoog.Settings.load
|
train
|
def load
@config = YAML.load_file(config_path)
@status.set(errors: Status::INFO_FILE_LOADED)
if @config == false
@status.set(errors: Status::ERR_NOT_LOADING_EMPTY_FILE)
end
rescue
@status.set(errors: Status::ERR_CANT_LOAD)
end
|
ruby
|
{
"resource": ""
}
|
q1902
|
PageRight.CssHelper.is_css_in_page?
|
train
|
def is_css_in_page?(css, flag=true)
if flag
assert page.has_css?("#{css}"), "Error: #{css} not found on page !"
else
assert !page.has_css?("#{css}"), "Error: #{css} found on page !"
end
end
|
ruby
|
{
"resource": ""
}
|
q1903
|
PageRight.CssHelper.is_css_in_section?
|
train
|
def is_css_in_section?(css1, css2, flag=true)
within("#{css1}") do
if flag
assert page.has_css?("#{css2}"), "Error: #{css2} not found in #{css1} !"
else
assert !page.has_css?("#{css2}"), "Error: #{css2} found in #{css1} !"
end
end
end
|
ruby
|
{
"resource": ""
}
|
q1904
|
Fix.On.its
|
train
|
def its(method, &spec)
i = It.new(described, (challenges + [Defi.send(method)]), helpers.dup)
result = i.verify(&spec)
if configuration.fetch(:verbose, true)
print result.to_char(configuration.fetch(:color, false))
end
results << result
end
|
ruby
|
{
"resource": ""
}
|
q1905
|
DataTypes.BaseType.before_dump
|
train
|
def before_dump(value)
self.value = value if !value.nil?
if [email protected]?
value = @parent.instance_exec( self, :dump, &@block )
end
self.value = value if !value.nil?
end
|
ruby
|
{
"resource": ""
}
|
q1906
|
DaemonRunner.ShellOut.run_and_detach
|
train
|
def run_and_detach
log_r, log_w = IO.pipe
@pid = Process.spawn(command, pgroup: true, err: :out, out: log_w)
log_r.close
log_w.close
@pid
end
|
ruby
|
{
"resource": ""
}
|
q1907
|
Rackstash.Message.gsub
|
train
|
def gsub(pattern, replacement = UNDEFINED, &block)
if UNDEFINED.equal? replacement
if block_given?
copy_with @message.gsub(pattern, &block).freeze
else
enum_for(__method__)
end
else
copy_with @message.gsub(pattern, replacement, &block).freeze
end
end
|
ruby
|
{
"resource": ""
}
|
q1908
|
Rackstash.Message.sub
|
train
|
def sub(pattern, replacement = UNDEFINED, &block)
message =
if UNDEFINED.equal? replacement
@message.sub(pattern, &block)
else
@message.sub(pattern, replacement, &block)
end
copy_with(message.freeze)
end
|
ruby
|
{
"resource": ""
}
|
q1909
|
SignedForm.HMAC.secure_compare
|
train
|
def secure_compare(a, b)
return false unless a.bytesize == b.bytesize
l = a.unpack("C*")
r, i = 0, -1
b.each_byte { |v| r |= v ^ l[i+=1] }
r == 0
end
|
ruby
|
{
"resource": ""
}
|
q1910
|
Danger.DangerSlack.notify
|
train
|
def notify(channel: '#general', text: nil, **opts)
attachments = text.nil? ? report : []
text ||= '<http://danger.systems/|Danger> reports'
@conn.post do |req|
req.url 'chat.postMessage'
req.params = {
token: @api_token,
channel: channel,
text: text,
attachments: attachments.to_json,
link_names: 1,
**opts
}
end
end
|
ruby
|
{
"resource": ""
}
|
q1911
|
Danger.DangerSlack.report
|
train
|
def report
attachment = status_report
.reject { |_, v| v.empty? }
.map do |k, v|
case k.to_s
when 'errors' then
{
text: v.join("\n"),
color: 'danger'
}
when 'warnings' then
{
text: v.join("\n"),
color: 'warning'
}
when 'messages' then
{
text: v.join("\n"),
color: 'good'
}
when 'markdowns' then
v.map do |val|
{
text: val.message,
fields: fields(val)
}
end
end
end
attachment.flatten
end
|
ruby
|
{
"resource": ""
}
|
q1912
|
Danger.DangerSlack.fields
|
train
|
def fields(markdown)
fields = []
if markdown.file
fields.push(title: 'file',
value: markdown.file,
short: true)
end
if markdown.line
fields.push(title: 'line',
value: markdown.line,
short: true)
end
fields
end
|
ruby
|
{
"resource": ""
}
|
q1913
|
SignedForm.FormBuilder.fields_for
|
train
|
def fields_for(record_name, record_object = nil, fields_options = {}, &block)
hash = {}
array = []
if nested_attributes_association?(record_name)
hash["#{record_name}_attributes"] = fields_options[:signed_attributes_context] = array
else
hash[record_name] = fields_options[:signed_attributes_context] = array
end
add_signed_fields hash
content = super
array.uniq!
content
end
|
ruby
|
{
"resource": ""
}
|
q1914
|
DataMapper.Migration.say_with_time
|
train
|
def say_with_time(message, indent = 2)
say(message, indent)
result = nil
time = Benchmark.measure { result = yield }
say("-> %.4fs" % time.real, indent)
result
end
|
ruby
|
{
"resource": ""
}
|
q1915
|
DataMapper.Migration.update_migration_info
|
train
|
def update_migration_info(direction)
save, @verbose = @verbose, false
create_migration_info_table_if_needed
if direction.to_sym == :up
execute("INSERT INTO #{migration_info_table} (#{migration_name_column}) VALUES (#{quoted_name})")
elsif direction.to_sym == :down
execute("DELETE FROM #{migration_info_table} WHERE #{migration_name_column} = #{quoted_name}")
end
@verbose = save
end
|
ruby
|
{
"resource": ""
}
|
q1916
|
DataMapper.Migration.setup!
|
train
|
def setup!
@adapter = DataMapper.repository(@repository).adapter
case @adapter.class.name
when /Sqlite/ then @adapter.extend(SQL::Sqlite)
when /Mysql/ then @adapter.extend(SQL::Mysql)
when /Postgres/ then @adapter.extend(SQL::Postgres)
when /Sqlserver/ then @adapter.extend(SQL::Sqlserver)
when /Oracle/ then @adapter.extend(SQL::Oracle)
else
raise(RuntimeError,"Unsupported Migration Adapter #{@adapter.class}",caller)
end
end
|
ruby
|
{
"resource": ""
}
|
q1917
|
DataMapper.MigrationRunner.migration
|
train
|
def migration( number, name, opts = {}, &block )
raise "Migration name conflict: '#{name}'" if migrations.map { |m| m.name }.include?(name.to_s)
migrations << DataMapper::Migration.new( number, name.to_s, opts, &block )
end
|
ruby
|
{
"resource": ""
}
|
q1918
|
DataMapper.MigrationRunner.migrate_up!
|
train
|
def migrate_up!(level = nil)
migrations.sort.each do |migration|
if level.nil?
migration.perform_up()
else
migration.perform_up() if migration.position <= level.to_i
end
end
end
|
ruby
|
{
"resource": ""
}
|
q1919
|
DataMapper.MigrationRunner.migrate_down!
|
train
|
def migrate_down!(level = nil)
migrations.sort.reverse.each do |migration|
if level.nil?
migration.perform_down()
else
migration.perform_down() if migration.position > level.to_i
end
end
end
|
ruby
|
{
"resource": ""
}
|
q1920
|
Dropbox.Client.copy
|
train
|
def copy(from_path, to_path)
resp = request('/files/copy', from_path: from_path, to_path: to_path)
parse_tagged_response(resp)
end
|
ruby
|
{
"resource": ""
}
|
q1921
|
Dropbox.Client.get_copy_reference
|
train
|
def get_copy_reference(path)
resp = request('/files/copy_reference/get', path: path)
metadata = parse_tagged_response(resp['metadata'])
return metadata, resp['copy_reference']
end
|
ruby
|
{
"resource": ""
}
|
q1922
|
Dropbox.Client.save_copy_reference
|
train
|
def save_copy_reference(copy_reference, path)
resp = request('/files/copy_reference/save', copy_reference: copy_reference, path: path)
parse_tagged_response(resp['metadata'])
end
|
ruby
|
{
"resource": ""
}
|
q1923
|
Dropbox.Client.download
|
train
|
def download(path)
resp, body = content_request('/files/download', path: path)
return FileMetadata.new(resp), body
end
|
ruby
|
{
"resource": ""
}
|
q1924
|
Dropbox.Client.get_preview
|
train
|
def get_preview(path)
resp, body = content_request('/files/get_preview', path: path)
return FileMetadata.new(resp), body
end
|
ruby
|
{
"resource": ""
}
|
q1925
|
Dropbox.Client.get_temporary_link
|
train
|
def get_temporary_link(path)
resp = request('/files/get_temporary_link', path: path)
return FileMetadata.new(resp['metadata']), resp['link']
end
|
ruby
|
{
"resource": ""
}
|
q1926
|
Dropbox.Client.get_thumbnail
|
train
|
def get_thumbnail(path, format='jpeg', size='w64h64')
resp, body = content_request('/files/get_thumbnail', path: path, format: format, size: size)
return FileMetadata.new(resp), body
end
|
ruby
|
{
"resource": ""
}
|
q1927
|
Dropbox.Client.list_folder
|
train
|
def list_folder(path)
resp = request('/files/list_folder', path: path)
resp['entries'].map { |e| parse_tagged_response(e) }
end
|
ruby
|
{
"resource": ""
}
|
q1928
|
Dropbox.Client.continue_list_folder
|
train
|
def continue_list_folder(cursor)
resp = request('/files/list_folder/continue', cursor: cursor)
resp['entries'].map { |e| parse_tagged_response(e) }
end
|
ruby
|
{
"resource": ""
}
|
q1929
|
Dropbox.Client.list_revisions
|
train
|
def list_revisions(path)
resp = request('/files/list_revisions', path: path)
entries = resp['entries'].map { |e| FileMetadata.new(e) }
return entries, resp['is_deleted']
end
|
ruby
|
{
"resource": ""
}
|
q1930
|
Dropbox.Client.move
|
train
|
def move(from_path, to_path)
resp = request('/files/move', from_path: from_path, to_path: to_path)
parse_tagged_response(resp)
end
|
ruby
|
{
"resource": ""
}
|
q1931
|
Dropbox.Client.restore
|
train
|
def restore(path, rev)
resp = request('/files/restore', path: path, rev: rev)
FileMetadata.new(resp)
end
|
ruby
|
{
"resource": ""
}
|
q1932
|
Dropbox.Client.save_url
|
train
|
def save_url(path, url)
resp = request('/files/save_url', path: path, url: url)
parse_tagged_response(resp)
end
|
ruby
|
{
"resource": ""
}
|
q1933
|
Dropbox.Client.search
|
train
|
def search(path, query, start=0, max_results=100, mode='filename')
resp = request('/files/search', path: path, query: query, start: start,
max_results: max_results, mode: mode)
matches = resp['matches'].map { |m| parse_tagged_response(m['metadata']) }
return matches
end
|
ruby
|
{
"resource": ""
}
|
q1934
|
Dropbox.Client.upload
|
train
|
def upload(path, body, options={})
options[:client_modified] = Time.now.utc.iso8601
options[:path] = path
resp = upload_request('/files/upload', body, options.merge(path: path))
FileMetadata.new(resp)
end
|
ruby
|
{
"resource": ""
}
|
q1935
|
Dropbox.Client.start_upload_session
|
train
|
def start_upload_session(body, close=false)
resp = upload_request('/files/upload_session/start', body, close: close)
UploadSessionCursor.new(resp['session_id'], body.length)
end
|
ruby
|
{
"resource": ""
}
|
q1936
|
Dropbox.Client.append_upload_session
|
train
|
def append_upload_session(cursor, body, close=false)
args = {cursor: cursor.to_h, close: close}
resp = upload_request('/files/upload_session/append_v2', body, args)
cursor.offset += body.length
cursor
end
|
ruby
|
{
"resource": ""
}
|
q1937
|
Dropbox.Client.finish_upload_session
|
train
|
def finish_upload_session(cursor, path, body, options={})
options[:client_modified] = Time.now.utc.iso8601
options[:path] = path
args = {cursor: cursor.to_h, commit: options}
resp = upload_request('/files/upload_session/finish', body, args)
FileMetadata.new(resp)
end
|
ruby
|
{
"resource": ""
}
|
q1938
|
Dropbox.Client.get_account_batch
|
train
|
def get_account_batch(account_ids)
resp = request('/users/get_account_batch', account_ids: account_ids)
resp.map { |a| BasicAccount.new(a) }
end
|
ruby
|
{
"resource": ""
}
|
q1939
|
TTY.Editor.tempfile_path
|
train
|
def tempfile_path(content)
tempfile = Tempfile.new('tty-editor')
tempfile << content
tempfile.flush
unless tempfile.nil?
tempfile.close
end
tempfile.path
end
|
ruby
|
{
"resource": ""
}
|
q1940
|
TTY.Editor.open
|
train
|
def open
status = system(env, *Shellwords.split(command_path))
return status if status
fail CommandInvocationError,
"`#{command_path}` failed with status: #{$? ? $?.exitstatus : nil}"
end
|
ruby
|
{
"resource": ""
}
|
q1941
|
RVM.Environment.gemset_globalcache
|
train
|
def gemset_globalcache(enable = true)
case enable
when "enabled", :enabled
run(:__rvm_using_gemset_globalcache).successful?
when true, "enable", :enable
rvm(:gemset, :globalcache, :enable).successful?
when false, "disable", :disable
rvm(:gemset, :globalcache, :disable).successful?
else
false
end
end
|
ruby
|
{
"resource": ""
}
|
q1942
|
ActsAsOrderedTree.Node.scope
|
train
|
def scope
if tree.columns.scope?
tree.base_class.where Hash[tree.columns.scope.map { |column| [column, record[column]] }]
else
tree.base_class.where(nil)
end
end
|
ruby
|
{
"resource": ""
}
|
q1943
|
ActsAsOrderedTree.Position.lower
|
train
|
def lower
position? ?
siblings.where(klass.arel_table[klass.ordered_tree.columns.position].gteq(position)) :
siblings
end
|
ruby
|
{
"resource": ""
}
|
q1944
|
Lowdown.Client.disconnect
|
train
|
def disconnect
if @connection.respond_to?(:actors)
@connection.actors.each do |connection|
connection.async.disconnect if connection.alive?
end
else
@connection.async.disconnect if @connection.alive?
end
end
|
ruby
|
{
"resource": ""
}
|
q1945
|
Lowdown.Client.group
|
train
|
def group(timeout: nil)
group = nil
monitor do |condition|
group = RequestGroup.new(self, condition)
yield group
if !group.empty? && exception = condition.wait(timeout || DEFAULT_GROUP_TIMEOUT)
raise exception
end
end
ensure
group.terminate
end
|
ruby
|
{
"resource": ""
}
|
q1946
|
Lowdown.Client.monitor
|
train
|
def monitor
condition = Connection::Monitor::Condition.new
if defined?(Mock::Connection) && @connection.class == Mock::Connection
yield condition
else
begin
@connection.__register_lowdown_crash_condition__(condition)
yield condition
ensure
@connection.__deregister_lowdown_crash_condition__(condition)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q1947
|
Lowdown.Client.send_notification
|
train
|
def send_notification(notification, delegate:, context: nil)
raise ArgumentError, "Invalid notification: #{notification.inspect}" unless notification.valid?
topic = notification.topic || @default_topic
headers = {}
headers["apns-expiration"] = (notification.expiration || 0).to_i
headers["apns-id"] = notification.formatted_id
headers["apns-priority"] = notification.priority if notification.priority
headers["apns-topic"] = topic if topic
body = notification.formatted_payload.to_json
@connection.async.post(path: "/3/device/#{notification.token}",
headers: headers,
body: body,
delegate: delegate,
context: context)
end
|
ruby
|
{
"resource": ""
}
|
q1948
|
SneakersPacker.RpcClient.call
|
train
|
def call(request, options = {})
add_request(request)
@publisher.publish(request.message,
routing_key: request.name,
correlation_id: request.call_id,
reply_to: @subscriber.reply_queue_name)
timeout = (options[:timeout] || SneakersPacker.conf.rpc_timeout).to_i
client_lock.synchronize { request.condition.wait(client_lock, timeout) }
remove_request(request)
if request.processed?
request.response_data
else
raise RemoteCallTimeoutError, "Remote call timeouts.Exceed #{timeout} seconds."
end
end
|
ruby
|
{
"resource": ""
}
|
q1949
|
Fleximage.Helper.embedded_image_tag
|
train
|
def embedded_image_tag(model, options = {})
model.load_image
format = options[:format] || :jpg
mime = Mime::Type.lookup_by_extension(format.to_s).to_s
image = model.output_image(:format => format)
data = Base64.encode64(image)
options = { :alt => model.class.to_s }.merge(options)
result = image_tag("data:#{mime};base64,#{data}", options)
result.gsub(%r{src=".*/images/data:}, 'src="data:')
rescue Fleximage::Model::MasterImageNotFound => e
nil
end
|
ruby
|
{
"resource": ""
}
|
q1950
|
Fleximage.Helper.link_to_edit_in_aviary
|
train
|
def link_to_edit_in_aviary(text, model, options = {})
key = aviary_image_hash(model)
image_url = options.delete(:image_url) || url_for(:action => 'aviary_image', :id => model, :only_path => false, :key => key)
post_url = options.delete(:image_update_url) || url_for(:action => 'aviary_image_update', :id => model, :only_path => false, :key => key)
api_key = Fleximage::AviaryController.api_key
url = "http://aviary.com/flash/aviary/index.aspx?tid=1&phoenix&apil=#{api_key}&loadurl=#{CGI.escape image_url}&posturl=#{CGI.escape post_url}"
link_to text, url, { :target => 'aviary' }.merge(options)
end
|
ruby
|
{
"resource": ""
}
|
q1951
|
RVM.Environment.alias_list
|
train
|
def alias_list
lines = normalize_array(rvm(:alias, :list).stdout)
lines.inject({}) do |acc, current|
alias_name, ruby_string = current.to_s.split(" => ")
unless alias_name.empty? || ruby_string.empty?
acc[alias_name] = ruby_string
end
acc
end
end
|
ruby
|
{
"resource": ""
}
|
q1952
|
Lowdown.Connection.post
|
train
|
def post(path:, headers:, body:, delegate:, context: nil)
request("POST", path, headers, body, delegate, context)
end
|
ruby
|
{
"resource": ""
}
|
q1953
|
RVM.Environment.ruby
|
train
|
def ruby(runnable, options = {})
if runnable.respond_to?(:path)
# Call the path
ruby_run runnable.path, options
elsif runnable.respond_to?(:to_str)
runnable = runnable.to_str
File.exist?(runnable) ? ruby_run(runnable, options) : ruby_eval(runnable, options)
elsif runnable.respond_to?(:read)
ruby_run runnable.read
end
end
|
ruby
|
{
"resource": ""
}
|
q1954
|
RVM.Environment.system
|
train
|
def system(command, *args)
identifier = extract_identifier!(args)
args = [identifier, :exec, command, *args].compact
rvm(*args).successful?
end
|
ruby
|
{
"resource": ""
}
|
q1955
|
RVM.Environment.extract_environment!
|
train
|
def extract_environment!(options)
values = []
[:environment, :env, :rubies, :ruby].each do |k|
values << options.delete(k)
end
values.compact.first
end
|
ruby
|
{
"resource": ""
}
|
q1956
|
RVM.Environment.extract_identifier!
|
train
|
def extract_identifier!(args)
options = extract_options!(args)
identifier = normalize_set_identifier(extract_environment!(options))
args << options
identifier
end
|
ruby
|
{
"resource": ""
}
|
q1957
|
RVM.Environment.chdir
|
train
|
def chdir(dir)
run_silently :pushd, dir.to_s
result = Dir.chdir(dir) { yield }
run_silently :popd
result
end
|
ruby
|
{
"resource": ""
}
|
q1958
|
RVM.Environment.normalize_array
|
train
|
def normalize_array(value)
value.split("\n").map { |line| line.strip }.reject { |line| line.empty? }
end
|
ruby
|
{
"resource": ""
}
|
q1959
|
RVM.Environment.hash_to_options
|
train
|
def hash_to_options(options)
result = []
options.each_pair do |key, value|
real_key = "--#{key.to_s.gsub("_", "-")}"
if value == true
result << real_key
elsif value != false
result << real_key
result << value.to_s
end
end
result
end
|
ruby
|
{
"resource": ""
}
|
q1960
|
RVM.Environment.normalize_option_value
|
train
|
def normalize_option_value(value)
case value
when Array
value.map { |option| normalize_option_value(option) }.join(",")
else
value.to_s
end
end
|
ruby
|
{
"resource": ""
}
|
q1961
|
RVM.Environment.tools_path_identifier
|
train
|
def tools_path_identifier(path)
path_identifier = rvm(:tools, "path-identifier", path.to_s)
if path_identifier.exit_status == 2
error_message = "The rvmrc located in '#{path}' could not be loaded, likely due to trust mechanisms."
error_message << " Please run 'rvm rvmrc {trust,untrust} \"#{path}\"' to continue, or set rvm_trust_rvmrcs_flag to 1."
raise ErrorLoadingRVMRC, error_message
end
return normalize(path_identifier.stdout)
end
|
ruby
|
{
"resource": ""
}
|
q1962
|
RVM.Environment.use
|
train
|
def use(ruby_string, opts = {})
ruby_string = ruby_string.to_s
result = rvm(:use, ruby_string)
successful = result.successful?
if successful
@environment_name = ruby_string
@expanded_name = nil
use_env_from_result! result if opts[:replace_env]
end
successful
end
|
ruby
|
{
"resource": ""
}
|
q1963
|
RVM.Environment.source_rvm_environment
|
train
|
def source_rvm_environment
rvm_path = config_value_for(:rvm_path, self.class.default_rvm_path, false)
actual_config = defined_config.merge('rvm_path' => rvm_path)
config = []
actual_config.each_pair do |k, v|
config << "#{k}=#{escape_argument(v.to_s)}"
end
run_silently "export #{config.join(" ")}"
run_silently :source, File.join(rvm_path, "scripts", "rvm")
end
|
ruby
|
{
"resource": ""
}
|
q1964
|
Lowdown.Notification.formatted_payload
|
train
|
def formatted_payload
if @payload.key?("aps")
@payload
else
payload = {}
payload["aps"] = aps = {}
@payload.each do |key, value|
next if value.nil?
key = key.to_s
if APS_KEYS.include?(key)
aps[key] = value
else
payload[key] = value
end
end
payload
end
end
|
ruby
|
{
"resource": ""
}
|
q1965
|
ActsAsOrderedTree.PerseveringTransaction.start
|
train
|
def start(&block)
@attempts += 1
with_transaction_state(&block)
rescue ActiveRecord::StatementInvalid => error
raise unless connection.open_transactions.zero?
raise unless error.message =~ DEADLOCK_MESSAGES
raise if attempts >= RETRY_COUNT
logger.info "Deadlock detected on attempt #{attempts}, restarting transaction"
pause and retry
end
|
ruby
|
{
"resource": ""
}
|
q1966
|
Challah.Encrypter.compare
|
train
|
def compare(crypted_string, plain_string)
BCrypt::Password.new(crypted_string).is_password?(plain_string)
rescue BCrypt::Errors::InvalidHash
false
end
|
ruby
|
{
"resource": ""
}
|
q1967
|
Challah.Audit.clear_audit_attributes
|
train
|
def clear_audit_attributes
all_audit_attributes.each do |attribute_name|
if respond_to?(attribute_name) && respond_to?("#{ attribute_name }=")
write_attribute(attribute_name, nil)
end
end
@changed_attributes = changed_attributes.reduce(ActiveSupport::HashWithIndifferentAccess.new) do |result, (key, value)|
unless all_audit_attributes.include?(key.to_sym)
result[key] = value
end
result
end
end
|
ruby
|
{
"resource": ""
}
|
q1968
|
BingSearch.Client.image
|
train
|
def image(query, opts = {})
invoke 'Image',
query,
opts,
param_name_replacements: {filters: 'ImageFilters'},
params: {filters: image_filters_from_opts(opts)}
end
|
ruby
|
{
"resource": ""
}
|
q1969
|
BingSearch.Client.video
|
train
|
def video(query, opts = {})
invoke 'Video',
query,
opts,
passthrough_opts: %i(filters sort),
enum_opt_to_module: {filters: VideoFilter, sort: VideoSort},
param_name_replacements: {filters: 'VideoFilters', sort: 'VideoSortBy'}
end
|
ruby
|
{
"resource": ""
}
|
q1970
|
BingSearch.Client.news
|
train
|
def news(query, opts = {})
invoke 'News',
query,
opts,
passthrough_opts: %i(category location_override sort),
enum_opt_to_module: {category: NewsCategory, sort: NewsSort},
param_name_replacements: {category: 'NewsCategory', location_override: 'NewsLocationOverride', sort: 'NewsSortBy'}
end
|
ruby
|
{
"resource": ""
}
|
q1971
|
Challah.PasswordValidator.validate
|
train
|
def validate(record)
if record.password_provider? or options[:force]
if record.new_record? and record.password.to_s.blank? and !record.password_changed?
record.errors.add :password, :blank
elsif record.password_changed?
if record.password.to_s.size < 4
record.errors.add :password, :invalid_password
elsif record.password.to_s != record.password_confirmation.to_s
record.errors.add :password, :no_match_password
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q1972
|
Settler.AbstractSetting.valid_values
|
train
|
def valid_values
if validators['inclusion']
return case
when validators['inclusion'].is_a?(Array) then validators['inclusion']
when validators['inclusion'].is_a?(String) then validators['inclusion'].to_s.split(',').map{|v| v.to_s.strip }
else nil
end
end
nil
end
|
ruby
|
{
"resource": ""
}
|
q1973
|
Hike.CachedTrail.find_in_paths
|
train
|
def find_in_paths(logical_path, &block)
dirname, basename = File.split(logical_path)
@paths.each do |base_path|
match(File.expand_path(dirname, base_path), basename, &block)
end
end
|
ruby
|
{
"resource": ""
}
|
q1974
|
Hike.CachedTrail.match
|
train
|
def match(dirname, basename)
# Potential `entries` syscall
matches = @entries[dirname]
pattern = @patterns[basename]
matches = matches.select { |m| m =~ pattern }
sort_matches(matches, basename).each do |path|
filename = File.join(dirname, path)
# Potential `stat` syscall
stat = @stats[filename]
# Exclude directories
if stat && stat.file?
yield filename
end
end
end
|
ruby
|
{
"resource": ""
}
|
q1975
|
Hike.CachedTrail.sort_matches
|
train
|
def sort_matches(matches, basename)
extname = File.extname(basename)
aliases = @reverse_aliases[extname] || []
matches.sort_by do |match|
extnames = match.sub(basename, '').scan(/\.[^.]+/)
extnames.inject(0) do |sum, ext|
if i = extensions.index(ext)
sum + i + 1
elsif i = aliases.index(ext)
sum + i + 11
else
sum
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q1976
|
Challah.UserProvideable.update_modified_providers_after_save
|
train
|
def update_modified_providers_after_save
# Save password provider
if @password_updated or @username_updated
Challah.providers[:password].save(self)
@password_updated = false
@username_updated = false
@password = nil
end
# Save any other providers
Challah.custom_providers.each do |name, klass|
custom_provider_attributes = provider_attributes[name]
if custom_provider_attributes.respond_to?(:fetch)
if klass.valid?(self)
klass.save(self)
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q1977
|
Challah.Session.method_missing
|
train
|
def method_missing(sym, *args, &block)
if @params.has_key?(sym)
return @params[sym]
elsif sym.to_s =~ /^[a-z0-9_]*=$/
return @params[sym.to_s.sub(/^(.*?)=$/, '\1').to_sym] = args.shift
elsif sym.to_s =~ /^[a-z0-9_]*\?$/
return !!@params[sym.to_s.sub(/^(.*?)\?$/, '\1').to_sym]
end
super(sym, *args, &block)
end
|
ruby
|
{
"resource": ""
}
|
q1978
|
Challah.Session.authenticate!
|
train
|
def authenticate!
Challah.techniques.values.each do |klass|
technique = klass.new(self)
technique.user_model = user_model if technique.respond_to?(:"user_model=")
@user = technique.authenticate
if @user
@persist = technique.respond_to?(:persist?) ? technique.persist? : false
break
end
end
if @user
# Only update user record if persistence is on for the technique.
# Otherwise this builds up quick (one session for each API call)
if @persist
@user.successful_authentication!(ip)
end
return @valid = true
end
@valid = false
end
|
ruby
|
{
"resource": ""
}
|
q1979
|
Redistat.Buffer.buffer_key
|
train
|
def buffer_key(key, opts)
# covert keys to strings, as sorting a Hash with Symbol keys fails on
# Ruby 1.8.x.
opts = opts.inject({}) do |result, (k, v)|
result[k.to_s] = v
result
end
"#{key.to_s}:#{opts.sort.flatten.join(':')}"
end
|
ruby
|
{
"resource": ""
}
|
q1980
|
Challah.Plugins.register_plugin
|
train
|
def register_plugin(name, &block)
plugin = Plugin.new
plugin.instance_eval(&block)
@plugins[name] = plugin
end
|
ruby
|
{
"resource": ""
}
|
q1981
|
Drawers.DependencyExtensions.resource_path_from_qualified_name
|
train
|
def resource_path_from_qualified_name(qualified_name)
path_options = path_options_for_qualified_name(qualified_name)
file_path = ''
path_options.uniq.each do |path_option|
file_path = search_for_file(path_option)
break if file_path.present?
end
return file_path if file_path
# Note that sometimes, the resource_type path may only be defined in a
# resource type folder
# So, look for the first file within the resource type folder
# because of ruby namespacing conventions if there is a file in the folder,
# it MUST define the namespace
path_for_first_file_in(path_options.last) || path_for_first_file_in(path_options[-2])
end
|
ruby
|
{
"resource": ""
}
|
q1982
|
Challah.SimpleCookieStore.existing?
|
train
|
def existing?
exists = false
if session_cookie and validation_cookie
session_tmp = session_cookie.to_s
validation_tmp = validation_cookie.to_s
if validation_tmp == validation_cookie_value(session_tmp)
exists = true
end
end
exists
end
|
ruby
|
{
"resource": ""
}
|
q1983
|
Challah.PasswordTechnique.authenticate
|
train
|
def authenticate
if username? and password?
user = user_model.find_for_session(username)
if user
if user.valid_session?
if user.authenticate(@password)
return user
end
end
user.failed_authentication!
user = nil
end
end
nil
end
|
ruby
|
{
"resource": ""
}
|
q1984
|
Hike.FileUtils.entries
|
train
|
def entries(path)
if File.directory?(path)
Dir.entries(path).reject { |entry| entry =~ /^\.|~$|^\#.*\#$/ }.sort
else
[]
end
end
|
ruby
|
{
"resource": ""
}
|
q1985
|
Challah.EmailValidator.validate_each
|
train
|
def validate_each(record, attribute, value)
unless value =~ EmailValidator.pattern
record.errors.add(attribute, options[:message] || :invalid_email)
end
end
|
ruby
|
{
"resource": ""
}
|
q1986
|
Challah.UserAuthenticateable.authenticate
|
train
|
def authenticate(*args)
return false unless active?
if args.length > 1
method = args.shift
if Challah.authenticators[method]
return Challah.authenticators[method].match?(self, providers[method], *args)
end
false
else
self.authenticate(:password, args[0])
end
end
|
ruby
|
{
"resource": ""
}
|
q1987
|
Challah.UserAuthenticateable.successful_authentication!
|
train
|
def successful_authentication!(ip_address = nil)
self.last_session_at = Time.now
self.last_session_ip = ip_address if respond_to?(:last_session_ip=)
self.save
self.increment!(:session_count, 1)
end
|
ruby
|
{
"resource": ""
}
|
q1988
|
RTP.ControlPoint.dcm_mlc_positions
|
train
|
def dcm_mlc_positions(scale=nil)
coeff = (scale == :elekta ? -1 : 1)
# As with the collimators, the first side (1/a) may need scale invertion:
pos_a = @mlc_lp_a.collect{|p| (p.to_f * 10 * coeff).round(1) unless p.empty?}.compact
pos_b = @mlc_lp_b.collect{|p| (p.to_f * 10).round(1) unless p.empty?}.compact
(pos_a + pos_b).join("\\")
end
|
ruby
|
{
"resource": ""
}
|
q1989
|
RTP.ControlPoint.dcm_collimator_1
|
train
|
def dcm_collimator_1(scale=nil, axis)
coeff = 1
if scale == :elekta
axis = (axis == :x ? :y : :x)
coeff = -1
elsif scale == :varian
coeff = -1
end
dcm_collimator(axis, coeff, side=1)
end
|
ruby
|
{
"resource": ""
}
|
q1990
|
Secretary.VersionedAttributes.versioned_changes
|
train
|
def versioned_changes
modified_changes = {}
raw_changes = self.changes.select {|k,_| versioned_attribute?(k)}.to_hash
raw_changes.each do |key, (previous, current)|
if reflection = self.class.reflect_on_association(key.to_sym)
if reflection.collection?
previous = previous.map(&:versioned_attributes)
current = current.map(&:versioned_attributes)
else
previous = previous ? previous.versioned_attributes : {}
current = if current && !current.marked_for_destruction?
current.versioned_attributes
else
{}
end
end
end
# This really shouldn't need to be here,
# but there is some confusion if we're destroying
# an associated object in a save callback on the
# parent object. We can't know that the callback
# is going to destroy this object on save,
# so we just have to add the association normally
# and then filter it out here.
if previous != current
modified_changes[key] = [previous, current]
end
end
modified_changes
end
|
ruby
|
{
"resource": ""
}
|
q1991
|
Secretary.VersionedAttributes.versioned_attributes
|
train
|
def versioned_attributes
json = self.as_json(:root => false).select do |k,_|
versioned_attribute?(k)
end
json.to_hash
end
|
ruby
|
{
"resource": ""
}
|
q1992
|
Disqus.Forum.get_thread_by_url
|
train
|
def get_thread_by_url(url)
response = Disqus::Api::get_thread_by_url(:url => url, :forum_api_key => key)
if response["succeeded"]
t = response["message"]
Thread.new(t["id"], self, t["slug"], t["title"], t["created_at"], t["allow_comments"], t["url"], t["identifier"])
else
raise_api_error(response)
end
end
|
ruby
|
{
"resource": ""
}
|
q1993
|
Secretary.Version.attribute_diffs
|
train
|
def attribute_diffs
@attribute_diffs ||= begin
changes = self.object_changes.dup
attribute_diffs = {}
# Compare each of object_b's attributes to object_a's attributes
# And if there is a difference, add it to the Diff
changes.each do |attribute, values|
# values is [previous_value, new_value]
diff = Diffy::Diff.new(values[0].to_s, values[1].to_s)
attribute_diffs[attribute] = diff
end
attribute_diffs
end
end
|
ruby
|
{
"resource": ""
}
|
q1994
|
Secretary.DirtyAssociations.__compat_set_attribute_was
|
train
|
def __compat_set_attribute_was(name, previous)
if respond_to?(:set_attribute_was, true)
# Rails 4.2+
set_attribute_was(name, previous)
else
# Rails < 4.2
changed_attributes[name] = previous
end
end
|
ruby
|
{
"resource": ""
}
|
q1995
|
RTP.Record.encode
|
train
|
def encode(options={})
encoded_values = values.collect {|v| v && v.encode('ISO8859-1')}
encoded_values = discard_unsupported_attributes(encoded_values, options) if options[:version]
content = CSV.generate_line(encoded_values, force_quotes: true, row_sep: '') + ","
checksum = content.checksum
# Complete string is content + checksum (in double quotes) + carriage return + line feed
return (content + checksum.to_s.wrap + "\r\n").encode('ISO8859-1')
end
|
ruby
|
{
"resource": ""
}
|
q1996
|
RTP.Record.get_parent
|
train
|
def get_parent(last_parent, klass)
if last_parent.is_a?(klass)
return last_parent
else
return last_parent.get_parent(last_parent.parent, klass)
end
end
|
ruby
|
{
"resource": ""
}
|
q1997
|
RTP.Record.load
|
train
|
def load(string, options={})
# Extract processed values:
values = string.to_s.values(options[:repair])
raise ArgumentError, "Invalid argument 'string': Expected at least #{@min_elements} elements for #{@keyword}, got #{values.length}." if values.length < @min_elements
RTP.logger.warn "The number of given elements (#{values.length}) exceeds the known number of data elements for this record (#{@max_elements}). This may indicate an invalid string record or that the RTP format has recently been expanded with new elements." if values.length > @max_elements
self.send(:set_attributes, values)
self
end
|
ruby
|
{
"resource": ""
}
|
q1998
|
RTP.Record.to_s
|
train
|
def to_s(options={})
str = encode(options)
children.each do |child|
# Note that the extended plan record was introduced in Mosaiq 2.5.
str += child.to_s(options) unless child.class == ExtendedPlan && options[:version].to_f < 2.5
end
str
end
|
ruby
|
{
"resource": ""
}
|
q1999
|
RTP.Record.delete_child
|
train
|
def delete_child(attribute, instance=nil)
if self.send(attribute).is_a?(Array)
deleted = self.send(attribute).delete(instance)
deleted.parent = nil if deleted
else
self.send(attribute).parent = nil if self.send(attribute)
self.instance_variable_set("@#{attribute}", nil)
end
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.