_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q6800
|
Kalindar.Event.finish_time_f
|
train
|
def finish_time_f day
if dtend.class == Date
# whole day
""
elsif finish_time.to_date == day.to_date
finish_time.strftime('%H:%M')
else
return "..."
end
end
|
ruby
|
{
"resource": ""
}
|
q6801
|
Kalindar.Event.time_f
|
train
|
def time_f day
start = start_time_f day
finish = finish_time_f day
if start == finish && start == ""
# whole day
""
elsif start == finish && start == "..."
"..."
else
"#{start_time_f day} - #{finish_time_f day}"
end
end
|
ruby
|
{
"resource": ""
}
|
q6802
|
Garcon.ExecutorOptions.get_executor_from
|
train
|
def get_executor_from(opts = {})
if (executor = opts[:executor]).is_a? Symbol
case opts[:executor]
when :fast
Garcon.global_fast_executor
when :io
Garcon.global_io_executor
when :immediate
Garcon::ImmediateExecutor.new
else
raise ArgumentError, "executor '#{executor}' not recognized"
end
elsif opts[:executor]
opts[:executor]
else
nil
end
end
|
ruby
|
{
"resource": ""
}
|
q6803
|
Familia.Tools.rename
|
train
|
def rename(filter, source_uri, target_uri=nil, &each_key)
target_uri ||= source_uri
move_keys filter, source_uri, target_uri if source_uri != target_uri
source_keys = Familia.redis(source_uri).keys(filter)
puts "Renaming #{source_keys.size} keys from #{source_uri} (filter: #{filter})"
source_keys.each_with_index do |key,idx|
Familia.trace :RENAME1, Familia.redis(source_uri), "#{key}", ''
type = Familia.redis(source_uri).type key
ttl = Familia.redis(source_uri).ttl key
newkey = each_key.call(idx, type, key, ttl) unless each_key.nil?
Familia.trace :RENAME2, Familia.redis(source_uri), "#{key} -> #{newkey}", caller[0]
ret = Familia.redis(source_uri).renamenx key, newkey
end
end
|
ruby
|
{
"resource": ""
}
|
q6804
|
Roroacms.Comment.deal_with_abnormalaties
|
train
|
def deal_with_abnormalaties
self.comment = comment.to_s.gsub(%r{</?[^>]+?>}, '').gsub(/<script.*?>[\s\S]*<\/script>/i, "")
if !self.website.blank?
website = self.website.sub(/^https?\:\/\//, '').sub(/^www./,'')
unless self.website[/\Awww.\/\//] || self.website[/\Awww.\/\//]
website = "www.#{website}"
end
self.website = "http://#{website}"
end
end
|
ruby
|
{
"resource": ""
}
|
q6805
|
Bullring.ServerRegistry.lease_server!
|
train
|
def lease_server!
begin
if num_current_generation_servers < MAX_SERVERS_PER_GENERATION && registry_open?
start_a_server
end
lease_server
rescue ServerOffline => e
Bullring.logger.debug {"Lost connection with a server, retrying..."}
retry
end
end
|
ruby
|
{
"resource": ""
}
|
q6806
|
CurrentCost.Meter.update
|
train
|
def update(message)
unless message.nil?
# Parse reading from message
@latest_reading = Reading.from_xml(message)
# Inform observers
changed
notify_observers(@latest_reading)
end
rescue CurrentCost::ParseError
nil
end
|
ruby
|
{
"resource": ""
}
|
q6807
|
OrientdbBinary.Database.open
|
train
|
def open
conn = connection.protocol::DbOpen.new(params(name: @name, storage: @storage, user: @user, password: @password)).process(connection)
@session = conn[:session] || OrientdbBinary::OperationTypes::NEW_SESSION
@clusters = conn[:clusters]
self
end
|
ruby
|
{
"resource": ""
}
|
q6808
|
OrientdbBinary.Database.reload
|
train
|
def reload
answer = connection.protocol::DbReload.new(params).process(connection)
@clusters = answer[:clusters]
self
end
|
ruby
|
{
"resource": ""
}
|
q6809
|
Sendregning.Client.send_invoice
|
train
|
def send_invoice(invoice)
response = post_xml(invoice.to_xml, {:action => 'send', :type => 'invoice'})
InvoiceParser.parse(response, invoice)
end
|
ruby
|
{
"resource": ""
}
|
q6810
|
Sendregning.Client.find_invoice
|
train
|
def find_invoice(invoice_id)
builder = Builder::XmlMarkup.new(:indent=>2)
builder.instruct! :xml, :version=>"1.0", :encoding=>"UTF-8"
request_xml = builder.select do |select|
select.invoiceNumbers do |numbers|
numbers.invoiceNumber invoice_id
end
end
response = post_xml(request_xml, {:action => 'select', :type => 'invoice'})
InvoiceParser.parse(response) rescue nil
end
|
ruby
|
{
"resource": ""
}
|
q6811
|
LogCabin.DirCollection.find_file
|
train
|
def find_file(name)
@load_path.each do |dir|
file_path = File.join(dir, "#{name}.rb")
return file_path if File.exist? file_path
end
raise("Module #{name} not found")
end
|
ruby
|
{
"resource": ""
}
|
q6812
|
Figs.DirectoryFlattener.flattened_filenames
|
train
|
def flattened_filenames(filenames)
# Expect an array of filenames return otherwise
return filenames if !filenames.is_a?(Array)
# Iterate through array
filenames.map! do |filename|
# Flatten if its a file, flatten if a dir.
Dir.exist?(filename) ? directory_to_filenames(filename) : filename
end
# Flattern the array and remove all nils
filenames.flatten.compact
end
|
ruby
|
{
"resource": ""
}
|
q6813
|
Figs.DirectoryFlattener.flatten_files
|
train
|
def flatten_files(directoryname,filename)
# If the filename turns out to be a directory...
if Dir.exist?("#{directoryname}/#{filename}")
# do a recursive call to the parent method, unless the directory is . or ..
directory_to_filenames("#{directoryname}/#{filename}") unless ['.','..'].include?(filename)
else
# Otherwise check if its actually a file and return its filepath.
"#{directoryname}/#{filename}" if File.exists?("#{directoryname}/#{filename}")
end
end
|
ruby
|
{
"resource": ""
}
|
q6814
|
Balancer.Profile.profile_name
|
train
|
def profile_name
# allow user to specify the path also
if @options[:profile] && File.exist?(@options[:profile])
filename_profile = File.basename(@options[:profile], '.yml')
end
name = derandomize(@name)
if File.exist?(profile_file(name))
name_profile = name
end
filename_profile ||
@options[:profile] ||
name_profile || # conventional profile is the name of the elb
"default"
end
|
ruby
|
{
"resource": ""
}
|
q6815
|
BarkestCore.MsSqlDbDefinition.add_source
|
train
|
def add_source(sql)
sql_def = BarkestCore::MsSqlDefinition.new(sql, '')
sql_def.instance_variable_set(:@source_location, "::#{sql_def.name}::")
add_sql_def sql_def
nil
end
|
ruby
|
{
"resource": ""
}
|
q6816
|
BarkestCore.MsSqlDbDefinition.add_source_path
|
train
|
def add_source_path(path)
raise 'path must be a string' unless path.is_a?(String)
path = File.expand_path(path)
raise 'cannot add root path' if path == '/'
path = path[0...-1] if path[-1] == '/'
unless @source_paths.include?(path)
@source_paths << path
if Dir.exist?(path)
Dir.glob("#{path}/*.sql").each do |source|
add_sql_def BarkestCore::MsSqlDefinition.new(File.read(source), source, File.mtime(source))
end
end
end
nil
end
|
ruby
|
{
"resource": ""
}
|
q6817
|
Remi.Extractor::SftpFile.extract
|
train
|
def extract
begin_connection
entries.map do |entry|
local_file = File.join(@local_path, entry.name)
logger.info "Downloading #{entry.name} to #{local_file}"
sftp_retry { sftp_session.download!(File.join(@remote_path, entry.name), local_file) }
local_file
end
ensure
end_connection
end
|
ruby
|
{
"resource": ""
}
|
q6818
|
Remi.Loader::SftpFile.load
|
train
|
def load(data)
begin_connection
logger.info "Uploading #{data} to #{@username}@#{@host}: #{@remote_path}"
sftp_retry { sftp_session.upload! data, @remote_path }
true
ensure
end_connection
end
|
ruby
|
{
"resource": ""
}
|
q6819
|
CssCompare.Comparison.run
|
train
|
def run
result = CssCompare::Engine.new(@options)
.parse!
.equal?
write_output(result.to_s + "\n", @options[:output])
end
|
ruby
|
{
"resource": ""
}
|
q6820
|
GhostInThePost.PhantomTransform.html_file
|
train
|
def html_file(html)
file = Tempfile.new(['ghost_in_the_post', '.html'], encoding: Encoding::UTF_8)
file.write(html)
file.close #closing the file makes it accessible by phantom
file
end
|
ruby
|
{
"resource": ""
}
|
q6821
|
BibSonomy.CSL.render
|
train
|
def render(grouping, name, tags, count)
# get posts from BibSonomy
posts = JSON.parse(@bibsonomy.get_posts(grouping, name, 'publication', tags, 0, count))
# render them with citeproc
cp = CiteProc::Processor.new style: @style, format: 'html'
cp.import posts
# to check for duplicate file names
file_names = []
# filter posts by group
# 2017-05-30, rja, disabled until group information is returned by the API
# posts.delete_if do |v|
# if v["group"] == @group
# true
# else
# print("WARN: " + v["group"])
# false
# end
# end
# sort posts by year
sorted_keys = posts.keys.sort { |a,b| get_sort_posts(posts[b], posts[a]) }
result = ""
# print first heading
last_year = 0
if @year_headings and sorted_keys.length > 0
last_year = get_year(posts[sorted_keys[0]])
result += "<h3>" + last_year + "</h3>"
end
result += "<ul class='#{@css_class}'>\n"
for post_id in sorted_keys
post = posts[post_id]
# print heading
if @year_headings
year = get_year(post)
if year != last_year
last_year = year
result += "</ul>\n<h3>" + last_year + "</h3>\n<ul class='#{@css_class}'>\n"
end
end
# render metadata
csl = cp.render(:bibliography, id: post_id)
result += "<li class='" + post["type"] + "'>#{csl[0]}"
# extract the post's id
intra_hash, user_name = get_intra_hash(post_id)
# optional parts
options = []
# attach documents
if @pdf_dir
for doc in get_public_docs(post["documents"])
# fileHash, fileName, md5hash, userName
file_path = get_document(@bibsonomy, intra_hash, user_name, doc, @pdf_dir, file_names)
options << "<a href='#{file_path}'>PDF</a>"
end
end
# attach DOI
doi = post["DOI"]
if @doi_link and doi != ""
doi, doi_url = get_doi(doi)
options << "DOI:<a href='#{doi_url}'>#{doi}</a>"
end
# attach URL
url = post["URL"]
if @url_link and url != ""
options << "<a href='#{url}'>URL</a>"
end
# attach BibTeX
if @bibtex_link
options << "<a href='https://www.bibsonomy.org/bib/publication/#{intra_hash}/#{user_name}'>BibTeX</a>"
end
# attach link to BibSonomy
if @bibsonomy_link
options << "<a href='https://www.bibsonomy.org/publication/#{intra_hash}/#{user_name}'>BibSonomy</a>"
end
# attach options
if options.length > 0
result += " <span class='opt'>[" + options.join(@opt_sep) + "]</span>"
end
# attach Altmetric badge
if @altmetric_badge_type and doi != ""
doi, doi_url = get_doi(doi)
result += "<div class='altmetric-embed' data-badge-type='#{@altmetric_badge_type}' data-doi='#{doi}'></div>"
end
result += "</li>\n"
end
result += "</ul>\n"
return result
end
|
ruby
|
{
"resource": ""
}
|
q6822
|
BibSonomy.CSL.get_public_docs
|
train
|
def get_public_docs(documents)
result = []
for doc in documents
file_name = doc["fileName"]
if file_name.end_with? ".pdf"
if documents.length < 2 or file_name.end_with? @public_doc_postfix
result << doc
end
end
end
return result
end
|
ruby
|
{
"resource": ""
}
|
q6823
|
Garcon.ChefHelpers.find_by
|
train
|
def find_by(type, filter, single = true, &block)
nodes = []
env = node.chef_environment
if node.public_send(Inflections.pluralize(type.to_s)).include? filter
nodes << node
end
if !single || nodes.empty?
search(:node, "#{type}:#{filter} AND chef_environment:#{env}") do |n|
nodes << n
end
end
if block_given?
nodes.each { |n| yield n }
else
single ? nodes.first : nodes
end
end
|
ruby
|
{
"resource": ""
}
|
q6824
|
Garcon.ChefHelpers.cookbook_version
|
train
|
def cookbook_version(name = nil)
cookbook = name.nil? ? cookbook_name : name
node.run_context.cookbook_collection[cookbook].metadata.version
end
|
ruby
|
{
"resource": ""
}
|
q6825
|
Garcon.ChefHelpers.file_cache_path
|
train
|
def file_cache_path(*args)
if args.nil?
Chef::Config[:file_cache_path]
else
::File.join(Chef::Config[:file_cache_path], args)
end
end
|
ruby
|
{
"resource": ""
}
|
q6826
|
Garcon.ChefHelpers._?
|
train
|
def _?(*args, &block)
if args.empty? && block_given?
yield self
else
resp = public_send(*args[0], &block) if respond_to?(args.first)
return nil if resp.nil?
!!resp == resp ? args[1] : [args[1], resp]
end
end
|
ruby
|
{
"resource": ""
}
|
q6827
|
Garcon.ChefHelpers.zip_hash
|
train
|
def zip_hash(col1, col2)
col1.zip(col2).inject({}) { |r, i| r[i[0]] = i[1]; r }
end
|
ruby
|
{
"resource": ""
}
|
q6828
|
Garcon.ChefHelpers.with_tmp_dir
|
train
|
def with_tmp_dir(&block)
Dir.mktmpdir(SecureRandom.hex(3)) do |tmp_dir|
Dir.chdir(tmp_dir, &block)
end
end
|
ruby
|
{
"resource": ""
}
|
q6829
|
Evvnt.ClassTemplateMethods.create
|
train
|
def create(**params)
path = nest_path_within_parent(plural_resource_path, params)
api_request(:post, path, params: params)
end
|
ruby
|
{
"resource": ""
}
|
q6830
|
Evvnt.ClassTemplateMethods.index
|
train
|
def index(**params)
params.stringify_keys!
path = nest_path_within_parent(plural_resource_path, params)
api_request(:get, path, params: params)
end
|
ruby
|
{
"resource": ""
}
|
q6831
|
Evvnt.ClassTemplateMethods.show
|
train
|
def show(record_id = nil, **params)
if record_id.nil? && !singular_resource?
raise ArgumentError, "record_id cannot be nil"
end
path = nest_path_within_parent(singular_path_for_record(record_id, params), params)
api_request(:get, path, params: params)
end
|
ruby
|
{
"resource": ""
}
|
q6832
|
Fried::Schema::Attribute.DefineWriter.call
|
train
|
def call(definition, klass)
is_a = is[definition.type]
define_writer(definition, is_a, klass)
end
|
ruby
|
{
"resource": ""
}
|
q6833
|
RailsExtension::ActionControllerExtension::Routing.ClassMethods.assert_no_route
|
train
|
def assert_no_route(verb,action,args={})
test "#{brand}no route to #{verb} #{action} #{args}" do
assert_raise(ActionController::RoutingError){
send(verb,action,args)
}
end
end
|
ruby
|
{
"resource": ""
}
|
q6834
|
Richcss.RichUI.debug
|
train
|
def debug(depth = 0)
if debug?
debug_info = yield
debug_info = debug_info.inspect unless debug_info.is_a?(String)
STDERR.puts debug_info.split("\n").map {|s| " " * depth + s }
end
end
|
ruby
|
{
"resource": ""
}
|
q6835
|
Bebox.RoleCommands.role_list_command
|
train
|
def role_list_command(role_command)
role_command.desc _('cli.role.list.desc')
role_command.command :list do |role_list_command|
role_list_command.action do |global_options,options,args|
roles = Bebox::Role.list(project_root)
title _('cli.role.list.current_roles')
roles.map{|role| msg(role)}
warn(_('cli.role.list.no_roles')) if roles.empty?
linebreak
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6836
|
Bebox.RoleCommands.role_new_command
|
train
|
def role_new_command(role_command)
role_command.desc _('cli.role.new.desc')
role_command.arg_name "[name]"
role_command.command :new do |role_new_command|
role_new_command.action do |global_options,options,args|
help_now!(error(_('cli.role.new.name_arg_missing'))) if args.count == 0
Bebox::RoleWizard.new.create_new_role(project_root, args.first)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6837
|
Bebox.RoleCommands.generate_role_command
|
train
|
def generate_role_command(role_command, command, send_command, description)
role_command.desc description
role_command.command command do |generated_command|
generated_command.action do |global_options,options,args|
Bebox::RoleWizard.new.send(send_command, project_root)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6838
|
Bebox.RoleCommands.role_list_profiles_command
|
train
|
def role_list_profiles_command(role_command)
role_command.desc _('cli.role.list_profiles.desc')
role_command.arg_name "[role_name]"
role_command.command :list_profiles do |list_profiles_command|
list_profiles_command.action do |global_options,options,args|
help_now!(error(_('cli.role.list_profiles.name_arg_missing'))) if args.count == 0
role = args.first
print_profiles(role, Bebox::Role.list_profiles(project_root, role))
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6839
|
Pushfile.Util.filename
|
train
|
def filename(name)
# Replace space with underscore and downcase extension
pre, dot, ext = name.rpartition('.')
name = "#{pre.gsub(' ', '_')}.#{ext.downcase}"
# Remove illegal characters
# http://stackoverflow.com/questions/13517100/whats-the-difference-between-palpha-i-and-pl-i-in-ruby
name = name.gsub(%r{[^\p{L}\-\_\.0-9]}, '')
name
end
|
ruby
|
{
"resource": ""
}
|
q6840
|
Garcon.MemStash.load
|
train
|
def load(data)
@monitor.synchronize do
data.each do |key, value|
expire!
store(key, val)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6841
|
Garcon.MemStash.fetch
|
train
|
def fetch(key)
@monitor.synchronize do
found, value = get(key)
found ? value : store(key, yield)
end
end
|
ruby
|
{
"resource": ""
}
|
q6842
|
Garcon.MemStash.delete
|
train
|
def delete(key)
@monitor.synchronize do
entry = @stash.delete(key)
if entry
@expires_at.delete(entry)
entry.value
else
nil
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6843
|
RichUnits.Duration.reset_segments
|
train
|
def reset_segments(segmentA=nil, segmentB=nil)
if !segmentA
@segments = [:days, :hours, :minutes, :seconds]
elsif !segmentB
case segmentA
when Array
@segments = segmentA.map{ |p| (p.to_s.downcase.chomp('s') + 's').to_sym }
raise ArgumentError unless @segments.all?{ |s| SEGMENTS.include?(s) }
else
f = SEGMENTS.index(segmentA)
@segments = SEGMENTS[f..0]
end
else # segmentA && segmentB
f = SEGMENTS.index(segmentA)
t = SEGMENTS.index(segmentB)
@segments = SEGMENTS[f..t]
end
end
|
ruby
|
{
"resource": ""
}
|
q6844
|
RichUnits.Duration.strftime
|
train
|
def strftime(fmt)
h = to_h
hx = {
'y' => h[:years] ,
'w' => h[:weeks] ,
'd' => h[:days] ,
'h' => h[:hours] ,
'm' => h[:minutes],
's' => h[:seconds],
't' => total,
'x' => to_s
}
fmt.gsub(/%?%(w|d|h|m|s|t|x)/) do |match|
hx[match[1..1]]
end.gsub('%%', '%')
end
|
ruby
|
{
"resource": ""
}
|
q6845
|
BarkestCore.RecaptchaHelper.verify_recaptcha_challenge
|
train
|
def verify_recaptcha_challenge(model = nil)
# always true in tests.
return true if recaptcha_disabled?
# model must respond to the 'errors' message and the result of that must respond to 'add'
if !model || !model.respond_to?('errors') || !model.send('errors').respond_to?('add')
model = nil
end
begin
recaptcha = nil
http = Net::HTTP
remote_ip = (request.respond_to?('remote_ip') && request.send('remote_ip')) || (env && env['REMOTE_ADDR'])
verify_hash = {
secret: recaptcha_secret_key,
remoteip: remote_ip,
response: params['g-recaptcha-response']
}
Timeout::timeout(5) do
uri = URI.parse('https://www.google.com/recaptcha/api/siteverify')
http_instance = http.new(uri.host, uri.port)
if uri.port == 443
http_instance.use_ssl = true
http_instance.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
request = Net::HTTP::Post.new(uri.request_uri)
request.set_form_data(verify_hash)
recaptcha = http_instance.request(request)
end
answer = JSON.parse(recaptcha.body)
if answer['success'].to_s.downcase == 'true'
return true
else
if model
model.errors.add(:base, 'Recaptcha verification failed.')
end
return false
end
rescue Timeout::Error
if model
model.errors.add(:base, 'Recaptcha unreachable.')
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6846
|
SqsMocks.MockClient.get_queue_attributes
|
train
|
def get_queue_attributes(queue_url: nil, attribute_names: nil)
r = MockResponse.new
if attribute_names == "All"
r.attributes = FAUX_ATTRIBUTES
else
attribute_names.each do |attribute_name|
r.attributes[attribute_name] = FAUX_ATTRIBUTES[attribute_name]
end
end
r
end
|
ruby
|
{
"resource": ""
}
|
q6847
|
MetaEnum.Type.[]
|
train
|
def [](key)
case key
when Element, MissingElement
raise ArgumentError, "wrong type" unless key.type == self
key
when Symbol
elements_by_name.fetch(key)
else
key = normalize_value(key)
elements_by_value.fetch(key) { MissingElement.new key, self }
end
end
|
ruby
|
{
"resource": ""
}
|
q6848
|
Hoodie.UrlHelper.unshorten
|
train
|
def unshorten(url, opts= {})
options = {
max_level: opts.fetch(:max_level, 10),
timeout: opts.fetch(:timeout, 2),
use_cache: opts.fetch(:use_cache, true)
}
url = (url =~ /^https?:/i) ? url : "http://#{url}"
__unshorten__(url, options)
end
|
ruby
|
{
"resource": ""
}
|
q6849
|
EventHub.Helper.format_string
|
train
|
def format_string(message,max_characters=80)
max_characters = 5 if max_characters < 5
m = message.gsub(/\r\n|\n|\r/m,";")
return (m[0..max_characters-4] + "...") if m.size > max_characters
return m
end
|
ruby
|
{
"resource": ""
}
|
q6850
|
WatsonNLPWrapper.WatsonNLPApi.analyze
|
train
|
def analyze(text, features = default_features)
if text.nil? || features.nil?
raise ArgumentError.new(NIL_ARGUMENT_ERROR)
end
response = self.class.post(
"#{@url}/analyze?version=#{@version}",
body: {
text: text.to_s,
features: features
}.to_json,
basic_auth: auth,
headers: {
"Content-Type" => CONTENT_TYPE
}
)
response.parsed_response
end
|
ruby
|
{
"resource": ""
}
|
q6851
|
WatsonNLPWrapper.WatsonNLPApi.default_features
|
train
|
def default_features
{
entities: {
emotion: true,
sentiment: true,
limit: 2
},
keywords: {
emotion: true,
sentiment: true,
limit: 2
}
}
end
|
ruby
|
{
"resource": ""
}
|
q6852
|
CapybaraObjects.PageObject.visit
|
train
|
def visit
raise ::CapybaraObjects::Exceptions::MissingUrl unless url.present?
page.visit url
validate!
self
end
|
ruby
|
{
"resource": ""
}
|
q6853
|
Spidercrawl.Request.curl
|
train
|
def curl
puts "fetching #{@uri.to_s}".green.on_black
start_time = Time.now
begin
c = @c
c.url = @uri.to_s
c.perform
end_time = Time.now
case c.response_code
when 200 then
page = Page.new(@uri, response_code: c.response_code,
response_head: c.header_str,
response_body: c.body_str,
response_time: ((end_time-start_time)*1000).round,
crawled_time: (Time.now.to_f*1000).to_i)
when 300..307 then
page = Page.new(@uri, response_code: c.response_code,
response_head: c.header_str,
response_body: c.body_str,
response_time: ((end_time-start_time)*1000).round,
redirect_url: c.redirect_url)
when 404 then
page = Page.new(@uri, response_code: c.response_code,
response_time: ((end_time-start_time)*1000).round)
end
rescue Exception => e
puts e.inspect
puts e.backtrace
end
end
|
ruby
|
{
"resource": ""
}
|
q6854
|
Incline.EmailValidator.validate_each
|
train
|
def validate_each(record, attribute, value)
unless value.blank?
record.errors[attribute] << (options[:message] || 'is not a valid email address') unless value =~ VALID_EMAIL_REGEX
end
end
|
ruby
|
{
"resource": ""
}
|
q6855
|
Garcon.Interpolation.interpolate
|
train
|
def interpolate(item = self, parent = nil)
item = render item, parent
item.is_a?(Hash) ? ::Mash.new(item) : item
end
|
ruby
|
{
"resource": ""
}
|
q6856
|
Garcon.Interpolation.render
|
train
|
def render(item, parent = nil)
item = item.to_hash if item.respond_to?(:to_hash)
if item.is_a?(Hash)
item = item.inject({}) { |memo, (k,v)| memo[sym(k)] = v; memo }
item.inject({}) {|memo, (k,v)| memo[sym(k)] = render(v, item); memo}
elsif item.is_a?(Array)
item.map { |i| render(i, parent) }
elsif item.is_a?(String)
item % parent rescue item
else
item
end
end
|
ruby
|
{
"resource": ""
}
|
q6857
|
ActionCommand.ExecutableTransaction.execute
|
train
|
def execute(result)
if ActiveRecord::Base.connection.open_transactions >= 1
super(result)
else
result.info('start_transaction')
ActiveRecord::Base.transaction do
super(result)
if result.ok?
result.info('end_transaction')
else
result.info('rollback_transaction')
raise ActiveRecord::Rollback, 'rollback transaction'
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6858
|
UlePage.SitePrismExtender.element_collection
|
train
|
def element_collection(collection_name, *find_args)
build collection_name, *find_args do
define_method collection_name.to_s do |*runtime_args, &element_block|
self.class.raise_if_block(self, collection_name.to_s, !element_block.nil?)
page.all(*find_args)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6859
|
UlePage.SitePrismExtender.define_elements_js
|
train
|
def define_elements_js(model_class, excluded_props = [])
attributes = model_class.new.attributes.keys
attributes.each do |attri|
unless excluded_props.include? attri
selector = "#"+attri
# self.class.send "element", attri.to_sym, selector
element attri, selector
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6860
|
MultiBitField.ClassMethods.range_for
|
train
|
def range_for column_name, field_name
column = @@bitfields[column_name]
raise ArgumentError, "Unknown column for bitfield: #{column_name}" if column.nil?
return column[field_name] if column[field_name]
raise ArugmentError, "Unknown field: #{field_name} for column #{column_name}"
end
|
ruby
|
{
"resource": ""
}
|
q6861
|
MultiBitField.ClassMethods.reset_mask_for
|
train
|
def reset_mask_for column_name, *fields
fields = bitfields if fields.empty?
max = bitfield_max(column_name)
(0..max).sum{|i| 2 ** i} - only_mask_for(column_name, *fields)
end
|
ruby
|
{
"resource": ""
}
|
q6862
|
MultiBitField.ClassMethods.increment_mask_for
|
train
|
def increment_mask_for column_name, *fields
fields = bitfields if fields.empty?
column = @@bitfields[column_name]
raise ArgumentError, "Unknown column for bitfield: #{column_name}" if column.nil?
fields.sum do |field_name|
raise ArugmentError, "Unknown field: #{field_name} for column #{column_name}" if column[field_name].nil?
2 ** (bitfield_max(column_name) - column[field_name].last)
end
end
|
ruby
|
{
"resource": ""
}
|
q6863
|
MultiBitField.ClassMethods.only_mask_for
|
train
|
def only_mask_for column_name, *fields
fields = bitfields if fields.empty?
column = @@bitfields[column_name]
max = bitfield_max(column_name)
raise ArgumentError, "Unknown column for bitfield: #{column_name}" if column.nil?
column.sum do |field_name, range|
fields.include?(field_name) ? range.invert(max).sum{|i| 2 ** i} : 0
end
# fields.inject("0" * (bitfield_max(column_name) + 1)) do |mask, field_name|
# raise ArugmentError, "Unknown field: #{field_name} for column #{column_name}" if column[field_name].nil?
# range = column[field_name]
# mask[range] = "1" * range.count
# mask
# end.to_i(2)
end
|
ruby
|
{
"resource": ""
}
|
q6864
|
MultiBitField.ClassMethods.count_by
|
train
|
def count_by column_name, field
inc = increment_mask_for column_name, field
only = only_mask_for column_name, field
# Create super-special-bitfield-grouping-query w/ AREL
sql = arel_table.
project("count(#{primary_key}) as #{field}_count, (#{column_name} & #{only})/#{inc} as #{field}").
group(field).to_sql
connection.send :select, sql, 'AREL' # Execute the query
end
|
ruby
|
{
"resource": ""
}
|
q6865
|
MultiBitField.InstanceMethods.reset_bitfields
|
train
|
def reset_bitfields column_name, *fields
mask = self.class.reset_mask_for column_name, *fields
self[column_name] = self[column_name] & mask
save
end
|
ruby
|
{
"resource": ""
}
|
q6866
|
MultiBitField.InstanceMethods.increment_bitfields
|
train
|
def increment_bitfields column_name, *fields
mask = self.class.increment_mask_for column_name, *fields
self[column_name] = self[column_name] += mask
save
end
|
ruby
|
{
"resource": ""
}
|
q6867
|
OpenStax::Connect.CurrentUserManager.connect_current_user=
|
train
|
def connect_current_user=(user)
@connect_current_user = user || User.anonymous
@app_current_user = user_provider.connect_user_to_app_user(@connect_current_user)
if @connect_current_user.is_anonymous?
@session[:user_id] = nil
@cookies.delete(:secure_user_id)
else
@session[:user_id] = @connect_current_user.id
@cookies.signed[:secure_user_id] = {secure: true, value: "secure#{@connect_current_user.id}"}
end
@connect_current_user
end
|
ruby
|
{
"resource": ""
}
|
q6868
|
Vidibus.Encoder.register_format
|
train
|
def register_format(name, processor)
unless processor.new.is_a?(Vidibus::Encoder::Base)
raise(ArgumentError, 'The processor must inherit Vidibus::Encoder::Base')
end
@formats ||= {}
@formats[name] = processor
end
|
ruby
|
{
"resource": ""
}
|
q6869
|
RComp.Conf.read_conf_file
|
train
|
def read_conf_file
conf = {}
if File.exists?(CONF_PATH) && File.size?(CONF_PATH)
# Store valid conf keys
YAML.load_file(CONF_PATH).each do |key, value|
if VALID_KEYS.include? key
conf[key] = value
else
say "Invalid configuration key: #{key}"
end
end
end
conf
end
|
ruby
|
{
"resource": ""
}
|
q6870
|
Monet.BaselineControl.rebase
|
train
|
def rebase(image)
new_path = @router.baseline_dir(image.name)
create_path_for_file(new_path)
FileUtils.move(image.path, new_path)
Monet::Image.new(new_path)
end
|
ruby
|
{
"resource": ""
}
|
q6871
|
Associates.Persistence.save
|
train
|
def save(*args)
return false unless valid?
ActiveRecord::Base.transaction do
begin
associates.all? do |associate|
send(associate.name).send(:save!, *args)
end
rescue ActiveRecord::RecordInvalid
false
end
end
end
|
ruby
|
{
"resource": ""
}
|
q6872
|
Auger.Project.connections
|
train
|
def connections(*roles)
if roles.empty?
@connections
else
@connections.select { |c| c.roles.empty? or !(c.roles & roles).empty? }
end
end
|
ruby
|
{
"resource": ""
}
|
q6873
|
Poster.Rss.extract_data
|
train
|
def extract_data item, text_limit: 1200
link = item.link
desc = item.description
title = item.title.force_encoding('UTF-8')
# Extract main image
case
when desc.match(/\|.*\|/m)
img, terms, text = desc.split('|')
when desc.include?('|')
img, text = desc.split('|')
terms = nil
when desc.match(/<img.*?src="(.*?)\"/)
img = desc.match(/<img.*?src="(.*?)\"/)[1]
text = desc
terms = nil
else
img, terms, text = nil, nil, desc
end
# Extract categories
categories =
if terms
terms.split(/term_group: .*\n/).
select {|g| g.match /taxonomy: category/}.
map {|c| c.match( /name: (.*)\n/)[1]}
else
[]
end
# Crop text
short_text = strip_tags(text)[0..text_limit]
# Normalize newlines
short_text = short_text.gsub(/\A\s+/,"").gsub(/\n+/,"\n\n")
# Right-strip to end of last paragraph
short_text = short_text[0..short_text.rindex(/\.\n/)]
[title, link, img, short_text, categories]
end
|
ruby
|
{
"resource": ""
}
|
q6874
|
GoogleAnymote.Pair.start_pairing
|
train
|
def start_pairing
@gtv = GoogleAnymote::TV.new(@cert, host, 9551 + 1)
# Let the TV know that we want to pair with it
send_message(pair, OuterMessage::MessageType::MESSAGE_TYPE_PAIRING_REQUEST)
# Build the options and send them to the TV
options = Options.new
encoding = Options::Encoding.new
encoding.type = Options::Encoding::EncodingType::ENCODING_TYPE_HEXADECIMAL
encoding.symbol_length = 4
options.input_encodings << encoding
options.output_encodings << encoding
send_message(options, OuterMessage::MessageType::MESSAGE_TYPE_OPTIONS)
# Build configuration and send it to the TV
config = Configuration.new
encoding = Options::Encoding.new
encoding.type = Options::Encoding::EncodingType::ENCODING_TYPE_HEXADECIMAL
config.encoding = encoding
config.encoding.symbol_length = 4
config.client_role = Options::RoleType::ROLE_TYPE_INPUT
outer = send_message(config, OuterMessage::MessageType::MESSAGE_TYPE_CONFIGURATION)
raise PairingFailed, outer.status unless OuterMessage::Status::STATUS_OK == outer.status
end
|
ruby
|
{
"resource": ""
}
|
q6875
|
GoogleAnymote.Pair.complete_pairing
|
train
|
def complete_pairing(code)
# Send secret code to the TV to compete the pairing process
secret = Secret.new
secret.secret = encode_hex_secret(code)
outer = send_message(secret, OuterMessage::MessageType::MESSAGE_TYPE_SECRET)
# Clean up
@gtv.ssl_client.close
raise PairingFailed, outer.status unless OuterMessage::Status::STATUS_OK == outer.status
end
|
ruby
|
{
"resource": ""
}
|
q6876
|
GoogleAnymote.Pair.send_message
|
train
|
def send_message(msg, type)
# Build the message and get it's size
message = wrap_message(msg, type).serialize_to_string
message_size = [message.length].pack('N')
# Write the message to the SSL client and get the response
@gtv.ssl_client.write(message_size + message)
data = ""
@gtv.ssl_client.readpartial(1000,data)
@gtv.ssl_client.readpartial(1000,data)
# Extract the response from the Google TV
outer = OuterMessage.new
outer.parse_from_string(data)
return outer
end
|
ruby
|
{
"resource": ""
}
|
q6877
|
GoogleAnymote.Pair.wrap_message
|
train
|
def wrap_message(msg, type)
# Wrap it in an envelope
outer = OuterMessage.new
outer.protocol_version = 1
outer.status = OuterMessage::Status::STATUS_OK
outer.type = type
outer.payload = msg.serialize_to_string
return outer
end
|
ruby
|
{
"resource": ""
}
|
q6878
|
GoogleAnymote.Pair.encode_hex_secret
|
train
|
def encode_hex_secret secret
# TODO(stevenle): Something further encodes the secret to a 64-char hex
# string. For now, use adb logcat to figure out what the expected challenge
# is. Eventually, make sure the encoding matches the server reference
# implementation:
# http://code.google.com/p/google-tv-pairing-protocol/source/browse/src/com/google/polo/pairing/PoloChallengeResponse.java
encoded_secret = [secret.to_i(16)].pack("N").unpack("cccc")[2..3].pack("c*")
# Per "Polo Implementation Overview", section 6.1, client key material is
# hashed first, followed by the server key material, followed by the nonce.
digest = OpenSSL::Digest::Digest.new('sha256')
digest << @gtv.ssl_client.cert.public_key.n.to_s(2) # client modulus
digest << @gtv.ssl_client.cert.public_key.e.to_s(2) # client exponent
digest << @gtv.ssl_client.peer_cert.public_key.n.to_s(2) # server modulus
digest << @gtv.ssl_client.peer_cert.public_key.e.to_s(2) # server exponent
digest << encoded_secret[encoded_secret.size / 2]
return digest.digest
end
|
ruby
|
{
"resource": ""
}
|
q6879
|
Sumac.IDAllocator.free
|
train
|
def free(id)
enclosing_range_index = @allocated_ranges.index { |range| range.last >= id && range.first <= id }
enclosing_range = @allocated_ranges[enclosing_range_index]
if enclosing_range.size == 1
@allocated_ranges.delete(enclosing_range)
elsif enclosing_range.first == id
@allocated_ranges[enclosing_range_index] = (enclosing_range.first.succ..enclosing_range.last)
elsif enclosing_range.last == id
@allocated_ranges[enclosing_range_index] = (enclosing_range.first..enclosing_range.last.pred)
else
@allocated_ranges[enclosing_range_index] = (enclosing_range.first..id.pred)
@allocated_ranges.insert(enclosing_range_index.succ, (id.succ..enclosing_range.last))
end
end
|
ruby
|
{
"resource": ""
}
|
q6880
|
Incline::Extensions.ActionViewBase.full_title
|
train
|
def full_title(page_title = '')
aname = Rails.application.app_name.strip
return aname if page_title.blank?
"#{page_title.strip} | #{aname}"
end
|
ruby
|
{
"resource": ""
}
|
q6881
|
Incline::Extensions.ActionViewBase.glyph
|
train
|
def glyph(name, size = '')
size =
case size.to_s.downcase
when 'small', 'sm'
'glyphicon-small'
when 'large', 'lg'
'glyphicon-large'
else
nil
end
name = name.to_s.strip
return nil if name.blank?
result = '<i class="glyphicon glyphicon-' + CGI::escape_html(name)
result += ' ' + size unless size.blank?
result += '"></i>'
result.html_safe
end
|
ruby
|
{
"resource": ""
}
|
q6882
|
Incline::Extensions.ActionViewBase.fmt_num
|
train
|
def fmt_num(value, places = 2)
return nil if value.blank?
value =
if value.respond_to?(:to_f)
value.to_f
else
nil
end
return nil unless value.is_a?(::Float)
"%0.#{places}f" % value.round(places)
end
|
ruby
|
{
"resource": ""
}
|
q6883
|
Incline::Extensions.ActionViewBase.panel
|
train
|
def panel(title, options = { }, &block)
options = {
type: 'primary',
size: 6,
offset: 3,
open_body: true
}.merge(options || {})
options[:type] = options[:type].to_s.downcase
options[:type] = 'primary' unless %w(primary success info warning danger).include?(options[:type])
options[:size] = 6 unless (1..12).include?(options[:size])
options[:offset] = 3 unless (0..12).include?(options[:offset])
ret = "<div class=\"col-md-#{options[:size]} col-md-offset-#{options[:offset]}\"><div class=\"panel panel-#{options[:type]}\"><div class=\"panel-heading\"><h4 class=\"panel-title\">#{h title}</h4></div>"
ret += '<div class="panel-body">' if options[:open_body]
if block_given?
content = capture { block.call }
content = CGI::escape_html(content) unless content.html_safe?
ret += content
end
ret += '</div>' if options[:open_body]
ret += '</div></div>'
ret.html_safe
end
|
ruby
|
{
"resource": ""
}
|
q6884
|
M4DBI.Model.delete
|
train
|
def delete
if self.class.hooks[:active]
self.class.hooks[:before_delete].each do |block|
self.class.hooks[:active] = false
block.yield self
self.class.hooks[:active] = true
end
end
st = prepare("DELETE FROM #{table} WHERE #{pk_clause}")
num_deleted = st.execute( *pk_values ).affected_count
st.finish
if num_deleted != 1
false
else
if self.class.hooks[:active]
self.class.hooks[:after_delete].each do |block|
self.class.hooks[:active] = false
block.yield self
self.class.hooks[:active] = true
end
end
true
end
end
|
ruby
|
{
"resource": ""
}
|
q6885
|
Sock.Server.subscribe
|
train
|
def subscribe(subscription)
@logger.info "Subscribing to: #{subscription + '*'}"
pubsub.psubscribe(subscription + '*') do |chan, msg|
@logger.info "pushing c: #{chan} msg: #{msg}"
channel(chan).push(msg)
end
end
|
ruby
|
{
"resource": ""
}
|
q6886
|
LiveFront.TabHelper.nav_link
|
train
|
def nav_link(options = {}, &block)
c, a = fetch_controller_and_action(options)
p = options.delete(:params) || {}
klass = page_active?(c, a, p) ? 'active' : ''
# Add our custom class into the html_options, which may or may not exist
# and which may or may not already have a :class key
o = options.delete(:html_options) || {}
o[:class] = "#{o[:class]} #{klass}".strip
if block_given?
content_tag(:li, capture(&block), o)
else
content_tag(:li, nil, o)
end
end
|
ruby
|
{
"resource": ""
}
|
q6887
|
HotTub.Sessions.get_or_set
|
train
|
def get_or_set(key, pool_options={}, &client_block)
unless @_staged[key]
@mutex.synchronize do
@_staged[key] ||= [pool_options,client_block]
end
end
get(key)
end
|
ruby
|
{
"resource": ""
}
|
q6888
|
HotTub.Sessions.delete
|
train
|
def delete(key)
deleted = false
pool = nil
@mutex.synchronize do
pool = @_sessions.delete(key)
end
if pool
pool.shutdown!
deleted = true
HotTub.logger.info "[HotTub] #{key} was deleted from #{@name}." if HotTub.logger
end
deleted
end
|
ruby
|
{
"resource": ""
}
|
q6889
|
HotTub.Sessions.reap!
|
train
|
def reap!
HotTub.logger.info "[HotTub] Reaping #{@name}!" if HotTub.log_trace?
@mutex.synchronize do
@_sessions.each_value do |pool|
break if @shutdown
pool.reap!
end
end
nil
end
|
ruby
|
{
"resource": ""
}
|
q6890
|
BetterRailsDebugger::Parser::Ruby.Processor.emit_signal
|
train
|
def emit_signal(signal_name, node)
@subscriptions ||= Hash.new()
@runner ||= BetterRailsDebugger::Parser::Ruby::ContextRunner.new self
(@subscriptions[signal_name] || {}).values.each do |block|
@runner.node = node
@runner.instance_eval &block
# block.call(node)
end
end
|
ruby
|
{
"resource": ""
}
|
q6891
|
BetterRailsDebugger::Parser::Ruby.Processor.subscribe_signal
|
train
|
def subscribe_signal(signal_name, step=:first_pass, &block)
key = SecureRandom.hex(5)
@subscriptions ||= Hash.new()
@subscriptions[signal_name] ||= Hash.new
@subscriptions[signal_name][key] = block
key
end
|
ruby
|
{
"resource": ""
}
|
q6892
|
SublimeSunippetter.Dsl.add
|
train
|
def add(method_name, *args)
return if error?(method_name, *args)
has_do_block = args.include?('block@d')
has_brace_block = args.include?('block@b')
args = delete_block_args args
@target_methods << TargetMethod.new do |t|
t.method_name = method_name
t.args = args
t.has_do_block = has_do_block
t.has_brace_block = has_brace_block
end
end
|
ruby
|
{
"resource": ""
}
|
q6893
|
WhoopsLogger.Sender.send_message
|
train
|
def send_message(data)
# TODO: format
# TODO: validation
data = prepare_data(data)
logger.debug { "Sending request to #{url.to_s}:\n#{data}" } if logger
http =
Net::HTTP::Proxy(proxy_host, proxy_port, proxy_user, proxy_pass).
new(url.host, url.port)
http.read_timeout = http_read_timeout
http.open_timeout = http_open_timeout
http.use_ssl = secure
response = begin
http.post(url.path, data, HEADERS)
rescue *HTTP_ERRORS => e
log :error, "Timeout while contacting the Whoops server."
nil
end
case response
when Net::HTTPSuccess then
log :info, "Success: #{response.class}", response
else
log :error, "Failure: #{response.class}", response
end
if response && response.respond_to?(:body)
error_id = response.body.match(%r{<error-id[^>]*>(.*?)</error-id>})
error_id[1] if error_id
end
end
|
ruby
|
{
"resource": ""
}
|
q6894
|
Shoehorn.DocumentsBase.status
|
train
|
def status(inserter_id)
status_hash = Hash.new
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.GetDocumentStatusCall do |xml|
xml.InserterId(inserter_id)
end
end
response = connection.post_xml(xml)
document = REXML::Document.new(response)
status_hash[:status] = document.elements["GetDocumentStatusCallResponse"].elements["Status"].text
status_hash[:document_id] = document.elements["GetDocumentStatusCallResponse"].elements["DocumentId"].text
status_hash[:document_type] = document.elements["GetDocumentStatusCallResponse"].elements["DocumentType"].text
status_hash
end
|
ruby
|
{
"resource": ""
}
|
q6895
|
HtmlMockup::Release::Processors.Requirejs.rjs_check
|
train
|
def rjs_check(path = @options[:rjs])
rjs_command = rjs_file(path) || rjs_bin(path)
if !(rjs_command)
raise RuntimeError, "Could not find r.js optimizer in #{path.inspect} - try updating this by npm install -g requirejs"
end
rjs_command
end
|
ruby
|
{
"resource": ""
}
|
q6896
|
Types.Type.match_type?
|
train
|
def match_type?(object)
result = object.kind_of_any? self.type_classes
if not result
result = object.type_of_any? self.type_types
end
return result
end
|
ruby
|
{
"resource": ""
}
|
q6897
|
Hook.Collection.create
|
train
|
def create data
if data.kind_of?(Array)
# TODO: server should accept multiple items to create,
# instead of making multiple requests.
data.map {|item| self.create(item) }
else
@client.post @segments, data
end
end
|
ruby
|
{
"resource": ""
}
|
q6898
|
Hook.Collection.where
|
train
|
def where fields = {}, operation = 'and'
fields.each_pair do |k, value|
field = (k.respond_to?(:field) ? k.field : k).to_s
comparation = k.respond_to?(:comparation) ? k.comparation : '='
# Range syntatic sugar
value = [ value.first, value.last ] if value.kind_of?(Range)
@wheres << [field, comparation, value, operation]
end
self
end
|
ruby
|
{
"resource": ""
}
|
q6899
|
Hook.Collection.order
|
train
|
def order fields
by_num = { 1 => 'asc', -1 => 'desc' }
ordering = []
fields.each_pair do |key, value|
ordering << [key.to_s, by_num[value] || value]
end
@ordering = ordering
self
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.