repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
leesharma/rescuetime
lib/rescuetime/collection.rb
Rescuetime.Collection.parse_response
def parse_response(body) report = CSV.new(body, headers: true, header_converters: :symbol, converters: :all) format = @format.to_s.downcase report_formatter = formatters.find(format) report_formatter.format report end
ruby
def parse_response(body) report = CSV.new(body, headers: true, header_converters: :symbol, converters: :all) format = @format.to_s.downcase report_formatter = formatters.find(format) report_formatter.format report end
[ "def", "parse_response", "(", "body", ")", "report", "=", "CSV", ".", "new", "(", "body", ",", "headers", ":", "true", ",", "header_converters", ":", ":symbol", ",", "converters", ":", ":all", ")", "format", "=", "@format", ".", "to_s", ".", "downcase", ...
Parses a response from the string response body to the desired format. @param [String] body response body @return [Array, CSV]
[ "Parses", "a", "response", "from", "the", "string", "response", "body", "to", "the", "desired", "format", "." ]
c69e6d41f31dbaf5053be51a1e45293605612f1e
https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/collection.rb#L93-L103
valid
leesharma/rescuetime
lib/rescuetime/report_formatters.rb
Rescuetime.ReportFormatters.find
def find(name) formatter = formatters.find do |f| standardize(f.name) == standardize(name) end formatter || raise(Rescuetime::Errors::InvalidFormatError) end
ruby
def find(name) formatter = formatters.find do |f| standardize(f.name) == standardize(name) end formatter || raise(Rescuetime::Errors::InvalidFormatError) end
[ "def", "find", "(", "name", ")", "formatter", "=", "formatters", ".", "find", "do", "|", "f", "|", "standardize", "(", "f", ".", "name", ")", "==", "standardize", "(", "name", ")", "end", "formatter", "||", "raise", "(", "Rescuetime", "::", "Errors", ...
Returns the formatter with the specified name or, if not found, raises an exception @param [String] name the name of the desired formatter @return [Class] the specified formatter @raise [Rescuetime::Errors::InvalidFormatError]
[ "Returns", "the", "formatter", "with", "the", "specified", "name", "or", "if", "not", "found", "raises", "an", "exception" ]
c69e6d41f31dbaf5053be51a1e45293605612f1e
https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/report_formatters.rb#L70-L75
valid
leesharma/rescuetime
lib/rescuetime/query_buildable.rb
Rescuetime.QueryBuildable.order_by
def order_by(order, interval: nil) # set order and intervals as symbols order = order.to_s interval = interval ? interval.to_s : nil # guards against invalid order or interval unless valid_order? order raise Errors::InvalidQueryError, "#{order} is not a valid order" end unless valid_interval? interval raise Errors::InvalidQueryError, "#{interval} is not a valid interval" end add_to_query perspective: (order == 'time' ? 'interval' : order), resolution_time: interval end
ruby
def order_by(order, interval: nil) # set order and intervals as symbols order = order.to_s interval = interval ? interval.to_s : nil # guards against invalid order or interval unless valid_order? order raise Errors::InvalidQueryError, "#{order} is not a valid order" end unless valid_interval? interval raise Errors::InvalidQueryError, "#{interval} is not a valid interval" end add_to_query perspective: (order == 'time' ? 'interval' : order), resolution_time: interval end
[ "def", "order_by", "(", "order", ",", "interval", ":", "nil", ")", "order", "=", "order", ".", "to_s", "interval", "=", "interval", "?", "interval", ".", "to_s", ":", "nil", "unless", "valid_order?", "order", "raise", "Errors", "::", "InvalidQueryError", "...
Specifies the ordering and the interval of the returned Rescuetime report. For example, the results can be ordered by time, activity rank, or member; The results can be returned in intervals spanning a month, a week, a day, an hour, or 5-minutes. Efficiency reports default to :time order; everything else defaults to :rank order. @example Basic Use client = Rescuetime::Client.new client.order_by 'time' # interval is not required #=> #<Rescuetime::Collection:0x007f93841681a8> client.order_by 'rank', interval: 'hour' #=> #<Rescuetime::Collection:0x007f93841681a8> client.order_by :rank, interval: :hour # Symbols are also valid #=> #<Rescuetime::Collection:0x007f93841681a8> @example Invalid Values Raise Errors client = Rescuetime::Client.new client.order_by 'invalid' # => Rescuetime::Errors::InvalidQueryError: invalid is not a valid order client.order_by 'time', interval: 'invalid' # => Rescuetime::Errors::InvalidQueryError: invalid is not a valid interval @param [#to_s] order an order for the results (ex. 'time') @param [#intern, nil] interval a chunking interval for results (ex. 'month'). defaults to nil @return [Rescuetime::Collection] a Rescuetime Collection specifying order and interval (if set) @raise [Rescuetime::Errors::InvalidQueryError] if either order or interval are invalid @see https://www.rescuetime.com/apidoc#paramlist Rescuetime API docs (see: perspective, resolution_time) @see Rescuetime::QueryBuildable::VALID List of valid values
[ "Specifies", "the", "ordering", "and", "the", "interval", "of", "the", "returned", "Rescuetime", "report", ".", "For", "example", "the", "results", "can", "be", "ordered", "by", "time", "activity", "rank", "or", "member", ";", "The", "results", "can", "be", ...
c69e6d41f31dbaf5053be51a1e45293605612f1e
https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/query_buildable.rb#L191-L207
valid
leesharma/rescuetime
lib/rescuetime/query_buildable.rb
Rescuetime.QueryBuildable.where
def where(name: nil, document: nil) # Stand-in for required keyword arguments name || raise(ArgumentError, 'missing keyword: name') add_to_query restrict_thing: name, restrict_thingy: document end
ruby
def where(name: nil, document: nil) # Stand-in for required keyword arguments name || raise(ArgumentError, 'missing keyword: name') add_to_query restrict_thing: name, restrict_thingy: document end
[ "def", "where", "(", "name", ":", "nil", ",", "document", ":", "nil", ")", "name", "||", "raise", "(", "ArgumentError", ",", "'missing keyword: name'", ")", "add_to_query", "restrict_thing", ":", "name", ",", "restrict_thingy", ":", "document", "end" ]
Limits the Rescuetime report to specific activities and documents. The name option limits the results to those where name is an exact match; this can be used on the overview, activity, and category report. The document option limits the specific document title; this is only available on the activity report. If a value is passed for an unsupported report, it will be ignored. To see the category and document names for your account, please look at your rescuetime dashboard or generated rescuetime report. :name can be used on: - Overview report - Category report - Activity report :document can be used on: - Activity report when :name is set @example Basic Use client = Rescuetime::Client.new client.activities.where name: 'github.com', document: 'leesharma/rescuetime' #=> #<Rescuetime::Collection:0x007f93841681a8> @example Valid reports client.overview.where name: 'Utilities' client.categories.where name: 'Intelligence' client.activities.where name: 'github.com' client.activities.where name: 'github.com', document: 'rails/rails' @example Invalid reports client.productivity.where name: 'Intelligence' # Invalid! client.efficiency.where name: 'Intelligence' # Invalid! client.activities.where document: 'rails/rails' # Invalid! @param [String] name Rescuetime category name, valid on overview, category, and activity reports @param [String] document Specific document name, valid on activity reports when :name is set @return [Rescuetime::Collection] a Rescuetime Collection specifying category name and (optionally) document @raise [ArgumentError] if name is not set @see #overview @see #activities @see #categories @see https://www.rescuetime.com/apidoc#paramlist Rescuetime API docs (see: restrict_thing, restrict_thingy) @since v0.3.0
[ "Limits", "the", "Rescuetime", "report", "to", "specific", "activities", "and", "documents", ".", "The", "name", "option", "limits", "the", "results", "to", "those", "where", "name", "is", "an", "exact", "match", ";", "this", "can", "be", "used", "on", "th...
c69e6d41f31dbaf5053be51a1e45293605612f1e
https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/query_buildable.rb#L362-L368
valid
leesharma/rescuetime
lib/rescuetime/query_buildable.rb
Rescuetime.QueryBuildable.add_to_query
def add_to_query(**terms) if is_a? Rescuetime::Collection self << terms self else Rescuetime::Collection.new(BASE_PARAMS, state, terms) end end
ruby
def add_to_query(**terms) if is_a? Rescuetime::Collection self << terms self else Rescuetime::Collection.new(BASE_PARAMS, state, terms) end end
[ "def", "add_to_query", "(", "**", "terms", ")", "if", "is_a?", "Rescuetime", "::", "Collection", "self", "<<", "terms", "self", "else", "Rescuetime", "::", "Collection", ".", "new", "(", "BASE_PARAMS", ",", "state", ",", "terms", ")", "end", "end" ]
Adds terms to the Rescuetime collection query @param [Hash] terms a set of terms to add to the query @return [Rescuetime::Collection]
[ "Adds", "terms", "to", "the", "Rescuetime", "collection", "query" ]
c69e6d41f31dbaf5053be51a1e45293605612f1e
https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/query_buildable.rb#L376-L383
valid
leesharma/rescuetime
lib/rescuetime/client.rb
Rescuetime.Client.valid_credentials?
def valid_credentials? return false unless api_key? !activities.all.nil? rescue Rescuetime::Errors::InvalidCredentialsError false end
ruby
def valid_credentials? return false unless api_key? !activities.all.nil? rescue Rescuetime::Errors::InvalidCredentialsError false end
[ "def", "valid_credentials?", "return", "false", "unless", "api_key?", "!", "activities", ".", "all", ".", "nil?", "rescue", "Rescuetime", "::", "Errors", "::", "InvalidCredentialsError", "false", "end" ]
Returns true if the provided api key is valid. Performs a request to the Rescuetime API. @example Basic Use # Assuming that INVALID_KEY is an invalid Rescuetime API key # and VALID_KEY is a valid one client = Rescuetime::Client client.valid_credentials? # => false client.api_key = INVALID_KEY client.valid_credentials? # Performs a request to the Rescuetime API # => false client.api_key = VALID_KEY client.valid_credentials? # Performs a request to the Rescuetime API # => true @return [Boolean]
[ "Returns", "true", "if", "the", "provided", "api", "key", "is", "valid", ".", "Performs", "a", "request", "to", "the", "Rescuetime", "API", "." ]
c69e6d41f31dbaf5053be51a1e45293605612f1e
https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/client.rb#L91-L96
valid
leesharma/rescuetime
lib/rescuetime/formatters.rb
Rescuetime.Formatters.load_formatter_files
def load_formatter_files(local_path: LOCAL_FORMATTER_PATH) # require all formatters, local and configured paths = Rescuetime.configuration.formatter_paths << local_path paths.each do |path| Dir[File.expand_path(path, __FILE__)].each { |file| require file } end end
ruby
def load_formatter_files(local_path: LOCAL_FORMATTER_PATH) # require all formatters, local and configured paths = Rescuetime.configuration.formatter_paths << local_path paths.each do |path| Dir[File.expand_path(path, __FILE__)].each { |file| require file } end end
[ "def", "load_formatter_files", "(", "local_path", ":", "LOCAL_FORMATTER_PATH", ")", "paths", "=", "Rescuetime", ".", "configuration", ".", "formatter_paths", "<<", "local_path", "paths", ".", "each", "do", "|", "path", "|", "Dir", "[", "File", ".", "expand_path"...
Requires all formatter files, determined by the local path for formatters plus any additional paths set in the Rescuetime configuration. @param [String] local_path the location of the local in-gem formatters @see Rescuetime::Configuration.formatter_paths
[ "Requires", "all", "formatter", "files", "determined", "by", "the", "local", "path", "for", "formatters", "plus", "any", "additional", "paths", "set", "in", "the", "Rescuetime", "configuration", "." ]
c69e6d41f31dbaf5053be51a1e45293605612f1e
https://github.com/leesharma/rescuetime/blob/c69e6d41f31dbaf5053be51a1e45293605612f1e/lib/rescuetime/formatters.rb#L40-L46
valid
mislav/nibbler
lib/nibbler.rb
NibblerMethods.InstanceMethods.parse
def parse self.class.rules.each do |target, (selector, delegate, plural)| if plural send(target).concat @doc.search(selector).map { |i| parse_result(i, delegate) } else send("#{target}=", parse_result(@doc.at(selector), delegate)) end end self end
ruby
def parse self.class.rules.each do |target, (selector, delegate, plural)| if plural send(target).concat @doc.search(selector).map { |i| parse_result(i, delegate) } else send("#{target}=", parse_result(@doc.at(selector), delegate)) end end self end
[ "def", "parse", "self", ".", "class", ".", "rules", ".", "each", "do", "|", "target", ",", "(", "selector", ",", "delegate", ",", "plural", ")", "|", "if", "plural", "send", "(", "target", ")", ".", "concat", "@doc", ".", "search", "(", "selector", ...
Initialize the parser with a document Parse the document and save values returned by selectors
[ "Initialize", "the", "parser", "with", "a", "document", "Parse", "the", "document", "and", "save", "values", "returned", "by", "selectors" ]
32ae685077fdf11731ab26bc7ff3e44026cf380e
https://github.com/mislav/nibbler/blob/32ae685077fdf11731ab26bc7ff3e44026cf380e/lib/nibbler.rb#L71-L80
valid
mislav/nibbler
lib/nibbler.rb
NibblerMethods.InstanceMethods.to_hash
def to_hash converter = lambda { |obj| obj.respond_to?(:to_hash) ? obj.to_hash : obj } self.class.rules.keys.inject({}) do |hash, name| value = send(name) hash[name.to_sym] = Array === value ? value.map(&converter) : converter[value] hash end end
ruby
def to_hash converter = lambda { |obj| obj.respond_to?(:to_hash) ? obj.to_hash : obj } self.class.rules.keys.inject({}) do |hash, name| value = send(name) hash[name.to_sym] = Array === value ? value.map(&converter) : converter[value] hash end end
[ "def", "to_hash", "converter", "=", "lambda", "{", "|", "obj", "|", "obj", ".", "respond_to?", "(", ":to_hash", ")", "?", "obj", ".", "to_hash", ":", "obj", "}", "self", ".", "class", ".", "rules", ".", "keys", ".", "inject", "(", "{", "}", ")", ...
Dump the extracted data into a hash with symbolized keys
[ "Dump", "the", "extracted", "data", "into", "a", "hash", "with", "symbolized", "keys" ]
32ae685077fdf11731ab26bc7ff3e44026cf380e
https://github.com/mislav/nibbler/blob/32ae685077fdf11731ab26bc7ff3e44026cf380e/lib/nibbler.rb#L83-L90
valid
mislav/nibbler
lib/nibbler.rb
NibblerMethods.InstanceMethods.parse_result
def parse_result(node, delegate) if delegate method = delegate.is_a?(Proc) ? delegate : delegate.method(delegate.respond_to?(:call) ? :call : :parse) method.arity == 1 ? method[node] : method[node, self] else node end unless node.nil? end
ruby
def parse_result(node, delegate) if delegate method = delegate.is_a?(Proc) ? delegate : delegate.method(delegate.respond_to?(:call) ? :call : :parse) method.arity == 1 ? method[node] : method[node, self] else node end unless node.nil? end
[ "def", "parse_result", "(", "node", ",", "delegate", ")", "if", "delegate", "method", "=", "delegate", ".", "is_a?", "(", "Proc", ")", "?", "delegate", ":", "delegate", ".", "method", "(", "delegate", ".", "respond_to?", "(", ":call", ")", "?", ":call", ...
`delegate` is optional, but should respond to `call` or `parse`
[ "delegate", "is", "optional", "but", "should", "respond", "to", "call", "or", "parse" ]
32ae685077fdf11731ab26bc7ff3e44026cf380e
https://github.com/mislav/nibbler/blob/32ae685077fdf11731ab26bc7ff3e44026cf380e/lib/nibbler.rb#L95-L102
valid
mislav/nibbler
examples/tweetburner.rb
Tweetburner.Scraper.get_document
def get_document(url) URI === url ? Nokogiri::HTML::Document.parse(open(url), url.to_s, 'UTF-8') : url rescue OpenURI::HTTPError $stderr.puts "ERROR opening #{url}" Nokogiri('') end
ruby
def get_document(url) URI === url ? Nokogiri::HTML::Document.parse(open(url), url.to_s, 'UTF-8') : url rescue OpenURI::HTTPError $stderr.puts "ERROR opening #{url}" Nokogiri('') end
[ "def", "get_document", "(", "url", ")", "URI", "===", "url", "?", "Nokogiri", "::", "HTML", "::", "Document", ".", "parse", "(", "open", "(", "url", ")", ",", "url", ".", "to_s", ",", "'UTF-8'", ")", ":", "url", "rescue", "OpenURI", "::", "HTTPError"...
open web pages with UTF-8 encoding
[ "open", "web", "pages", "with", "UTF", "-", "8", "encoding" ]
32ae685077fdf11731ab26bc7ff3e44026cf380e
https://github.com/mislav/nibbler/blob/32ae685077fdf11731ab26bc7ff3e44026cf380e/examples/tweetburner.rb#L27-L32
valid
monde/mms2r
lib/mms2r/media.rb
MMS2R.MMS2R::Media.subject
def subject unless @subject subject = mail.subject.strip rescue "" ignores = config['ignore']['text/plain'] if ignores && ignores.detect{|s| s == subject} @subject = "" else @subject = transform_text('text/plain', subject).last end end @subject end
ruby
def subject unless @subject subject = mail.subject.strip rescue "" ignores = config['ignore']['text/plain'] if ignores && ignores.detect{|s| s == subject} @subject = "" else @subject = transform_text('text/plain', subject).last end end @subject end
[ "def", "subject", "unless", "@subject", "subject", "=", "mail", ".", "subject", ".", "strip", "rescue", "\"\"", "ignores", "=", "config", "[", "'ignore'", "]", "[", "'text/plain'", "]", "if", "ignores", "&&", "ignores", ".", "detect", "{", "|", "s", "|",...
Return the Subject for this message, returns "" for default carrier subject such as 'Multimedia message' for ATT&T carrier.
[ "Return", "the", "Subject", "for", "this", "message", "returns", "for", "default", "carrier", "subject", "such", "as", "Multimedia", "message", "for", "ATT&T", "carrier", "." ]
4b4419580a1eccb55cc1862795d926852d4554bd
https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L246-L259
valid
monde/mms2r
lib/mms2r/media.rb
MMS2R.MMS2R::Media.ignore_media?
def ignore_media?(type, part) ignores = config['ignore'][type] || [] ignore = ignores.detect{ |test| filename?(part) == test} ignore ||= ignores.detect{ |test| filename?(part) =~ test if test.is_a?(Regexp) } ignore ||= ignores.detect{ |test| part.body.decoded.strip =~ test if test.is_a?(Regexp) } ignore ||= (part.body.decoded.strip.size == 0 ? true : nil) ignore.nil? ? false : true end
ruby
def ignore_media?(type, part) ignores = config['ignore'][type] || [] ignore = ignores.detect{ |test| filename?(part) == test} ignore ||= ignores.detect{ |test| filename?(part) =~ test if test.is_a?(Regexp) } ignore ||= ignores.detect{ |test| part.body.decoded.strip =~ test if test.is_a?(Regexp) } ignore ||= (part.body.decoded.strip.size == 0 ? true : nil) ignore.nil? ? false : true end
[ "def", "ignore_media?", "(", "type", ",", "part", ")", "ignores", "=", "config", "[", "'ignore'", "]", "[", "type", "]", "||", "[", "]", "ignore", "=", "ignores", ".", "detect", "{", "|", "test", "|", "filename?", "(", "part", ")", "==", "test", "}...
Helper for process template method to determine if media contained in a part should be ignored. Producers should override this method to return true for media such as images that are advertising, carrier logos, etc. See the ignore section in the discussion of the built-in configuration.
[ "Helper", "for", "process", "template", "method", "to", "determine", "if", "media", "contained", "in", "a", "part", "should", "be", "ignored", ".", "Producers", "should", "override", "this", "method", "to", "return", "true", "for", "media", "such", "as", "im...
4b4419580a1eccb55cc1862795d926852d4554bd
https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L380-L387
valid
monde/mms2r
lib/mms2r/media.rb
MMS2R.MMS2R::Media.process_media
def process_media(part) # Mail body auto-magically decodes quoted # printable for text/html type. file = temp_file(part) if part.part_type? =~ /^text\// || part.part_type? == 'application/smil' type, content = transform_text_part(part) else if part.part_type? == 'application/octet-stream' type = type_from_filename(filename?(part)) else type = part.part_type? end content = part.body.decoded end return type, nil if content.nil? || content.empty? log("#{self.class} writing file #{file}", :info) File.open(file, 'wb'){ |f| f.write(content) } return type, file end
ruby
def process_media(part) # Mail body auto-magically decodes quoted # printable for text/html type. file = temp_file(part) if part.part_type? =~ /^text\// || part.part_type? == 'application/smil' type, content = transform_text_part(part) else if part.part_type? == 'application/octet-stream' type = type_from_filename(filename?(part)) else type = part.part_type? end content = part.body.decoded end return type, nil if content.nil? || content.empty? log("#{self.class} writing file #{file}", :info) File.open(file, 'wb'){ |f| f.write(content) } return type, file end
[ "def", "process_media", "(", "part", ")", "file", "=", "temp_file", "(", "part", ")", "if", "part", ".", "part_type?", "=~", "/", "\\/", "/", "||", "part", ".", "part_type?", "==", "'application/smil'", "type", ",", "content", "=", "transform_text_part", "...
Helper for process template method to decode the part based on its type and write its content to a temporary file. Returns path to temporary file that holds the content. Parts with a main type of text will have their contents transformed with a call to transform_text Producers should only override this method if the parts of the MMS need special treatment besides what is expected for a normal mime part (like Sprint). Returns a tuple of content type, file path
[ "Helper", "for", "process", "template", "method", "to", "decode", "the", "part", "based", "on", "its", "type", "and", "write", "its", "content", "to", "a", "temporary", "file", ".", "Returns", "path", "to", "temporary", "file", "that", "holds", "the", "con...
4b4419580a1eccb55cc1862795d926852d4554bd
https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L401-L421
valid
monde/mms2r
lib/mms2r/media.rb
MMS2R.MMS2R::Media.process_part
def process_part(part) return if ignore_media?(part.part_type?, part) type, file = process_media(part) add_file(type, file) unless type.nil? || file.nil? end
ruby
def process_part(part) return if ignore_media?(part.part_type?, part) type, file = process_media(part) add_file(type, file) unless type.nil? || file.nil? end
[ "def", "process_part", "(", "part", ")", "return", "if", "ignore_media?", "(", "part", ".", "part_type?", ",", "part", ")", "type", ",", "file", "=", "process_media", "(", "part", ")", "add_file", "(", "type", ",", "file", ")", "unless", "type", ".", "...
Helper to decide if a part should be kept or ignored
[ "Helper", "to", "decide", "if", "a", "part", "should", "be", "kept", "or", "ignored" ]
4b4419580a1eccb55cc1862795d926852d4554bd
https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L426-L431
valid
monde/mms2r
lib/mms2r/media.rb
MMS2R.MMS2R::Media.transform_text
def transform_text(type, text) return type, text if !config['transform'] || !(transforms = config['transform'][type]) if RUBY_VERSION < "1.9" require 'iconv' ic = Iconv.new('UTF-8', 'ISO-8859-1') text = ic.iconv(text) text << ic.iconv(nil) ic.close end transforms.each do |transform| next unless transform.size == 2 p = transform.first r = transform.last text = text.gsub(p, r) rescue text end return type, text end
ruby
def transform_text(type, text) return type, text if !config['transform'] || !(transforms = config['transform'][type]) if RUBY_VERSION < "1.9" require 'iconv' ic = Iconv.new('UTF-8', 'ISO-8859-1') text = ic.iconv(text) text << ic.iconv(nil) ic.close end transforms.each do |transform| next unless transform.size == 2 p = transform.first r = transform.last text = text.gsub(p, r) rescue text end return type, text end
[ "def", "transform_text", "(", "type", ",", "text", ")", "return", "type", ",", "text", "if", "!", "config", "[", "'transform'", "]", "||", "!", "(", "transforms", "=", "config", "[", "'transform'", "]", "[", "type", "]", ")", "if", "RUBY_VERSION", "<",...
Helper for process_media template method to transform text. See the transform section in the discussion of the built-in configuration.
[ "Helper", "for", "process_media", "template", "method", "to", "transform", "text", ".", "See", "the", "transform", "section", "in", "the", "discussion", "of", "the", "built", "-", "in", "configuration", "." ]
4b4419580a1eccb55cc1862795d926852d4554bd
https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L447-L466
valid
monde/mms2r
lib/mms2r/media.rb
MMS2R.MMS2R::Media.transform_text_part
def transform_text_part(part) type = part.part_type? text = part.body.decoded.strip transform_text(type, text) end
ruby
def transform_text_part(part) type = part.part_type? text = part.body.decoded.strip transform_text(type, text) end
[ "def", "transform_text_part", "(", "part", ")", "type", "=", "part", ".", "part_type?", "text", "=", "part", ".", "body", ".", "decoded", ".", "strip", "transform_text", "(", "type", ",", "text", ")", "end" ]
Helper for process_media template method to transform text.
[ "Helper", "for", "process_media", "template", "method", "to", "transform", "text", "." ]
4b4419580a1eccb55cc1862795d926852d4554bd
https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L471-L475
valid
monde/mms2r
lib/mms2r/media.rb
MMS2R.MMS2R::Media.temp_file
def temp_file(part) file_name = filename?(part) File.expand_path(File.join(msg_tmp_dir(),File.basename(file_name))) end
ruby
def temp_file(part) file_name = filename?(part) File.expand_path(File.join(msg_tmp_dir(),File.basename(file_name))) end
[ "def", "temp_file", "(", "part", ")", "file_name", "=", "filename?", "(", "part", ")", "File", ".", "expand_path", "(", "File", ".", "join", "(", "msg_tmp_dir", "(", ")", ",", "File", ".", "basename", "(", "file_name", ")", ")", ")", "end" ]
Helper for process template method to name a temporary filepath based on information in the part. This version attempts to honor the name of the media as labeled in the part header and creates a unique temporary directory for writing the file so filename collision does not occur. Consumers of this method expect the directory structure to the file exists, if the method is overridden it is mandatory that this behavior is retained.
[ "Helper", "for", "process", "template", "method", "to", "name", "a", "temporary", "filepath", "based", "on", "information", "in", "the", "part", ".", "This", "version", "attempts", "to", "honor", "the", "name", "of", "the", "media", "as", "labeled", "in", ...
4b4419580a1eccb55cc1862795d926852d4554bd
https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L486-L489
valid
monde/mms2r
lib/mms2r/media.rb
MMS2R.MMS2R::Media.add_file
def add_file(type, file) media[type] = [] unless media[type] media[type] << file end
ruby
def add_file(type, file) media[type] = [] unless media[type] media[type] << file end
[ "def", "add_file", "(", "type", ",", "file", ")", "media", "[", "type", "]", "=", "[", "]", "unless", "media", "[", "type", "]", "media", "[", "type", "]", "<<", "file", "end" ]
Helper to add a file to the media hash.
[ "Helper", "to", "add", "a", "file", "to", "the", "media", "hash", "." ]
4b4419580a1eccb55cc1862795d926852d4554bd
https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L503-L506
valid
monde/mms2r
lib/mms2r/media.rb
MMS2R.MMS2R::Media.msg_tmp_dir
def msg_tmp_dir @dir_count += 1 dir = File.expand_path(File.join(@media_dir, "#{@dir_count}")) FileUtils.mkdir_p(dir) dir end
ruby
def msg_tmp_dir @dir_count += 1 dir = File.expand_path(File.join(@media_dir, "#{@dir_count}")) FileUtils.mkdir_p(dir) dir end
[ "def", "msg_tmp_dir", "@dir_count", "+=", "1", "dir", "=", "File", ".", "expand_path", "(", "File", ".", "join", "(", "@media_dir", ",", "\"#{@dir_count}\"", ")", ")", "FileUtils", ".", "mkdir_p", "(", "dir", ")", "dir", "end" ]
Helper to temp_file to create a unique temporary directory that is a child of tmp_dir This version is based on the message_id of the mail.
[ "Helper", "to", "temp_file", "to", "create", "a", "unique", "temporary", "directory", "that", "is", "a", "child", "of", "tmp_dir", "This", "version", "is", "based", "on", "the", "message_id", "of", "the", "mail", "." ]
4b4419580a1eccb55cc1862795d926852d4554bd
https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L512-L517
valid
monde/mms2r
lib/mms2r/media.rb
MMS2R.MMS2R::Media.filename?
def filename?(part) name = part.filename if (name.nil? || name.empty?) if part.content_id && (matched = /^<(.+)>$/.match(part.content_id)) name = matched[1] else name = "#{Time.now.to_f}.#{self.default_ext(part.part_type?)}" end end # FIXME FWIW, janky look for dot extension 1 to 4 chars long name = (name =~ /\..{1,4}$/ ? name : "#{name}.#{self.default_ext(part.part_type?)}").strip # handle excessively large filenames if name.size > 255 ext = File.extname(name) base = File.basename(name, ext) name = "#{base[0, 255 - ext.size]}#{ext}" end name end
ruby
def filename?(part) name = part.filename if (name.nil? || name.empty?) if part.content_id && (matched = /^<(.+)>$/.match(part.content_id)) name = matched[1] else name = "#{Time.now.to_f}.#{self.default_ext(part.part_type?)}" end end # FIXME FWIW, janky look for dot extension 1 to 4 chars long name = (name =~ /\..{1,4}$/ ? name : "#{name}.#{self.default_ext(part.part_type?)}").strip # handle excessively large filenames if name.size > 255 ext = File.extname(name) base = File.basename(name, ext) name = "#{base[0, 255 - ext.size]}#{ext}" end name end
[ "def", "filename?", "(", "part", ")", "name", "=", "part", ".", "filename", "if", "(", "name", ".", "nil?", "||", "name", ".", "empty?", ")", "if", "part", ".", "content_id", "&&", "(", "matched", "=", "/", "/", ".", "match", "(", "part", ".", "c...
returns a filename declared for a part, or a default if its not defined
[ "returns", "a", "filename", "declared", "for", "a", "part", "or", "a", "default", "if", "its", "not", "defined" ]
4b4419580a1eccb55cc1862795d926852d4554bd
https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L522-L542
valid
monde/mms2r
lib/mms2r/media.rb
MMS2R.MMS2R::Media.type_from_filename
def type_from_filename(filename) ext = filename.split('.').last ent = MMS2R::EXT.detect{|k,v| v == ext} ent.nil? ? nil : ent.first end
ruby
def type_from_filename(filename) ext = filename.split('.').last ent = MMS2R::EXT.detect{|k,v| v == ext} ent.nil? ? nil : ent.first end
[ "def", "type_from_filename", "(", "filename", ")", "ext", "=", "filename", ".", "split", "(", "'.'", ")", ".", "last", "ent", "=", "MMS2R", "::", "EXT", ".", "detect", "{", "|", "k", ",", "v", "|", "v", "==", "ext", "}", "ent", ".", "nil?", "?", ...
guess content type from filename
[ "guess", "content", "type", "from", "filename" ]
4b4419580a1eccb55cc1862795d926852d4554bd
https://github.com/monde/mms2r/blob/4b4419580a1eccb55cc1862795d926852d4554bd/lib/mms2r/media.rb#L779-L783
valid
pierrickrouxel/activerecord-jdbcas400-adapter
lib/arjdbc/as400/adapter.rb
ArJdbc.AS400.prefetch_primary_key?
def prefetch_primary_key?(table_name = nil) return true if table_name.nil? table_name = table_name.to_s primary_keys(table_name.to_s).size == 0 end
ruby
def prefetch_primary_key?(table_name = nil) return true if table_name.nil? table_name = table_name.to_s primary_keys(table_name.to_s).size == 0 end
[ "def", "prefetch_primary_key?", "(", "table_name", "=", "nil", ")", "return", "true", "if", "table_name", ".", "nil?", "table_name", "=", "table_name", ".", "to_s", "primary_keys", "(", "table_name", ".", "to_s", ")", ".", "size", "==", "0", "end" ]
If true, next_sequence_value is called before each insert statement to set the record's primary key. By default DB2 for i supports IDENTITY_VAL_LOCAL for tables that have one primary key.
[ "If", "true", "next_sequence_value", "is", "called", "before", "each", "insert", "statement", "to", "set", "the", "record", "s", "primary", "key", ".", "By", "default", "DB2", "for", "i", "supports", "IDENTITY_VAL_LOCAL", "for", "tables", "that", "have", "one"...
01505cc6d2da476aaf11133b3d5cfd05b6ef7d8c
https://github.com/pierrickrouxel/activerecord-jdbcas400-adapter/blob/01505cc6d2da476aaf11133b3d5cfd05b6ef7d8c/lib/arjdbc/as400/adapter.rb#L72-L76
valid
pierrickrouxel/activerecord-jdbcas400-adapter
lib/arjdbc/as400/adapter.rb
ArJdbc.AS400.execute_and_auto_confirm
def execute_and_auto_confirm(sql, name = nil) begin execute_system_command('CHGJOB INQMSGRPY(*SYSRPYL)') execute_system_command("ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I')") rescue Exception => e raise unauthorized_error_message("CHGJOB INQMSGRPY(*SYSRPYL) and ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I')", e) end begin result = execute(sql, name) rescue Exception raise else # Return if all work fine result ensure # Ensure default configuration restoration begin execute_system_command('CHGJOB INQMSGRPY(*DFT)') execute_system_command('RMVRPYLE SEQNBR(9876)') rescue Exception => e raise unauthorized_error_message('CHGJOB INQMSGRPY(*DFT) and RMVRPYLE SEQNBR(9876)', e) end end end
ruby
def execute_and_auto_confirm(sql, name = nil) begin execute_system_command('CHGJOB INQMSGRPY(*SYSRPYL)') execute_system_command("ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I')") rescue Exception => e raise unauthorized_error_message("CHGJOB INQMSGRPY(*SYSRPYL) and ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I')", e) end begin result = execute(sql, name) rescue Exception raise else # Return if all work fine result ensure # Ensure default configuration restoration begin execute_system_command('CHGJOB INQMSGRPY(*DFT)') execute_system_command('RMVRPYLE SEQNBR(9876)') rescue Exception => e raise unauthorized_error_message('CHGJOB INQMSGRPY(*DFT) and RMVRPYLE SEQNBR(9876)', e) end end end
[ "def", "execute_and_auto_confirm", "(", "sql", ",", "name", "=", "nil", ")", "begin", "execute_system_command", "(", "'CHGJOB INQMSGRPY(*SYSRPYL)'", ")", "execute_system_command", "(", "\"ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I')\"", ")", "rescue", "Exception", "=>", "e...
Holy moly batman! all this to tell AS400 "yes i am sure"
[ "Holy", "moly", "batman!", "all", "this", "to", "tell", "AS400", "yes", "i", "am", "sure" ]
01505cc6d2da476aaf11133b3d5cfd05b6ef7d8c
https://github.com/pierrickrouxel/activerecord-jdbcas400-adapter/blob/01505cc6d2da476aaf11133b3d5cfd05b6ef7d8c/lib/arjdbc/as400/adapter.rb#L154-L181
valid
jens-na/travis-custom-deploy
lib/travis-custom-deploy/deployment.rb
TravisCustomDeploy.Deployment.get_transfer
def get_transfer(type) type = type[0].upcase + type[1..-1] try_require(type) Transfer.const_get(type).new(@options, @files) end
ruby
def get_transfer(type) type = type[0].upcase + type[1..-1] try_require(type) Transfer.const_get(type).new(@options, @files) end
[ "def", "get_transfer", "(", "type", ")", "type", "=", "type", "[", "0", "]", ".", "upcase", "+", "type", "[", "1", "..", "-", "1", "]", "try_require", "(", "type", ")", "Transfer", ".", "const_get", "(", "type", ")", ".", "new", "(", "@options", ...
Creates an instance for the transfer type and return it type - the transfer type like sftp, ftp, etc.
[ "Creates", "an", "instance", "for", "the", "transfer", "type", "and", "return", "it" ]
5c767322074d69edced7bc2ae22afa3b0b874a79
https://github.com/jens-na/travis-custom-deploy/blob/5c767322074d69edced7bc2ae22afa3b0b874a79/lib/travis-custom-deploy/deployment.rb#L28-L32
valid
thumblemonks/smurf
lib/smurf/javascript.rb
Smurf.Javascript.peek
def peek(aheadCount=1) history = [] aheadCount.times { history << @input.getc } history.reverse.each { |chr| @input.ungetc(chr) } return history.last.chr end
ruby
def peek(aheadCount=1) history = [] aheadCount.times { history << @input.getc } history.reverse.each { |chr| @input.ungetc(chr) } return history.last.chr end
[ "def", "peek", "(", "aheadCount", "=", "1", ")", "history", "=", "[", "]", "aheadCount", ".", "times", "{", "history", "<<", "@input", ".", "getc", "}", "history", ".", "reverse", ".", "each", "{", "|", "chr", "|", "@input", ".", "ungetc", "(", "ch...
Get the next character without getting it.
[ "Get", "the", "next", "character", "without", "getting", "it", "." ]
09e10d7934786a3c9baf118d503f65b62ba13ae0
https://github.com/thumblemonks/smurf/blob/09e10d7934786a3c9baf118d503f65b62ba13ae0/lib/smurf/javascript.rb#L80-L85
valid
dblandin/motion-capture
lib/project/motion-capture.rb
Motion.Capture.captureOutput
def captureOutput(output, didFinishProcessingPhoto: photo, error: error) if error error_callback.call(error) else @capture_callback.call(photo.fileDataRepresentation) end end
ruby
def captureOutput(output, didFinishProcessingPhoto: photo, error: error) if error error_callback.call(error) else @capture_callback.call(photo.fileDataRepresentation) end end
[ "def", "captureOutput", "(", "output", ",", "didFinishProcessingPhoto", ":", "photo", ",", "error", ":", "error", ")", "if", "error", "error_callback", ".", "call", "(", "error", ")", "else", "@capture_callback", ".", "call", "(", "photo", ".", "fileDataRepres...
iOS 11+ AVCapturePhotoCaptureDelegate method
[ "iOS", "11", "+", "AVCapturePhotoCaptureDelegate", "method" ]
5e7bfd5636f75493f322d6e9e416253c940d0d14
https://github.com/dblandin/motion-capture/blob/5e7bfd5636f75493f322d6e9e416253c940d0d14/lib/project/motion-capture.rb#L107-L113
valid
dblandin/motion-capture
lib/project/motion-capture.rb
Motion.Capture.captureOutput
def captureOutput(output, didFinishProcessingPhotoSampleBuffer: photo_sample_buffer, previewPhotoSampleBuffer: preview_photo_sample_buffer, resolvedSettings: resolved_settings, bracketSettings: bracket_settings, error: error) if error error_callback.call(error) else jpeg_data = AVCapturePhotoOutput.jpegPhotoDataRepresentation( forJPEGSampleBuffer: photo_sample_buffer, previewPhotoSampleBuffer: preview_photo_sample_buffer ) @capture_callback.call(jpeg_data) end end
ruby
def captureOutput(output, didFinishProcessingPhotoSampleBuffer: photo_sample_buffer, previewPhotoSampleBuffer: preview_photo_sample_buffer, resolvedSettings: resolved_settings, bracketSettings: bracket_settings, error: error) if error error_callback.call(error) else jpeg_data = AVCapturePhotoOutput.jpegPhotoDataRepresentation( forJPEGSampleBuffer: photo_sample_buffer, previewPhotoSampleBuffer: preview_photo_sample_buffer ) @capture_callback.call(jpeg_data) end end
[ "def", "captureOutput", "(", "output", ",", "didFinishProcessingPhotoSampleBuffer", ":", "photo_sample_buffer", ",", "previewPhotoSampleBuffer", ":", "preview_photo_sample_buffer", ",", "resolvedSettings", ":", "resolved_settings", ",", "bracketSettings", ":", "bracket_settings...
iOS 10 AVCapturePhotoCaptureDelegate method
[ "iOS", "10", "AVCapturePhotoCaptureDelegate", "method" ]
5e7bfd5636f75493f322d6e9e416253c940d0d14
https://github.com/dblandin/motion-capture/blob/5e7bfd5636f75493f322d6e9e416253c940d0d14/lib/project/motion-capture.rb#L116-L126
valid
dblandin/motion-capture
lib/project/motion-capture.rb
Motion.Capture.save_to_assets_library
def save_to_assets_library(jpeg_data, &block) assets_library.writeImageDataToSavedPhotosAlbum(jpeg_data, metadata: nil, completionBlock: -> (asset_url, error) { error ? error_callback.call(error) : block.call(asset_url) }) end
ruby
def save_to_assets_library(jpeg_data, &block) assets_library.writeImageDataToSavedPhotosAlbum(jpeg_data, metadata: nil, completionBlock: -> (asset_url, error) { error ? error_callback.call(error) : block.call(asset_url) }) end
[ "def", "save_to_assets_library", "(", "jpeg_data", ",", "&", "block", ")", "assets_library", ".", "writeImageDataToSavedPhotosAlbum", "(", "jpeg_data", ",", "metadata", ":", "nil", ",", "completionBlock", ":", "->", "(", "asset_url", ",", "error", ")", "{", "err...
iOS 4-8
[ "iOS", "4", "-", "8" ]
5e7bfd5636f75493f322d6e9e416253c940d0d14
https://github.com/dblandin/motion-capture/blob/5e7bfd5636f75493f322d6e9e416253c940d0d14/lib/project/motion-capture.rb#L161-L165
valid
dblandin/motion-capture
lib/project/motion-capture.rb
Motion.Capture.save_to_photo_library
def save_to_photo_library(jpeg_data, &block) photo_library.performChanges(-> { image = UIImage.imageWithData(jpeg_data) PHAssetChangeRequest.creationRequestForAssetFromImage(image) }, completionHandler: -> (success, error) { if error error_callback.call(error) else block.call(nil) # asset url is not returned in completion block end }) end
ruby
def save_to_photo_library(jpeg_data, &block) photo_library.performChanges(-> { image = UIImage.imageWithData(jpeg_data) PHAssetChangeRequest.creationRequestForAssetFromImage(image) }, completionHandler: -> (success, error) { if error error_callback.call(error) else block.call(nil) # asset url is not returned in completion block end }) end
[ "def", "save_to_photo_library", "(", "jpeg_data", ",", "&", "block", ")", "photo_library", ".", "performChanges", "(", "->", "{", "image", "=", "UIImage", ".", "imageWithData", "(", "jpeg_data", ")", "PHAssetChangeRequest", ".", "creationRequestForAssetFromImage", "...
iOS 8+
[ "iOS", "8", "+" ]
5e7bfd5636f75493f322d6e9e416253c940d0d14
https://github.com/dblandin/motion-capture/blob/5e7bfd5636f75493f322d6e9e416253c940d0d14/lib/project/motion-capture.rb#L168-L179
valid
dblandin/motion-capture
lib/project/motion-capture.rb
Motion.Capture.update_video_orientation!
def update_video_orientation! photo_output.connectionWithMediaType(AVMediaTypeVideo).tap do |connection| device_orientation = UIDevice.currentDevice.orientation video_orientation = orientation_mapping.fetch(device_orientation, AVCaptureVideoOrientationPortrait) connection.setVideoOrientation(video_orientation) if connection.videoOrientationSupported? end end
ruby
def update_video_orientation! photo_output.connectionWithMediaType(AVMediaTypeVideo).tap do |connection| device_orientation = UIDevice.currentDevice.orientation video_orientation = orientation_mapping.fetch(device_orientation, AVCaptureVideoOrientationPortrait) connection.setVideoOrientation(video_orientation) if connection.videoOrientationSupported? end end
[ "def", "update_video_orientation!", "photo_output", ".", "connectionWithMediaType", "(", "AVMediaTypeVideo", ")", ".", "tap", "do", "|", "connection", "|", "device_orientation", "=", "UIDevice", ".", "currentDevice", ".", "orientation", "video_orientation", "=", "orient...
iOS 10+
[ "iOS", "10", "+" ]
5e7bfd5636f75493f322d6e9e416253c940d0d14
https://github.com/dblandin/motion-capture/blob/5e7bfd5636f75493f322d6e9e416253c940d0d14/lib/project/motion-capture.rb#L255-L262
valid
Hamdiakoguz/onedclusterer
lib/onedclusterer/ckmeans.rb
OnedClusterer.Ckmeans.select_levels
def select_levels(data, backtrack, kmin, kmax) return kmin if kmin == kmax method = :normal # "uniform" or "normal" kopt = kmin base = 1 # The position of first element in x: 1 or 0. n = data.size - base max_bic = 0.0 for k in kmin..kmax cluster_sizes = [] kbacktrack = backtrack[0..k] backtrack(kbacktrack) do |cluster, left, right| cluster_sizes[cluster] = right - left + 1 end index_left = base index_right = 0 likelihood = 0 bin_left, bin_right = 0 for i in 0..(k-1) points_in_bin = cluster_sizes[i + base] index_right = index_left + points_in_bin - 1 if data[index_left] < data[index_right] bin_left = data[index_left] bin_right = data[index_right] elsif data[index_left] == data[index_right] bin_left = index_left == base ? data[base] : (data[index_left-1] + data[index_left]) / 2 bin_right = index_right < n-1+base ? (data[index_right] + data[index_right+1]) / 2 : data[n-1+base] else raise "ERROR: binLeft > binRight" end bin_width = bin_right - bin_left if method == :uniform likelihood += points_in_bin * Math.log(points_in_bin / bin_width / n) else mean = 0.0 variance = 0.0 for j in index_left..index_right mean += data[j] variance += data[j] ** 2 end mean /= points_in_bin variance = (variance - points_in_bin * mean ** 2) / (points_in_bin - 1) if points_in_bin > 1 if variance > 0 for j in index_left..index_right likelihood += - (data[j] - mean) ** 2 / (2.0 * variance) end likelihood += points_in_bin * (Math.log(points_in_bin / Float(n)) - 0.5 * Math.log( 2 * Math::PI * variance)) else likelihood += points_in_bin * Math.log(1.0 / bin_width / n) end end index_left = index_right + 1 end # Compute the Bayesian information criterion bic = 2 * likelihood - (3 * k - 1) * Math.log(Float(n)) if k == kmin max_bic = bic kopt = kmin elsif bic > max_bic max_bic = bic kopt = k end end kopt end
ruby
def select_levels(data, backtrack, kmin, kmax) return kmin if kmin == kmax method = :normal # "uniform" or "normal" kopt = kmin base = 1 # The position of first element in x: 1 or 0. n = data.size - base max_bic = 0.0 for k in kmin..kmax cluster_sizes = [] kbacktrack = backtrack[0..k] backtrack(kbacktrack) do |cluster, left, right| cluster_sizes[cluster] = right - left + 1 end index_left = base index_right = 0 likelihood = 0 bin_left, bin_right = 0 for i in 0..(k-1) points_in_bin = cluster_sizes[i + base] index_right = index_left + points_in_bin - 1 if data[index_left] < data[index_right] bin_left = data[index_left] bin_right = data[index_right] elsif data[index_left] == data[index_right] bin_left = index_left == base ? data[base] : (data[index_left-1] + data[index_left]) / 2 bin_right = index_right < n-1+base ? (data[index_right] + data[index_right+1]) / 2 : data[n-1+base] else raise "ERROR: binLeft > binRight" end bin_width = bin_right - bin_left if method == :uniform likelihood += points_in_bin * Math.log(points_in_bin / bin_width / n) else mean = 0.0 variance = 0.0 for j in index_left..index_right mean += data[j] variance += data[j] ** 2 end mean /= points_in_bin variance = (variance - points_in_bin * mean ** 2) / (points_in_bin - 1) if points_in_bin > 1 if variance > 0 for j in index_left..index_right likelihood += - (data[j] - mean) ** 2 / (2.0 * variance) end likelihood += points_in_bin * (Math.log(points_in_bin / Float(n)) - 0.5 * Math.log( 2 * Math::PI * variance)) else likelihood += points_in_bin * Math.log(1.0 / bin_width / n) end end index_left = index_right + 1 end # Compute the Bayesian information criterion bic = 2 * likelihood - (3 * k - 1) * Math.log(Float(n)) if k == kmin max_bic = bic kopt = kmin elsif bic > max_bic max_bic = bic kopt = k end end kopt end
[ "def", "select_levels", "(", "data", ",", "backtrack", ",", "kmin", ",", "kmax", ")", "return", "kmin", "if", "kmin", "==", "kmax", "method", "=", ":normal", "kopt", "=", "kmin", "base", "=", "1", "n", "=", "data", ".", "size", "-", "base", "max_bic"...
Choose an optimal number of levels between Kmin and Kmax
[ "Choose", "an", "optimal", "number", "of", "levels", "between", "Kmin", "and", "Kmax" ]
5d134970cb7e2bc0d29ae108d952c081707e02b6
https://github.com/Hamdiakoguz/onedclusterer/blob/5d134970cb7e2bc0d29ae108d952c081707e02b6/lib/onedclusterer/ckmeans.rb#L147-L227
valid
raykin/source-route
lib/source_route/config.rb
SourceRoute.ParamsConfigParser.full_feature
def full_feature(value=true) return unless value @config.formulize @config.event = (@config.event + [:call, :return]).uniq @config.import_return_to_call = true @config.show_additional_attrs = [:path, :lineno] # JSON serialize trigger many problems when handle complicated object(in rails?) # a Back Door to open more data. but be care it could trigger weird crash when Jsonify these vars if value == 10 @config.include_instance_var = true @config.include_local_var = true end end
ruby
def full_feature(value=true) return unless value @config.formulize @config.event = (@config.event + [:call, :return]).uniq @config.import_return_to_call = true @config.show_additional_attrs = [:path, :lineno] # JSON serialize trigger many problems when handle complicated object(in rails?) # a Back Door to open more data. but be care it could trigger weird crash when Jsonify these vars if value == 10 @config.include_instance_var = true @config.include_local_var = true end end
[ "def", "full_feature", "(", "value", "=", "true", ")", "return", "unless", "value", "@config", ".", "formulize", "@config", ".", "event", "=", "(", "@config", ".", "event", "+", "[", ":call", ",", ":return", "]", ")", ".", "uniq", "@config", ".", "impo...
todo. value equal 10 may not be a good params
[ "todo", ".", "value", "equal", "10", "may", "not", "be", "a", "good", "params" ]
c45feacd080511ca85691a2e2176bd0125e9ca09
https://github.com/raykin/source-route/blob/c45feacd080511ca85691a2e2176bd0125e9ca09/lib/source_route/config.rb#L119-L131
valid
hassox/pancake
lib/pancake/middleware.rb
Pancake.Middleware.stack
def stack(name = nil, opts = {}) if self::StackMiddleware._mwares[name] && mw = self::StackMiddleware._mwares[name] unless mw.stack == self mw = self::StackMiddleware._mwares[name] = self::StackMiddleware._mwares[name].dup end mw else self::StackMiddleware.new(name, self, opts) end end
ruby
def stack(name = nil, opts = {}) if self::StackMiddleware._mwares[name] && mw = self::StackMiddleware._mwares[name] unless mw.stack == self mw = self::StackMiddleware._mwares[name] = self::StackMiddleware._mwares[name].dup end mw else self::StackMiddleware.new(name, self, opts) end end
[ "def", "stack", "(", "name", "=", "nil", ",", "opts", "=", "{", "}", ")", "if", "self", "::", "StackMiddleware", ".", "_mwares", "[", "name", "]", "&&", "mw", "=", "self", "::", "StackMiddleware", ".", "_mwares", "[", "name", "]", "unless", "mw", "...
Useful for adding additional information into your middleware stack definition @param [Object] name The name of a given middleware. Each piece of middleware has a name in the stack. By naming middleware we can refer to it later, swap it out for a different class or even just remove it from the stack. @param [Hash] opts An options hash @option opts [Object] :before Sets this middlware to be run after the middleware named. Name is either the name given to the middleware stack, or the Middleware class itself. @option opts [Object] :after Sets this middleware to be run after the middleware name. Name is either the name given to the middleware stack or the Middleware class itself. @example Declaring un-named middleware via the stack MyClass.stack.use(MyMiddleware) This middleware will be named MyMiddleware, and can be specified with (:before | :after) => MyMiddleware @example Declaring a named middleware via the stack MyClass.stack(:foo).use(MyMiddleware) This middleware will be named :foo and can be specified with (:before | :after) => :foo @example Declaring a named middleware with a :before key MyClass.stack(:foo, :before => :bar).use(MyMiddleware) This middleware will be named :foo and will be run before the middleware named :bar If :bar is not run, :foo will not be run either @example Declaring a named middlware with an :after key MyClass.stack(:foo, :after => :bar).use(MyMiddleware) This middleware will be named :foo and will be run after the middleware named :bar If :bar is not run, :foo will not be run either @see Pancake::Middleware#use @api public @since 0.1.0 @author Daniel Neighman
[ "Useful", "for", "adding", "additional", "information", "into", "your", "middleware", "stack", "definition" ]
774b1e878cf8d4f8e7160173ed9a236a290989e6
https://github.com/hassox/pancake/blob/774b1e878cf8d4f8e7160173ed9a236a290989e6/lib/pancake/middleware.rb#L100-L109
valid
hassox/pancake
lib/pancake/middleware.rb
Pancake.Middleware.use
def use(middleware, *_args, &block) stack(middleware).use(middleware, *_args, &block) end
ruby
def use(middleware, *_args, &block) stack(middleware).use(middleware, *_args, &block) end
[ "def", "use", "(", "middleware", ",", "*", "_args", ",", "&", "block", ")", "stack", "(", "middleware", ")", ".", "use", "(", "middleware", ",", "*", "_args", ",", "&", "block", ")", "end" ]
Adds middleware to the current stack definition @param [Class] middleware The middleware class to use in the stack @param [Hash] opts An options hash that is passed through to the middleware when it is instantiated @yield The block is provided to the middlewares #new method when it is initialized @example Bare use call MyApp.use(MyMiddleware, :some => :option){ # middleware initialization block here } @example Use call after a stack call MyApp.stack(:foo).use(MyMiddleware, :some => :option){ # middleware initialization block here } @see Pancake::Middleware#stack @api public @since 0.1.0 @author Daniel Neighman
[ "Adds", "middleware", "to", "the", "current", "stack", "definition" ]
774b1e878cf8d4f8e7160173ed9a236a290989e6
https://github.com/hassox/pancake/blob/774b1e878cf8d4f8e7160173ed9a236a290989e6/lib/pancake/middleware.rb#L128-L130
valid
OregonDigital/metadata-ingest-form
lib/metadata/ingest/translators/form_to_attributes.rb
Metadata::Ingest::Translators.FormToAttributes.attribute_lookup
def attribute_lookup(assoc) group_data = @map[assoc.group.to_sym] return nil unless group_data attribute = group_data[assoc.type.to_sym] return attribute end
ruby
def attribute_lookup(assoc) group_data = @map[assoc.group.to_sym] return nil unless group_data attribute = group_data[assoc.type.to_sym] return attribute end
[ "def", "attribute_lookup", "(", "assoc", ")", "group_data", "=", "@map", "[", "assoc", ".", "group", ".", "to_sym", "]", "return", "nil", "unless", "group_data", "attribute", "=", "group_data", "[", "assoc", ".", "type", ".", "to_sym", "]", "return", "attr...
Extracts the attribute definition for a given association
[ "Extracts", "the", "attribute", "definition", "for", "a", "given", "association" ]
1d36b5a1380fe009cda797555883b1d258463682
https://github.com/OregonDigital/metadata-ingest-form/blob/1d36b5a1380fe009cda797555883b1d258463682/lib/metadata/ingest/translators/form_to_attributes.rb#L60-L66
valid
OregonDigital/metadata-ingest-form
lib/metadata/ingest/translators/form_to_attributes.rb
Metadata::Ingest::Translators.FormToAttributes.translate_association
def translate_association(assoc) attribute = attribute_lookup(assoc) return unless attribute # Make sure we properly handle destroyed values by forcing them to an # empty association. We keep their state up to this point because the # caller may be using the prior value for something. if assoc.marked_for_destruction? assoc = @form.create_association end add_association_to_attribute_map(attribute, assoc) end
ruby
def translate_association(assoc) attribute = attribute_lookup(assoc) return unless attribute # Make sure we properly handle destroyed values by forcing them to an # empty association. We keep their state up to this point because the # caller may be using the prior value for something. if assoc.marked_for_destruction? assoc = @form.create_association end add_association_to_attribute_map(attribute, assoc) end
[ "def", "translate_association", "(", "assoc", ")", "attribute", "=", "attribute_lookup", "(", "assoc", ")", "return", "unless", "attribute", "if", "assoc", ".", "marked_for_destruction?", "assoc", "=", "@form", ".", "create_association", "end", "add_association_to_att...
Maps an association to the attribute its data will be tied
[ "Maps", "an", "association", "to", "the", "attribute", "its", "data", "will", "be", "tied" ]
1d36b5a1380fe009cda797555883b1d258463682
https://github.com/OregonDigital/metadata-ingest-form/blob/1d36b5a1380fe009cda797555883b1d258463682/lib/metadata/ingest/translators/form_to_attributes.rb#L69-L81
valid
OregonDigital/metadata-ingest-form
lib/metadata/ingest/translators/form_to_attributes.rb
Metadata::Ingest::Translators.FormToAttributes.add_association_to_attribute_map
def add_association_to_attribute_map(attribute, assoc) current = @attributes[attribute] # If there's already a value, we can safely ignore the empty association return if current && assoc.blank? case current when nil then @attributes[attribute] = [assoc] when Array then @attributes[attribute].push(assoc) end end
ruby
def add_association_to_attribute_map(attribute, assoc) current = @attributes[attribute] # If there's already a value, we can safely ignore the empty association return if current && assoc.blank? case current when nil then @attributes[attribute] = [assoc] when Array then @attributes[attribute].push(assoc) end end
[ "def", "add_association_to_attribute_map", "(", "attribute", ",", "assoc", ")", "current", "=", "@attributes", "[", "attribute", "]", "return", "if", "current", "&&", "assoc", ".", "blank?", "case", "current", "when", "nil", "then", "@attributes", "[", "attribut...
Adds the given association to an array of associations for the given attribute
[ "Adds", "the", "given", "association", "to", "an", "array", "of", "associations", "for", "the", "given", "attribute" ]
1d36b5a1380fe009cda797555883b1d258463682
https://github.com/OregonDigital/metadata-ingest-form/blob/1d36b5a1380fe009cda797555883b1d258463682/lib/metadata/ingest/translators/form_to_attributes.rb#L85-L95
valid
OregonDigital/metadata-ingest-form
lib/metadata/ingest/translators/form_to_attributes.rb
Metadata::Ingest::Translators.FormToAttributes.store_associations_on_object
def store_associations_on_object(object, attribute, associations) values = associations.collect do |assoc| assoc.internal.blank? ? assoc.value : assoc.internal end # Clean up values values.compact! case values.length when 0 then values = nil when 1 then values = values.first end object.send("#{attribute}=", values) end
ruby
def store_associations_on_object(object, attribute, associations) values = associations.collect do |assoc| assoc.internal.blank? ? assoc.value : assoc.internal end # Clean up values values.compact! case values.length when 0 then values = nil when 1 then values = values.first end object.send("#{attribute}=", values) end
[ "def", "store_associations_on_object", "(", "object", ",", "attribute", ",", "associations", ")", "values", "=", "associations", ".", "collect", "do", "|", "assoc", "|", "assoc", ".", "internal", ".", "blank?", "?", "assoc", ".", "value", ":", "assoc", ".", ...
Stores all association data on the object at the given attribute. Associations with internal data use that instead of value. If only one association is present, it is extracted from the array and stored as-is.
[ "Stores", "all", "association", "data", "on", "the", "object", "at", "the", "given", "attribute", ".", "Associations", "with", "internal", "data", "use", "that", "instead", "of", "value", ".", "If", "only", "one", "association", "is", "present", "it", "is", ...
1d36b5a1380fe009cda797555883b1d258463682
https://github.com/OregonDigital/metadata-ingest-form/blob/1d36b5a1380fe009cda797555883b1d258463682/lib/metadata/ingest/translators/form_to_attributes.rb#L100-L113
valid
OregonDigital/metadata-ingest-form
lib/metadata/ingest/translators/attributes_to_form.rb
Metadata::Ingest::Translators.AttributesToForm.setup_form
def setup_form(group, type, attr_definition) attr_trans = single_attribute_translator.new( source: @source, form: @form, group: group, type: type, attribute_definition: attr_definition ) attr_trans.add_associations_to_form end
ruby
def setup_form(group, type, attr_definition) attr_trans = single_attribute_translator.new( source: @source, form: @form, group: group, type: type, attribute_definition: attr_definition ) attr_trans.add_associations_to_form end
[ "def", "setup_form", "(", "group", ",", "type", ",", "attr_definition", ")", "attr_trans", "=", "single_attribute_translator", ".", "new", "(", "source", ":", "@source", ",", "form", ":", "@form", ",", "group", ":", "group", ",", "type", ":", "type", ",", ...
Sets up translation state instance to hold various attributes that need to be passed around, and calls helpers to build the necessary associations and attach them to the form.
[ "Sets", "up", "translation", "state", "instance", "to", "hold", "various", "attributes", "that", "need", "to", "be", "passed", "around", "and", "calls", "helpers", "to", "build", "the", "necessary", "associations", "and", "attach", "them", "to", "the", "form",...
1d36b5a1380fe009cda797555883b1d258463682
https://github.com/OregonDigital/metadata-ingest-form/blob/1d36b5a1380fe009cda797555883b1d258463682/lib/metadata/ingest/translators/attributes_to_form.rb#L67-L77
valid
hassox/pancake
lib/pancake/router.rb
Pancake.Router.mount
def mount(mounted_app, path, options = {}) mounted_app = MountedApplication.new(mounted_app, path, options) self.class.mounted_applications << mounted_app mounted_app end
ruby
def mount(mounted_app, path, options = {}) mounted_app = MountedApplication.new(mounted_app, path, options) self.class.mounted_applications << mounted_app mounted_app end
[ "def", "mount", "(", "mounted_app", ",", "path", ",", "options", "=", "{", "}", ")", "mounted_app", "=", "MountedApplication", ".", "new", "(", "mounted_app", ",", "path", ",", "options", ")", "self", ".", "class", ".", "mounted_applications", "<<", "mount...
Mounts an application in the router as a sub application in the url space. This will route directly to the sub application and skip any middlewares etc defined on a stack
[ "Mounts", "an", "application", "in", "the", "router", "as", "a", "sub", "application", "in", "the", "url", "space", ".", "This", "will", "route", "directly", "to", "the", "sub", "application", "and", "skip", "any", "middlewares", "etc", "defined", "on", "a...
774b1e878cf8d4f8e7160173ed9a236a290989e6
https://github.com/hassox/pancake/blob/774b1e878cf8d4f8e7160173ed9a236a290989e6/lib/pancake/router.rb#L90-L94
valid
raykin/source-route
lib/source_route/generate_result.rb
SourceRoute.GenerateResult.assign_tp_self_caches
def assign_tp_self_caches(tp_ins) unless tp_self_caches.find { |tp_cache| tp_cache.object_id.equal? tp_ins.self.object_id } tp_self_caches.push tp_ins.self end end
ruby
def assign_tp_self_caches(tp_ins) unless tp_self_caches.find { |tp_cache| tp_cache.object_id.equal? tp_ins.self.object_id } tp_self_caches.push tp_ins.self end end
[ "def", "assign_tp_self_caches", "(", "tp_ins", ")", "unless", "tp_self_caches", ".", "find", "{", "|", "tp_cache", "|", "tp_cache", ".", "object_id", ".", "equal?", "tp_ins", ".", "self", ".", "object_id", "}", "tp_self_caches", ".", "push", "tp_ins", ".", "...
include? will evaluate @tp.self, if @tp.self is AR::Relation, it could cause problems So that's why I use object_id as replace
[ "include?", "will", "evaluate" ]
c45feacd080511ca85691a2e2176bd0125e9ca09
https://github.com/raykin/source-route/blob/c45feacd080511ca85691a2e2176bd0125e9ca09/lib/source_route/generate_result.rb#L84-L88
valid
hassox/pancake
lib/pancake/logger.rb
Pancake.Logger.set_log
def set_log(stream = Pancake.configuration.log_stream, log_level = Pancake.configuration.log_level, delimiter = Pancake.configuration.log_delimiter, auto_flush = Pancake.configuration.log_auto_flush) @buffer = [] @delimiter = delimiter @auto_flush = auto_flush if Levels[log_level] @level = Levels[log_level] else @level = log_level end @log = stream @log.sync = true @mutex = (@@mutex[@log] ||= Mutex.new) end
ruby
def set_log(stream = Pancake.configuration.log_stream, log_level = Pancake.configuration.log_level, delimiter = Pancake.configuration.log_delimiter, auto_flush = Pancake.configuration.log_auto_flush) @buffer = [] @delimiter = delimiter @auto_flush = auto_flush if Levels[log_level] @level = Levels[log_level] else @level = log_level end @log = stream @log.sync = true @mutex = (@@mutex[@log] ||= Mutex.new) end
[ "def", "set_log", "(", "stream", "=", "Pancake", ".", "configuration", ".", "log_stream", ",", "log_level", "=", "Pancake", ".", "configuration", ".", "log_level", ",", "delimiter", "=", "Pancake", ".", "configuration", ".", "log_delimiter", ",", "auto_flush", ...
To initialize the logger you create a new object, proxies to set_log. ==== Parameters *args:: Arguments to create the log from. See set_logs for specifics. Replaces an existing logger with a new one. ==== Parameters log<IO, String>:: Either an IO object or a name of a logfile. log_level<~to_sym>:: The log level from, e.g. :fatal or :info. Defaults to :error in the production environment and :debug otherwise. delimiter<String>:: Delimiter to use between message sections. Defaults to " ~ ". auto_flush<Boolean>:: Whether the log should automatically flush after new messages are added. Defaults to false.
[ "To", "initialize", "the", "logger", "you", "create", "a", "new", "object", "proxies", "to", "set_log", "." ]
774b1e878cf8d4f8e7160173ed9a236a290989e6
https://github.com/hassox/pancake/blob/774b1e878cf8d4f8e7160173ed9a236a290989e6/lib/pancake/logger.rb#L84-L102
valid
hassox/pancake
lib/pancake/paths.rb
Pancake.Paths.dirs_for
def dirs_for(name, opts = {}) if _load_paths[name].blank? [] else result = [] invert = !!opts[:invert] load_paths = invert ? _load_paths[name].reverse : _load_paths[name] roots.each do |root| load_paths.each do |paths, glob| paths = paths.reverse if invert result << paths.map{|p| File.join(root, p)} end end result.flatten end # if end
ruby
def dirs_for(name, opts = {}) if _load_paths[name].blank? [] else result = [] invert = !!opts[:invert] load_paths = invert ? _load_paths[name].reverse : _load_paths[name] roots.each do |root| load_paths.each do |paths, glob| paths = paths.reverse if invert result << paths.map{|p| File.join(root, p)} end end result.flatten end # if end
[ "def", "dirs_for", "(", "name", ",", "opts", "=", "{", "}", ")", "if", "_load_paths", "[", "name", "]", ".", "blank?", "[", "]", "else", "result", "=", "[", "]", "invert", "=", "!", "!", "opts", "[", ":invert", "]", "load_paths", "=", "invert", "...
Provides the directories or raw paths that are associated with a given name. @param [Symbol] name The name for the paths group @param [Hash] opts An options hash @option opts [Boolean] :invert (false) inverts the order of the returned paths @example Read Directories: MyClass.dirs_for(:models) @example Inverted Read: MyClass.dirs_for(:models, :invert => true) @return [Array] An array of the paths Returned in declared order unless the :invert option is set @api public @since 0.1.1 @author Daniel Neighman
[ "Provides", "the", "directories", "or", "raw", "paths", "that", "are", "associated", "with", "a", "given", "name", "." ]
774b1e878cf8d4f8e7160173ed9a236a290989e6
https://github.com/hassox/pancake/blob/774b1e878cf8d4f8e7160173ed9a236a290989e6/lib/pancake/paths.rb#L92-L107
valid
hassox/pancake
lib/pancake/paths.rb
Pancake.Paths.paths_for
def paths_for(name, opts = {}) result = [] dirs_and_glob_for(name, opts).each do |path, glob| next if glob.nil? paths = Dir[File.join(path, glob)] paths = paths.reverse if opts[:invert] paths.each do |full_path| result << [path, full_path.gsub(path, "")] end end result end
ruby
def paths_for(name, opts = {}) result = [] dirs_and_glob_for(name, opts).each do |path, glob| next if glob.nil? paths = Dir[File.join(path, glob)] paths = paths.reverse if opts[:invert] paths.each do |full_path| result << [path, full_path.gsub(path, "")] end end result end
[ "def", "paths_for", "(", "name", ",", "opts", "=", "{", "}", ")", "result", "=", "[", "]", "dirs_and_glob_for", "(", "name", ",", "opts", ")", ".", "each", "do", "|", "path", ",", "glob", "|", "next", "if", "glob", ".", "nil?", "paths", "=", "Dir...
Provides an expanded, globbed list of paths and files for a given name. @param [Symbol] name The name of the paths group @param [Hash] opts An options hash @option opts [Boolean] :invert (false) Inverts the order of the returned values @example MyClass.paths_for(:model) MyClass.paths_for(:model, :invert => true) @return [Array] An array of [path, file] arrays. These may be joined to get the full path. All matched files for [paths, glob] will be returned in declared and then found order unless +:invert+ is true. Any path that has a +nil+ glob associated with it will be excluded. @api public @since 0.1.1 @author Daniel Neighman
[ "Provides", "an", "expanded", "globbed", "list", "of", "paths", "and", "files", "for", "a", "given", "name", "." ]
774b1e878cf8d4f8e7160173ed9a236a290989e6
https://github.com/hassox/pancake/blob/774b1e878cf8d4f8e7160173ed9a236a290989e6/lib/pancake/paths.rb#L160-L171
valid
hassox/pancake
lib/pancake/paths.rb
Pancake.Paths.unique_paths_for
def unique_paths_for(name, opts = {}) tally = {} output = [] paths_for(name, opts).reverse.each do |ary| tally[ary[1]] ||= ary[0] output << ary if tally[ary[1]] == ary[0] end output.reverse end
ruby
def unique_paths_for(name, opts = {}) tally = {} output = [] paths_for(name, opts).reverse.each do |ary| tally[ary[1]] ||= ary[0] output << ary if tally[ary[1]] == ary[0] end output.reverse end
[ "def", "unique_paths_for", "(", "name", ",", "opts", "=", "{", "}", ")", "tally", "=", "{", "}", "output", "=", "[", "]", "paths_for", "(", "name", ",", "opts", ")", ".", "reverse", ".", "each", "do", "|", "ary", "|", "tally", "[", "ary", "[", ...
Provides an expanded, globbed list of paths and files for a given name. The result includes only the last matched file of a given sub path and name. @param [Symbol] name The name of the paths group @param [Hash] opts An options hash @option opts [Boolean] :invert (false) Inverts the order of returned paths and files @example #Given the following: # /path/one/file1.rb # /path/one/file2.rb # /path/two/file1.rb MyClass.push_path(:files, ["/path/one", "/path/two"], "**/*.rb") MyClass.unique_paths_for(:files) MyClass.unique_paths_for(:files, :invert => true) @return [Array] Returns an array of [path, file] arrays Results are retuned in declared order. Only unique files are returned (the file part - the path) In the above example, the following would be returned for the standard call [ ["#{root}/path/one", "/file2.rb"], ["#{root}/path/two", "/file1.rb"] ] For the inverted example the following is returned: [ ["#{root}/path/one/file2.rb"], ["#{root}/path/one/file1.rb"] ] @api public @since 0.1.1 @author Daniel Neighman
[ "Provides", "an", "expanded", "globbed", "list", "of", "paths", "and", "files", "for", "a", "given", "name", ".", "The", "result", "includes", "only", "the", "last", "matched", "file", "of", "a", "given", "sub", "path", "and", "name", "." ]
774b1e878cf8d4f8e7160173ed9a236a290989e6
https://github.com/hassox/pancake/blob/774b1e878cf8d4f8e7160173ed9a236a290989e6/lib/pancake/paths.rb#L208-L216
valid
OregonDigital/metadata-ingest-form
lib/metadata/ingest/translators/single_attribute_translator.rb
Metadata::Ingest::Translators.SingleAttributeTranslator.build_association
def build_association(value) association = @form.create_association( group: @group.to_s, type: @type.to_s, value: value ) # Since the associations are fake, we just set persistence to the parent # object's value association.persisted = @source.persisted? return association end
ruby
def build_association(value) association = @form.create_association( group: @group.to_s, type: @type.to_s, value: value ) # Since the associations are fake, we just set persistence to the parent # object's value association.persisted = @source.persisted? return association end
[ "def", "build_association", "(", "value", ")", "association", "=", "@form", ".", "create_association", "(", "group", ":", "@group", ".", "to_s", ",", "type", ":", "@type", ".", "to_s", ",", "value", ":", "value", ")", "association", ".", "persisted", "=", ...
Builds a single association with the given data
[ "Builds", "a", "single", "association", "with", "the", "given", "data" ]
1d36b5a1380fe009cda797555883b1d258463682
https://github.com/OregonDigital/metadata-ingest-form/blob/1d36b5a1380fe009cda797555883b1d258463682/lib/metadata/ingest/translators/single_attribute_translator.rb#L49-L61
valid
raykin/source-route
lib/source_route/trace_filter.rb
SourceRoute.TraceFilter.block_it?
def block_it?(tp) if @cond.track_params return true if negative_check(tp) if positives_check(tp) return !tp.binding.eval('local_variables').any? do |v| tp.binding.local_variable_get(v).object_id == @cond.track_params end end else return true if negative_check(tp) return false if positives_check(tp) end true # default is blocked the tp end
ruby
def block_it?(tp) if @cond.track_params return true if negative_check(tp) if positives_check(tp) return !tp.binding.eval('local_variables').any? do |v| tp.binding.local_variable_get(v).object_id == @cond.track_params end end else return true if negative_check(tp) return false if positives_check(tp) end true # default is blocked the tp end
[ "def", "block_it?", "(", "tp", ")", "if", "@cond", ".", "track_params", "return", "true", "if", "negative_check", "(", "tp", ")", "if", "positives_check", "(", "tp", ")", "return", "!", "tp", ".", "binding", ".", "eval", "(", "'local_variables'", ")", "....
to improve performance, we didnt assign tp as instance variable
[ "to", "improve", "performance", "we", "didnt", "assign", "tp", "as", "instance", "variable" ]
c45feacd080511ca85691a2e2176bd0125e9ca09
https://github.com/raykin/source-route/blob/c45feacd080511ca85691a2e2176bd0125e9ca09/lib/source_route/trace_filter.rb#L10-L23
valid
Hamdiakoguz/onedclusterer
lib/onedclusterer/clusterer.rb
OnedClusterer.Clusterer.classify
def classify(value) raise ArgumentError, "value: #{value} must be in data array" unless @data.include?(value) bounds[1..-1].index { |bound| value <= bound } end
ruby
def classify(value) raise ArgumentError, "value: #{value} must be in data array" unless @data.include?(value) bounds[1..-1].index { |bound| value <= bound } end
[ "def", "classify", "(", "value", ")", "raise", "ArgumentError", ",", "\"value: #{value} must be in data array\"", "unless", "@data", ".", "include?", "(", "value", ")", "bounds", "[", "1", "..", "-", "1", "]", ".", "index", "{", "|", "bound", "|", "value", ...
Returns zero based index of cluster which a value belongs to value must be in data array
[ "Returns", "zero", "based", "index", "of", "cluster", "which", "a", "value", "belongs", "to", "value", "must", "be", "in", "data", "array" ]
5d134970cb7e2bc0d29ae108d952c081707e02b6
https://github.com/Hamdiakoguz/onedclusterer/blob/5d134970cb7e2bc0d29ae108d952c081707e02b6/lib/onedclusterer/clusterer.rb#L8-L12
valid
Hamdiakoguz/onedclusterer
lib/onedclusterer/clusterer.rb
OnedClusterer.Clusterer.intervals
def intervals first, *rest = bounds.each_cons(2).to_a [first, *rest.map {|lower, upper| [data[data.rindex(lower) + 1] , upper] }] end
ruby
def intervals first, *rest = bounds.each_cons(2).to_a [first, *rest.map {|lower, upper| [data[data.rindex(lower) + 1] , upper] }] end
[ "def", "intervals", "first", ",", "*", "rest", "=", "bounds", ".", "each_cons", "(", "2", ")", ".", "to_a", "[", "first", ",", "*", "rest", ".", "map", "{", "|", "lower", ",", "upper", "|", "[", "data", "[", "data", ".", "rindex", "(", "lower", ...
Returns inclusive interval limits
[ "Returns", "inclusive", "interval", "limits" ]
5d134970cb7e2bc0d29ae108d952c081707e02b6
https://github.com/Hamdiakoguz/onedclusterer/blob/5d134970cb7e2bc0d29ae108d952c081707e02b6/lib/onedclusterer/clusterer.rb#L15-L18
valid
Hamdiakoguz/onedclusterer
lib/onedclusterer/jenks.rb
OnedClusterer.Jenks.matrices
def matrices rows = data.size cols = n_classes # in the original implementation, these matrices are referred to # as `LC` and `OP` # * lower_class_limits (LC): optimal lower class limits # * variance_combinations (OP): optimal variance combinations for all classes lower_class_limits = *Matrix.zero(rows + 1, cols + 1) variance_combinations = *Matrix.zero(rows + 1, cols + 1) # the variance, as computed at each step in the calculation variance = 0 for i in 1..cols lower_class_limits[1][i] = 1 variance_combinations[1][i] = 0 for j in 2..rows variance_combinations[j][i] = Float::INFINITY end end for l in 2..rows sum = 0 # `SZ` originally. this is the sum of the values seen thus far when calculating variance. sum_squares = 0 # `ZSQ` originally. the sum of squares of values seen thus far w = 0 # `WT` originally. This is the number of data points considered so far. for m in 1..l lower_class_limit = l - m + 1 # `III` originally val = data[lower_class_limit - 1] # here we're estimating variance for each potential classing # of the data, for each potential number of classes. `w` # is the number of data points considered so far. w += 1 # increase the current sum and sum-of-squares sum += val sum_squares += (val ** 2) # the variance at this point in the sequence is the difference # between the sum of squares and the total x 2, over the number # of samples. variance = sum_squares - (sum ** 2) / w i4 = lower_class_limit - 1 # `IV` originally if i4 != 0 for j in 2..cols # if adding this element to an existing class # will increase its variance beyond the limit, break # the class at this point, setting the lower_class_limit # at this point. if variance_combinations[l][j] >= (variance + variance_combinations[i4][j - 1]) lower_class_limits[l][j] = lower_class_limit variance_combinations[l][j] = variance + variance_combinations[i4][j - 1] end end end end lower_class_limits[l][1] = 1 variance_combinations[l][1] = variance end [lower_class_limits, variance_combinations] end
ruby
def matrices rows = data.size cols = n_classes # in the original implementation, these matrices are referred to # as `LC` and `OP` # * lower_class_limits (LC): optimal lower class limits # * variance_combinations (OP): optimal variance combinations for all classes lower_class_limits = *Matrix.zero(rows + 1, cols + 1) variance_combinations = *Matrix.zero(rows + 1, cols + 1) # the variance, as computed at each step in the calculation variance = 0 for i in 1..cols lower_class_limits[1][i] = 1 variance_combinations[1][i] = 0 for j in 2..rows variance_combinations[j][i] = Float::INFINITY end end for l in 2..rows sum = 0 # `SZ` originally. this is the sum of the values seen thus far when calculating variance. sum_squares = 0 # `ZSQ` originally. the sum of squares of values seen thus far w = 0 # `WT` originally. This is the number of data points considered so far. for m in 1..l lower_class_limit = l - m + 1 # `III` originally val = data[lower_class_limit - 1] # here we're estimating variance for each potential classing # of the data, for each potential number of classes. `w` # is the number of data points considered so far. w += 1 # increase the current sum and sum-of-squares sum += val sum_squares += (val ** 2) # the variance at this point in the sequence is the difference # between the sum of squares and the total x 2, over the number # of samples. variance = sum_squares - (sum ** 2) / w i4 = lower_class_limit - 1 # `IV` originally if i4 != 0 for j in 2..cols # if adding this element to an existing class # will increase its variance beyond the limit, break # the class at this point, setting the lower_class_limit # at this point. if variance_combinations[l][j] >= (variance + variance_combinations[i4][j - 1]) lower_class_limits[l][j] = lower_class_limit variance_combinations[l][j] = variance + variance_combinations[i4][j - 1] end end end end lower_class_limits[l][1] = 1 variance_combinations[l][1] = variance end [lower_class_limits, variance_combinations] end
[ "def", "matrices", "rows", "=", "data", ".", "size", "cols", "=", "n_classes", "lower_class_limits", "=", "*", "Matrix", ".", "zero", "(", "rows", "+", "1", ",", "cols", "+", "1", ")", "variance_combinations", "=", "*", "Matrix", ".", "zero", "(", "row...
Compute the matrices required for Jenks breaks. These matrices can be used for any classing of data with `classes <= n_classes`
[ "Compute", "the", "matrices", "required", "for", "Jenks", "breaks", ".", "These", "matrices", "can", "be", "used", "for", "any", "classing", "of", "data", "with", "classes", "<", "=", "n_classes" ]
5d134970cb7e2bc0d29ae108d952c081707e02b6
https://github.com/Hamdiakoguz/onedclusterer/blob/5d134970cb7e2bc0d29ae108d952c081707e02b6/lib/onedclusterer/jenks.rb#L67-L133
valid
jvanbaarsen/omdb
lib/omdb/api.rb
Omdb.Api.fetch
def fetch(title, year = "", tomatoes = false, plot = "short") res = network.call({ t: title, y: year, tomatoes: tomatoes, plot: plot }) if res[:data]["Response"] == "False" { status: 404 } else { status: res[:code], movie: parse_movie(res[:data]) } end end
ruby
def fetch(title, year = "", tomatoes = false, plot = "short") res = network.call({ t: title, y: year, tomatoes: tomatoes, plot: plot }) if res[:data]["Response"] == "False" { status: 404 } else { status: res[:code], movie: parse_movie(res[:data]) } end end
[ "def", "fetch", "(", "title", ",", "year", "=", "\"\"", ",", "tomatoes", "=", "false", ",", "plot", "=", "\"short\"", ")", "res", "=", "network", ".", "call", "(", "{", "t", ":", "title", ",", "y", ":", "year", ",", "tomatoes", ":", "tomatoes", "...
fetchs a movie with a given title set tomatoes to true if you want to get the rotten tomatoes ranking set plot to full if you want to have the full, long plot
[ "fetchs", "a", "movie", "with", "a", "given", "title", "set", "tomatoes", "to", "true", "if", "you", "want", "to", "get", "the", "rotten", "tomatoes", "ranking", "set", "plot", "to", "full", "if", "you", "want", "to", "have", "the", "full", "long", "pl...
b9b08658c2c0e7d62536153f8b7f299cfa630709
https://github.com/jvanbaarsen/omdb/blob/b9b08658c2c0e7d62536153f8b7f299cfa630709/lib/omdb/api.rb#L17-L25
valid
jvanbaarsen/omdb
lib/omdb/api.rb
Omdb.Api.find
def find(id, tomatoes = false, plot = "short") res = network.call({ i: id, tomatoes: tomatoes, plot: plot }) if res[:data]["Response"] == "False" { status: 404 } else { status: res[:code], movie: parse_movie(res[:data]) } end end
ruby
def find(id, tomatoes = false, plot = "short") res = network.call({ i: id, tomatoes: tomatoes, plot: plot }) if res[:data]["Response"] == "False" { status: 404 } else { status: res[:code], movie: parse_movie(res[:data]) } end end
[ "def", "find", "(", "id", ",", "tomatoes", "=", "false", ",", "plot", "=", "\"short\"", ")", "res", "=", "network", ".", "call", "(", "{", "i", ":", "id", ",", "tomatoes", ":", "tomatoes", ",", "plot", ":", "plot", "}", ")", "if", "res", "[", "...
fetches a movie by IMDB id set tomatoes to true if you want to get the rotten tomatoes ranking set plot to full if you want to have the full, long plot
[ "fetches", "a", "movie", "by", "IMDB", "id", "set", "tomatoes", "to", "true", "if", "you", "want", "to", "get", "the", "rotten", "tomatoes", "ranking", "set", "plot", "to", "full", "if", "you", "want", "to", "have", "the", "full", "long", "plot" ]
b9b08658c2c0e7d62536153f8b7f299cfa630709
https://github.com/jvanbaarsen/omdb/blob/b9b08658c2c0e7d62536153f8b7f299cfa630709/lib/omdb/api.rb#L30-L38
valid
G5/g5_authentication_client
lib/g5_authentication_client/configuration.rb
G5AuthenticationClient.Configuration.options
def options VALID_CONFIG_OPTIONS.inject({}) do |option, key| option.merge!(key => send(key)) end end
ruby
def options VALID_CONFIG_OPTIONS.inject({}) do |option, key| option.merge!(key => send(key)) end end
[ "def", "options", "VALID_CONFIG_OPTIONS", ".", "inject", "(", "{", "}", ")", "do", "|", "option", ",", "key", "|", "option", ".", "merge!", "(", "key", "=>", "send", "(", "key", ")", ")", "end", "end" ]
Create a hash of configuration options and their values. @return [Hash<Symbol,Object>] the options hash
[ "Create", "a", "hash", "of", "configuration", "options", "and", "their", "values", "." ]
c9e470b006706e68682692772b6e3d43ff782f78
https://github.com/G5/g5_authentication_client/blob/c9e470b006706e68682692772b6e3d43ff782f78/lib/g5_authentication_client/configuration.rb#L123-L127
valid
G5/g5_authentication_client
lib/g5_authentication_client/client.rb
G5AuthenticationClient.Client.create_user
def create_user(options={}) user=User.new(options) user.validate_for_create! body = user_hash(user.to_hash) response=oauth_access_token.post('/v1/users', body: body) User.new(response.parsed) end
ruby
def create_user(options={}) user=User.new(options) user.validate_for_create! body = user_hash(user.to_hash) response=oauth_access_token.post('/v1/users', body: body) User.new(response.parsed) end
[ "def", "create_user", "(", "options", "=", "{", "}", ")", "user", "=", "User", ".", "new", "(", "options", ")", "user", ".", "validate_for_create!", "body", "=", "user_hash", "(", "user", ".", "to_hash", ")", "response", "=", "oauth_access_token", ".", "...
Create a user from the options @param [Hash] options @option options [String] :email The new user's email address @option options [String] :password The new user's password @option options [String] :password_confirmation The new user's password confirmation string @return [G5AuthenticationClient::User]
[ "Create", "a", "user", "from", "the", "options" ]
c9e470b006706e68682692772b6e3d43ff782f78
https://github.com/G5/g5_authentication_client/blob/c9e470b006706e68682692772b6e3d43ff782f78/lib/g5_authentication_client/client.rb#L100-L106
valid
G5/g5_authentication_client
lib/g5_authentication_client/client.rb
G5AuthenticationClient.Client.update_user
def update_user(options={}) user=User.new(options) user.validate! response=oauth_access_token.put("/v1/users/#{user.id}", body: user_hash(user.to_hash)) User.new(response.parsed) end
ruby
def update_user(options={}) user=User.new(options) user.validate! response=oauth_access_token.put("/v1/users/#{user.id}", body: user_hash(user.to_hash)) User.new(response.parsed) end
[ "def", "update_user", "(", "options", "=", "{", "}", ")", "user", "=", "User", ".", "new", "(", "options", ")", "user", ".", "validate!", "response", "=", "oauth_access_token", ".", "put", "(", "\"/v1/users/#{user.id}\"", ",", "body", ":", "user_hash", "("...
Update an existing user @param [Hash] options @option options [String] :email The new user's email address @option options [String] :password The new user's password @option options [String] :password_confirmation The new user's password confirmation string @return [G5AuthenticationClient::User]
[ "Update", "an", "existing", "user" ]
c9e470b006706e68682692772b6e3d43ff782f78
https://github.com/G5/g5_authentication_client/blob/c9e470b006706e68682692772b6e3d43ff782f78/lib/g5_authentication_client/client.rb#L114-L119
valid
G5/g5_authentication_client
lib/g5_authentication_client/client.rb
G5AuthenticationClient.Client.find_user_by_email
def find_user_by_email(email) response = oauth_access_token.get('/v1/users', params: { email: email }) user = response.parsed.first if user user=User.new(user) end user end
ruby
def find_user_by_email(email) response = oauth_access_token.get('/v1/users', params: { email: email }) user = response.parsed.first if user user=User.new(user) end user end
[ "def", "find_user_by_email", "(", "email", ")", "response", "=", "oauth_access_token", ".", "get", "(", "'/v1/users'", ",", "params", ":", "{", "email", ":", "email", "}", ")", "user", "=", "response", ".", "parsed", ".", "first", "if", "user", "user", "...
Find a user by email @param [String] email address @return [G5AuthenticationClient::User]
[ "Find", "a", "user", "by", "email" ]
c9e470b006706e68682692772b6e3d43ff782f78
https://github.com/G5/g5_authentication_client/blob/c9e470b006706e68682692772b6e3d43ff782f78/lib/g5_authentication_client/client.rb#L124-L131
valid
G5/g5_authentication_client
lib/g5_authentication_client/client.rb
G5AuthenticationClient.Client.sign_out_url
def sign_out_url(redirect_url=nil) auth_server_url = Addressable::URI.parse(endpoint) auth_server_url.path = '/users/sign_out' auth_server_url.query_values = {redirect_url: redirect_url} if redirect_url auth_server_url.to_s end
ruby
def sign_out_url(redirect_url=nil) auth_server_url = Addressable::URI.parse(endpoint) auth_server_url.path = '/users/sign_out' auth_server_url.query_values = {redirect_url: redirect_url} if redirect_url auth_server_url.to_s end
[ "def", "sign_out_url", "(", "redirect_url", "=", "nil", ")", "auth_server_url", "=", "Addressable", "::", "URI", ".", "parse", "(", "endpoint", ")", "auth_server_url", ".", "path", "=", "'/users/sign_out'", "auth_server_url", ".", "query_values", "=", "{", "redi...
Return the URL for signing out of the auth server. Clients should redirect to this URL to globally sign out. @param [String] redirect_url the URL that the auth server should redirect back to after sign out @return [String] the auth server endpoint for signing out
[ "Return", "the", "URL", "for", "signing", "out", "of", "the", "auth", "server", ".", "Clients", "should", "redirect", "to", "this", "URL", "to", "globally", "sign", "out", "." ]
c9e470b006706e68682692772b6e3d43ff782f78
https://github.com/G5/g5_authentication_client/blob/c9e470b006706e68682692772b6e3d43ff782f78/lib/g5_authentication_client/client.rb#L168-L173
valid
G5/g5_authentication_client
lib/g5_authentication_client/client.rb
G5AuthenticationClient.Client.list_users
def list_users response=oauth_access_token.get("/v1/users") response.parsed.collect { |parsed_user| User.new(parsed_user) } end
ruby
def list_users response=oauth_access_token.get("/v1/users") response.parsed.collect { |parsed_user| User.new(parsed_user) } end
[ "def", "list_users", "response", "=", "oauth_access_token", ".", "get", "(", "\"/v1/users\"", ")", "response", ".", "parsed", ".", "collect", "{", "|", "parsed_user", "|", "User", ".", "new", "(", "parsed_user", ")", "}", "end" ]
Return all users from the remote service @return [Array<G5AuthenticationClient::User>]
[ "Return", "all", "users", "from", "the", "remote", "service" ]
c9e470b006706e68682692772b6e3d43ff782f78
https://github.com/G5/g5_authentication_client/blob/c9e470b006706e68682692772b6e3d43ff782f78/lib/g5_authentication_client/client.rb#L177-L180
valid
G5/g5_authentication_client
lib/g5_authentication_client/client.rb
G5AuthenticationClient.Client.list_roles
def list_roles response = oauth_access_token.get('/v1/roles') response.parsed.collect { |parsed_role| Role.new(parsed_role) } end
ruby
def list_roles response = oauth_access_token.get('/v1/roles') response.parsed.collect { |parsed_role| Role.new(parsed_role) } end
[ "def", "list_roles", "response", "=", "oauth_access_token", ".", "get", "(", "'/v1/roles'", ")", "response", ".", "parsed", ".", "collect", "{", "|", "parsed_role", "|", "Role", ".", "new", "(", "parsed_role", ")", "}", "end" ]
Return all user roles from the remote service @return [Array<G5AuthenticationClient::Role>]
[ "Return", "all", "user", "roles", "from", "the", "remote", "service" ]
c9e470b006706e68682692772b6e3d43ff782f78
https://github.com/G5/g5_authentication_client/blob/c9e470b006706e68682692772b6e3d43ff782f78/lib/g5_authentication_client/client.rb#L184-L187
valid
aaronrussell/cloudapp_api
lib/cloudapp/client.rb
CloudApp.Client.bookmark
def bookmark(*args) if args[0].is_a? Array Drop.create(:bookmarks, args) else url, name = args[0], (args[1] || "") Drop.create(:bookmark, {:name => name, :redirect_url => url}) end end
ruby
def bookmark(*args) if args[0].is_a? Array Drop.create(:bookmarks, args) else url, name = args[0], (args[1] || "") Drop.create(:bookmark, {:name => name, :redirect_url => url}) end end
[ "def", "bookmark", "(", "*", "args", ")", "if", "args", "[", "0", "]", ".", "is_a?", "Array", "Drop", ".", "create", "(", ":bookmarks", ",", "args", ")", "else", "url", ",", "name", "=", "args", "[", "0", "]", ",", "(", "args", "[", "1", "]", ...
Create one or more new bookmark drops. Requires authentication. @overload bookmark(url, name = "") @param [String] url url to bookmark @param [String] name name of bookmark @overload bookmark(opts) @param [Array] opts array of bookmark option parameters (containing +:name+ and +:redirect_url+) @return [CloudApp::Drop]
[ "Create", "one", "or", "more", "new", "bookmark", "drops", "." ]
6d28d0541cb0f938a8fc2fed3a2fcaddf5391988
https://github.com/aaronrussell/cloudapp_api/blob/6d28d0541cb0f938a8fc2fed3a2fcaddf5391988/lib/cloudapp/client.rb#L105-L112
valid
aaronrussell/cloudapp_api
lib/cloudapp/client.rb
CloudApp.Client.rename
def rename(id, name = "") drop = Drop.find(id) drop.update(:name => name) end
ruby
def rename(id, name = "") drop = Drop.find(id) drop.update(:name => name) end
[ "def", "rename", "(", "id", ",", "name", "=", "\"\"", ")", "drop", "=", "Drop", ".", "find", "(", "id", ")", "drop", ".", "update", "(", ":name", "=>", "name", ")", "end" ]
Change the name of the drop. Finds the drop by it's slug id, for example "2wr4". Requires authentication. @param [String] id drop id @param [String] name new drop name @return [CloudApp::Drop]
[ "Change", "the", "name", "of", "the", "drop", "." ]
6d28d0541cb0f938a8fc2fed3a2fcaddf5391988
https://github.com/aaronrussell/cloudapp_api/blob/6d28d0541cb0f938a8fc2fed3a2fcaddf5391988/lib/cloudapp/client.rb#L135-L138
valid
aaronrussell/cloudapp_api
lib/cloudapp/client.rb
CloudApp.Client.privacy
def privacy(id, privacy = false) drop = Drop.find(id) drop.update(:private => privacy) end
ruby
def privacy(id, privacy = false) drop = Drop.find(id) drop.update(:private => privacy) end
[ "def", "privacy", "(", "id", ",", "privacy", "=", "false", ")", "drop", "=", "Drop", ".", "find", "(", "id", ")", "drop", ".", "update", "(", ":private", "=>", "privacy", ")", "end" ]
Modify a drop with a private URL to have a public URL or vice versa. Finds the drop by it's slug id, for example "2wr4". Requires authentication. @param [String] id drop id @param [Boolean] privacy privacy setting @return [CloudApp::Drop]
[ "Modify", "a", "drop", "with", "a", "private", "URL", "to", "have", "a", "public", "URL", "or", "vice", "versa", "." ]
6d28d0541cb0f938a8fc2fed3a2fcaddf5391988
https://github.com/aaronrussell/cloudapp_api/blob/6d28d0541cb0f938a8fc2fed3a2fcaddf5391988/lib/cloudapp/client.rb#L149-L152
valid
aaronrussell/cloudapp_api
lib/cloudapp/base.rb
CloudApp.Base.load
def load(attributes = {}) attributes.each do |key, val| if key =~ /^.*_at$/ and val # if this is a date/time key and it's not nil, try to parse it first # as DateTime, then as Date only begin dt = DateTime.strptime(val, "%Y-%m-%dT%H:%M:%SZ") newval = Time.utc(dt.year, dt.month, dt.day, dt.hour, dt.min, dt.sec) rescue ArgumentError => ex newval = DateTime.strptime(val, "%Y-%m-%d") end self.instance_variable_set("@#{key}", newval) else self.instance_variable_set("@#{key}", val) end end end
ruby
def load(attributes = {}) attributes.each do |key, val| if key =~ /^.*_at$/ and val # if this is a date/time key and it's not nil, try to parse it first # as DateTime, then as Date only begin dt = DateTime.strptime(val, "%Y-%m-%dT%H:%M:%SZ") newval = Time.utc(dt.year, dt.month, dt.day, dt.hour, dt.min, dt.sec) rescue ArgumentError => ex newval = DateTime.strptime(val, "%Y-%m-%d") end self.instance_variable_set("@#{key}", newval) else self.instance_variable_set("@#{key}", val) end end end
[ "def", "load", "(", "attributes", "=", "{", "}", ")", "attributes", ".", "each", "do", "|", "key", ",", "val", "|", "if", "key", "=~", "/", "/", "and", "val", "begin", "dt", "=", "DateTime", ".", "strptime", "(", "val", ",", "\"%Y-%m-%dT%H:%M:%SZ\"",...
Sets the attributes for object. @param [Hash] attributes
[ "Sets", "the", "attributes", "for", "object", "." ]
6d28d0541cb0f938a8fc2fed3a2fcaddf5391988
https://github.com/aaronrussell/cloudapp_api/blob/6d28d0541cb0f938a8fc2fed3a2fcaddf5391988/lib/cloudapp/base.rb#L60-L76
valid
mattetti/wd-sinatra
lib/wd_sinatra/app_loader.rb
WDSinatra.AppLoader.load_environment
def load_environment(env=RACK_ENV) # Load the default which can be overwritten or extended by specific # env config files. require File.join(root_path, 'config', 'environments', 'default.rb') env_file = File.join(root_path, "config", "environments", "#{env}.rb") if File.exist?(env_file) require env_file else debug_msg = "Environment file: #{env_file} couldn't be found, using only the default environment config instead." unless env == 'development' end # making sure we have a LOGGER constant defined. unless Object.const_defined?(:LOGGER) Object.const_set(:LOGGER, Logger.new($stdout)) end LOGGER.debug(debug_msg) if debug_msg end
ruby
def load_environment(env=RACK_ENV) # Load the default which can be overwritten or extended by specific # env config files. require File.join(root_path, 'config', 'environments', 'default.rb') env_file = File.join(root_path, "config", "environments", "#{env}.rb") if File.exist?(env_file) require env_file else debug_msg = "Environment file: #{env_file} couldn't be found, using only the default environment config instead." unless env == 'development' end # making sure we have a LOGGER constant defined. unless Object.const_defined?(:LOGGER) Object.const_set(:LOGGER, Logger.new($stdout)) end LOGGER.debug(debug_msg) if debug_msg end
[ "def", "load_environment", "(", "env", "=", "RACK_ENV", ")", "require", "File", ".", "join", "(", "root_path", ",", "'config'", ",", "'environments'", ",", "'default.rb'", ")", "env_file", "=", "File", ".", "join", "(", "root_path", ",", "\"config\"", ",", ...
Loads an environment specific config if available, the config file is where the logger should be set if it was not, we are using stdout.
[ "Loads", "an", "environment", "specific", "config", "if", "available", "the", "config", "file", "is", "where", "the", "logger", "should", "be", "set", "if", "it", "was", "not", "we", "are", "using", "stdout", "." ]
cead82665da00dfefc800132ecfc2ab58010eb46
https://github.com/mattetti/wd-sinatra/blob/cead82665da00dfefc800132ecfc2ab58010eb46/lib/wd_sinatra/app_loader.rb#L55-L70
valid
mattetti/wd-sinatra
lib/wd_sinatra/app_loader.rb
WDSinatra.AppLoader.load_apis
def load_apis Dir.glob(File.join(root_path, "api", "**", "*.rb")).each do |api| require api end end
ruby
def load_apis Dir.glob(File.join(root_path, "api", "**", "*.rb")).each do |api| require api end end
[ "def", "load_apis", "Dir", ".", "glob", "(", "File", ".", "join", "(", "root_path", ",", "\"api\"", ",", "\"**\"", ",", "\"*.rb\"", ")", ")", ".", "each", "do", "|", "api", "|", "require", "api", "end", "end" ]
DSL routes are located in the api folder
[ "DSL", "routes", "are", "located", "in", "the", "api", "folder" ]
cead82665da00dfefc800132ecfc2ab58010eb46
https://github.com/mattetti/wd-sinatra/blob/cead82665da00dfefc800132ecfc2ab58010eb46/lib/wd_sinatra/app_loader.rb#L98-L102
valid
tribune/is_it_working
lib/is_it_working/filter.rb
IsItWorking.Filter.run
def run status = Status.new(name) runner = (async ? AsyncRunner : SyncRunner).new do t = Time.now begin @check.call(status) rescue Exception => e status.fail("#{name} error: #{e.inspect}") end status.time = Time.now - t end runner.filter_status = status runner end
ruby
def run status = Status.new(name) runner = (async ? AsyncRunner : SyncRunner).new do t = Time.now begin @check.call(status) rescue Exception => e status.fail("#{name} error: #{e.inspect}") end status.time = Time.now - t end runner.filter_status = status runner end
[ "def", "run", "status", "=", "Status", ".", "new", "(", "name", ")", "runner", "=", "(", "async", "?", "AsyncRunner", ":", "SyncRunner", ")", ".", "new", "do", "t", "=", "Time", ".", "now", "begin", "@check", ".", "call", "(", "status", ")", "rescu...
Create a new filter to run a status check. The name is used for display purposes. Run a status the status check. This method keeps track of the time it took to run the check and will trap any unexpected exceptions and report them as failures.
[ "Create", "a", "new", "filter", "to", "run", "a", "status", "check", ".", "The", "name", "is", "used", "for", "display", "purposes", ".", "Run", "a", "status", "the", "status", "check", ".", "This", "method", "keeps", "track", "of", "the", "time", "it"...
44645f8f676dd9fd25cff2d93cfdff0876cef36d
https://github.com/tribune/is_it_working/blob/44645f8f676dd9fd25cff2d93cfdff0876cef36d/lib/is_it_working/filter.rb#L30-L43
valid
tribune/is_it_working
lib/is_it_working/handler.rb
IsItWorking.Handler.call
def call(env) if @app.nil? || env[PATH_INFO] == @route_path statuses = [] t = Time.now statuses = Filter.run_filters(@filters) render(statuses, Time.now - t) else @app.call(env) end end
ruby
def call(env) if @app.nil? || env[PATH_INFO] == @route_path statuses = [] t = Time.now statuses = Filter.run_filters(@filters) render(statuses, Time.now - t) else @app.call(env) end end
[ "def", "call", "(", "env", ")", "if", "@app", ".", "nil?", "||", "env", "[", "PATH_INFO", "]", "==", "@route_path", "statuses", "=", "[", "]", "t", "=", "Time", ".", "now", "statuses", "=", "Filter", ".", "run_filters", "(", "@filters", ")", "render"...
Create a new handler. This method can take a block which will yield itself so it can be configured. The handler can be set up in one of two ways. If no arguments are supplied, it will return a regular Rack handler that can be used with a rackup +run+ method or in a Rails 3+ routes.rb file. Otherwise, an application stack can be supplied in the first argument and a routing path in the second (defaults to <tt>/is_it_working</tt>) so it can be used with the rackup +use+ method or in Rails.middleware.
[ "Create", "a", "new", "handler", ".", "This", "method", "can", "take", "a", "block", "which", "will", "yield", "itself", "so", "it", "can", "be", "configured", "." ]
44645f8f676dd9fd25cff2d93cfdff0876cef36d
https://github.com/tribune/is_it_working/blob/44645f8f676dd9fd25cff2d93cfdff0876cef36d/lib/is_it_working/handler.rb#L41-L50
valid
tribune/is_it_working
lib/is_it_working/handler.rb
IsItWorking.Handler.check
def check (name, *options_or_check, &block) raise ArgumentError("Too many arguments to #{self.class.name}#check") if options_or_check.size > 2 check = nil options = {:async => true} unless options_or_check.empty? if options_or_check[0].is_a?(Hash) options = options.merge(options_or_check[0]) else check = options_or_check[0] end if options_or_check[1].is_a?(Hash) options = options.merge(options_or_check[1]) end end unless check if block check = block else check = lookup_check(name, options) end end @filters << Filter.new(name, check, options[:async]) end
ruby
def check (name, *options_or_check, &block) raise ArgumentError("Too many arguments to #{self.class.name}#check") if options_or_check.size > 2 check = nil options = {:async => true} unless options_or_check.empty? if options_or_check[0].is_a?(Hash) options = options.merge(options_or_check[0]) else check = options_or_check[0] end if options_or_check[1].is_a?(Hash) options = options.merge(options_or_check[1]) end end unless check if block check = block else check = lookup_check(name, options) end end @filters << Filter.new(name, check, options[:async]) end
[ "def", "check", "(", "name", ",", "*", "options_or_check", ",", "&", "block", ")", "raise", "ArgumentError", "(", "\"Too many arguments to #{self.class.name}#check\"", ")", "if", "options_or_check", ".", "size", ">", "2", "check", "=", "nil", "options", "=", "{"...
Add a status check to the handler. If a block is given, it will be used as the status check and will be yielded to with a Status object. If the name matches one of the pre-defined status check classes, a new instance will be created using the rest of the arguments as the arguments to the initializer. The pre-defined classes are: * <tt>:action_mailer</tt> - Check if the send mail configuration used by ActionMailer is available * <tt>:active_record</tt> - Check if the database connection for an ActiveRecord class is up * <tt>:dalli</tt> - DalliCheck checks if all the servers in a MemCache cluster are available using dalli * <tt>:directory</tt> - DirectoryCheck checks for the accessibilty of a file system directory * <tt>:ping</tt> - Check if a host is reachable and accepting connections on a port * <tt>:url</tt> - Check if a getting a URL returns a success response
[ "Add", "a", "status", "check", "to", "the", "handler", "." ]
44645f8f676dd9fd25cff2d93cfdff0876cef36d
https://github.com/tribune/is_it_working/blob/44645f8f676dd9fd25cff2d93cfdff0876cef36d/lib/is_it_working/handler.rb#L74-L99
valid
tribune/is_it_working
lib/is_it_working/handler.rb
IsItWorking.Handler.lookup_check
def lookup_check(name, options) #:nodoc: check_class_name = "#{name.to_s.gsub(/(^|_)([a-z])/){|m| m.sub('_', '').upcase}}Check" check = nil if IsItWorking.const_defined?(check_class_name) check_class = IsItWorking.const_get(check_class_name) check = check_class.new(options) else raise ArgumentError.new("Check not defined #{check_class_name}") end check end
ruby
def lookup_check(name, options) #:nodoc: check_class_name = "#{name.to_s.gsub(/(^|_)([a-z])/){|m| m.sub('_', '').upcase}}Check" check = nil if IsItWorking.const_defined?(check_class_name) check_class = IsItWorking.const_get(check_class_name) check = check_class.new(options) else raise ArgumentError.new("Check not defined #{check_class_name}") end check end
[ "def", "lookup_check", "(", "name", ",", "options", ")", "check_class_name", "=", "\"#{name.to_s.gsub(/(^|_)([a-z])/){|m| m.sub('_', '').upcase}}Check\"", "check", "=", "nil", "if", "IsItWorking", ".", "const_defined?", "(", "check_class_name", ")", "check_class", "=", "I...
Lookup a status check filter from the name and arguments
[ "Lookup", "a", "status", "check", "filter", "from", "the", "name", "and", "arguments" ]
44645f8f676dd9fd25cff2d93cfdff0876cef36d
https://github.com/tribune/is_it_working/blob/44645f8f676dd9fd25cff2d93cfdff0876cef36d/lib/is_it_working/handler.rb#L112-L122
valid
tribune/is_it_working
lib/is_it_working/handler.rb
IsItWorking.Handler.render
def render(statuses, elapsed_time) #:nodoc: fail = statuses.all?{|s| s.success?} headers = { "Content-Type" => "text/plain; charset=utf8", "Cache-Control" => "no-cache", "Date" => Time.now.httpdate, } messages = [] statuses.each do |status| status.messages.each do |m| messages << "#{m.ok? ? 'OK: ' : 'FAIL:'} #{status.name} - #{m.message} (#{status.time ? sprintf('%0.000f', status.time * 1000) : '?'}ms)" end end info = [] info << "Host: #{@hostname}" unless @hostname.size == 0 info << "PID: #{$$}" info << "Timestamp: #{Time.now.iso8601}" info << "Elapsed Time: #{(elapsed_time * 1000).round}ms" code = (fail ? 200 : 500) [code, headers, [info.join("\n"), "\n\n", messages.join("\n")]] end
ruby
def render(statuses, elapsed_time) #:nodoc: fail = statuses.all?{|s| s.success?} headers = { "Content-Type" => "text/plain; charset=utf8", "Cache-Control" => "no-cache", "Date" => Time.now.httpdate, } messages = [] statuses.each do |status| status.messages.each do |m| messages << "#{m.ok? ? 'OK: ' : 'FAIL:'} #{status.name} - #{m.message} (#{status.time ? sprintf('%0.000f', status.time * 1000) : '?'}ms)" end end info = [] info << "Host: #{@hostname}" unless @hostname.size == 0 info << "PID: #{$$}" info << "Timestamp: #{Time.now.iso8601}" info << "Elapsed Time: #{(elapsed_time * 1000).round}ms" code = (fail ? 200 : 500) [code, headers, [info.join("\n"), "\n\n", messages.join("\n")]] end
[ "def", "render", "(", "statuses", ",", "elapsed_time", ")", "fail", "=", "statuses", ".", "all?", "{", "|", "s", "|", "s", ".", "success?", "}", "headers", "=", "{", "\"Content-Type\"", "=>", "\"text/plain; charset=utf8\"", ",", "\"Cache-Control\"", "=>", "\...
Output the plain text response from calling all the filters.
[ "Output", "the", "plain", "text", "response", "from", "calling", "all", "the", "filters", "." ]
44645f8f676dd9fd25cff2d93cfdff0876cef36d
https://github.com/tribune/is_it_working/blob/44645f8f676dd9fd25cff2d93cfdff0876cef36d/lib/is_it_working/handler.rb#L125-L149
valid
tribune/is_it_working
lib/is_it_working/checks/ping_check.rb
IsItWorking.PingCheck.call
def call(status) begin ping(@host, @port) status.ok("#{@alias} is accepting connections on port #{@port.inspect}") rescue Errno::ECONNREFUSED status.fail("#{@alias} is not accepting connections on port #{@port.inspect}") rescue SocketError => e status.fail("connection to #{@alias} on port #{@port.inspect} failed with '#{e.message}'") rescue Timeout::Error status.fail("#{@alias} did not respond on port #{@port.inspect} within #{@timeout} seconds") end end
ruby
def call(status) begin ping(@host, @port) status.ok("#{@alias} is accepting connections on port #{@port.inspect}") rescue Errno::ECONNREFUSED status.fail("#{@alias} is not accepting connections on port #{@port.inspect}") rescue SocketError => e status.fail("connection to #{@alias} on port #{@port.inspect} failed with '#{e.message}'") rescue Timeout::Error status.fail("#{@alias} did not respond on port #{@port.inspect} within #{@timeout} seconds") end end
[ "def", "call", "(", "status", ")", "begin", "ping", "(", "@host", ",", "@port", ")", "status", ".", "ok", "(", "\"#{@alias} is accepting connections on port #{@port.inspect}\"", ")", "rescue", "Errno", "::", "ECONNREFUSED", "status", ".", "fail", "(", "\"#{@alias}...
Check if a host is reachable and accepting connections on a specified port. The host and port to ping are specified with the <tt>:host</tt> and <tt>:port</tt> options. The port can be either a port number or port name for a well known port (i.e. "smtp" and 25 are equivalent). The default timeout to wait for a response is 2 seconds. This can be changed with the <tt>:timeout</tt> option. By default, the host name will be included in the output. If this could pose a security risk by making the existence of the host known to the world, you can supply the <tt>:alias</tt> option which will be used for output purposes. In general, you should supply this option unless the host is on a private network behind a firewall. === Example IsItWorking::Handler.new do |h| h.check :ping, :host => "example.com", :port => "ftp", :timeout => 4 end
[ "Check", "if", "a", "host", "is", "reachable", "and", "accepting", "connections", "on", "a", "specified", "port", "." ]
44645f8f676dd9fd25cff2d93cfdff0876cef36d
https://github.com/tribune/is_it_working/blob/44645f8f676dd9fd25cff2d93cfdff0876cef36d/lib/is_it_working/checks/ping_check.rb#L32-L43
valid
LynxEyes/bootstrap_admin
lib/bootstrap_admin/controller_helpers.rb
BootstrapAdmin.ControllerHelpers.respond_to?
def respond_to? method, include_private = false true if bootstrap_admin_config.respond_to? method super method, include_private end
ruby
def respond_to? method, include_private = false true if bootstrap_admin_config.respond_to? method super method, include_private end
[ "def", "respond_to?", "method", ",", "include_private", "=", "false", "true", "if", "bootstrap_admin_config", ".", "respond_to?", "method", "super", "method", ",", "include_private", "end" ]
self responds_to bootstrap_admin_config methods via method_missing!
[ "self", "responds_to", "bootstrap_admin_config", "methods", "via", "method_missing!" ]
f0f1b265a4f05bc65724c540b90a1f0425a772d8
https://github.com/LynxEyes/bootstrap_admin/blob/f0f1b265a4f05bc65724c540b90a1f0425a772d8/lib/bootstrap_admin/controller_helpers.rb#L69-L72
valid
tribune/is_it_working
lib/is_it_working/checks/url_check.rb
IsItWorking.UrlCheck.instantiate_http
def instantiate_http #:nodoc: http_class = nil if @proxy && @proxy[:host] http_class = Net::HTTP::Proxy(@proxy[:host], @proxy[:port], @proxy[:username], @proxy[:password]) else http_class = Net::HTTP end http = http_class.new(@uri.host, @uri.port) if @uri.scheme == 'https' http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_PEER end http.open_timeout = @open_timeout http.read_timeout = @read_timeout return http end
ruby
def instantiate_http #:nodoc: http_class = nil if @proxy && @proxy[:host] http_class = Net::HTTP::Proxy(@proxy[:host], @proxy[:port], @proxy[:username], @proxy[:password]) else http_class = Net::HTTP end http = http_class.new(@uri.host, @uri.port) if @uri.scheme == 'https' http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_PEER end http.open_timeout = @open_timeout http.read_timeout = @read_timeout return http end
[ "def", "instantiate_http", "http_class", "=", "nil", "if", "@proxy", "&&", "@proxy", "[", ":host", "]", "http_class", "=", "Net", "::", "HTTP", "::", "Proxy", "(", "@proxy", "[", ":host", "]", ",", "@proxy", "[", ":port", "]", ",", "@proxy", "[", ":use...
Create an HTTP object with the options set.
[ "Create", "an", "HTTP", "object", "with", "the", "options", "set", "." ]
44645f8f676dd9fd25cff2d93cfdff0876cef36d
https://github.com/tribune/is_it_working/blob/44645f8f676dd9fd25cff2d93cfdff0876cef36d/lib/is_it_working/checks/url_check.rb#L51-L69
valid
tribune/is_it_working
lib/is_it_working/checks/url_check.rb
IsItWorking.UrlCheck.perform_http_request
def perform_http_request #:nodoc: request = Net::HTTP::Get.new(@uri.request_uri, @headers) request.basic_auth(@username, @password) if @username || @password http = instantiate_http http.start do http.request(request) end end
ruby
def perform_http_request #:nodoc: request = Net::HTTP::Get.new(@uri.request_uri, @headers) request.basic_auth(@username, @password) if @username || @password http = instantiate_http http.start do http.request(request) end end
[ "def", "perform_http_request", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "@uri", ".", "request_uri", ",", "@headers", ")", "request", ".", "basic_auth", "(", "@username", ",", "@password", ")", "if", "@username", "||", "@password", ...
Perform an HTTP request and return the response
[ "Perform", "an", "HTTP", "request", "and", "return", "the", "response" ]
44645f8f676dd9fd25cff2d93cfdff0876cef36d
https://github.com/tribune/is_it_working/blob/44645f8f676dd9fd25cff2d93cfdff0876cef36d/lib/is_it_working/checks/url_check.rb#L72-L79
valid
Undev/libftdi-ruby
lib/ftdi.rb
Ftdi.Context.usb_open
def usb_open(vendor, product) raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum) raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum) check_result(Ftdi.ftdi_usb_open(ctx, vendor, product)) end
ruby
def usb_open(vendor, product) raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum) raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum) check_result(Ftdi.ftdi_usb_open(ctx, vendor, product)) end
[ "def", "usb_open", "(", "vendor", ",", "product", ")", "raise", "ArgumentError", ".", "new", "(", "'vendor should be Fixnum'", ")", "unless", "vendor", ".", "kind_of?", "(", "Fixnum", ")", "raise", "ArgumentError", ".", "new", "(", "'product should be Fixnum'", ...
Opens the first device with a given vendor and product ids. @param [Fixnum] vendor Vendor id. @param [Fixnum] product Product id. @return [NilClass] nil @raise [StatusCodeError] libftdi reports error. @raise [ArgumentError] Bad arguments.
[ "Opens", "the", "first", "device", "with", "a", "given", "vendor", "and", "product", "ids", "." ]
6fe45a1580df6db08324a237f56d2136fe721dcc
https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L175-L179
valid
Undev/libftdi-ruby
lib/ftdi.rb
Ftdi.Context.usb_open_desc
def usb_open_desc(vendor, product, description, serial) raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum) raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum) check_result(Ftdi.ftdi_usb_open_desc(ctx, vendor, product, description, serial)) end
ruby
def usb_open_desc(vendor, product, description, serial) raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum) raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum) check_result(Ftdi.ftdi_usb_open_desc(ctx, vendor, product, description, serial)) end
[ "def", "usb_open_desc", "(", "vendor", ",", "product", ",", "description", ",", "serial", ")", "raise", "ArgumentError", ".", "new", "(", "'vendor should be Fixnum'", ")", "unless", "vendor", ".", "kind_of?", "(", "Fixnum", ")", "raise", "ArgumentError", ".", ...
Opens the first device with a given vendor and product ids, description and serial. @param [Fixnum] vendor Vendor id. @param [Fixnum] product Product id. @param [String] description Description to search for. Use nil if not needed. @param [String] serial Serial to search for. Use nil if not needed. @return [NilClass] nil @raise [StatusCodeError] libftdi reports error. @raise [ArgumentError] Bad arguments.
[ "Opens", "the", "first", "device", "with", "a", "given", "vendor", "and", "product", "ids", "description", "and", "serial", "." ]
6fe45a1580df6db08324a237f56d2136fe721dcc
https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L189-L193
valid
Undev/libftdi-ruby
lib/ftdi.rb
Ftdi.Context.usb_open_desc_index
def usb_open_desc_index(vendor, product, description, serial, index) raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum) raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum) raise ArgumentError.new('index should be Fixnum') unless index.kind_of?(Fixnum) raise ArgumentError.new('index should be greater than or equal to zero') if index < 0 check_result(Ftdi.ftdi_usb_open_desc_index(ctx, vendor, product, description, serial, index)) end
ruby
def usb_open_desc_index(vendor, product, description, serial, index) raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum) raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum) raise ArgumentError.new('index should be Fixnum') unless index.kind_of?(Fixnum) raise ArgumentError.new('index should be greater than or equal to zero') if index < 0 check_result(Ftdi.ftdi_usb_open_desc_index(ctx, vendor, product, description, serial, index)) end
[ "def", "usb_open_desc_index", "(", "vendor", ",", "product", ",", "description", ",", "serial", ",", "index", ")", "raise", "ArgumentError", ".", "new", "(", "'vendor should be Fixnum'", ")", "unless", "vendor", ".", "kind_of?", "(", "Fixnum", ")", "raise", "A...
Opens the index-th device with a given vendor and product ids, description and serial. @param [Fixnum] vendor Vendor id. @param [Fixnum] product Product id. @param [String] description Description to search for. Use nil if not needed. @param [String] serial Serial to search for. Use nil if not needed. @param [Fixnum] index Number of matching device to open if there are more than one, starts with 0. @return [NilClass] nil @raise [StatusCodeError] libftdi reports error. @raise [ArgumentError] Bad arguments.
[ "Opens", "the", "index", "-", "th", "device", "with", "a", "given", "vendor", "and", "product", "ids", "description", "and", "serial", "." ]
6fe45a1580df6db08324a237f56d2136fe721dcc
https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L204-L210
valid
Undev/libftdi-ruby
lib/ftdi.rb
Ftdi.Context.baudrate=
def baudrate=(new_baudrate) raise ArgumentError.new('baudrate should be Fixnum') unless new_baudrate.kind_of?(Fixnum) check_result(Ftdi.ftdi_set_baudrate(ctx, new_baudrate)) end
ruby
def baudrate=(new_baudrate) raise ArgumentError.new('baudrate should be Fixnum') unless new_baudrate.kind_of?(Fixnum) check_result(Ftdi.ftdi_set_baudrate(ctx, new_baudrate)) end
[ "def", "baudrate", "=", "(", "new_baudrate", ")", "raise", "ArgumentError", ".", "new", "(", "'baudrate should be Fixnum'", ")", "unless", "new_baudrate", ".", "kind_of?", "(", "Fixnum", ")", "check_result", "(", "Ftdi", ".", "ftdi_set_baudrate", "(", "ctx", ","...
Sets the chip baud rate. @raise [StatusCodeError] libftdi reports error. @raise [ArgumentError] Bad arguments. @return [NilClass] nil
[ "Sets", "the", "chip", "baud", "rate", "." ]
6fe45a1580df6db08324a237f56d2136fe721dcc
https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L236-L239
valid
Undev/libftdi-ruby
lib/ftdi.rb
Ftdi.Context.write_data_chunksize
def write_data_chunksize p = FFI::MemoryPointer.new(:uint, 1) check_result(Ftdi.ftdi_write_data_get_chunksize(ctx, p)) p.read_uint end
ruby
def write_data_chunksize p = FFI::MemoryPointer.new(:uint, 1) check_result(Ftdi.ftdi_write_data_get_chunksize(ctx, p)) p.read_uint end
[ "def", "write_data_chunksize", "p", "=", "FFI", "::", "MemoryPointer", ".", "new", "(", ":uint", ",", "1", ")", "check_result", "(", "Ftdi", ".", "ftdi_write_data_get_chunksize", "(", "ctx", ",", "p", ")", ")", "p", ".", "read_uint", "end" ]
Gets write buffer chunk size. @return [Fixnum] Write buffer chunk size. @raise [StatusCodeError] libftdi reports error. @see #write_data_chunksize=
[ "Gets", "write", "buffer", "chunk", "size", "." ]
6fe45a1580df6db08324a237f56d2136fe721dcc
https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L289-L293
valid
Undev/libftdi-ruby
lib/ftdi.rb
Ftdi.Context.write_data
def write_data(bytes) bytes = bytes.pack('c*') if bytes.respond_to?(:pack) size = bytes.respond_to?(:bytesize) ? bytes.bytesize : bytes.size mem_buf = FFI::MemoryPointer.new(:char, size) mem_buf.put_bytes(0, bytes) bytes_written = Ftdi.ftdi_write_data(ctx, mem_buf, size) check_result(bytes_written) bytes_written end
ruby
def write_data(bytes) bytes = bytes.pack('c*') if bytes.respond_to?(:pack) size = bytes.respond_to?(:bytesize) ? bytes.bytesize : bytes.size mem_buf = FFI::MemoryPointer.new(:char, size) mem_buf.put_bytes(0, bytes) bytes_written = Ftdi.ftdi_write_data(ctx, mem_buf, size) check_result(bytes_written) bytes_written end
[ "def", "write_data", "(", "bytes", ")", "bytes", "=", "bytes", ".", "pack", "(", "'c*'", ")", "if", "bytes", ".", "respond_to?", "(", ":pack", ")", "size", "=", "bytes", ".", "respond_to?", "(", ":bytesize", ")", "?", "bytes", ".", "bytesize", ":", "...
Writes data. @param [String, Array] bytes String or array of integers that will be interpreted as bytes using pack('c*'). @return [Fixnum] Number of written bytes. @raise [StatusCodeError] libftdi reports error.
[ "Writes", "data", "." ]
6fe45a1580df6db08324a237f56d2136fe721dcc
https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L310-L318
valid
Undev/libftdi-ruby
lib/ftdi.rb
Ftdi.Context.read_data_chunksize
def read_data_chunksize p = FFI::MemoryPointer.new(:uint, 1) check_result(Ftdi.ftdi_read_data_get_chunksize(ctx, p)) p.read_uint end
ruby
def read_data_chunksize p = FFI::MemoryPointer.new(:uint, 1) check_result(Ftdi.ftdi_read_data_get_chunksize(ctx, p)) p.read_uint end
[ "def", "read_data_chunksize", "p", "=", "FFI", "::", "MemoryPointer", ".", "new", "(", ":uint", ",", "1", ")", "check_result", "(", "Ftdi", ".", "ftdi_read_data_get_chunksize", "(", "ctx", ",", "p", ")", ")", "p", ".", "read_uint", "end" ]
Gets read buffer chunk size. @return [Fixnum] Read buffer chunk size. @raise [StatusCodeError] libftdi reports error. @see #read_data_chunksize=
[ "Gets", "read", "buffer", "chunk", "size", "." ]
6fe45a1580df6db08324a237f56d2136fe721dcc
https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L324-L328
valid
Undev/libftdi-ruby
lib/ftdi.rb
Ftdi.Context.read_data
def read_data chunksize = read_data_chunksize p = FFI::MemoryPointer.new(:char, chunksize) bytes_read = Ftdi.ftdi_read_data(ctx, p, chunksize) check_result(bytes_read) r = p.read_bytes(bytes_read) r.force_encoding("ASCII-8BIT") if r.respond_to?(:force_encoding) r end
ruby
def read_data chunksize = read_data_chunksize p = FFI::MemoryPointer.new(:char, chunksize) bytes_read = Ftdi.ftdi_read_data(ctx, p, chunksize) check_result(bytes_read) r = p.read_bytes(bytes_read) r.force_encoding("ASCII-8BIT") if r.respond_to?(:force_encoding) r end
[ "def", "read_data", "chunksize", "=", "read_data_chunksize", "p", "=", "FFI", "::", "MemoryPointer", ".", "new", "(", ":char", ",", "chunksize", ")", "bytes_read", "=", "Ftdi", ".", "ftdi_read_data", "(", "ctx", ",", "p", ",", "chunksize", ")", "check_result...
Reads data in chunks from the chip. Returns when at least one byte is available or when the latency timer has elapsed. Automatically strips the two modem status bytes transfered during every read. @return [String] Bytes read; Empty string if no bytes read. @see #read_data_chunksize @raise [StatusCodeError] libftdi reports error.
[ "Reads", "data", "in", "chunks", "from", "the", "chip", ".", "Returns", "when", "at", "least", "one", "byte", "is", "available", "or", "when", "the", "latency", "timer", "has", "elapsed", ".", "Automatically", "strips", "the", "two", "modem", "status", "by...
6fe45a1580df6db08324a237f56d2136fe721dcc
https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L347-L355
valid
Undev/libftdi-ruby
lib/ftdi.rb
Ftdi.Context.read_pins
def read_pins p = FFI::MemoryPointer.new(:uchar, 1) check_result(Ftdi.ftdi_read_pins(ctx, p)) p.read_uchar end
ruby
def read_pins p = FFI::MemoryPointer.new(:uchar, 1) check_result(Ftdi.ftdi_read_pins(ctx, p)) p.read_uchar end
[ "def", "read_pins", "p", "=", "FFI", "::", "MemoryPointer", ".", "new", "(", ":uchar", ",", "1", ")", "check_result", "(", "Ftdi", ".", "ftdi_read_pins", "(", "ctx", ",", "p", ")", ")", "p", ".", "read_uchar", "end" ]
Directly read pin state, circumventing the read buffer. Useful for bitbang mode. @return [Fixnum] Pins state @raise [StatusCodeError] libftdi reports error. @see #set_bitmode
[ "Directly", "read", "pin", "state", "circumventing", "the", "read", "buffer", ".", "Useful", "for", "bitbang", "mode", "." ]
6fe45a1580df6db08324a237f56d2136fe721dcc
https://github.com/Undev/libftdi-ruby/blob/6fe45a1580df6db08324a237f56d2136fe721dcc/lib/ftdi.rb#L361-L365
valid
dark-panda/geos-extensions
lib/geos/google_maps/api_2.rb
Geos::GoogleMaps::Api2.Geometry.to_g_marker_api2
def to_g_marker_api2(marker_options = {}, options = {}) klass = if options[:short_class] 'GMarker' else 'google.maps.Marker' end opts = Geos::Helper.camelize_keys(marker_options) "new #{klass}(#{self.centroid.to_g_lat_lng(options)}, #{opts.to_json})" end
ruby
def to_g_marker_api2(marker_options = {}, options = {}) klass = if options[:short_class] 'GMarker' else 'google.maps.Marker' end opts = Geos::Helper.camelize_keys(marker_options) "new #{klass}(#{self.centroid.to_g_lat_lng(options)}, #{opts.to_json})" end
[ "def", "to_g_marker_api2", "(", "marker_options", "=", "{", "}", ",", "options", "=", "{", "}", ")", "klass", "=", "if", "options", "[", ":short_class", "]", "'GMarker'", "else", "'google.maps.Marker'", "end", "opts", "=", "Geos", "::", "Helper", ".", "cam...
Returns a new GMarker at the centroid of the geometry. The options Hash works the same as the Google Maps API GMarkerOptions class does, but allows for underscored Ruby-like options which are then converted to the appropriate camel-cased Javascript options.
[ "Returns", "a", "new", "GMarker", "at", "the", "centroid", "of", "the", "geometry", ".", "The", "options", "Hash", "works", "the", "same", "as", "the", "Google", "Maps", "API", "GMarkerOptions", "class", "does", "but", "allows", "for", "underscored", "Ruby",...
59b4b84bbed0d551b696dbea909f26f8aca50498
https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/google_maps/api_2.rb#L39-L49
valid
dark-panda/geos-extensions
lib/geos/google_maps/api_2.rb
Geos::GoogleMaps::Api2.CoordinateSequence.to_g_polyline_api2
def to_g_polyline_api2(polyline_options = {}, options = {}) klass = if options[:short_class] 'GPolyline' else 'google.maps.Polyline' end poly_opts = if polyline_options[:polyline_options] Geos::Helper.camelize_keys(polyline_options[:polyline_options]) end args = [ (polyline_options[:color] ? "'#{Geos::Helper.escape_javascript(polyline_options[:color])}'" : 'null'), (polyline_options[:weight] || 'null'), (polyline_options[:opacity] || 'null'), (poly_opts ? poly_opts.to_json : 'null') ].join(', ') "new #{klass}([#{self.to_g_lat_lng(options).join(', ')}], #{args})" end
ruby
def to_g_polyline_api2(polyline_options = {}, options = {}) klass = if options[:short_class] 'GPolyline' else 'google.maps.Polyline' end poly_opts = if polyline_options[:polyline_options] Geos::Helper.camelize_keys(polyline_options[:polyline_options]) end args = [ (polyline_options[:color] ? "'#{Geos::Helper.escape_javascript(polyline_options[:color])}'" : 'null'), (polyline_options[:weight] || 'null'), (polyline_options[:opacity] || 'null'), (poly_opts ? poly_opts.to_json : 'null') ].join(', ') "new #{klass}([#{self.to_g_lat_lng(options).join(', ')}], #{args})" end
[ "def", "to_g_polyline_api2", "(", "polyline_options", "=", "{", "}", ",", "options", "=", "{", "}", ")", "klass", "=", "if", "options", "[", ":short_class", "]", "'GPolyline'", "else", "'google.maps.Polyline'", "end", "poly_opts", "=", "if", "polyline_options", ...
Returns a new GPolyline. Note that this GPolyline just uses whatever coordinates are found in the sequence in order, so it might not make much sense at all. The options Hash follows the Google Maps API arguments to the GPolyline constructor and include :color, :weight, :opacity and :options. 'null' is used in place of any unset options.
[ "Returns", "a", "new", "GPolyline", ".", "Note", "that", "this", "GPolyline", "just", "uses", "whatever", "coordinates", "are", "found", "in", "the", "sequence", "in", "order", "so", "it", "might", "not", "make", "much", "sense", "at", "all", "." ]
59b4b84bbed0d551b696dbea909f26f8aca50498
https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/google_maps/api_2.rb#L73-L92
valid
dark-panda/geos-extensions
lib/geos/google_maps/api_2.rb
Geos::GoogleMaps::Api2.CoordinateSequence.to_g_polygon_api2
def to_g_polygon_api2(polygon_options = {}, options = {}) klass = if options[:short_class] 'GPolygon' else 'google.maps.Polygon' end poly_opts = if polygon_options[:polygon_options] Geos::Helper.camelize_keys(polygon_options[:polygon_options]) end args = [ (polygon_options[:stroke_color] ? "'#{Geos::Helper.escape_javascript(polygon_options[:stroke_color])}'" : 'null'), (polygon_options[:stroke_weight] || 'null'), (polygon_options[:stroke_opacity] || 'null'), (polygon_options[:fill_color] ? "'#{Geos::Helper.escape_javascript(polygon_options[:fill_color])}'" : 'null'), (polygon_options[:fill_opacity] || 'null'), (poly_opts ? poly_opts.to_json : 'null') ].join(', ') "new #{klass}([#{self.to_g_lat_lng_api2(options).join(', ')}], #{args})" end
ruby
def to_g_polygon_api2(polygon_options = {}, options = {}) klass = if options[:short_class] 'GPolygon' else 'google.maps.Polygon' end poly_opts = if polygon_options[:polygon_options] Geos::Helper.camelize_keys(polygon_options[:polygon_options]) end args = [ (polygon_options[:stroke_color] ? "'#{Geos::Helper.escape_javascript(polygon_options[:stroke_color])}'" : 'null'), (polygon_options[:stroke_weight] || 'null'), (polygon_options[:stroke_opacity] || 'null'), (polygon_options[:fill_color] ? "'#{Geos::Helper.escape_javascript(polygon_options[:fill_color])}'" : 'null'), (polygon_options[:fill_opacity] || 'null'), (poly_opts ? poly_opts.to_json : 'null') ].join(', ') "new #{klass}([#{self.to_g_lat_lng_api2(options).join(', ')}], #{args})" end
[ "def", "to_g_polygon_api2", "(", "polygon_options", "=", "{", "}", ",", "options", "=", "{", "}", ")", "klass", "=", "if", "options", "[", ":short_class", "]", "'GPolygon'", "else", "'google.maps.Polygon'", "end", "poly_opts", "=", "if", "polygon_options", "["...
Returns a new GPolygon. Note that this GPolygon just uses whatever coordinates are found in the sequence in order, so it might not make much sense at all. The options Hash follows the Google Maps API arguments to the GPolygon constructor and include :stroke_color, :stroke_weight, :stroke_opacity, :fill_color, :fill_opacity and :options. 'null' is used in place of any unset options.
[ "Returns", "a", "new", "GPolygon", ".", "Note", "that", "this", "GPolygon", "just", "uses", "whatever", "coordinates", "are", "found", "in", "the", "sequence", "in", "order", "so", "it", "might", "not", "make", "much", "sense", "at", "all", "." ]
59b4b84bbed0d551b696dbea909f26f8aca50498
https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/google_maps/api_2.rb#L102-L122
valid
dark-panda/geos-extensions
lib/geos/geometry.rb
Geos.Geometry.to_bbox
def to_bbox(long_or_short_names = :long) case long_or_short_names when :long { :north => self.north, :east => self.east, :south => self.south, :west => self.west } when :short { :n => self.north, :e => self.east, :s => self.south, :w => self.west } else raise ArgumentError.new("Expected either :long or :short for long_or_short_names argument") end end
ruby
def to_bbox(long_or_short_names = :long) case long_or_short_names when :long { :north => self.north, :east => self.east, :south => self.south, :west => self.west } when :short { :n => self.north, :e => self.east, :s => self.south, :w => self.west } else raise ArgumentError.new("Expected either :long or :short for long_or_short_names argument") end end
[ "def", "to_bbox", "(", "long_or_short_names", "=", ":long", ")", "case", "long_or_short_names", "when", ":long", "{", ":north", "=>", "self", ".", "north", ",", ":east", "=>", "self", ".", "east", ",", ":south", "=>", "self", ".", "south", ",", ":west", ...
Spits out a Hash containing the cardinal points that describe the Geometry's bbox.
[ "Spits", "out", "a", "Hash", "containing", "the", "cardinal", "points", "that", "describe", "the", "Geometry", "s", "bbox", "." ]
59b4b84bbed0d551b696dbea909f26f8aca50498
https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/geometry.rb#L226-L245
valid
dark-panda/geos-extensions
lib/geos/point.rb
Geos.Point.to_georss
def to_georss(*args) xml = Geos::Helper.xml_options(*args)[0] xml.georss(:where) do xml.gml(:Point) do xml.gml(:pos, "#{self.lat} #{self.lng}") end end end
ruby
def to_georss(*args) xml = Geos::Helper.xml_options(*args)[0] xml.georss(:where) do xml.gml(:Point) do xml.gml(:pos, "#{self.lat} #{self.lng}") end end end
[ "def", "to_georss", "(", "*", "args", ")", "xml", "=", "Geos", "::", "Helper", ".", "xml_options", "(", "*", "args", ")", "[", "0", "]", "xml", ".", "georss", "(", ":where", ")", "do", "xml", ".", "gml", "(", ":Point", ")", "do", "xml", ".", "g...
Build some XmlMarkup for GeoRSS. You should include the appropriate georss and gml XML namespaces in your document.
[ "Build", "some", "XmlMarkup", "for", "GeoRSS", ".", "You", "should", "include", "the", "appropriate", "georss", "and", "gml", "XML", "namespaces", "in", "your", "document", "." ]
59b4b84bbed0d551b696dbea909f26f8aca50498
https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/point.rb#L93-L100
valid
dark-panda/geos-extensions
lib/geos/google_maps/api_3.rb
Geos::GoogleMaps.Api3::Geometry.to_g_marker_api3
def to_g_marker_api3(marker_options = {}, options = {}) options = { :escape => [], :lat_lng_options => {} }.merge(options) opts = Geos::Helper.camelize_keys(marker_options) opts[:position] = self.centroid.to_g_lat_lng(options[:lat_lng_options]) json = Geos::Helper.escape_json(opts, Geos::GoogleMaps::Api3Constants::UNESCAPED_MARKER_OPTIONS - options[:escape]) "new google.maps.Marker(#{json})" end
ruby
def to_g_marker_api3(marker_options = {}, options = {}) options = { :escape => [], :lat_lng_options => {} }.merge(options) opts = Geos::Helper.camelize_keys(marker_options) opts[:position] = self.centroid.to_g_lat_lng(options[:lat_lng_options]) json = Geos::Helper.escape_json(opts, Geos::GoogleMaps::Api3Constants::UNESCAPED_MARKER_OPTIONS - options[:escape]) "new google.maps.Marker(#{json})" end
[ "def", "to_g_marker_api3", "(", "marker_options", "=", "{", "}", ",", "options", "=", "{", "}", ")", "options", "=", "{", ":escape", "=>", "[", "]", ",", ":lat_lng_options", "=>", "{", "}", "}", ".", "merge", "(", "options", ")", "opts", "=", "Geos",...
Returns a new Marker at the centroid of the geometry. The options Hash works the same as the Google Maps API MarkerOptions class does, but allows for underscored Ruby-like options which are then converted to the appropriate camel-cased Javascript options.
[ "Returns", "a", "new", "Marker", "at", "the", "centroid", "of", "the", "geometry", ".", "The", "options", "Hash", "works", "the", "same", "as", "the", "Google", "Maps", "API", "MarkerOptions", "class", "does", "but", "allows", "for", "underscored", "Ruby", ...
59b4b84bbed0d551b696dbea909f26f8aca50498
https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/google_maps/api_3.rb#L63-L74
valid
dark-panda/geos-extensions
lib/geos/google_maps/api_3.rb
Geos::GoogleMaps.Api3::CoordinateSequence.to_g_polyline_api3
def to_g_polyline_api3(polyline_options = {}, options = {}) options = { :escape => [], :lat_lng_options => {} }.merge(options) opts = Geos::Helper.camelize_keys(polyline_options) opts[:path] = "[#{self.to_g_lat_lng_api3(options[:lat_lng_options]).join(', ')}]" json = Geos::Helper.escape_json(opts, Geos::GoogleMaps::Api3Constants::UNESCAPED_POLY_OPTIONS - options[:escape]) "new google.maps.Polyline(#{json})" end
ruby
def to_g_polyline_api3(polyline_options = {}, options = {}) options = { :escape => [], :lat_lng_options => {} }.merge(options) opts = Geos::Helper.camelize_keys(polyline_options) opts[:path] = "[#{self.to_g_lat_lng_api3(options[:lat_lng_options]).join(', ')}]" json = Geos::Helper.escape_json(opts, Geos::GoogleMaps::Api3Constants::UNESCAPED_POLY_OPTIONS - options[:escape]) "new google.maps.Polyline(#{json})" end
[ "def", "to_g_polyline_api3", "(", "polyline_options", "=", "{", "}", ",", "options", "=", "{", "}", ")", "options", "=", "{", ":escape", "=>", "[", "]", ",", ":lat_lng_options", "=>", "{", "}", "}", ".", "merge", "(", "options", ")", "opts", "=", "Ge...
Returns a new Polyline. Note that this Polyline just uses whatever coordinates are found in the sequence in order, so it might not make much sense at all. The polyline_options Hash follows the Google Maps API arguments to the Polyline constructor and include :clickable, :geodesic, :map, etc. See the Google Maps API documentation for details. The options Hash allows you to specify if certain arguments should be escaped on output. Usually the options in UNESCAPED_POLY_OPTIONS are escaped, but if for some reason you want some other options to be escaped, pass them along in options[:escape]. The options Hash also passes along options to to_g_lat_lng_api3.
[ "Returns", "a", "new", "Polyline", ".", "Note", "that", "this", "Polyline", "just", "uses", "whatever", "coordinates", "are", "found", "in", "the", "sequence", "in", "order", "so", "it", "might", "not", "make", "much", "sense", "at", "all", "." ]
59b4b84bbed0d551b696dbea909f26f8aca50498
https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/google_maps/api_3.rb#L98-L109
valid
dark-panda/geos-extensions
lib/geos/coordinate_sequence.rb
Geos.CoordinateSequence.to_georss
def to_georss(*args) xml = Geos::Helper.xml_options(*args)[0] xml.georss(:where) do xml.gml(:LineString) do xml.gml(:posList) do xml << self.to_a.collect do |p| "#{p[1]} #{p[0]}" end.join(' ') end end end end
ruby
def to_georss(*args) xml = Geos::Helper.xml_options(*args)[0] xml.georss(:where) do xml.gml(:LineString) do xml.gml(:posList) do xml << self.to_a.collect do |p| "#{p[1]} #{p[0]}" end.join(' ') end end end end
[ "def", "to_georss", "(", "*", "args", ")", "xml", "=", "Geos", "::", "Helper", ".", "xml_options", "(", "*", "args", ")", "[", "0", "]", "xml", ".", "georss", "(", ":where", ")", "do", "xml", ".", "gml", "(", ":LineString", ")", "do", "xml", ".",...
Build some XmlMarkup for GeoRSS GML. You should include the appropriate georss and gml XML namespaces in your document.
[ "Build", "some", "XmlMarkup", "for", "GeoRSS", "GML", ".", "You", "should", "include", "the", "appropriate", "georss", "and", "gml", "XML", "namespaces", "in", "your", "document", "." ]
59b4b84bbed0d551b696dbea909f26f8aca50498
https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/coordinate_sequence.rb#L27-L39
valid
ngelx/solidus_import_products
app/services/solidus_import_products/process_row.rb
SolidusImportProducts.ProcessRow.convert_to_price
def convert_to_price(price_str) raise SolidusImportProducts::Exception::InvalidPrice unless price_str punt = price_str.index('.') coma = price_str.index(',') if !coma.nil? && !punt.nil? price_str.gsub!(punt < coma ? '.' : ',', '') end price_str.tr(',', '.').to_f end
ruby
def convert_to_price(price_str) raise SolidusImportProducts::Exception::InvalidPrice unless price_str punt = price_str.index('.') coma = price_str.index(',') if !coma.nil? && !punt.nil? price_str.gsub!(punt < coma ? '.' : ',', '') end price_str.tr(',', '.').to_f end
[ "def", "convert_to_price", "(", "price_str", ")", "raise", "SolidusImportProducts", "::", "Exception", "::", "InvalidPrice", "unless", "price_str", "punt", "=", "price_str", ".", "index", "(", "'.'", ")", "coma", "=", "price_str", ".", "index", "(", "','", ")"...
Special process of prices because of locales and different decimal separator characters. We want to get a format with dot as decimal separator and without thousand separator
[ "Special", "process", "of", "prices", "because", "of", "locales", "and", "different", "decimal", "separator", "characters", ".", "We", "want", "to", "get", "a", "format", "with", "dot", "as", "decimal", "separator", "and", "without", "thousand", "separator" ]
643ce2a38c0c0ee26c8919e630ad7dad0adc568a
https://github.com/ngelx/solidus_import_products/blob/643ce2a38c0c0ee26c8919e630ad7dad0adc568a/app/services/solidus_import_products/process_row.rb#L83-L91
valid
westernmilling/synchronized_model
lib/synchronized_model/support.rb
SynchronizedModel.Support.matches
def matches(regexp, word) if regexp.respond_to?(:match?) regexp.match?(word) else regexp.match(word) end end
ruby
def matches(regexp, word) if regexp.respond_to?(:match?) regexp.match?(word) else regexp.match(word) end end
[ "def", "matches", "(", "regexp", ",", "word", ")", "if", "regexp", ".", "respond_to?", "(", ":match?", ")", "regexp", ".", "match?", "(", "word", ")", "else", "regexp", ".", "match", "(", "word", ")", "end", "end" ]
`match?` was added in Ruby 2.4 this allows us to be backwards compatible with older Ruby versions
[ "match?", "was", "added", "in", "Ruby", "2", ".", "4", "this", "allows", "us", "to", "be", "backwards", "compatible", "with", "older", "Ruby", "versions" ]
f181f3d451ff94d25613232948e762f55292c51b
https://github.com/westernmilling/synchronized_model/blob/f181f3d451ff94d25613232948e762f55292c51b/lib/synchronized_model/support.rb#L22-L28
valid
dark-panda/geos-extensions
lib/geos/polygon.rb
Geos.Polygon.dump_points
def dump_points(cur_path = []) points = [ self.exterior_ring.dump_points ] self.interior_rings.each do |ring| points.push(ring.dump_points) end cur_path.concat(points) end
ruby
def dump_points(cur_path = []) points = [ self.exterior_ring.dump_points ] self.interior_rings.each do |ring| points.push(ring.dump_points) end cur_path.concat(points) end
[ "def", "dump_points", "(", "cur_path", "=", "[", "]", ")", "points", "=", "[", "self", ".", "exterior_ring", ".", "dump_points", "]", "self", ".", "interior_rings", ".", "each", "do", "|", "ring", "|", "points", ".", "push", "(", "ring", ".", "dump_poi...
Dumps points similarly to the PostGIS `ST_DumpPoints` function.
[ "Dumps", "points", "similarly", "to", "the", "PostGIS", "ST_DumpPoints", "function", "." ]
59b4b84bbed0d551b696dbea909f26f8aca50498
https://github.com/dark-panda/geos-extensions/blob/59b4b84bbed0d551b696dbea909f26f8aca50498/lib/geos/polygon.rb#L160-L168
valid
contently/prune_ar
lib/prune_ar/foreign_key_handler.rb
PruneAr.ForeignKeyHandler.generate_belongs_to_foreign_key_name
def generate_belongs_to_foreign_key_name(assoc) source = assoc.source_table[0..7] column = assoc.foreign_key_column[0..7] destination = assoc.destination_table[0..7] "fk_#{source}_#{column}_#{destination}_#{SecureRandom.hex}" end
ruby
def generate_belongs_to_foreign_key_name(assoc) source = assoc.source_table[0..7] column = assoc.foreign_key_column[0..7] destination = assoc.destination_table[0..7] "fk_#{source}_#{column}_#{destination}_#{SecureRandom.hex}" end
[ "def", "generate_belongs_to_foreign_key_name", "(", "assoc", ")", "source", "=", "assoc", ".", "source_table", "[", "0", "..", "7", "]", "column", "=", "assoc", ".", "foreign_key_column", "[", "0", "..", "7", "]", "destination", "=", "assoc", ".", "destinati...
Limited to 64 characters
[ "Limited", "to", "64", "characters" ]
7e2a7e0680cfd445a2b726b46175f1b35e31b17a
https://github.com/contently/prune_ar/blob/7e2a7e0680cfd445a2b726b46175f1b35e31b17a/lib/prune_ar/foreign_key_handler.rb#L77-L82
valid
a14m/EGP-Rates
lib/egp_rates/cib.rb
EGPRates.CIB.raw_exchange_rates
def raw_exchange_rates req = Net::HTTP::Post.new(@uri, 'Content-Type' => 'application/json') req.body = { lang: :en }.to_json response = Net::HTTP.start(@uri.hostname, @uri.port) do |http| http.request(req) end fail ResponseError, response.code unless response.is_a? Net::HTTPSuccess response = JSON.parse(response.body) # CIB provide 6 currencies only unless response['d'] && response['d'].size >= 6 fail ResponseError, "Unknown JSON #{response}" end response rescue JSON::ParserError raise ResponseError, "Unknown JSON: #{response.body}" end
ruby
def raw_exchange_rates req = Net::HTTP::Post.new(@uri, 'Content-Type' => 'application/json') req.body = { lang: :en }.to_json response = Net::HTTP.start(@uri.hostname, @uri.port) do |http| http.request(req) end fail ResponseError, response.code unless response.is_a? Net::HTTPSuccess response = JSON.parse(response.body) # CIB provide 6 currencies only unless response['d'] && response['d'].size >= 6 fail ResponseError, "Unknown JSON #{response}" end response rescue JSON::ParserError raise ResponseError, "Unknown JSON: #{response.body}" end
[ "def", "raw_exchange_rates", "req", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "@uri", ",", "'Content-Type'", "=>", "'application/json'", ")", "req", ".", "body", "=", "{", "lang", ":", ":en", "}", ".", "to_json", "response", "=", "Net", ...
Send the request to URL and return the JSON response @return [Hash] JSON response of the exchange rates { "d"=> [ { "__type"=>"LINKDev.CIB.CurrenciesFunds.CIBFund.CurrencyObject", "CurrencyID"=>"USD", "BuyRate"=>15.9, "SellRate"=>16.05 }, { "__type"=>"LINKDev.CIB.CurrenciesFunds.CIBFund.CurrencyObject", "CurrencyID"=>"EUR", "BuyRate"=>17.1904, "SellRate"=>17.5234 }, { ... } ] }
[ "Send", "the", "request", "to", "URL", "and", "return", "the", "JSON", "response" ]
ebb960c8cae62c5823aef50bb4121397276c7af6
https://github.com/a14m/EGP-Rates/blob/ebb960c8cae62c5823aef50bb4121397276c7af6/lib/egp_rates/cib.rb#L40-L57
valid
nicolasdespres/respect
lib/respect/format_validator.rb
Respect.FormatValidator.validate_ipv4_addr
def validate_ipv4_addr(value) ipaddr = IPAddr.new(value) unless ipaddr.ipv4? raise ValidationError, "IP address '#{value}' is not IPv4" end ipaddr rescue ArgumentError => e raise ValidationError, "invalid IPv4 address '#{value}' - #{e.message}" end
ruby
def validate_ipv4_addr(value) ipaddr = IPAddr.new(value) unless ipaddr.ipv4? raise ValidationError, "IP address '#{value}' is not IPv4" end ipaddr rescue ArgumentError => e raise ValidationError, "invalid IPv4 address '#{value}' - #{e.message}" end
[ "def", "validate_ipv4_addr", "(", "value", ")", "ipaddr", "=", "IPAddr", ".", "new", "(", "value", ")", "unless", "ipaddr", ".", "ipv4?", "raise", "ValidationError", ",", "\"IP address '#{value}' is not IPv4\"", "end", "ipaddr", "rescue", "ArgumentError", "=>", "e...
Validate IPV4 using the standard "ipaddr" ruby module.
[ "Validate", "IPV4", "using", "the", "standard", "ipaddr", "ruby", "module", "." ]
916bef1c3a84788507a45cfb75b8f7d0c56b685f
https://github.com/nicolasdespres/respect/blob/916bef1c3a84788507a45cfb75b8f7d0c56b685f/lib/respect/format_validator.rb#L56-L64
valid
nicolasdespres/respect
lib/respect/format_validator.rb
Respect.FormatValidator.validate_ipv6_addr
def validate_ipv6_addr(value) ipaddr = IPAddr.new(value) unless ipaddr.ipv6? raise ValidationError, "IP address '#{value}' is not IPv6" end ipaddr rescue ArgumentError => e raise ValidationError, "invalid IPv6 address '#{value}' - #{e.message}" end
ruby
def validate_ipv6_addr(value) ipaddr = IPAddr.new(value) unless ipaddr.ipv6? raise ValidationError, "IP address '#{value}' is not IPv6" end ipaddr rescue ArgumentError => e raise ValidationError, "invalid IPv6 address '#{value}' - #{e.message}" end
[ "def", "validate_ipv6_addr", "(", "value", ")", "ipaddr", "=", "IPAddr", ".", "new", "(", "value", ")", "unless", "ipaddr", ".", "ipv6?", "raise", "ValidationError", ",", "\"IP address '#{value}' is not IPv6\"", "end", "ipaddr", "rescue", "ArgumentError", "=>", "e...
Validate that the given string _value_ describes a well-formed IPV6 network address using the standard "ipaddr" ruby module.
[ "Validate", "that", "the", "given", "string", "_value_", "describes", "a", "well", "-", "formed", "IPV6", "network", "address", "using", "the", "standard", "ipaddr", "ruby", "module", "." ]
916bef1c3a84788507a45cfb75b8f7d0c56b685f
https://github.com/nicolasdespres/respect/blob/916bef1c3a84788507a45cfb75b8f7d0c56b685f/lib/respect/format_validator.rb#L76-L84
valid
avinashbot/lazy_lazer
lib/lazy_lazer/internal_model.rb
LazyLazer.InternalModel.to_h
def to_h(strict: false) todo = @key_metadata.keys - @cache.keys todo.each_with_object({}) do |key, hsh| loaded_key = (strict ? load_key_strict(key) : load_key_lenient(key)) hsh[key] = loaded_key if exists_locally?(key) end end
ruby
def to_h(strict: false) todo = @key_metadata.keys - @cache.keys todo.each_with_object({}) do |key, hsh| loaded_key = (strict ? load_key_strict(key) : load_key_lenient(key)) hsh[key] = loaded_key if exists_locally?(key) end end
[ "def", "to_h", "(", "strict", ":", "false", ")", "todo", "=", "@key_metadata", ".", "keys", "-", "@cache", ".", "keys", "todo", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "key", ",", "hsh", "|", "loaded_key", "=", "(", "strict", "?", "...
Create an internal model with a reference to a public model. @param key_metadata [KeyMetadataStore] a reference to a metadata store @param parent [LazyLazer] a reference to a LazyLazer model Converts all unconverted keys and packages them as a hash. @return [Hash] the converted hash
[ "Create", "an", "internal", "model", "with", "a", "reference", "to", "a", "public", "model", "." ]
ed23f152697e76816872301363ab1daff2d2cfc7
https://github.com/avinashbot/lazy_lazer/blob/ed23f152697e76816872301363ab1daff2d2cfc7/lib/lazy_lazer/internal_model.rb#L22-L28
valid