id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
6,800
fwolfst/kalindar
lib/kalindar/event.rb
Kalindar.Event.finish_time_f
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
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
[ "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" ]
Time it finishes at day, or '...'
[ "Time", "it", "finishes", "at", "day", "or", "..." ]
8c81f0bc85ac8f7d0fc43b8e25eff6c08329b2c9
https://github.com/fwolfst/kalindar/blob/8c81f0bc85ac8f7d0fc43b8e25eff6c08329b2c9/lib/kalindar/event.rb#L33-L42
6,801
fwolfst/kalindar
lib/kalindar/event.rb
Kalindar.Event.time_f
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
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
[ "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" ]
Time it finishes and or starts at day, or '...'
[ "Time", "it", "finishes", "and", "or", "starts", "at", "day", "or", "..." ]
8c81f0bc85ac8f7d0fc43b8e25eff6c08329b2c9
https://github.com/fwolfst/kalindar/blob/8c81f0bc85ac8f7d0fc43b8e25eff6c08329b2c9/lib/kalindar/event.rb#L45-L56
6,802
riddopic/garcun
lib/garcon/task/executor_options.rb
Garcon.ExecutorOptions.get_executor_from
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
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
[ "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" ]
Get the requested `Executor` based on the values set in the options hash. @param [Hash] opts The options defining the requested executor. @option opts [Executor] :executor When set use the given `Executor` instance. Three special values are also supported: `:fast` returns the global fast executor, `:io` returns the global io executor, and `:immediate` returns a new `ImmediateExecutor` object. @return [Executor, nil] The requested thread pool, or nil when no option specified. @!visibility private
[ "Get", "the", "requested", "Executor", "based", "on", "the", "values", "set", "in", "the", "options", "hash", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/executor_options.rb#L40-L57
6,803
delano/familia
lib/familia/tools.rb
Familia.Tools.rename
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
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
[ "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" ]
Use the return value from each_key as the new key name
[ "Use", "the", "return", "value", "from", "each_key", "as", "the", "new", "key", "name" ]
4ecb29e796c86611c5d37e1924729fb562eeb529
https://github.com/delano/familia/blob/4ecb29e796c86611c5d37e1924729fb562eeb529/lib/familia/tools.rb#L34-L47
6,804
mrsimonfletcher/roroacms
app/models/roroacms/comment.rb
Roroacms.Comment.deal_with_abnormalaties
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
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
[ "def", "deal_with_abnormalaties", "self", ".", "comment", "=", "comment", ".", "to_s", ".", "gsub", "(", "%r{", "}", ",", "''", ")", ".", "gsub", "(", "/", "\\s", "\\S", "\\/", "/i", ",", "\"\"", ")", "if", "!", "self", ".", "website", ".", "blank?", "website", "=", "self", ".", "website", ".", "sub", "(", "/", "\\:", "\\/", "\\/", "/", ",", "''", ")", ".", "sub", "(", "/", "/", ",", "''", ")", "unless", "self", ".", "website", "[", "/", "\\A", "\\/", "\\/", "/", "]", "||", "self", ".", "website", "[", "/", "\\A", "\\/", "\\/", "/", "]", "website", "=", "\"www.#{website}\"", "end", "self", ".", "website", "=", "\"http://#{website}\"", "end", "end" ]
strip any sort of html, we don't want javascrpt injection
[ "strip", "any", "sort", "of", "html", "we", "don", "t", "want", "javascrpt", "injection" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/models/roroacms/comment.rb#L65-L74
6,805
kindlinglabs/bullring
lib/bullring/util/server_registry.rb
Bullring.ServerRegistry.lease_server!
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
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
[ "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" ]
First starts up a server if needed then blocks until it is available and returns it
[ "First", "starts", "up", "a", "server", "if", "needed", "then", "blocks", "until", "it", "is", "available", "and", "returns", "it" ]
30ea55f7ad3de4c8af710d141cf5dfda0f9c8a44
https://github.com/kindlinglabs/bullring/blob/30ea55f7ad3de4c8af710d141cf5dfda0f9c8a44/lib/bullring/util/server_registry.rb#L113-L124
6,806
Floppy/currentcost-ruby
lib/currentcost/meter.rb
CurrentCost.Meter.update
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
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
[ "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" ]
Internal use only, client code does not need to use this function. Informs the Meter object that a new message has been received by the serial port.
[ "Internal", "use", "only", "client", "code", "does", "not", "need", "to", "use", "this", "function", ".", "Informs", "the", "Meter", "object", "that", "a", "new", "message", "has", "been", "received", "by", "the", "serial", "port", "." ]
10be0a4193511c2cb08612d155e81e078e63def0
https://github.com/Floppy/currentcost-ruby/blob/10be0a4193511c2cb08612d155e81e078e63def0/lib/currentcost/meter.rb#L53-L63
6,807
espresse/orientdb_binary
lib/orientdb_binary/database.rb
OrientdbBinary.Database.open
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
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
[ "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" ]
Initializes connection to database @since 1.0 Opens connection to database @since 1.0
[ "Initializes", "connection", "to", "database" ]
b7f791c07a56eb6b551bed375504379487e28894
https://github.com/espresse/orientdb_binary/blob/b7f791c07a56eb6b551bed375504379487e28894/lib/orientdb_binary/database.rb#L25-L31
6,808
espresse/orientdb_binary
lib/orientdb_binary/database.rb
OrientdbBinary.Database.reload
def reload answer = connection.protocol::DbReload.new(params).process(connection) @clusters = answer[:clusters] self end
ruby
def reload answer = connection.protocol::DbReload.new(params).process(connection) @clusters = answer[:clusters] self end
[ "def", "reload", "answer", "=", "connection", ".", "protocol", "::", "DbReload", ".", "new", "(", "params", ")", ".", "process", "(", "connection", ")", "@clusters", "=", "answer", "[", ":clusters", "]", "self", "end" ]
Reloads information about database. @since 1.0
[ "Reloads", "information", "about", "database", "." ]
b7f791c07a56eb6b551bed375504379487e28894
https://github.com/espresse/orientdb_binary/blob/b7f791c07a56eb6b551bed375504379487e28894/lib/orientdb_binary/database.rb#L54-L58
6,809
elektronaut/sendregning
lib/sendregning/client.rb
Sendregning.Client.send_invoice
def send_invoice(invoice) response = post_xml(invoice.to_xml, {:action => 'send', :type => 'invoice'}) InvoiceParser.parse(response, invoice) end
ruby
def send_invoice(invoice) response = post_xml(invoice.to_xml, {:action => 'send', :type => 'invoice'}) InvoiceParser.parse(response, invoice) end
[ "def", "send_invoice", "(", "invoice", ")", "response", "=", "post_xml", "(", "invoice", ".", "to_xml", ",", "{", ":action", "=>", "'send'", ",", ":type", "=>", "'invoice'", "}", ")", "InvoiceParser", ".", "parse", "(", "response", ",", "invoice", ")", "end" ]
Sends an invoice
[ "Sends", "an", "invoice" ]
2b7eb61d5b2e1ee149935773b8917b4ab47f5447
https://github.com/elektronaut/sendregning/blob/2b7eb61d5b2e1ee149935773b8917b4ab47f5447/lib/sendregning/client.rb#L49-L52
6,810
elektronaut/sendregning
lib/sendregning/client.rb
Sendregning.Client.find_invoice
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
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
[ "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" ]
Finds an invoice by invoice number
[ "Finds", "an", "invoice", "by", "invoice", "number" ]
2b7eb61d5b2e1ee149935773b8917b4ab47f5447
https://github.com/elektronaut/sendregning/blob/2b7eb61d5b2e1ee149935773b8917b4ab47f5447/lib/sendregning/client.rb#L55-L65
6,811
akerl/logcabin
lib/logcabin/dircollection.rb
LogCabin.DirCollection.find_file
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
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
[ "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" ]
Check module path for module
[ "Check", "module", "path", "for", "module" ]
a0c793f4047f3a80fd232c582ecce55139092b8e
https://github.com/akerl/logcabin/blob/a0c793f4047f3a80fd232c582ecce55139092b8e/lib/logcabin/dircollection.rb#L23-L29
6,812
NYULibraries/figs
lib/figs/directory_flattener.rb
Figs.DirectoryFlattener.flattened_filenames
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
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
[ "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" ]
Creates an array consisting of only files contained in a directory and its subdirectories. Expects an array of filenames or dirnames or a combination of both.
[ "Creates", "an", "array", "consisting", "of", "only", "files", "contained", "in", "a", "directory", "and", "its", "subdirectories", "." ]
24484450a93f5927a0a1ac227a8ad572b70c1337
https://github.com/NYULibraries/figs/blob/24484450a93f5927a0a1ac227a8ad572b70c1337/lib/figs/directory_flattener.rb#L14-L24
6,813
NYULibraries/figs
lib/figs/directory_flattener.rb
Figs.DirectoryFlattener.flatten_files
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
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
[ "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" ]
Expects the directory path and filename, checks to see if its another directory or filename, if directory, calls directory_to_filenames.
[ "Expects", "the", "directory", "path", "and", "filename", "checks", "to", "see", "if", "its", "another", "directory", "or", "filename", "if", "directory", "calls", "directory_to_filenames", "." ]
24484450a93f5927a0a1ac227a8ad572b70c1337
https://github.com/NYULibraries/figs/blob/24484450a93f5927a0a1ac227a8ad572b70c1337/lib/figs/directory_flattener.rb#L40-L49
6,814
tongueroo/balancer
lib/balancer/profile.rb
Balancer.Profile.profile_name
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
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
[ "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" ]
Determines a valid profile_name. Falls back to default
[ "Determines", "a", "valid", "profile_name", ".", "Falls", "back", "to", "default" ]
c149498e78f73b1dc0a433cc693ec4327c409bab
https://github.com/tongueroo/balancer/blob/c149498e78f73b1dc0a433cc693ec4327c409bab/lib/balancer/profile.rb#L44-L59
6,815
barkerest/barkest_core
app/models/barkest_core/ms_sql_db_definition.rb
BarkestCore.MsSqlDbDefinition.add_source
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
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
[ "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" ]
Adds a source using a specific timestamp. The first line of the SQL should be a comment specifying the timestamp for the source. -- 2016-12-19 15:45 -- 2016-12-19 -- 201612191545 -- 20161219 The timestamp will be converted into a 12-digit number, if time is not specified it will be right-padded with zeroes to get to the 12-digit number. The +sql+ should be a valid create/alter table/view/function statement.
[ "Adds", "a", "source", "using", "a", "specific", "timestamp", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/ms_sql_db_definition.rb#L113-L118
6,816
barkerest/barkest_core
app/models/barkest_core/ms_sql_db_definition.rb
BarkestCore.MsSqlDbDefinition.add_source_path
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
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
[ "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" ]
Adds all SQL files found in the specified directory to the sources for this updater. The +path+ should contain the SQL files. If there are subdirectories, you should include them individually. The source files should specify a timestamp in the first comment. -- 2016-12-19 15:45 -- 2016-12-19 -- 201612191545 -- 20161219 The timestamp will be converted into a 12-digit number, if time is not specified it will be right-padded with zeroes to get to the 12-digit number.
[ "Adds", "all", "SQL", "files", "found", "in", "the", "specified", "directory", "to", "the", "sources", "for", "this", "updater", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/ms_sql_db_definition.rb#L144-L162
6,817
inside-track/remi
lib/remi/data_subjects/sftp_file.rb
Remi.Extractor::SftpFile.extract
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
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
[ "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" ]
Called to extract files from the source filesystem. @return [Array<String>] An array of paths to a local copy of the files extacted
[ "Called", "to", "extract", "files", "from", "the", "source", "filesystem", "." ]
f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7
https://github.com/inside-track/remi/blob/f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7/lib/remi/data_subjects/sftp_file.rb#L99-L110
6,818
inside-track/remi
lib/remi/data_subjects/sftp_file.rb
Remi.Loader::SftpFile.load
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
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
[ "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" ]
Copies data to the SFTP Server @param data [Object] The path to the file in the temporary work location @return [true] On success
[ "Copies", "data", "to", "the", "SFTP", "Server" ]
f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7
https://github.com/inside-track/remi/blob/f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7/lib/remi/data_subjects/sftp_file.rb#L189-L198
6,819
vecerek/css_compare
lib/css_compare/exec.rb
CssCompare.Comparison.run
def run result = CssCompare::Engine.new(@options) .parse! .equal? write_output(result.to_s + "\n", @options[:output]) end
ruby
def run result = CssCompare::Engine.new(@options) .parse! .equal? write_output(result.to_s + "\n", @options[:output]) end
[ "def", "run", "result", "=", "CssCompare", "::", "Engine", ".", "new", "(", "@options", ")", ".", "parse!", ".", "equal?", "write_output", "(", "result", ".", "to_s", "+", "\"\\n\"", ",", "@options", "[", ":output", "]", ")", "end" ]
Runs the comparison.
[ "Runs", "the", "comparison", "." ]
b87237a908c2c2f1c659d1160e8b266d594667dd
https://github.com/vecerek/css_compare/blob/b87237a908c2c2f1c659d1160e8b266d594667dd/lib/css_compare/exec.rb#L104-L109
6,820
tanema/ghost_in_the_post
lib/ghost_in_the_post/phantom_transform.rb
GhostInThePost.PhantomTransform.html_file
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
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
[ "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" ]
generate a tempfile with all the html that we need so that phantom can inject easily and not have to max out a single command
[ "generate", "a", "tempfile", "with", "all", "the", "html", "that", "we", "need", "so", "that", "phantom", "can", "inject", "easily", "and", "not", "have", "to", "max", "out", "a", "single", "command" ]
e47c5d8371141241699f5ba7dd743e60fa739573
https://github.com/tanema/ghost_in_the_post/blob/e47c5d8371141241699f5ba7dd743e60fa739573/lib/ghost_in_the_post/phantom_transform.rb#L49-L54
6,821
rjoberon/bibsonomy-ruby
lib/bibsonomy/csl.rb
BibSonomy.CSL.render
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
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
[ "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" ]
Create a new BibSonomy instance. @param user_name [String] the BibSonomy user name @param api_key [String] the API key of the user (get at https://www.bibsonomy.org/settings?selTab=1) Download `count` posts for the given `user` and `tag(s)` and render them with {http://citationstyles.org/ CSL}. @param grouping [String] the type of the name (either "user" or "group") @param name [String] the name of the group or user @param tags [Array<String>] the tags that all posts must contain (can be empty) @param count [Integer] number of posts to download @return [String] the rendered posts as HTML
[ "Create", "a", "new", "BibSonomy", "instance", "." ]
15afed3f32e434d28576ac62ecf3cfd8a392e055
https://github.com/rjoberon/bibsonomy-ruby/blob/15afed3f32e434d28576ac62ecf3cfd8a392e055/lib/bibsonomy/csl.rb#L123-L224
6,822
rjoberon/bibsonomy-ruby
lib/bibsonomy/csl.rb
BibSonomy.CSL.get_public_docs
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
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
[ "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" ]
only show PDF files
[ "only", "show", "PDF", "files" ]
15afed3f32e434d28576ac62ecf3cfd8a392e055
https://github.com/rjoberon/bibsonomy-ruby/blob/15afed3f32e434d28576ac62ecf3cfd8a392e055/lib/bibsonomy/csl.rb#L277-L288
6,823
riddopic/garcun
lib/garcon/chef/chef_helpers.rb
Garcon.ChefHelpers.find_by
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
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
[ "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" ]
Search for a matching node by a given role or tag. @param [Symbol] type The filter type, can be `:role` or `:tag`. @param [String] filter The role or tag to filter on. @param [Boolean] single True if we should return only a single match, or false to return all of the matches. @yield an optional block to enumerate over the nodes. @return [Array, Proc] The value of the passed block or node. @api public
[ "Search", "for", "a", "matching", "node", "by", "a", "given", "role", "or", "tag", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/chef/chef_helpers.rb#L72-L89
6,824
riddopic/garcun
lib/garcon/chef/chef_helpers.rb
Garcon.ChefHelpers.cookbook_version
def cookbook_version(name = nil) cookbook = name.nil? ? cookbook_name : name node.run_context.cookbook_collection[cookbook].metadata.version end
ruby
def cookbook_version(name = nil) cookbook = name.nil? ? cookbook_name : name node.run_context.cookbook_collection[cookbook].metadata.version end
[ "def", "cookbook_version", "(", "name", "=", "nil", ")", "cookbook", "=", "name", ".", "nil?", "?", "cookbook_name", ":", "name", "node", ".", "run_context", ".", "cookbook_collection", "[", "cookbook", "]", ".", "metadata", ".", "version", "end" ]
Retrieve the version number of the cookbook in the run list. @param name [String] name of cookbook to retrieve the version on. @return [Integer] version of the cookbook. @api public
[ "Retrieve", "the", "version", "number", "of", "the", "cookbook", "in", "the", "run", "list", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/chef/chef_helpers.rb#L183-L186
6,825
riddopic/garcun
lib/garcon/chef/chef_helpers.rb
Garcon.ChefHelpers.file_cache_path
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
def file_cache_path(*args) if args.nil? Chef::Config[:file_cache_path] else ::File.join(Chef::Config[:file_cache_path], args) end end
[ "def", "file_cache_path", "(", "*", "args", ")", "if", "args", ".", "nil?", "Chef", "::", "Config", "[", ":file_cache_path", "]", "else", "::", "File", ".", "join", "(", "Chef", "::", "Config", "[", ":file_cache_path", "]", ",", "args", ")", "end", "end" ]
Shortcut to return cache path, if you pass in a file it will return the file with the cache path. @example file_cache_path => "/var/chef/cache/" file_cache_path 'patch.tar.gz' => "/var/chef/cache/patch.tar.gz" file_cache_path "#{node[:name]}-backup.tar.gz" => "/var/chef/cache/c20d24209cc8-backup.tar.gz" @param [String] args name of file to return path with file @return [String] @api public
[ "Shortcut", "to", "return", "cache", "path", "if", "you", "pass", "in", "a", "file", "it", "will", "return", "the", "file", "with", "the", "cache", "path", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/chef/chef_helpers.rb#L207-L213
6,826
riddopic/garcun
lib/garcon/chef/chef_helpers.rb
Garcon.ChefHelpers._?
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
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
[ "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" ]
Invokes the public method whose name goes as first argument just like `public_send` does, except that if the receiver does not respond to it the call returns `nil` rather than raising an exception. @note `_?` is defined on `Object`. Therefore, it won't work with instances of classes that do not have `Object` among their ancestors, like direct subclasses of `BasicObject`. @param [String] object The object to send the method to. @param [Symbol] method The method to send to the object. @api public
[ "Invokes", "the", "public", "method", "whose", "name", "goes", "as", "first", "argument", "just", "like", "public_send", "does", "except", "that", "if", "the", "receiver", "does", "not", "respond", "to", "it", "the", "call", "returns", "nil", "rather", "than", "raising", "an", "exception", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/chef/chef_helpers.rb#L230-L238
6,827
riddopic/garcun
lib/garcon/chef/chef_helpers.rb
Garcon.ChefHelpers.zip_hash
def zip_hash(col1, col2) col1.zip(col2).inject({}) { |r, i| r[i[0]] = i[1]; r } end
ruby
def zip_hash(col1, col2) col1.zip(col2).inject({}) { |r, i| r[i[0]] = i[1]; r } end
[ "def", "zip_hash", "(", "col1", ",", "col2", ")", "col1", ".", "zip", "(", "col2", ")", ".", "inject", "(", "{", "}", ")", "{", "|", "r", ",", "i", "|", "r", "[", "i", "[", "0", "]", "]", "=", "i", "[", "1", "]", ";", "r", "}", "end" ]
Returns a hash using col1 as keys and col2 as values. @example zip_hash([:name, :age, :sex], ['Earl', 30, 'male']) => { :age => 30, :name => "Earl", :sex => "male" } @param [Array] col1 Containing the keys. @param [Array] col2 Values for hash. @return [Hash]
[ "Returns", "a", "hash", "using", "col1", "as", "keys", "and", "col2", "as", "values", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/chef/chef_helpers.rb#L282-L284
6,828
riddopic/garcun
lib/garcon/chef/chef_helpers.rb
Garcon.ChefHelpers.with_tmp_dir
def with_tmp_dir(&block) Dir.mktmpdir(SecureRandom.hex(3)) do |tmp_dir| Dir.chdir(tmp_dir, &block) end end
ruby
def with_tmp_dir(&block) Dir.mktmpdir(SecureRandom.hex(3)) do |tmp_dir| Dir.chdir(tmp_dir, &block) end end
[ "def", "with_tmp_dir", "(", "&", "block", ")", "Dir", ".", "mktmpdir", "(", "SecureRandom", ".", "hex", "(", "3", ")", ")", "do", "|", "tmp_dir", "|", "Dir", ".", "chdir", "(", "tmp_dir", ",", "block", ")", "end", "end" ]
Creates a temp directory executing the block provided. When done the temp directory and all it's contents are garbage collected. @yield [Proc] block A block that will be run @return [Object] Result of the block operation @api public
[ "Creates", "a", "temp", "directory", "executing", "the", "block", "provided", ".", "When", "done", "the", "temp", "directory", "and", "all", "it", "s", "contents", "are", "garbage", "collected", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/chef/chef_helpers.rb#L307-L311
6,829
KatanaCode/evvnt
lib/evvnt/class_template_methods.rb
Evvnt.ClassTemplateMethods.create
def create(**params) path = nest_path_within_parent(plural_resource_path, params) api_request(:post, path, params: params) end
ruby
def create(**params) path = nest_path_within_parent(plural_resource_path, params) api_request(:post, path, params: params) end
[ "def", "create", "(", "**", "params", ")", "path", "=", "nest_path_within_parent", "(", "plural_resource_path", ",", "params", ")", "api_request", "(", ":post", ",", "path", ",", "params", ":", "params", ")", "end" ]
Template method for creating a new record on the API. params - A Hash of params to send to the API. Returns {Evvnt::Base} subclass
[ "Template", "method", "for", "creating", "a", "new", "record", "on", "the", "API", "." ]
e13f6d84af09a71819356620fb25685a6cd159c9
https://github.com/KatanaCode/evvnt/blob/e13f6d84af09a71819356620fb25685a6cd159c9/lib/evvnt/class_template_methods.rb#L18-L21
6,830
KatanaCode/evvnt
lib/evvnt/class_template_methods.rb
Evvnt.ClassTemplateMethods.index
def index(**params) params.stringify_keys! path = nest_path_within_parent(plural_resource_path, params) api_request(:get, path, params: params) end
ruby
def index(**params) params.stringify_keys! path = nest_path_within_parent(plural_resource_path, params) api_request(:get, path, params: params) end
[ "def", "index", "(", "**", "params", ")", "params", ".", "stringify_keys!", "path", "=", "nest_path_within_parent", "(", "plural_resource_path", ",", "params", ")", "api_request", "(", ":get", ",", "path", ",", "params", ":", "params", ")", "end" ]
Template method for fetching an index of record from the API. params - A Hash of params to send to the API. Returns Array
[ "Template", "method", "for", "fetching", "an", "index", "of", "record", "from", "the", "API", "." ]
e13f6d84af09a71819356620fb25685a6cd159c9
https://github.com/KatanaCode/evvnt/blob/e13f6d84af09a71819356620fb25685a6cd159c9/lib/evvnt/class_template_methods.rb#L28-L32
6,831
KatanaCode/evvnt
lib/evvnt/class_template_methods.rb
Evvnt.ClassTemplateMethods.show
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
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
[ "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" ]
Template method for creating a given record record_id - An Integer or String representing the record ID on the API. params - A Hash of params to send to the API. Returns {Evvnt::Base} subclass
[ "Template", "method", "for", "creating", "a", "given", "record" ]
e13f6d84af09a71819356620fb25685a6cd159c9
https://github.com/KatanaCode/evvnt/blob/e13f6d84af09a71819356620fb25685a6cd159c9/lib/evvnt/class_template_methods.rb#L40-L46
6,832
Fire-Dragon-DoL/fried-schema
lib/fried/schema/attribute/define_writer.rb
Fried::Schema::Attribute.DefineWriter.call
def call(definition, klass) is_a = is[definition.type] define_writer(definition, is_a, klass) end
ruby
def call(definition, klass) is_a = is[definition.type] define_writer(definition, is_a, klass) end
[ "def", "call", "(", "definition", ",", "klass", ")", "is_a", "=", "is", "[", "definition", ".", "type", "]", "define_writer", "(", "definition", ",", "is_a", ",", "klass", ")", "end" ]
Creates write method with type-checking @param definition [Definition] @param klass [Class, Module] @return [Definition]
[ "Creates", "write", "method", "with", "type", "-", "checking" ]
85c5a093f319fc0f0d242264fdd7a2acfd805eea
https://github.com/Fire-Dragon-DoL/fried-schema/blob/85c5a093f319fc0f0d242264fdd7a2acfd805eea/lib/fried/schema/attribute/define_writer.rb#L26-L29
6,833
jakewendt/rails_extension
lib/rails_extension/action_controller_extension/routing.rb
RailsExtension::ActionControllerExtension::Routing.ClassMethods.assert_no_route
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
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
[ "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" ]
def assert_route end
[ "def", "assert_route", "end" ]
310774fea4a07821aee8f87b9f30d2b4b0bbe548
https://github.com/jakewendt/rails_extension/blob/310774fea4a07821aee8f87b9f30d2b4b0bbe548/lib/rails_extension/action_controller_extension/routing.rb#L12-L18
6,834
fdp-A4/richcss-cli
lib/richcss/richcss_ui.rb
Richcss.RichUI.debug
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
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
[ "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" ]
Conveys debug information to the user. @param [Integer] depth the current depth of the resolution process. @return [void]
[ "Conveys", "debug", "information", "to", "the", "user", "." ]
804f154032e223bae8f9884eb9aec91144d49494
https://github.com/fdp-A4/richcss-cli/blob/804f154032e223bae8f9884eb9aec91144d49494/lib/richcss/richcss_ui.rb#L10-L16
6,835
codescrum/bebox
lib/bebox/commands/role_commands.rb
Bebox.RoleCommands.role_list_command
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
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
[ "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" ]
Role list command
[ "Role", "list", "command" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/role_commands.rb#L21-L32
6,836
codescrum/bebox
lib/bebox/commands/role_commands.rb
Bebox.RoleCommands.role_new_command
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
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
[ "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" ]
Role new command
[ "Role", "new", "command" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/role_commands.rb#L35-L44
6,837
codescrum/bebox
lib/bebox/commands/role_commands.rb
Bebox.RoleCommands.generate_role_command
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
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
[ "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" ]
For add_profile remove_profile and remove_role commands
[ "For", "add_profile", "remove_profile", "and", "remove_role", "commands" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/role_commands.rb#L53-L60
6,838
codescrum/bebox
lib/bebox/commands/role_commands.rb
Bebox.RoleCommands.role_list_profiles_command
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
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
[ "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" ]
Role list profiles command
[ "Role", "list", "profiles", "command" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/role_commands.rb#L63-L73
6,839
fugroup/pushfile
lib/pushfile/util.rb
Pushfile.Util.filename
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
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
[ "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", "\\-", "\\_", "\\.", "}", ",", "''", ")", "name", "end" ]
Make sure the file name is valid
[ "Make", "sure", "the", "file", "name", "is", "valid" ]
dd06bd6b023514a1446544986b1ce85b7bae3f78
https://github.com/fugroup/pushfile/blob/dd06bd6b023514a1446544986b1ce85b7bae3f78/lib/pushfile/util.rb#L5-L15
6,840
riddopic/garcun
lib/garcon/utility/memstash.rb
Garcon.MemStash.load
def load(data) @monitor.synchronize do data.each do |key, value| expire! store(key, val) end end end
ruby
def load(data) @monitor.synchronize do data.each do |key, value| expire! store(key, val) end end end
[ "def", "load", "(", "data", ")", "@monitor", ".", "synchronize", "do", "data", ".", "each", "do", "|", "key", ",", "value", "|", "expire!", "store", "(", "key", ",", "val", ")", "end", "end", "end" ]
Initializes the cache. @param [Hash] opts The options to configure the cache. @option opts [Integer] :max_entries Maximum number of elements in the cache. @option opts [Numeric] :ttl Maximum time, in seconds, for a value to stay in the cache. @option opts [Numeric] :tti Maximum time, in seconds, for a value to stay in the cache without being accessed. @option opts [Integer] :interval Number of cache operations between calls to {#expire!}. Loads a hash of data into the stash. @param [Hash] data Hash of data with either String or Symbol keys. @return nothing.
[ "Initializes", "the", "cache", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/memstash.rb#L114-L121
6,841
riddopic/garcun
lib/garcon/utility/memstash.rb
Garcon.MemStash.fetch
def fetch(key) @monitor.synchronize do found, value = get(key) found ? value : store(key, yield) end end
ruby
def fetch(key) @monitor.synchronize do found, value = get(key) found ? value : store(key, yield) end end
[ "def", "fetch", "(", "key", ")", "@monitor", ".", "synchronize", "do", "found", ",", "value", "=", "get", "(", "key", ")", "found", "?", "value", ":", "store", "(", "key", ",", "yield", ")", "end", "end" ]
Retrieves a value from the cache, if available and not expired, or yields to a block that calculates the value to be stored in the cache. @param [Object] key The key to look up or store at. @yield yields when the value is not present. @yieldreturn [Object] The value to store in the cache. @return [Object] The value at the key.
[ "Retrieves", "a", "value", "from", "the", "cache", "if", "available", "and", "not", "expired", "or", "yields", "to", "a", "block", "that", "calculates", "the", "value", "to", "be", "stored", "in", "the", "cache", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/memstash.rb#L137-L142
6,842
riddopic/garcun
lib/garcon/utility/memstash.rb
Garcon.MemStash.delete
def delete(key) @monitor.synchronize do entry = @stash.delete(key) if entry @expires_at.delete(entry) entry.value else nil end end end
ruby
def delete(key) @monitor.synchronize do entry = @stash.delete(key) if entry @expires_at.delete(entry) entry.value else nil end end end
[ "def", "delete", "(", "key", ")", "@monitor", ".", "synchronize", "do", "entry", "=", "@stash", ".", "delete", "(", "key", ")", "if", "entry", "@expires_at", ".", "delete", "(", "entry", ")", "entry", ".", "value", "else", "nil", "end", "end", "end" ]
Removes a value from the cache. @param [Object] key The key to remove. @return [Object, nil] The value at the key, when present, or `nil`.
[ "Removes", "a", "value", "from", "the", "cache", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/memstash.rb#L187-L197
6,843
rubyworks/richunits
lib/richunits/duration.rb
RichUnits.Duration.reset_segments
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
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
[ "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" ]
Reset segments. call-seq: reset_segments(max-period) reset_segments(max-period, min-period) reset_segments([period1, period2, ...])
[ "Reset", "segments", "." ]
c92bec173fc63798013defdd9a1727b0d1d65d46
https://github.com/rubyworks/richunits/blob/c92bec173fc63798013defdd9a1727b0d1d65d46/lib/richunits/duration.rb#L46-L63
6,844
rubyworks/richunits
lib/richunits/duration.rb
RichUnits.Duration.strftime
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
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
[ "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", "(", "/", "/", ")", "do", "|", "match", "|", "hx", "[", "match", "[", "1", "..", "1", "]", "]", "end", ".", "gsub", "(", "'%%'", ",", "'%'", ")", "end" ]
Format duration. *Identifiers* %w -- Number of weeks %d -- Number of days %h -- Number of hours %m -- Number of minutes %s -- Number of seconds %t -- Total number of seconds %x -- Duration#to_s %% -- Literal `%' character *Example* d = Duration.new(:weeks => 10, :days => 7) => #<Duration: 11 weeks> d.strftime("It's been %w weeks!") => "It's been 11 weeks!"
[ "Format", "duration", "." ]
c92bec173fc63798013defdd9a1727b0d1d65d46
https://github.com/rubyworks/richunits/blob/c92bec173fc63798013defdd9a1727b0d1d65d46/lib/richunits/duration.rb#L191-L206
6,845
barkerest/barkest_core
app/helpers/barkest_core/recaptcha_helper.rb
BarkestCore.RecaptchaHelper.verify_recaptcha_challenge
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
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
[ "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" ]
Verifies the response from a recaptcha challenge in a controller. It will return true if the recaptcha challenge passed. It always returns true in the 'test' environment. If a +model+ is provided, then an error will be added to the model if the challenge fails. Because this is handled outside of the model (since it's based on the request and not the model), you should first check if the model is valid and then verify the recaptcha challenge to ensure you don't lose the recaptcha error message. if model.valid? && verify_recaptcha_challenge(model) model.save redirect_to :show, id: model else render 'edit' end
[ "Verifies", "the", "response", "from", "a", "recaptcha", "challenge", "in", "a", "controller", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/recaptcha_helper.rb#L63-L112
6,846
Referly/better_sqs
spec/support/mocks.rb
SqsMocks.MockClient.get_queue_attributes
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
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
[ "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" ]
Just a static mock of the get_queue_attributes API
[ "Just", "a", "static", "mock", "of", "the", "get_queue_attributes", "API" ]
c1e20bf5c079df1b65e6ed7702a2449ab2e991ba
https://github.com/Referly/better_sqs/blob/c1e20bf5c079df1b65e6ed7702a2449ab2e991ba/spec/support/mocks.rb#L80-L90
6,847
ccsalespro/meta_enum
lib/meta_enum/type.rb
MetaEnum.Type.[]
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
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
[ "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" ]
Initialize takes a single hash of name to value. e.g. MetaEnum::Type.new(red: 0, green: 1, blue: 2) Additional data can also be associated with each value by passing an array of [value, extra data]. This can be used for additional description or any other reason. e.g. MetaEnum::Type.new(small: [0, "Less than 10], large: [1, "At least 10"] value_normalizer is a callable object that normalizes values. The default converts all values to integers. To allow string values use method(:String). element_class is the class with which to create elements. It should be a sub-class of MetaEnum::Element (or otherwise match it's behavior). [] is a "do what I mean" operator. It returns the Element from this type depending on the key. When key is a symbol, it is considered the name of the Element to return. Since symbols are used from code, it is considered an error if the key is not found and it raises an exception. When key can be converted to an integer by value_normalizer, then it is considered the value of the Element to return. Retrieving by value is presumed to converting from external data where a missing value should not be considered fatal. In this case it returns a MissingElement is with value as the key. This allows a Type to only specify the values it needs while passing through the others unmodified. Finally, when key is a MetaEnum::Element, it is simply returned (unless it belongs to a different Type in which case an ArgumentError is raised). See #values_by_number and #values_by_name for non-fuzzy value selection.
[ "Initialize", "takes", "a", "single", "hash", "of", "name", "to", "value", "." ]
988147e7f730625bb9e1693c06415888d4732188
https://github.com/ccsalespro/meta_enum/blob/988147e7f730625bb9e1693c06415888d4732188/lib/meta_enum/type.rb#L80-L91
6,848
riddopic/hoodie
lib/hoodie/utils/url_helper.rb
Hoodie.UrlHelper.unshorten
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
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
[ "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", "=~", "/", "/i", ")", "?", "url", ":", "\"http://#{url}\"", "__unshorten__", "(", "url", ",", "options", ")", "end" ]
Unshorten a shortened URL. @param url [String] A shortened URL @param [Hash] opts @option opts [Integer] :max_level max redirect times @option opts [Integer] :timeout timeout in seconds, for every request @option opts [Boolean] :use_cache use cached result if available @return Original url, a url that does not redirects
[ "Unshorten", "a", "shortened", "URL", "." ]
921601dd4849845d3f5d3765dafcf00178b2aa66
https://github.com/riddopic/hoodie/blob/921601dd4849845d3f5d3765dafcf00178b2aa66/lib/hoodie/utils/url_helper.rb#L61-L69
6,849
thomis/eventhub-processor
lib/eventhub/helper.rb
EventHub.Helper.format_string
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
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
[ "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" ]
replaces CR, LF, CRLF with ";" and cut's string to requied length by adding "..." if string would be longer
[ "replaces", "CR", "LF", "CRLF", "with", ";", "and", "cut", "s", "string", "to", "requied", "length", "by", "adding", "...", "if", "string", "would", "be", "longer" ]
113ecd3aeb592e185716a7f80b0aefab57092c8c
https://github.com/thomis/eventhub-processor/blob/113ecd3aeb592e185716a7f80b0aefab57092c8c/lib/eventhub/helper.rb#L11-L16
6,850
thededlier/WatsonNLPWrapper
lib/WatsonNLPWrapper.rb
WatsonNLPWrapper.WatsonNLPApi.analyze
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
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
[ "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" ]
Initialize instance variables for use later Sends a POST request to analyze text with certain features enabled
[ "Initialize", "instance", "variables", "for", "use", "later", "Sends", "a", "POST", "request", "to", "analyze", "text", "with", "certain", "features", "enabled" ]
c5b9118e7f7d91dbd95d9991bd499e1f70e26a25
https://github.com/thededlier/WatsonNLPWrapper/blob/c5b9118e7f7d91dbd95d9991bd499e1f70e26a25/lib/WatsonNLPWrapper.rb#L23-L41
6,851
thededlier/WatsonNLPWrapper
lib/WatsonNLPWrapper.rb
WatsonNLPWrapper.WatsonNLPApi.default_features
def default_features { entities: { emotion: true, sentiment: true, limit: 2 }, keywords: { emotion: true, sentiment: true, limit: 2 } } end
ruby
def default_features { entities: { emotion: true, sentiment: true, limit: 2 }, keywords: { emotion: true, sentiment: true, limit: 2 } } end
[ "def", "default_features", "{", "entities", ":", "{", "emotion", ":", "true", ",", "sentiment", ":", "true", ",", "limit", ":", "2", "}", ",", "keywords", ":", "{", "emotion", ":", "true", ",", "sentiment", ":", "true", ",", "limit", ":", "2", "}", "}", "end" ]
Default features if no features specified
[ "Default", "features", "if", "no", "features", "specified" ]
c5b9118e7f7d91dbd95d9991bd499e1f70e26a25
https://github.com/thededlier/WatsonNLPWrapper/blob/c5b9118e7f7d91dbd95d9991bd499e1f70e26a25/lib/WatsonNLPWrapper.rb#L53-L66
6,852
garytaylor/capybara_objects
lib/capybara_objects/page_object.rb
CapybaraObjects.PageObject.visit
def visit raise ::CapybaraObjects::Exceptions::MissingUrl unless url.present? page.visit url validate! self end
ruby
def visit raise ::CapybaraObjects::Exceptions::MissingUrl unless url.present? page.visit url validate! self end
[ "def", "visit", "raise", "::", "CapybaraObjects", "::", "Exceptions", "::", "MissingUrl", "unless", "url", ".", "present?", "page", ".", "visit", "url", "validate!", "self", "end" ]
Visits the pre configured URL to make this page available @raise ::CapybaraPageObjects::Exceptions::MissingUrl @return [::CapybaraObjects::PageObject] self - allows chaining of methods
[ "Visits", "the", "pre", "configured", "URL", "to", "make", "this", "page", "available" ]
7cc2998400a35ceb6f9354cdf949fc59eddcdb12
https://github.com/garytaylor/capybara_objects/blob/7cc2998400a35ceb6f9354cdf949fc59eddcdb12/lib/capybara_objects/page_object.rb#L41-L46
6,853
belsonheng/spidercrawl
lib/spidercrawl/request.rb
Spidercrawl.Request.curl
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
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
[ "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" ]
Fetch a page from the given url using libcurl
[ "Fetch", "a", "page", "from", "the", "given", "url", "using", "libcurl" ]
195b067f551597657ad61251dc8d485ec0b0b9c7
https://github.com/belsonheng/spidercrawl/blob/195b067f551597657ad61251dc8d485ec0b0b9c7/lib/spidercrawl/request.rb#L32-L61
6,854
barkerest/incline
lib/incline/validators/email_validator.rb
Incline.EmailValidator.validate_each
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
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
[ "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" ]
Validates attributes to determine if they contain valid email addresses. Does not perform an in depth check, but does verify that the format is valid.
[ "Validates", "attributes", "to", "determine", "if", "they", "contain", "valid", "email", "addresses", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/validators/email_validator.rb#L29-L33
6,855
riddopic/garcun
lib/garcon/utility/interpolation.rb
Garcon.Interpolation.interpolate
def interpolate(item = self, parent = nil) item = render item, parent item.is_a?(Hash) ? ::Mash.new(item) : item end
ruby
def interpolate(item = self, parent = nil) item = render item, parent item.is_a?(Hash) ? ::Mash.new(item) : item end
[ "def", "interpolate", "(", "item", "=", "self", ",", "parent", "=", "nil", ")", "item", "=", "render", "item", ",", "parent", "item", ".", "is_a?", "(", "Hash", ")", "?", "::", "Mash", ".", "new", "(", "item", ")", ":", "item", "end" ]
Interpolate provides a means of externally using Ruby string interpolation mechinism. @example node[:ldap][:basedir] = '/opt' node[:ldap][:homedir] = '%{basedir}/openldap/slap/happy' interpolate(node[:ldap])[:homedir] # => "/opt/openldap/slap/happy" @param [String] item The string to interpolate. @param [String, Hash] parent The string used for substitution. @return [String] The interpolated string. @api public
[ "Interpolate", "provides", "a", "means", "of", "externally", "using", "Ruby", "string", "interpolation", "mechinism", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/interpolation.rb#L44-L47
6,856
riddopic/garcun
lib/garcon/utility/interpolation.rb
Garcon.Interpolation.render
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
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
[ "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" ]
Provides recursive interpolation of node objects, using standard string interpolation methods. @param [String] item The string to interpolate. @param [String, Hash] parent The string used for substitution. @return [String] @api private
[ "Provides", "recursive", "interpolation", "of", "node", "objects", "using", "standard", "string", "interpolation", "methods", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/interpolation.rb#L76-L88
6,857
chrisjones-tripletri/action_command
lib/action_command/executable_transaction.rb
ActionCommand.ExecutableTransaction.execute
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
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
[ "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" ]
starts a transaction only if we are not already within one.
[ "starts", "a", "transaction", "only", "if", "we", "are", "not", "already", "within", "one", "." ]
9b9a8ba30e407ca6d88a62a164d1dc22ba149874
https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/executable_transaction.rb#L8-L23
6,858
hongshu-corp/ule_page
lib/ule_page/site_prism_extender.rb
UlePage.SitePrismExtender.element_collection
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
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
[ "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" ]
why define this method? if we use the elements method directly, it will be conflicted with RSpec.Mather.BuiltIn.All.elements. I have not found one good method to solve the confliction.
[ "why", "define", "this", "method?", "if", "we", "use", "the", "elements", "method", "directly", "it", "will", "be", "conflicted", "with", "RSpec", ".", "Mather", ".", "BuiltIn", ".", "All", ".", "elements", ".", "I", "have", "not", "found", "one", "good", "method", "to", "solve", "the", "confliction", "." ]
599a1c1eb5c2df3b38b96896942d280284fd8ffa
https://github.com/hongshu-corp/ule_page/blob/599a1c1eb5c2df3b38b96896942d280284fd8ffa/lib/ule_page/site_prism_extender.rb#L11-L18
6,859
hongshu-corp/ule_page
lib/ule_page/site_prism_extender.rb
UlePage.SitePrismExtender.define_elements_js
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
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
[ "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" ]
instead of the rails traditional form in js mode, there is no prefix before the element name
[ "instead", "of", "the", "rails", "traditional", "form", "in", "js", "mode", "there", "is", "no", "prefix", "before", "the", "element", "name" ]
599a1c1eb5c2df3b38b96896942d280284fd8ffa
https://github.com/hongshu-corp/ule_page/blob/599a1c1eb5c2df3b38b96896942d280284fd8ffa/lib/ule_page/site_prism_extender.rb#L66-L77
6,860
spiegela/MultiBitField
lib/multi_bit_field.rb
MultiBitField.ClassMethods.range_for
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
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
[ "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" ]
Returns the column by name +column_for @param [ Symbol ] column_name column name that stores the bitfield integer
[ "Returns", "the", "column", "by", "name" ]
53674ba73caea8d871510d02271b71edaa1335f1
https://github.com/spiegela/MultiBitField/blob/53674ba73caea8d871510d02271b71edaa1335f1/lib/multi_bit_field.rb#L72-L77
6,861
spiegela/MultiBitField
lib/multi_bit_field.rb
MultiBitField.ClassMethods.reset_mask_for
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
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
[ "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" ]
Returns a "reset mask" for a list of fields +reset_mask_for :fields @example user.reset_mask_for :field @param [ Symbol ] column name of the column these fields are in @param [ Symbol ] field(s) name of the field(s) for the mask
[ "Returns", "a", "reset", "mask", "for", "a", "list", "of", "fields" ]
53674ba73caea8d871510d02271b71edaa1335f1
https://github.com/spiegela/MultiBitField/blob/53674ba73caea8d871510d02271b71edaa1335f1/lib/multi_bit_field.rb#L88-L92
6,862
spiegela/MultiBitField
lib/multi_bit_field.rb
MultiBitField.ClassMethods.increment_mask_for
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
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
[ "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" ]
Returns an "increment mask" for a list of fields +increment_mask_for :fields @example user.increment_mask_for :field @param [ Symbol ] column name of the column these fields are in @param [ Symbol ] field(s) name of the field(s) for the mask
[ "Returns", "an", "increment", "mask", "for", "a", "list", "of", "fields" ]
53674ba73caea8d871510d02271b71edaa1335f1
https://github.com/spiegela/MultiBitField/blob/53674ba73caea8d871510d02271b71edaa1335f1/lib/multi_bit_field.rb#L103-L111
6,863
spiegela/MultiBitField
lib/multi_bit_field.rb
MultiBitField.ClassMethods.only_mask_for
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
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
[ "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" ]
Returns an "only mask" for a list of fields +only_mask_for :fields @example user.only_mask_for :field @param [ Symbol ] column name of the column these fields are in @param [ Symbol ] field(s) name of the field(s) for the mask
[ "Returns", "an", "only", "mask", "for", "a", "list", "of", "fields" ]
53674ba73caea8d871510d02271b71edaa1335f1
https://github.com/spiegela/MultiBitField/blob/53674ba73caea8d871510d02271b71edaa1335f1/lib/multi_bit_field.rb#L122-L138
6,864
spiegela/MultiBitField
lib/multi_bit_field.rb
MultiBitField.ClassMethods.count_by
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
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
[ "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" ]
Counts resources grouped by a bitfield +count_by :column, :fields @example user.count_by :counter, :monthly @param [ Symbol ] column name of the column these fields are in @param [ Symbol ] field(s) name of the field(s) to reset
[ "Counts", "resources", "grouped", "by", "a", "bitfield" ]
53674ba73caea8d871510d02271b71edaa1335f1
https://github.com/spiegela/MultiBitField/blob/53674ba73caea8d871510d02271b71edaa1335f1/lib/multi_bit_field.rb#L179-L187
6,865
spiegela/MultiBitField
lib/multi_bit_field.rb
MultiBitField.InstanceMethods.reset_bitfields
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
def reset_bitfields column_name, *fields mask = self.class.reset_mask_for column_name, *fields self[column_name] = self[column_name] & mask save end
[ "def", "reset_bitfields", "column_name", ",", "*", "fields", "mask", "=", "self", ".", "class", ".", "reset_mask_for", "column_name", ",", "fields", "self", "[", "column_name", "]", "=", "self", "[", "column_name", "]", "&", "mask", "save", "end" ]
Sets one or more bitfields to 0 within a column +reset_bitfield :column, :fields @example user.reset_bitfield :column, :daily, :monthly @param [ Symbol ] column name of the column these fields are in @param [ Symbol ] field(s) name of the field(s) to reset
[ "Sets", "one", "or", "more", "bitfields", "to", "0", "within", "a", "column" ]
53674ba73caea8d871510d02271b71edaa1335f1
https://github.com/spiegela/MultiBitField/blob/53674ba73caea8d871510d02271b71edaa1335f1/lib/multi_bit_field.rb#L210-L214
6,866
spiegela/MultiBitField
lib/multi_bit_field.rb
MultiBitField.InstanceMethods.increment_bitfields
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
def increment_bitfields column_name, *fields mask = self.class.increment_mask_for column_name, *fields self[column_name] = self[column_name] += mask save end
[ "def", "increment_bitfields", "column_name", ",", "*", "fields", "mask", "=", "self", ".", "class", ".", "increment_mask_for", "column_name", ",", "fields", "self", "[", "column_name", "]", "=", "self", "[", "column_name", "]", "+=", "mask", "save", "end" ]
Increases one or more bitfields by 1 value +increment_bitfield :column, :fields @example user.increment_bitfield :column, :daily, :monthly @param [ Symbol ] column name of the column these fields are in @param [ Symbol ] field(s) name of the field(s) to reset
[ "Increases", "one", "or", "more", "bitfields", "by", "1", "value" ]
53674ba73caea8d871510d02271b71edaa1335f1
https://github.com/spiegela/MultiBitField/blob/53674ba73caea8d871510d02271b71edaa1335f1/lib/multi_bit_field.rb#L226-L230
6,867
openstax/connect-rails
lib/openstax/connect/current_user_manager.rb
OpenStax::Connect.CurrentUserManager.connect_current_user=
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
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
[ "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" ]
Sets the current connect user, updates the app user, and also updates the session and cookie state.
[ "Sets", "the", "current", "connect", "user", "updates", "the", "app", "user", "and", "also", "updates", "the", "session", "and", "cookie", "state", "." ]
4ac16cfa4316f9f0ba4df8b8d6dd960f90dbb962
https://github.com/openstax/connect-rails/blob/4ac16cfa4316f9f0ba4df8b8d6dd960f90dbb962/lib/openstax/connect/current_user_manager.rb#L80-L93
6,868
vidibus/vidibus-encoder
lib/vidibus/encoder.rb
Vidibus.Encoder.register_format
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
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
[ "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" ]
Register a new encoder format.
[ "Register", "a", "new", "encoder", "format", "." ]
71f682eeb28703b811fd7cd9f9b1b127a7c691c3
https://github.com/vidibus/vidibus-encoder/blob/71f682eeb28703b811fd7cd9f9b1b127a7c691c3/lib/vidibus/encoder.rb#L23-L29
6,869
cknadler/rcomp
lib/rcomp/conf.rb
RComp.Conf.read_conf_file
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
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
[ "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" ]
Read the config options from RComp's configuration file Returns a Hash of config options
[ "Read", "the", "config", "options", "from", "RComp", "s", "configuration", "file" ]
76fe71e1ef3b13923738ea6ab9cd502fe2f64f51
https://github.com/cknadler/rcomp/blob/76fe71e1ef3b13923738ea6ab9cd502fe2f64f51/lib/rcomp/conf.rb#L66-L79
6,870
plukevdh/monet
lib/monet/baseline_control.rb
Monet.BaselineControl.rebase
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
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
[ "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" ]
returns a new image for the moved image
[ "returns", "a", "new", "image", "for", "the", "moved", "image" ]
4e2a413e70371d0b3a6b05a2675c7b4a28e6c30b
https://github.com/plukevdh/monet/blob/4e2a413e70371d0b3a6b05a2675c7b4a28e6c30b/lib/monet/baseline_control.rb#L67-L74
6,871
phildionne/associates
lib/associates/persistence.rb
Associates.Persistence.save
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
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
[ "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" ]
Persists each associated model @return [Boolean] Wether or not all models are valid and persited
[ "Persists", "each", "associated", "model" ]
630edcc47340a73ad787feaf2cdf326b4487bb9f
https://github.com/phildionne/associates/blob/630edcc47340a73ad787feaf2cdf326b4487bb9f/lib/associates/persistence.rb#L16-L28
6,872
rlister/auger
lib/auger/project.rb
Auger.Project.connections
def connections(*roles) if roles.empty? @connections else @connections.select { |c| c.roles.empty? or !(c.roles & roles).empty? } end end
ruby
def connections(*roles) if roles.empty? @connections else @connections.select { |c| c.roles.empty? or !(c.roles & roles).empty? } end end
[ "def", "connections", "(", "*", "roles", ")", "if", "roles", ".", "empty?", "@connections", "else", "@connections", ".", "select", "{", "|", "c", "|", "c", ".", "roles", ".", "empty?", "or", "!", "(", "c", ".", "roles", "&", "roles", ")", ".", "empty?", "}", "end", "end" ]
return all connections, or those matching list of roles; connections with no roles match all, or find intersection with roles list
[ "return", "all", "connections", "or", "those", "matching", "list", "of", "roles", ";", "connections", "with", "no", "roles", "match", "all", "or", "find", "intersection", "with", "roles", "list" ]
45e220668251834cdf0cec78da5918aee6418d8e
https://github.com/rlister/auger/blob/45e220668251834cdf0cec78da5918aee6418d8e/lib/auger/project.rb#L54-L60
6,873
arvicco/poster
lib/poster/rss.rb
Poster.Rss.extract_data
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(/&lt;img.*?src="(.*?)\"/) img = desc.match(/&lt;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
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(/&lt;img.*?src="(.*?)\"/) img = desc.match(/&lt;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
[ "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", "=", "desc", ".", "match", "(", "/", "\\\"", "/", ")", "[", "1", "]", "text", "=", "desc", "terms", "=", "nil", "else", "img", ",", "terms", ",", "text", "=", "nil", ",", "nil", ",", "desc", "end", "# Extract categories", "categories", "=", "if", "terms", "terms", ".", "split", "(", "/", "\\n", "/", ")", ".", "select", "{", "|", "g", "|", "g", ".", "match", "/", "/", "}", ".", "map", "{", "|", "c", "|", "c", ".", "match", "(", "/", "\\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" ]
Extract news data from a feed item
[ "Extract", "news", "data", "from", "a", "feed", "item" ]
a5f22f7cb02116ab4dc5b7f2bdb672306b3dac63
https://github.com/arvicco/poster/blob/a5f22f7cb02116ab4dc5b7f2bdb672306b3dac63/lib/poster/rss.rb#L17-L57
6,874
rnhurt/google_anymote
lib/google_anymote/pair.rb
GoogleAnymote.Pair.start_pairing
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
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
[ "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" ]
Initializes the Pair class @param [Object] cert SSL certificate for this client @param [String] host hostname or IP address of the Google TV @param [String] client_name name of the client your connecting from @param [String] service_name name of the service (generally 'AnyMote') @return an instance of Pair Start the pairing process Once the TV recieves the pairing request it will display a 4 digit number. This number needs to be feed into the next step in the process, complete_pairing().
[ "Initializes", "the", "Pair", "class" ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/pair.rb#L36-L61
6,875
rnhurt/google_anymote
lib/google_anymote/pair.rb
GoogleAnymote.Pair.complete_pairing
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
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
[ "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" ]
Complete the pairing process @param [String] code The code displayed on the Google TV we are trying to pair with.
[ "Complete", "the", "pairing", "process" ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/pair.rb#L67-L77
6,876
rnhurt/google_anymote
lib/google_anymote/pair.rb
GoogleAnymote.Pair.send_message
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
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
[ "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" ]
Format and send the message to the GoogleTV @param [String] msg message to send @param [Object] type type of message to send @return [Object] the OuterMessage response from the TV
[ "Format", "and", "send", "the", "message", "to", "the", "GoogleTV" ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/pair.rb#L89-L105
6,877
rnhurt/google_anymote
lib/google_anymote/pair.rb
GoogleAnymote.Pair.wrap_message
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
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
[ "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" ]
Wrap the message in an OuterMessage @param [String] msg message to send @param [Object] type type of message to send @return [Object] a properly formatted OuterMessage
[ "Wrap", "the", "message", "in", "an", "OuterMessage" ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/pair.rb#L113-L122
6,878
rnhurt/google_anymote
lib/google_anymote/pair.rb
GoogleAnymote.Pair.encode_hex_secret
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
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
[ "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" ]
Encode the secret from the TV into an OpenSSL Digest @param [String] secret pairing code from the TV's screen @return [Digest] OpenSSL Digest containing the encoded secret
[ "Encode", "the", "secret", "from", "the", "TV", "into", "an", "OpenSSL", "Digest" ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/pair.rb#L129-L148
6,879
robfors/ruby-sumac
lib/sumac/id_allocator.rb
Sumac.IDAllocator.free
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
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
[ "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" ]
Return +id+ back to the allocator so it can be allocated again in the future. @note trying to free an unallocated id will cause undefined behavior @return [void]
[ "Return", "+", "id", "+", "back", "to", "the", "allocator", "so", "it", "can", "be", "allocated", "again", "in", "the", "future", "." ]
524fa68b7d1bb10a74baa69cd594ab2b8cae20a3
https://github.com/robfors/ruby-sumac/blob/524fa68b7d1bb10a74baa69cd594ab2b8cae20a3/lib/sumac/id_allocator.rb#L30-L43
6,880
barkerest/incline
lib/incline/extensions/action_view_base.rb
Incline::Extensions.ActionViewBase.full_title
def full_title(page_title = '') aname = Rails.application.app_name.strip return aname if page_title.blank? "#{page_title.strip} | #{aname}" end
ruby
def full_title(page_title = '') aname = Rails.application.app_name.strip return aname if page_title.blank? "#{page_title.strip} | #{aname}" end
[ "def", "full_title", "(", "page_title", "=", "''", ")", "aname", "=", "Rails", ".", "application", ".", "app_name", ".", "strip", "return", "aname", "if", "page_title", ".", "blank?", "\"#{page_title.strip} | #{aname}\"", "end" ]
Gets the full title of the page. If +page_title+ is left blank, then the +app_name+ attribute of your application is returned. Otherwise the +app_name+ attribute is appended to the +page_title+ after a pipe symbol. # app_name = 'My App' full_title # 'My App' full_title 'Welcome' # 'Welcome | My App'
[ "Gets", "the", "full", "title", "of", "the", "page", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/action_view_base.rb#L24-L28
6,881
barkerest/incline
lib/incline/extensions/action_view_base.rb
Incline::Extensions.ActionViewBase.glyph
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
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
[ "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" ]
Shows a glyph with an optional size. The glyph +name+ should be a valid {bootstrap glyph}[http://getbootstrap.com/components/#glyphicons] name. Strip the prefixed 'glyphicon-' from the name. The size can be left blank, or set to 'small' or 'large'. glyph('cloud') # '<i class="glyphicon glyphicon-cloud"></i>'
[ "Shows", "a", "glyph", "with", "an", "optional", "size", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/action_view_base.rb#L53-L71
6,882
barkerest/incline
lib/incline/extensions/action_view_base.rb
Incline::Extensions.ActionViewBase.fmt_num
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
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
[ "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" ]
Formats a number with the specified number of decimal places. The +value+ can be any valid numeric expression that can be converted into a float.
[ "Formats", "a", "number", "with", "the", "specified", "number", "of", "decimal", "places", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/action_view_base.rb#L299-L312
6,883
barkerest/incline
lib/incline/extensions/action_view_base.rb
Incline::Extensions.ActionViewBase.panel
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
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
[ "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" ]
Creates a panel with the specified title. Valid options: type:: Type can be :primary, :success, :info, :warning, or :danger. Default value is :primary. size:: Size can be any value from 1 through 12. Default value is 6. offset:: Offset can be any value from 1 through 12. Default value is 3. Common sense is required, for instance you would likely never use an offset of 12, but it is available. Likewise an offset of 8 with a size of 8 would usually have the same effect as an offset of 12 because there are only 12 columns to fit your 8 column wide panel in. open_body:: This can be true or false. Default value is true. If true, the body division is opened (and closed) by this helper. If false, then the panel is opened and closed, but the body division is not created. This allows you to add tables and divisions as you see fit. Provide a block to render content within the panel.
[ "Creates", "a", "panel", "with", "the", "specified", "title", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/action_view_base.rb#L360-L386
6,884
Pistos/m4dbi
lib/m4dbi/model.rb
M4DBI.Model.delete
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
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
[ "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" ]
Returns true iff the record and only the record was successfully deleted.
[ "Returns", "true", "iff", "the", "record", "and", "only", "the", "record", "was", "successfully", "deleted", "." ]
603d7fefb621fe34a940fa8e8b798ee581823cb3
https://github.com/Pistos/m4dbi/blob/603d7fefb621fe34a940fa8e8b798ee581823cb3/lib/m4dbi/model.rb#L456-L480
6,885
HParker/sock-drawer
lib/sock/server.rb
Sock.Server.subscribe
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
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
[ "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" ]
subscribe fires a event on a EM channel whenever a message is fired on a pattern matching `name`. @name (default: "sock-hook/") + '*'
[ "subscribe", "fires", "a", "event", "on", "a", "EM", "channel", "whenever", "a", "message", "is", "fired", "on", "a", "pattern", "matching", "name", "." ]
87fffa745cedc3adbeec41a3afdd19a3fae92ab2
https://github.com/HParker/sock-drawer/blob/87fffa745cedc3adbeec41a3afdd19a3fae92ab2/lib/sock/server.rb#L31-L37
6,886
LiveTyping/live-front-rails
lib/live-front/tab_helper.rb
LiveFront.TabHelper.nav_link
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
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
[ "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" ]
Navigation link helper Returns an `li` element with an 'active' class if the supplied controller(s) and/or action(s) are currently active. The content of the element is the value passed to the block. options - The options hash used to determine if the element is "active" (default: {}) :controller - One or more controller names to check (optional). :action - One or more action names to check (optional). :path - A shorthand path, such as 'dashboard#index', to check (optional). :html_options - Extra options to be passed to the list element (optional). block - An optional block that will become the contents of the returned `li` element. When both :controller and :action are specified, BOTH must match in order to be marked as active. When only one is given, either can match. Examples # Assuming we're on TreeController#show # Controller matches, but action doesn't nav_link(controller: [:tree, :refs], action: :edit) { "Hello" } # => '<li>Hello</li>' # Controller matches nav_link(controller: [:tree, :refs]) { "Hello" } # => '<li class="active">Hello</li>' # Shorthand path nav_link(path: 'tree#show') { "Hello" } # => '<li class="active">Hello</li>' # Supplying custom options for the list element nav_link(controller: :tree, html_options: {class: 'home'}) { "Hello" } # => '<li class="home active">Hello</li>' Returns a list item element String
[ "Navigation", "link", "helper" ]
605946ec748bab2a2a751fd7eebcbf9a0e99832c
https://github.com/LiveTyping/live-front-rails/blob/605946ec748bab2a2a751fd7eebcbf9a0e99832c/lib/live-front/tab_helper.rb#L43-L60
6,887
JoshMcKin/hot_tub
lib/hot_tub/sessions.rb
HotTub.Sessions.get_or_set
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
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
[ "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" ]
Adds session unless it already exists and returns the session
[ "Adds", "session", "unless", "it", "already", "exists", "and", "returns", "the", "session" ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/sessions.rb#L133-L140
6,888
JoshMcKin/hot_tub
lib/hot_tub/sessions.rb
HotTub.Sessions.delete
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
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
[ "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" ]
Deletes and shutdowns the pool if its found.
[ "Deletes", "and", "shutdowns", "the", "pool", "if", "its", "found", "." ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/sessions.rb#L144-L156
6,889
JoshMcKin/hot_tub
lib/hot_tub/sessions.rb
HotTub.Sessions.reap!
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
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
[ "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" ]
Remove and close extra clients
[ "Remove", "and", "close", "extra", "clients" ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/sessions.rb#L221-L230
6,890
anga/BetterRailsDebugger
lib/better_rails_debugger/parser/ruby/processor.rb
BetterRailsDebugger::Parser::Ruby.Processor.emit_signal
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
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
[ "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" ]
Call all subscriptions for the given signal @param signal_name Symbol @param args Hash
[ "Call", "all", "subscriptions", "for", "the", "given", "signal" ]
2ac7af13b8ee12483bd9a92680d8f43042f1f1d5
https://github.com/anga/BetterRailsDebugger/blob/2ac7af13b8ee12483bd9a92680d8f43042f1f1d5/lib/better_rails_debugger/parser/ruby/processor.rb#L10-L18
6,891
anga/BetterRailsDebugger
lib/better_rails_debugger/parser/ruby/processor.rb
BetterRailsDebugger::Parser::Ruby.Processor.subscribe_signal
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
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
[ "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" ]
Subscribe to a particular signal @param signal_name Symbol @param step Symbol May be :first_pass or :second_pass @param block Proc
[ "Subscribe", "to", "a", "particular", "signal" ]
2ac7af13b8ee12483bd9a92680d8f43042f1f1d5
https://github.com/anga/BetterRailsDebugger/blob/2ac7af13b8ee12483bd9a92680d8f43042f1f1d5/lib/better_rails_debugger/parser/ruby/processor.rb#L24-L30
6,892
tbpgr/sublime_sunippetter
lib/sublime_sunippetter_dsl.rb
SublimeSunippetter.Dsl.add
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
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
[ "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" ]
init default values add sunippet information
[ "init", "default", "values", "add", "sunippet", "information" ]
a731a8a52fe457d742e78f50a4009b5b01f0640d
https://github.com/tbpgr/sublime_sunippetter/blob/a731a8a52fe457d742e78f50a4009b5b01f0640d/lib/sublime_sunippetter_dsl.rb#L18-L29
6,893
flyingmachine/whoops_logger
lib/whoops_logger/sender.rb
WhoopsLogger.Sender.send_message
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
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
[ "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", "[", "1", "]", "if", "error_id", "end", "end" ]
Sends the notice data off to Whoops for processing. @param [Hash] data The notice to be sent off
[ "Sends", "the", "notice", "data", "off", "to", "Whoops", "for", "processing", "." ]
e1db5362b67c58f60018c9e0d653094fbe286014
https://github.com/flyingmachine/whoops_logger/blob/e1db5362b67c58f60018c9e0d653094fbe286014/lib/whoops_logger/sender.rb#L28-L60
6,894
ffmike/shoehorn
lib/shoehorn/documents_base.rb
Shoehorn.DocumentsBase.status
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
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
[ "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" ]
Requires an inserter id from an upload call
[ "Requires", "an", "inserter", "id", "from", "an", "upload", "call" ]
b3da6d2bc4bd49652ac76197d01077b14bafb70a
https://github.com/ffmike/shoehorn/blob/b3da6d2bc4bd49652ac76197d01077b14bafb70a/lib/shoehorn/documents_base.rb#L68-L84
6,895
DigitPaint/html_mockup
lib/html_mockup/release/processors/requirejs.rb
HtmlMockup::Release::Processors.Requirejs.rjs_check
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
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
[ "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" ]
Incase both a file and bin version are availble file version is taken @return rjs_command to invoke r.js optimizer with
[ "Incase", "both", "a", "file", "and", "bin", "version", "are", "availble", "file", "version", "is", "taken" ]
976edadc01216b82a8cea177f53fb32559eaf41e
https://github.com/DigitPaint/html_mockup/blob/976edadc01216b82a8cea177f53fb32559eaf41e/lib/html_mockup/release/processors/requirejs.rb#L88-L94
6,896
martinpoljak/types
lib/types.rb
Types.Type.match_type?
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
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
[ "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" ]
Matches object is of this type. @param [Object] object object for type matching @return [Boolean] +true+ if match, +false+ in otherwise
[ "Matches", "object", "is", "of", "this", "type", "." ]
7742b90580a375de71b25344369bb76283962798
https://github.com/martinpoljak/types/blob/7742b90580a375de71b25344369bb76283962798/lib/types.rb#L47-L54
6,897
doubleleft/hook-ruby
lib/hook-client/collection.rb
Hook.Collection.create
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
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
[ "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" ]
Create an item into the collection @param data [Hash, Array] item or array of items @return [Hash, Array]
[ "Create", "an", "item", "into", "the", "collection" ]
f6acdd89dfe6ed9161380300c2dff2f19f0f744a
https://github.com/doubleleft/hook-ruby/blob/f6acdd89dfe6ed9161380300c2dff2f19f0f744a/lib/hook-client/collection.rb#L35-L43
6,898
doubleleft/hook-ruby
lib/hook-client/collection.rb
Hook.Collection.where
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
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
[ "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" ]
Add where clause to the current query. Supported modifiers on fields: .gt, .gte, .lt, .lte, .ne, .in, .not_in, .nin, .like, .between, .not_between @param fields [Hash] fields and values to filter @param [String] operation (and, or) @example hook.collection(:movies).where({ :name => "Hook", :year.gt => 1990 }) @example Using Range hook.collection(:movies).where({ :name.like => "%panic%", :year.between => 1990..2014 }) @return [Collection] self
[ "Add", "where", "clause", "to", "the", "current", "query", "." ]
f6acdd89dfe6ed9161380300c2dff2f19f0f744a
https://github.com/doubleleft/hook-ruby/blob/f6acdd89dfe6ed9161380300c2dff2f19f0f744a/lib/hook-client/collection.rb#L92-L103
6,899
doubleleft/hook-ruby
lib/hook-client/collection.rb
Hook.Collection.order
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
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
[ "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" ]
Add order clause to the query. @param fields [String] ... @return [Collection] self
[ "Add", "order", "clause", "to", "the", "query", "." ]
f6acdd89dfe6ed9161380300c2dff2f19f0f744a
https://github.com/doubleleft/hook-ruby/blob/f6acdd89dfe6ed9161380300c2dff2f19f0f744a/lib/hook-client/collection.rb#L116-L124