id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
19,200
dbalmain/ferret
ruby/lib/ferret/index.rb
Ferret::Index.Index.highlight
def highlight(query, doc_id, options = {}) @dir.synchronize do ensure_searcher_open() @searcher.highlight(do_process_query(query), doc_id, options[:field]||@options[:default_field], options) end end
ruby
def highlight(query, doc_id, options = {}) @dir.synchronize do ensure_searcher_open() @searcher.highlight(do_process_query(query), doc_id, options[:field]||@options[:default_field], options) end end
[ "def", "highlight", "(", "query", ",", "doc_id", ",", "options", "=", "{", "}", ")", "@dir", ".", "synchronize", "do", "ensure_searcher_open", "(", ")", "@searcher", ".", "highlight", "(", "do_process_query", "(", "query", ")", ",", "doc_id", ",", "options", "[", ":field", "]", "||", "@options", "[", ":default_field", "]", ",", "options", ")", "end", "end" ]
If you create an Index without any options, it'll simply create an index in memory. But this class is highly configurable and every option that you can supply to IndexWriter and QueryParser, you can also set here. Please look at the options for the constructors to these classes. === Options See; * QueryParser * IndexWriter default_input_field:: Default: "id". This specifies the default field that will be used when you add a simple string to the index using #add_document or <<. id_field:: Default: "id". This field is as the field to search when doing searches on a term. For example, if you do a lookup by term "cat", ie index["cat"], this will be the field that is searched. key:: Default: nil. Expert: This should only be used if you really know what you are doing. Basically you can set a field or an array of fields to be the key for the index. So if you add a document with a same key as an existing document, the existing document will be replaced by the new object. Using a multiple field key will slow down indexing so it should not be done if performance is a concern. A single field key (or id) should be find however. Also, you must make sure that your key/keys are either untokenized or that they are not broken up by the analyzer. auto_flush:: Default: false. Set this option to true if you want the index automatically flushed every time you do a write (includes delete) to the index. This is useful if you have multiple processes accessing the index and you don't want lock errors. Setting :auto_flush to true has a huge performance impact so don't use it if you are concerned about performance. In that case you should think about setting up a DRb indexing service. lock_retry_time:: Default: 2 seconds. This parameter specifies how long to wait before retrying to obtain the commit lock when detecting if the IndexReader is at the latest version. close_dir:: Default: false. If you explicitly pass a Directory object to this class and you want Index to close it when it is closed itself then set this to true. use_typed_range_query:: Default: true. Use TypedRangeQuery instead of the standard RangeQuery when parsing range queries. This is useful if you have number fields which you want to perform range queries on. You won't need to pad or normalize the data in the field in anyway to get correct results. However, performance will be a lot slower for large indexes, hence the default. == Examples index = Index::Index.new(:analyzer => WhiteSpaceAnalyzer.new()) index = Index::Index.new(:path => '/path/to/index', :create_if_missing => false, :auto_flush => true) index = Index::Index.new(:dir => directory, :default_slop => 2, :handle_parse_errors => false) You can also pass a block if you like. The index will be yielded and closed at the index of the box. For example; Ferret::I.new() do |index| # do stuff with index. Most of your actions will be cached. end Returns an array of strings with the matches highlighted. The +query+ can either a query String or a Ferret::Search::Query object. The doc_id is the id of the document you want to highlight (usually returned by the search methods). There are also a number of options you can pass; === Options field:: Default: @options[:default_field]. The default_field is the field that is usually highlighted but you can specify which field you want to highlight here. If you want to highlight multiple fields then you will need to call this method multiple times. excerpt_length:: Default: 150. Length of excerpt to show. Highlighted terms will be in the centre of the excerpt. Set to :all to highlight the entire field. num_excerpts:: Default: 2. Number of excerpts to return. pre_tag:: Default: "<b>". Tag to place to the left of the match. You'll probably want to change this to a "<span>" tag with a class. Try "\033[36m" for use in a terminal. post_tag:: Default: "</b>". This tag should close the +:pre_tag+. Try tag "\033[m" in the terminal. ellipsis:: Default: "...". This is the string that is appended at the beginning and end of excerpts (unless the excerpt hits the start or end of the field. Alternatively you may want to use the HTML entity &#8230; or the UTF-8 string "\342\200\246".
[ "If", "you", "create", "an", "Index", "without", "any", "options", "it", "ll", "simply", "create", "an", "index", "in", "memory", ".", "But", "this", "class", "is", "highly", "configurable", "and", "every", "option", "that", "you", "can", "supply", "to", "IndexWriter", "and", "QueryParser", "you", "can", "also", "set", "here", ".", "Please", "look", "at", "the", "options", "for", "the", "constructors", "to", "these", "classes", "." ]
2451bc48c3aa162cbb87659b0f460b7821590cd1
https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/index.rb#L191-L199
19,201
dbalmain/ferret
ruby/lib/ferret/index.rb
Ferret::Index.Index.term_vector
def term_vector(id, field) @dir.synchronize do ensure_reader_open() if id.kind_of?(String) or id.kind_of?(Symbol) term_doc_enum = @reader.term_docs_for(@id_field, id.to_s) if term_doc_enum.next? id = term_doc_enum.doc else return nil end end return @reader.term_vector(id, field) end end
ruby
def term_vector(id, field) @dir.synchronize do ensure_reader_open() if id.kind_of?(String) or id.kind_of?(Symbol) term_doc_enum = @reader.term_docs_for(@id_field, id.to_s) if term_doc_enum.next? id = term_doc_enum.doc else return nil end end return @reader.term_vector(id, field) end end
[ "def", "term_vector", "(", "id", ",", "field", ")", "@dir", ".", "synchronize", "do", "ensure_reader_open", "(", ")", "if", "id", ".", "kind_of?", "(", "String", ")", "or", "id", ".", "kind_of?", "(", "Symbol", ")", "term_doc_enum", "=", "@reader", ".", "term_docs_for", "(", "@id_field", ",", "id", ".", "to_s", ")", "if", "term_doc_enum", ".", "next?", "id", "=", "term_doc_enum", ".", "doc", "else", "return", "nil", "end", "end", "return", "@reader", ".", "term_vector", "(", "id", ",", "field", ")", "end", "end" ]
Retrieves the term_vector for a document. The document can be referenced by either a string id to match the id field or an integer corresponding to Ferret's document number. See Ferret::Index::IndexReader#term_vector
[ "Retrieves", "the", "term_vector", "for", "a", "document", ".", "The", "document", "can", "be", "referenced", "by", "either", "a", "string", "id", "to", "match", "the", "id", "field", "or", "an", "integer", "corresponding", "to", "Ferret", "s", "document", "number", "." ]
2451bc48c3aa162cbb87659b0f460b7821590cd1
https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/index.rb#L471-L484
19,202
dbalmain/ferret
ruby/lib/ferret/index.rb
Ferret::Index.Index.query_delete
def query_delete(query) @dir.synchronize do ensure_writer_open() ensure_searcher_open() query = do_process_query(query) @searcher.search_each(query, :limit => :all) do |doc, score| @reader.delete(doc) end flush() if @auto_flush end end
ruby
def query_delete(query) @dir.synchronize do ensure_writer_open() ensure_searcher_open() query = do_process_query(query) @searcher.search_each(query, :limit => :all) do |doc, score| @reader.delete(doc) end flush() if @auto_flush end end
[ "def", "query_delete", "(", "query", ")", "@dir", ".", "synchronize", "do", "ensure_writer_open", "(", ")", "ensure_searcher_open", "(", ")", "query", "=", "do_process_query", "(", "query", ")", "@searcher", ".", "search_each", "(", "query", ",", ":limit", "=>", ":all", ")", "do", "|", "doc", ",", "score", "|", "@reader", ".", "delete", "(", "doc", ")", "end", "flush", "(", ")", "if", "@auto_flush", "end", "end" ]
Delete all documents returned by the query. query:: The query to find documents you wish to delete. Can either be a string (in which case it is parsed by the standard query parser) or an actual query object.
[ "Delete", "all", "documents", "returned", "by", "the", "query", "." ]
2451bc48c3aa162cbb87659b0f460b7821590cd1
https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/index.rb#L540-L550
19,203
dbalmain/ferret
ruby/lib/ferret/index.rb
Ferret::Index.Index.update
def update(id, new_doc) @dir.synchronize do ensure_writer_open() delete(id) if id.is_a?(String) or id.is_a?(Symbol) @writer.commit else ensure_writer_open() end @writer << new_doc flush() if @auto_flush end end
ruby
def update(id, new_doc) @dir.synchronize do ensure_writer_open() delete(id) if id.is_a?(String) or id.is_a?(Symbol) @writer.commit else ensure_writer_open() end @writer << new_doc flush() if @auto_flush end end
[ "def", "update", "(", "id", ",", "new_doc", ")", "@dir", ".", "synchronize", "do", "ensure_writer_open", "(", ")", "delete", "(", "id", ")", "if", "id", ".", "is_a?", "(", "String", ")", "or", "id", ".", "is_a?", "(", "Symbol", ")", "@writer", ".", "commit", "else", "ensure_writer_open", "(", ")", "end", "@writer", "<<", "new_doc", "flush", "(", ")", "if", "@auto_flush", "end", "end" ]
Update the document referenced by the document number +id+ if +id+ is an integer or all of the documents which have the term +id+ if +id+ is a term.. For batch update of set of documents, for performance reasons, see batch_update id:: The number of the document to update. Can also be a string representing the value in the +id+ field. Also consider using the :key attribute. new_doc:: The document to replace the old document with
[ "Update", "the", "document", "referenced", "by", "the", "document", "number", "+", "id", "+", "if", "+", "id", "+", "is", "an", "integer", "or", "all", "of", "the", "documents", "which", "have", "the", "term", "+", "id", "+", "if", "+", "id", "+", "is", "a", "term", "..", "For", "batch", "update", "of", "set", "of", "documents", "for", "performance", "reasons", "see", "batch_update" ]
2451bc48c3aa162cbb87659b0f460b7821590cd1
https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/index.rb#L569-L581
19,204
dbalmain/ferret
ruby/lib/ferret/index.rb
Ferret::Index.Index.batch_update
def batch_update(docs) @dir.synchronize do ids = nil case docs when Array ids = docs.collect{|doc| doc[@id_field].to_s} if ids.include?(nil) raise ArgumentError, "all documents must have an #{@id_field} " "field when doing a batch update" end when Hash ids = docs.keys docs = docs.values else raise ArgumentError, "must pass Hash or Array, not #{docs.class}" end batch_delete(ids) ensure_writer_open() docs.each {|new_doc| @writer << new_doc } flush() end end
ruby
def batch_update(docs) @dir.synchronize do ids = nil case docs when Array ids = docs.collect{|doc| doc[@id_field].to_s} if ids.include?(nil) raise ArgumentError, "all documents must have an #{@id_field} " "field when doing a batch update" end when Hash ids = docs.keys docs = docs.values else raise ArgumentError, "must pass Hash or Array, not #{docs.class}" end batch_delete(ids) ensure_writer_open() docs.each {|new_doc| @writer << new_doc } flush() end end
[ "def", "batch_update", "(", "docs", ")", "@dir", ".", "synchronize", "do", "ids", "=", "nil", "case", "docs", "when", "Array", "ids", "=", "docs", ".", "collect", "{", "|", "doc", "|", "doc", "[", "@id_field", "]", ".", "to_s", "}", "if", "ids", ".", "include?", "(", "nil", ")", "raise", "ArgumentError", ",", "\"all documents must have an #{@id_field} \"", "\"field when doing a batch update\"", "end", "when", "Hash", "ids", "=", "docs", ".", "keys", "docs", "=", "docs", ".", "values", "else", "raise", "ArgumentError", ",", "\"must pass Hash or Array, not #{docs.class}\"", "end", "batch_delete", "(", "ids", ")", "ensure_writer_open", "(", ")", "docs", ".", "each", "{", "|", "new_doc", "|", "@writer", "<<", "new_doc", "}", "flush", "(", ")", "end", "end" ]
Batch updates the documents in an index. You can pass either a Hash or an Array. === Array (recommended) If you pass an Array then each value needs to be a Document or a Hash and each of those documents must have an +:id_field+ which will be used to delete the old document that this document is replacing. === Hash If you pass a Hash then the keys of the Hash will be considered the +id+'s and the values will be the new documents to replace the old ones with.If the +id+ is an Integer then it is considered a Ferret document number and the corresponding document will be deleted. If the +id+ is a String or a Symbol then the +id+ will be considered a term and the documents that contain that term in the +:id_field+ will be deleted. Note: No error will be raised if the document does not currently exist. A new document will simply be created. == Examples # will replace the documents with the +id+'s id:133 and id:254 @index.batch_update({ '133' => {:id => '133', :content => 'yada yada yada'}, '253' => {:id => '253', :content => 'bla bla bal'} }) # will replace the documents with the Ferret Document numbers 2 and 92 @index.batch_update({ 2 => {:id => '133', :content => 'yada yada yada'}, 92 => {:id => '253', :content => 'bla bla bal'} }) # will replace the documents with the +id+'s id:133 and id:254 # this is recommended as it guarantees no duplicate keys @index.batch_update([ {:id => '133', :content => 'yada yada yada'}, {:id => '253', :content => 'bla bla bal'} ]) docs:: A Hash of id/document pairs. The set of documents to be updated
[ "Batch", "updates", "the", "documents", "in", "an", "index", ".", "You", "can", "pass", "either", "a", "Hash", "or", "an", "Array", "." ]
2451bc48c3aa162cbb87659b0f460b7821590cd1
https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/index.rb#L626-L647
19,205
dbalmain/ferret
ruby/lib/ferret/index.rb
Ferret::Index.Index.query_update
def query_update(query, new_val) @dir.synchronize do ensure_writer_open() ensure_searcher_open() docs_to_add = [] query = do_process_query(query) @searcher.search_each(query, :limit => :all) do |id, score| document = @searcher[id].load if new_val.is_a?(Hash) document.merge!(new_val) else new_val.is_a?(String) or new_val.is_a?(Symbol) document[@default_input_field] = new_val.to_s end docs_to_add << document @reader.delete(id) end ensure_writer_open() docs_to_add.each {|doc| @writer << doc } flush() if @auto_flush end end
ruby
def query_update(query, new_val) @dir.synchronize do ensure_writer_open() ensure_searcher_open() docs_to_add = [] query = do_process_query(query) @searcher.search_each(query, :limit => :all) do |id, score| document = @searcher[id].load if new_val.is_a?(Hash) document.merge!(new_val) else new_val.is_a?(String) or new_val.is_a?(Symbol) document[@default_input_field] = new_val.to_s end docs_to_add << document @reader.delete(id) end ensure_writer_open() docs_to_add.each {|doc| @writer << doc } flush() if @auto_flush end end
[ "def", "query_update", "(", "query", ",", "new_val", ")", "@dir", ".", "synchronize", "do", "ensure_writer_open", "(", ")", "ensure_searcher_open", "(", ")", "docs_to_add", "=", "[", "]", "query", "=", "do_process_query", "(", "query", ")", "@searcher", ".", "search_each", "(", "query", ",", ":limit", "=>", ":all", ")", "do", "|", "id", ",", "score", "|", "document", "=", "@searcher", "[", "id", "]", ".", "load", "if", "new_val", ".", "is_a?", "(", "Hash", ")", "document", ".", "merge!", "(", "new_val", ")", "else", "new_val", ".", "is_a?", "(", "String", ")", "or", "new_val", ".", "is_a?", "(", "Symbol", ")", "document", "[", "@default_input_field", "]", "=", "new_val", ".", "to_s", "end", "docs_to_add", "<<", "document", "@reader", ".", "delete", "(", "id", ")", "end", "ensure_writer_open", "(", ")", "docs_to_add", ".", "each", "{", "|", "doc", "|", "@writer", "<<", "doc", "}", "flush", "(", ")", "if", "@auto_flush", "end", "end" ]
Update all the documents returned by the query. query:: The query to find documents you wish to update. Can either be a string (in which case it is parsed by the standard query parser) or an actual query object. new_val:: The values we are updating. This can be a string in which case the default field is updated, or it can be a hash, in which case, all fields in the hash are merged into the old hash. That is, the old fields are replaced by values in the new hash if they exist. === Example index << {:id => "26", :title => "Babylon", :artist => "David Grey"} index << {:id => "29", :title => "My Oh My", :artist => "David Grey"} # correct index.query_update('artist:"David Grey"', {:artist => "David Gray"}) index["26"] #=> {:id => "26", :title => "Babylon", :artist => "David Gray"} index["28"] #=> {:id => "28", :title => "My Oh My", :artist => "David Gray"}
[ "Update", "all", "the", "documents", "returned", "by", "the", "query", "." ]
2451bc48c3aa162cbb87659b0f460b7821590cd1
https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/index.rb#L674-L694
19,206
dbalmain/ferret
ruby/lib/ferret/index.rb
Ferret::Index.Index.explain
def explain(query, doc) @dir.synchronize do ensure_searcher_open() query = do_process_query(query) return @searcher.explain(query, doc) end end
ruby
def explain(query, doc) @dir.synchronize do ensure_searcher_open() query = do_process_query(query) return @searcher.explain(query, doc) end end
[ "def", "explain", "(", "query", ",", "doc", ")", "@dir", ".", "synchronize", "do", "ensure_searcher_open", "(", ")", "query", "=", "do_process_query", "(", "query", ")", "return", "@searcher", ".", "explain", "(", "query", ",", "doc", ")", "end", "end" ]
Returns an Explanation that describes how +doc+ scored against +query+. This is intended to be used in developing Similarity implementations, and, for good performance, should not be displayed with every hit. Computing an explanation is as expensive as executing the query over the entire index.
[ "Returns", "an", "Explanation", "that", "describes", "how", "+", "doc", "+", "scored", "against", "+", "query", "+", "." ]
2451bc48c3aa162cbb87659b0f460b7821590cd1
https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/index.rb#L823-L830
19,207
dbalmain/ferret
ruby/lib/ferret/index.rb
Ferret::Index.Index.ensure_reader_open
def ensure_reader_open(get_latest = true) raise "tried to use a closed index" if not @open if @reader if get_latest latest = false begin latest = @reader.latest? rescue Lock::LockError sleep(@options[:lock_retry_time]) # sleep for 2 seconds and try again latest = @reader.latest? end if not latest @searcher.close if @searcher @reader.close return @reader = IndexReader.new(@dir) end end else if @writer @writer.close @writer = nil end return @reader = IndexReader.new(@dir) end return false end
ruby
def ensure_reader_open(get_latest = true) raise "tried to use a closed index" if not @open if @reader if get_latest latest = false begin latest = @reader.latest? rescue Lock::LockError sleep(@options[:lock_retry_time]) # sleep for 2 seconds and try again latest = @reader.latest? end if not latest @searcher.close if @searcher @reader.close return @reader = IndexReader.new(@dir) end end else if @writer @writer.close @writer = nil end return @reader = IndexReader.new(@dir) end return false end
[ "def", "ensure_reader_open", "(", "get_latest", "=", "true", ")", "raise", "\"tried to use a closed index\"", "if", "not", "@open", "if", "@reader", "if", "get_latest", "latest", "=", "false", "begin", "latest", "=", "@reader", ".", "latest?", "rescue", "Lock", "::", "LockError", "sleep", "(", "@options", "[", ":lock_retry_time", "]", ")", "# sleep for 2 seconds and try again", "latest", "=", "@reader", ".", "latest?", "end", "if", "not", "latest", "@searcher", ".", "close", "if", "@searcher", "@reader", ".", "close", "return", "@reader", "=", "IndexReader", ".", "new", "(", "@dir", ")", "end", "end", "else", "if", "@writer", "@writer", ".", "close", "@writer", "=", "nil", "end", "return", "@reader", "=", "IndexReader", ".", "new", "(", "@dir", ")", "end", "return", "false", "end" ]
returns the new reader if one is opened
[ "returns", "the", "new", "reader", "if", "one", "is", "opened" ]
2451bc48c3aa162cbb87659b0f460b7821590cd1
https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/index.rb#L864-L889
19,208
dbalmain/ferret
ruby/lib/ferret/browser.rb
Ferret::Browser.ViewHelper.truncate
def truncate(str, len = 80) if str and str.length > len and (add = str[len..-1].index(' ')) str = str[0, len + add] + '&#8230;' end str end
ruby
def truncate(str, len = 80) if str and str.length > len and (add = str[len..-1].index(' ')) str = str[0, len + add] + '&#8230;' end str end
[ "def", "truncate", "(", "str", ",", "len", "=", "80", ")", "if", "str", "and", "str", ".", "length", ">", "len", "and", "(", "add", "=", "str", "[", "len", "..", "-", "1", "]", ".", "index", "(", "' '", ")", ")", "str", "=", "str", "[", "0", ",", "len", "+", "add", "]", "+", "'&#8230;'", "end", "str", "end" ]
truncates the string at the first space after +len+ characters
[ "truncates", "the", "string", "at", "the", "first", "space", "after", "+", "len", "+", "characters" ]
2451bc48c3aa162cbb87659b0f460b7821590cd1
https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/browser.rb#L72-L77
19,209
dbalmain/ferret
ruby/lib/ferret/browser.rb
Ferret::Browser.Controller.paginate
def paginate(idx, max, url, &b) return '' if max == 0 url = url.gsub(%r{^/?(.*?)/?$}, '\1') b ||= lambda{} link = lambda {|*args| i, title, text = args "<a href=\"/#{url}/#{i}#{'?' + @query_string if @query_string}\" " + "#{'onclick="return false;"' if (i == idx)} " + "class=\"#{'disabled ' if (i == idx)}#{b.call(i)}\" " + "title=\"#{title||"Go to page #{i}"}\">#{text||i}</a>" } res = '<div class="nav">' if (idx > 0) res << link.call(idx - 1, "Go to previous page", "&#171; Previous") else res << "<a href=\"/#{url}/0\" onclick=\"return false;\" " + "class=\"disabled\" title=\"Disabled\">&#171; Previous</a>" end if idx < 10 idx.times {|i| res << link.call(i)} else (0..2).each {|i| res << link.call(i)} res << '&nbsp;&#8230;&nbsp;' ((idx-4)...idx).each {|i| res << link.call(i)} end res << link.call(idx, 'Current Page') if idx > (max - 10) ((idx+1)...max).each {|i| res << link.call(i)} else ((idx+1)..(idx+4)).each {|i| res << link.call(i)} res << '&nbsp;&#8230;&nbsp;' ((max-3)...max).each {|i| res << link.call(i)} end if (idx < (max - 1)) res << link.call(idx + 1, "Go to next page", "Next &#187;") else res << "<a href=\"/#{url}/#{max-1}\" onclick=\"return false;\" " + "class=\"disabled\" title=\"Disabled\"}\">Next &#187;</a>" end res << '</div>' end
ruby
def paginate(idx, max, url, &b) return '' if max == 0 url = url.gsub(%r{^/?(.*?)/?$}, '\1') b ||= lambda{} link = lambda {|*args| i, title, text = args "<a href=\"/#{url}/#{i}#{'?' + @query_string if @query_string}\" " + "#{'onclick="return false;"' if (i == idx)} " + "class=\"#{'disabled ' if (i == idx)}#{b.call(i)}\" " + "title=\"#{title||"Go to page #{i}"}\">#{text||i}</a>" } res = '<div class="nav">' if (idx > 0) res << link.call(idx - 1, "Go to previous page", "&#171; Previous") else res << "<a href=\"/#{url}/0\" onclick=\"return false;\" " + "class=\"disabled\" title=\"Disabled\">&#171; Previous</a>" end if idx < 10 idx.times {|i| res << link.call(i)} else (0..2).each {|i| res << link.call(i)} res << '&nbsp;&#8230;&nbsp;' ((idx-4)...idx).each {|i| res << link.call(i)} end res << link.call(idx, 'Current Page') if idx > (max - 10) ((idx+1)...max).each {|i| res << link.call(i)} else ((idx+1)..(idx+4)).each {|i| res << link.call(i)} res << '&nbsp;&#8230;&nbsp;' ((max-3)...max).each {|i| res << link.call(i)} end if (idx < (max - 1)) res << link.call(idx + 1, "Go to next page", "Next &#187;") else res << "<a href=\"/#{url}/#{max-1}\" onclick=\"return false;\" " + "class=\"disabled\" title=\"Disabled\"}\">Next &#187;</a>" end res << '</div>' end
[ "def", "paginate", "(", "idx", ",", "max", ",", "url", ",", "&", "b", ")", "return", "''", "if", "max", "==", "0", "url", "=", "url", ".", "gsub", "(", "%r{", "}", ",", "'\\1'", ")", "b", "||=", "lambda", "{", "}", "link", "=", "lambda", "{", "|", "*", "args", "|", "i", ",", "title", ",", "text", "=", "args", "\"<a href=\\\"/#{url}/#{i}#{'?' + @query_string if @query_string}\\\" \"", "+", "\"#{'onclick=\"return false;\"' if (i == idx)} \"", "+", "\"class=\\\"#{'disabled ' if (i == idx)}#{b.call(i)}\\\" \"", "+", "\"title=\\\"#{title||\"Go to page #{i}\"}\\\">#{text||i}</a>\"", "}", "res", "=", "'<div class=\"nav\">'", "if", "(", "idx", ">", "0", ")", "res", "<<", "link", ".", "call", "(", "idx", "-", "1", ",", "\"Go to previous page\"", ",", "\"&#171; Previous\"", ")", "else", "res", "<<", "\"<a href=\\\"/#{url}/0\\\" onclick=\\\"return false;\\\" \"", "+", "\"class=\\\"disabled\\\" title=\\\"Disabled\\\">&#171; Previous</a>\"", "end", "if", "idx", "<", "10", "idx", ".", "times", "{", "|", "i", "|", "res", "<<", "link", ".", "call", "(", "i", ")", "}", "else", "(", "0", "..", "2", ")", ".", "each", "{", "|", "i", "|", "res", "<<", "link", ".", "call", "(", "i", ")", "}", "res", "<<", "'&nbsp;&#8230;&nbsp;'", "(", "(", "idx", "-", "4", ")", "...", "idx", ")", ".", "each", "{", "|", "i", "|", "res", "<<", "link", ".", "call", "(", "i", ")", "}", "end", "res", "<<", "link", ".", "call", "(", "idx", ",", "'Current Page'", ")", "if", "idx", ">", "(", "max", "-", "10", ")", "(", "(", "idx", "+", "1", ")", "...", "max", ")", ".", "each", "{", "|", "i", "|", "res", "<<", "link", ".", "call", "(", "i", ")", "}", "else", "(", "(", "idx", "+", "1", ")", "..", "(", "idx", "+", "4", ")", ")", ".", "each", "{", "|", "i", "|", "res", "<<", "link", ".", "call", "(", "i", ")", "}", "res", "<<", "'&nbsp;&#8230;&nbsp;'", "(", "(", "max", "-", "3", ")", "...", "max", ")", ".", "each", "{", "|", "i", "|", "res", "<<", "link", ".", "call", "(", "i", ")", "}", "end", "if", "(", "idx", "<", "(", "max", "-", "1", ")", ")", "res", "<<", "link", ".", "call", "(", "idx", "+", "1", ",", "\"Go to next page\"", ",", "\"Next &#187;\"", ")", "else", "res", "<<", "\"<a href=\\\"/#{url}/#{max-1}\\\" onclick=\\\"return false;\\\" \"", "+", "\"class=\\\"disabled\\\" title=\\\"Disabled\\\"}\\\">Next &#187;</a>\"", "end", "res", "<<", "'</div>'", "end" ]
takes an optional block to set optional attributes in the links
[ "takes", "an", "optional", "block", "to", "set", "optional", "attributes", "in", "the", "links" ]
2451bc48c3aa162cbb87659b0f460b7821590cd1
https://github.com/dbalmain/ferret/blob/2451bc48c3aa162cbb87659b0f460b7821590cd1/ruby/lib/ferret/browser.rb#L126-L166
19,210
clbustos/rubyvis
lib/rubyvis/scene/svg_curve.rb
Rubyvis::SvgScene.PathBasis.weight
def weight(w) OpenStruct.new({ :x=> w[0] * p0.left + w[1] * p1.left + w[2] * p2.left + w[3] * p3.left, :y=> w[0] * p0.top + w[1] * p1.top + w[2] * p2.top + w[3] * p3.top }) end
ruby
def weight(w) OpenStruct.new({ :x=> w[0] * p0.left + w[1] * p1.left + w[2] * p2.left + w[3] * p3.left, :y=> w[0] * p0.top + w[1] * p1.top + w[2] * p2.top + w[3] * p3.top }) end
[ "def", "weight", "(", "w", ")", "OpenStruct", ".", "new", "(", "{", ":x", "=>", "w", "[", "0", "]", "*", "p0", ".", "left", "+", "w", "[", "1", "]", "*", "p1", ".", "left", "+", "w", "[", "2", "]", "*", "p2", ".", "left", "+", "w", "[", "3", "]", "*", "p3", ".", "left", ",", ":y", "=>", "w", "[", "0", "]", "*", "p0", ".", "top", "+", "w", "[", "1", "]", "*", "p1", ".", "top", "+", "w", "[", "2", "]", "*", "p2", ".", "top", "+", "w", "[", "3", "]", "*", "p3", ".", "top", "}", ")", "end" ]
Returns the point that is the weighted sum of the specified control points, using the specified weights. This method requires that there are four weights and four control points.
[ "Returns", "the", "point", "that", "is", "the", "weighted", "sum", "of", "the", "specified", "control", "points", "using", "the", "specified", "weights", ".", "This", "method", "requires", "that", "there", "are", "four", "weights", "and", "four", "control", "points", "." ]
59f5e76f1c352d68dd8f471f77a441ac9aaf784b
https://github.com/clbustos/rubyvis/blob/59f5e76f1c352d68dd8f471f77a441ac9aaf784b/lib/rubyvis/scene/svg_curve.rb#L27-L32
19,211
dejan/espeak-ruby
lib/espeak/speech.rb
ESpeak.Speech.save
def save(filename) speech = bytes_wav res = IO.popen(lame_command(filename, command_options), 'r+') do |process| process.write(speech) process.close_write process.read end res.to_s end
ruby
def save(filename) speech = bytes_wav res = IO.popen(lame_command(filename, command_options), 'r+') do |process| process.write(speech) process.close_write process.read end res.to_s end
[ "def", "save", "(", "filename", ")", "speech", "=", "bytes_wav", "res", "=", "IO", ".", "popen", "(", "lame_command", "(", "filename", ",", "command_options", ")", ",", "'r+'", ")", "do", "|", "process", "|", "process", ".", "write", "(", "speech", ")", "process", ".", "close_write", "process", ".", "read", "end", "res", ".", "to_s", "end" ]
Generates mp3 file as a result of Text-To-Speech conversion.
[ "Generates", "mp3", "file", "as", "a", "result", "of", "Text", "-", "To", "-", "Speech", "conversion", "." ]
96602f68615f9c8c4f5aea58a747de7c69798097
https://github.com/dejan/espeak-ruby/blob/96602f68615f9c8c4f5aea58a747de7c69798097/lib/espeak/speech.rb#L30-L38
19,212
dejan/espeak-ruby
lib/espeak/speech.rb
ESpeak.Speech.bytes
def bytes() speech = bytes_wav res = IO.popen(std_lame_command(command_options), 'r+') do |process| process.write(speech) process.close_write process.read end res.to_s end
ruby
def bytes() speech = bytes_wav res = IO.popen(std_lame_command(command_options), 'r+') do |process| process.write(speech) process.close_write process.read end res.to_s end
[ "def", "bytes", "(", ")", "speech", "=", "bytes_wav", "res", "=", "IO", ".", "popen", "(", "std_lame_command", "(", "command_options", ")", ",", "'r+'", ")", "do", "|", "process", "|", "process", ".", "write", "(", "speech", ")", "process", ".", "close_write", "process", ".", "read", "end", "res", ".", "to_s", "end" ]
Returns mp3 file bytes as a result of Text-To-Speech conversion.
[ "Returns", "mp3", "file", "bytes", "as", "a", "result", "of", "Text", "-", "To", "-", "Speech", "conversion", "." ]
96602f68615f9c8c4f5aea58a747de7c69798097
https://github.com/dejan/espeak-ruby/blob/96602f68615f9c8c4f5aea58a747de7c69798097/lib/espeak/speech.rb#L43-L51
19,213
clbustos/rubyvis
lib/rubyvis/flatten.rb
Rubyvis.Flatten.array
def array @entries=[] @stack=[] if @leaf recurse(@map,0) return @entries end visit(@map,0) @entries.map {|stack| m={} @keys.each_with_index {|k,i| v=stack[i] m[k.name]=k.value ? k.value.js_call(self,v) : v } m } end
ruby
def array @entries=[] @stack=[] if @leaf recurse(@map,0) return @entries end visit(@map,0) @entries.map {|stack| m={} @keys.each_with_index {|k,i| v=stack[i] m[k.name]=k.value ? k.value.js_call(self,v) : v } m } end
[ "def", "array", "@entries", "=", "[", "]", "@stack", "=", "[", "]", "if", "@leaf", "recurse", "(", "@map", ",", "0", ")", "return", "@entries", "end", "visit", "(", "@map", ",", "0", ")", "@entries", ".", "map", "{", "|", "stack", "|", "m", "=", "{", "}", "@keys", ".", "each_with_index", "{", "|", "k", ",", "i", "|", "v", "=", "stack", "[", "i", "]", "m", "[", "k", ".", "name", "]", "=", "k", ".", "value", "?", "k", ".", "value", ".", "js_call", "(", "self", ",", "v", ")", ":", "v", "}", "m", "}", "end" ]
Returns the flattened array. Each entry in the array is an object; each object has attributes corresponding to this flatten operator's keys. @returns an array of elements from the flattened map.
[ "Returns", "the", "flattened", "array", ".", "Each", "entry", "in", "the", "array", "is", "an", "object", ";", "each", "object", "has", "attributes", "corresponding", "to", "this", "flatten", "operator", "s", "keys", "." ]
59f5e76f1c352d68dd8f471f77a441ac9aaf784b
https://github.com/clbustos/rubyvis/blob/59f5e76f1c352d68dd8f471f77a441ac9aaf784b/lib/rubyvis/flatten.rb#L107-L123
19,214
clbustos/rubyvis
lib/rubyvis/mark/image.rb
Rubyvis.Image.bind
def bind mark_bind bind=self.binds mark=self begin binds.image = mark._image end while(!binds.image and (mark==mark.proto)) end
ruby
def bind mark_bind bind=self.binds mark=self begin binds.image = mark._image end while(!binds.image and (mark==mark.proto)) end
[ "def", "bind", "mark_bind", "bind", "=", "self", ".", "binds", "mark", "=", "self", "begin", "binds", ".", "image", "=", "mark", ".", "_image", "end", "while", "(", "!", "binds", ".", "image", "and", "(", "mark", "==", "mark", ".", "proto", ")", ")", "end" ]
Scan the proto chain for an image function.
[ "Scan", "the", "proto", "chain", "for", "an", "image", "function", "." ]
59f5e76f1c352d68dd8f471f77a441ac9aaf784b
https://github.com/clbustos/rubyvis/blob/59f5e76f1c352d68dd8f471f77a441ac9aaf784b/lib/rubyvis/mark/image.rb#L74-L81
19,215
clbustos/rubyvis
lib/rubyvis/scale/quantitative.rb
Rubyvis.Scale::Quantitative.scale
def scale(x) return nil if x.nil? x=x.to_f j=Rubyvis.search(@d, x) j=-j-2 if (j<0) j=[0,[@i.size-1,j].min].max # p @l # puts "Primero #{j}: #{@f.call(x) - @l[j]}" # puts "Segundo #{(@l[j + 1] - @l[j])}" @i[j].call((@f.call(x) - @l[j]) .quo(@l[j + 1] - @l[j])); end
ruby
def scale(x) return nil if x.nil? x=x.to_f j=Rubyvis.search(@d, x) j=-j-2 if (j<0) j=[0,[@i.size-1,j].min].max # p @l # puts "Primero #{j}: #{@f.call(x) - @l[j]}" # puts "Segundo #{(@l[j + 1] - @l[j])}" @i[j].call((@f.call(x) - @l[j]) .quo(@l[j + 1] - @l[j])); end
[ "def", "scale", "(", "x", ")", "return", "nil", "if", "x", ".", "nil?", "x", "=", "x", ".", "to_f", "j", "=", "Rubyvis", ".", "search", "(", "@d", ",", "x", ")", "j", "=", "-", "j", "-", "2", "if", "(", "j", "<", "0", ")", "j", "=", "[", "0", ",", "[", "@i", ".", "size", "-", "1", ",", "j", "]", ".", "min", "]", ".", "max", "# p @l", "# puts \"Primero #{j}: #{@f.call(x) - @l[j]}\"", "# puts \"Segundo #{(@l[j + 1] - @l[j])}\"", "@i", "[", "j", "]", ".", "call", "(", "(", "@f", ".", "call", "(", "x", ")", "-", "@l", "[", "j", "]", ")", ".", "quo", "(", "@l", "[", "j", "+", "1", "]", "-", "@l", "[", "j", "]", ")", ")", ";", "end" ]
Transform value +x+ according to domain and range
[ "Transform", "value", "+", "x", "+", "according", "to", "domain", "and", "range" ]
59f5e76f1c352d68dd8f471f77a441ac9aaf784b
https://github.com/clbustos/rubyvis/blob/59f5e76f1c352d68dd8f471f77a441ac9aaf784b/lib/rubyvis/scale/quantitative.rb#L94-L104
19,216
clbustos/rubyvis
lib/rubyvis/scale/log.rb
Rubyvis.Scale::Log.ticks
def ticks(subdivisions=nil) d = domain n = d[0] < 0 subdivisions||=@b span=@b.to_f / subdivisions # puts "dom: #{d[0]} -> #{n}" i = (n ? -log(-d[0]) : log(d[0])).floor j = (n ? -log(-d[1]) : log(d[1])).ceil ticks = []; if n ticks.push(-pow(-i)) (i..j).each {|ii| ((@b-1)...0).each {|k| ticks.push(-pow(-ii) * k) } } else (i...j).each {|ii| (1..subdivisions).each {|k| if k==1 ticks.push(pow(ii)) else next if subdivisions==@b and k==2 ticks.push(pow(ii)*span*(k-1)) end } } ticks.push(pow(j)); end # for (i = 0; ticks[i] < d[0]; i++); // strip small values # for (j = ticks.length; ticks[j - 1] > d[1]; j--); // strip big values # return ticks.slice(i, j); ticks.find_all {|v| v>=d[0] and v<=d[1]} end
ruby
def ticks(subdivisions=nil) d = domain n = d[0] < 0 subdivisions||=@b span=@b.to_f / subdivisions # puts "dom: #{d[0]} -> #{n}" i = (n ? -log(-d[0]) : log(d[0])).floor j = (n ? -log(-d[1]) : log(d[1])).ceil ticks = []; if n ticks.push(-pow(-i)) (i..j).each {|ii| ((@b-1)...0).each {|k| ticks.push(-pow(-ii) * k) } } else (i...j).each {|ii| (1..subdivisions).each {|k| if k==1 ticks.push(pow(ii)) else next if subdivisions==@b and k==2 ticks.push(pow(ii)*span*(k-1)) end } } ticks.push(pow(j)); end # for (i = 0; ticks[i] < d[0]; i++); // strip small values # for (j = ticks.length; ticks[j - 1] > d[1]; j--); // strip big values # return ticks.slice(i, j); ticks.find_all {|v| v>=d[0] and v<=d[1]} end
[ "def", "ticks", "(", "subdivisions", "=", "nil", ")", "d", "=", "domain", "n", "=", "d", "[", "0", "]", "<", "0", "subdivisions", "||=", "@b", "span", "=", "@b", ".", "to_f", "/", "subdivisions", "# puts \"dom: #{d[0]} -> #{n}\"", "i", "=", "(", "n", "?", "-", "log", "(", "-", "d", "[", "0", "]", ")", ":", "log", "(", "d", "[", "0", "]", ")", ")", ".", "floor", "j", "=", "(", "n", "?", "-", "log", "(", "-", "d", "[", "1", "]", ")", ":", "log", "(", "d", "[", "1", "]", ")", ")", ".", "ceil", "ticks", "=", "[", "]", ";", "if", "n", "ticks", ".", "push", "(", "-", "pow", "(", "-", "i", ")", ")", "(", "i", "..", "j", ")", ".", "each", "{", "|", "ii", "|", "(", "(", "@b", "-", "1", ")", "...", "0", ")", ".", "each", "{", "|", "k", "|", "ticks", ".", "push", "(", "-", "pow", "(", "-", "ii", ")", "*", "k", ")", "}", "}", "else", "(", "i", "...", "j", ")", ".", "each", "{", "|", "ii", "|", "(", "1", "..", "subdivisions", ")", ".", "each", "{", "|", "k", "|", "if", "k", "==", "1", "ticks", ".", "push", "(", "pow", "(", "ii", ")", ")", "else", "next", "if", "subdivisions", "==", "@b", "and", "k", "==", "2", "ticks", ".", "push", "(", "pow", "(", "ii", ")", "*", "span", "(", "k", "-", "1", ")", ")", "end", "}", "}", "ticks", ".", "push", "(", "pow", "(", "j", ")", ")", ";", "end", "# for (i = 0; ticks[i] < d[0]; i++); // strip small values", "# for (j = ticks.length; ticks[j - 1] > d[1]; j--); // strip big values", "# return ticks.slice(i, j);", "ticks", ".", "find_all", "{", "|", "v", "|", "v", ">=", "d", "[", "0", "]", "and", "v", "<=", "d", "[", "1", "]", "}", "end" ]
Returns an array of evenly-spaced, suitably-rounded values in the input domain. These values are frequently used in conjunction with Rule to display tick marks or grid lines. Subdivisions set the number of division inside each base^x By default, is set to base
[ "Returns", "an", "array", "of", "evenly", "-", "spaced", "suitably", "-", "rounded", "values", "in", "the", "input", "domain", ".", "These", "values", "are", "frequently", "used", "in", "conjunction", "with", "Rule", "to", "display", "tick", "marks", "or", "grid", "lines", "." ]
59f5e76f1c352d68dd8f471f77a441ac9aaf784b
https://github.com/clbustos/rubyvis/blob/59f5e76f1c352d68dd8f471f77a441ac9aaf784b/lib/rubyvis/scale/log.rb#L36-L71
19,217
motion-kit/motion-kit
lib/motion-kit/helpers/parent.rb
MotionKit.Parent.try
def try(*method_chain) obj = self.element method_chain.each do |m| # We'll break out and return nil if any part of the chain # doesn't respond properly. (obj = nil) && break unless obj.respond_to?(m) obj = obj.send(m) end obj end
ruby
def try(*method_chain) obj = self.element method_chain.each do |m| # We'll break out and return nil if any part of the chain # doesn't respond properly. (obj = nil) && break unless obj.respond_to?(m) obj = obj.send(m) end obj end
[ "def", "try", "(", "*", "method_chain", ")", "obj", "=", "self", ".", "element", "method_chain", ".", "each", "do", "|", "m", "|", "# We'll break out and return nil if any part of the chain", "# doesn't respond properly.", "(", "obj", "=", "nil", ")", "&&", "break", "unless", "obj", ".", "respond_to?", "(", "m", ")", "obj", "=", "obj", ".", "send", "(", "m", ")", "end", "obj", "end" ]
Convenience method that takes a list of method calls and tries them end-to-end, returning nil if any fail to respond to that method name. Very similar to ActiveSupport's `.try` method.
[ "Convenience", "method", "that", "takes", "a", "list", "of", "method", "calls", "and", "tries", "them", "end", "-", "to", "-", "end", "returning", "nil", "if", "any", "fail", "to", "respond", "to", "that", "method", "name", ".", "Very", "similar", "to", "ActiveSupport", "s", ".", "try", "method", "." ]
fa01dd08497b0dd01090156e58552be9d3b25ef1
https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/parent.rb#L59-L68
19,218
motion-kit/motion-kit
lib/motion-kit/helpers/base_layout_class_methods.rb
MotionKit.BaseLayoutClassMethods.memoize
def memoize(klass) @memoize ||= {} @memoize[klass] ||= begin while klass break if registered_class = target_klasses[klass] klass = klass.superclass end @memoize[klass] = registered_class if registered_class end @memoize[klass] end
ruby
def memoize(klass) @memoize ||= {} @memoize[klass] ||= begin while klass break if registered_class = target_klasses[klass] klass = klass.superclass end @memoize[klass] = registered_class if registered_class end @memoize[klass] end
[ "def", "memoize", "(", "klass", ")", "@memoize", "||=", "{", "}", "@memoize", "[", "klass", "]", "||=", "begin", "while", "klass", "break", "if", "registered_class", "=", "target_klasses", "[", "klass", "]", "klass", "=", "klass", ".", "superclass", "end", "@memoize", "[", "klass", "]", "=", "registered_class", "if", "registered_class", "end", "@memoize", "[", "klass", "]", "end" ]
Cache registered classes
[ "Cache", "registered", "classes" ]
fa01dd08497b0dd01090156e58552be9d3b25ef1
https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/base_layout_class_methods.rb#L31-L41
19,219
motion-kit/motion-kit
lib/motion-kit/helpers/tree_layout.rb
MotionKit.TreeLayout.create
def create(element, element_id=nil, &block) element = initialize_element(element, element_id) style_and_context(element, element_id, &block) element end
ruby
def create(element, element_id=nil, &block) element = initialize_element(element, element_id) style_and_context(element, element_id, &block) element end
[ "def", "create", "(", "element", ",", "element_id", "=", "nil", ",", "&", "block", ")", "element", "=", "initialize_element", "(", "element", ",", "element_id", ")", "style_and_context", "(", "element", ",", "element_id", ",", "block", ")", "element", "end" ]
instantiates a view, possibly running a 'layout block' to add child views.
[ "instantiates", "a", "view", "possibly", "running", "a", "layout", "block", "to", "add", "child", "views", "." ]
fa01dd08497b0dd01090156e58552be9d3b25ef1
https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L129-L134
19,220
motion-kit/motion-kit
lib/motion-kit/helpers/tree_layout.rb
MotionKit.TreeLayout.reapply
def reapply(&block) raise ArgumentError.new('Block required') unless block raise InvalidDeferredError.new('reapply must be run inside of a context') unless @context if reapply? yield end block = block.weak! parent_layout.reapply_blocks << [@context, block] return self end
ruby
def reapply(&block) raise ArgumentError.new('Block required') unless block raise InvalidDeferredError.new('reapply must be run inside of a context') unless @context if reapply? yield end block = block.weak! parent_layout.reapply_blocks << [@context, block] return self end
[ "def", "reapply", "(", "&", "block", ")", "raise", "ArgumentError", ".", "new", "(", "'Block required'", ")", "unless", "block", "raise", "InvalidDeferredError", ".", "new", "(", "'reapply must be run inside of a context'", ")", "unless", "@context", "if", "reapply?", "yield", "end", "block", "=", "block", ".", "weak!", "parent_layout", ".", "reapply_blocks", "<<", "[", "@context", ",", "block", "]", "return", "self", "end" ]
Blocks passed to `reapply` are only run when `reapply!` is called.
[ "Blocks", "passed", "to", "reapply", "are", "only", "run", "when", "reapply!", "is", "called", "." ]
fa01dd08497b0dd01090156e58552be9d3b25ef1
https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L163-L174
19,221
motion-kit/motion-kit
lib/motion-kit/helpers/tree_layout.rb
MotionKit.TreeLayout.get_view
def get_view(element_id) element = get(element_id) if element.is_a?(Layout) element = element.view end element end
ruby
def get_view(element_id) element = get(element_id) if element.is_a?(Layout) element = element.view end element end
[ "def", "get_view", "(", "element_id", ")", "element", "=", "get", "(", "element_id", ")", "if", "element", ".", "is_a?", "(", "Layout", ")", "element", "=", "element", ".", "view", "end", "element", "end" ]
Just like `get`, but if `get` returns a Layout, this method returns the layout's view.
[ "Just", "like", "get", "but", "if", "get", "returns", "a", "Layout", "this", "method", "returns", "the", "layout", "s", "view", "." ]
fa01dd08497b0dd01090156e58552be9d3b25ef1
https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L252-L258
19,222
motion-kit/motion-kit
lib/motion-kit/helpers/tree_layout.rb
MotionKit.TreeLayout.last_view
def last_view(element_id) element = last(element_id) if element.is_a?(Layout) element = element.view end element end
ruby
def last_view(element_id) element = last(element_id) if element.is_a?(Layout) element = element.view end element end
[ "def", "last_view", "(", "element_id", ")", "element", "=", "last", "(", "element_id", ")", "if", "element", ".", "is_a?", "(", "Layout", ")", "element", "=", "element", ".", "view", "end", "element", "end" ]
Just like `last`, but if `last` returns a Layout, this method returns the layout's view.
[ "Just", "like", "last", "but", "if", "last", "returns", "a", "Layout", "this", "method", "returns", "the", "layout", "s", "view", "." ]
fa01dd08497b0dd01090156e58552be9d3b25ef1
https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L272-L278
19,223
motion-kit/motion-kit
lib/motion-kit/helpers/tree_layout.rb
MotionKit.TreeLayout.all_views
def all_views(element_id) element = all(element_id) if element.is_a?(Layout) element = element.view end element end
ruby
def all_views(element_id) element = all(element_id) if element.is_a?(Layout) element = element.view end element end
[ "def", "all_views", "(", "element_id", ")", "element", "=", "all", "(", "element_id", ")", "if", "element", ".", "is_a?", "(", "Layout", ")", "element", "=", "element", ".", "view", "end", "element", "end" ]
Just like `all`, but if `all` returns a Layout, this method returns the layout's view.
[ "Just", "like", "all", "but", "if", "all", "returns", "a", "Layout", "this", "method", "returns", "the", "layout", "s", "view", "." ]
fa01dd08497b0dd01090156e58552be9d3b25ef1
https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L290-L296
19,224
motion-kit/motion-kit
lib/motion-kit/helpers/tree_layout.rb
MotionKit.TreeLayout.nth_view
def nth_view(element_id, index) element = nth(element_id) if element.is_a?(Layout) element = element.view end element end
ruby
def nth_view(element_id, index) element = nth(element_id) if element.is_a?(Layout) element = element.view end element end
[ "def", "nth_view", "(", "element_id", ",", "index", ")", "element", "=", "nth", "(", "element_id", ")", "if", "element", ".", "is_a?", "(", "Layout", ")", "element", "=", "element", ".", "view", "end", "element", "end" ]
Just like `nth`, but if `nth` returns a Layout, this method returns the layout's view.
[ "Just", "like", "nth", "but", "if", "nth", "returns", "a", "Layout", "this", "method", "returns", "the", "layout", "s", "view", "." ]
fa01dd08497b0dd01090156e58552be9d3b25ef1
https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L306-L312
19,225
motion-kit/motion-kit
lib/motion-kit/helpers/tree_layout.rb
MotionKit.TreeLayout.forget
def forget(element_id) unless is_parent_layout? return parent_layout.remove(element_id) end removed = nil context(self.view) do removed = all(element_id) @elements[element_id] = nil end removed end
ruby
def forget(element_id) unless is_parent_layout? return parent_layout.remove(element_id) end removed = nil context(self.view) do removed = all(element_id) @elements[element_id] = nil end removed end
[ "def", "forget", "(", "element_id", ")", "unless", "is_parent_layout?", "return", "parent_layout", ".", "remove", "(", "element_id", ")", "end", "removed", "=", "nil", "context", "(", "self", ".", "view", ")", "do", "removed", "=", "all", "(", "element_id", ")", "@elements", "[", "element_id", "]", "=", "nil", "end", "removed", "end" ]
Removes a view from the list of elements this layout is "tracking", but leaves it in the view hierarchy. Returns the views that were removed.
[ "Removes", "a", "view", "from", "the", "list", "of", "elements", "this", "layout", "is", "tracking", "but", "leaves", "it", "in", "the", "view", "hierarchy", ".", "Returns", "the", "views", "that", "were", "removed", "." ]
fa01dd08497b0dd01090156e58552be9d3b25ef1
https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L450-L460
19,226
motion-kit/motion-kit
lib/motion-kit/helpers/tree_layout.rb
MotionKit.TreeLayout.forget_tree
def forget_tree(element_id, view) removed = forget_view(element_id, view) if view.subviews view.subviews.each do | sub | if (sub_ids = sub.motion_kit_meta[:motion_kit_ids]) sub_ids.each do | sub_id | forget_tree(sub_id, sub) || [] end end end end removed end
ruby
def forget_tree(element_id, view) removed = forget_view(element_id, view) if view.subviews view.subviews.each do | sub | if (sub_ids = sub.motion_kit_meta[:motion_kit_ids]) sub_ids.each do | sub_id | forget_tree(sub_id, sub) || [] end end end end removed end
[ "def", "forget_tree", "(", "element_id", ",", "view", ")", "removed", "=", "forget_view", "(", "element_id", ",", "view", ")", "if", "view", ".", "subviews", "view", ".", "subviews", ".", "each", "do", "|", "sub", "|", "if", "(", "sub_ids", "=", "sub", ".", "motion_kit_meta", "[", ":motion_kit_ids", "]", ")", "sub_ids", ".", "each", "do", "|", "sub_id", "|", "forget_tree", "(", "sub_id", ",", "sub", ")", "||", "[", "]", "end", "end", "end", "end", "removed", "end" ]
returns the root view that was removed, if any
[ "returns", "the", "root", "view", "that", "was", "removed", "if", "any" ]
fa01dd08497b0dd01090156e58552be9d3b25ef1
https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L475-L487
19,227
motion-kit/motion-kit
lib/motion-kit/helpers/tree_layout.rb
MotionKit.TreeLayout.build_view
def build_view # Only in the 'layout' method will we allow default container to be # created automatically (when 'add' is called) @assign_root = true prev_should_run = @should_run_deferred @should_run_deferred = true layout unless @view if @assign_root create_default_root_context @view = @context else NSLog('Warning! No root view was set in TreeLayout#layout. Did you mean to call `root`?') end end run_deferred(@view) @should_run_deferred = prev_should_run @assign_root = false # context can be set via the 'create_default_root_context' method, which # may be outside a 'context' block, so make sure to restore context to # it's previous value @context = nil if @preset_root @view = WeakRef.new(@view) @preset_root = nil end @view end
ruby
def build_view # Only in the 'layout' method will we allow default container to be # created automatically (when 'add' is called) @assign_root = true prev_should_run = @should_run_deferred @should_run_deferred = true layout unless @view if @assign_root create_default_root_context @view = @context else NSLog('Warning! No root view was set in TreeLayout#layout. Did you mean to call `root`?') end end run_deferred(@view) @should_run_deferred = prev_should_run @assign_root = false # context can be set via the 'create_default_root_context' method, which # may be outside a 'context' block, so make sure to restore context to # it's previous value @context = nil if @preset_root @view = WeakRef.new(@view) @preset_root = nil end @view end
[ "def", "build_view", "# Only in the 'layout' method will we allow default container to be", "# created automatically (when 'add' is called)", "@assign_root", "=", "true", "prev_should_run", "=", "@should_run_deferred", "@should_run_deferred", "=", "true", "layout", "unless", "@view", "if", "@assign_root", "create_default_root_context", "@view", "=", "@context", "else", "NSLog", "(", "'Warning! No root view was set in TreeLayout#layout. Did you mean to call `root`?'", ")", "end", "end", "run_deferred", "(", "@view", ")", "@should_run_deferred", "=", "prev_should_run", "@assign_root", "=", "false", "# context can be set via the 'create_default_root_context' method, which", "# may be outside a 'context' block, so make sure to restore context to", "# it's previous value", "@context", "=", "nil", "if", "@preset_root", "@view", "=", "WeakRef", ".", "new", "(", "@view", ")", "@preset_root", "=", "nil", "end", "@view", "end" ]
This method builds the layout and returns the root view.
[ "This", "method", "builds", "the", "layout", "and", "returns", "the", "root", "view", "." ]
fa01dd08497b0dd01090156e58552be9d3b25ef1
https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L504-L533
19,228
motion-kit/motion-kit
lib/motion-kit/helpers/tree_layout.rb
MotionKit.TreeLayout.initialize_element
def initialize_element(elem, element_id) if elem.is_a?(Class) && elem < TreeLayout layout = elem.new elem = layout.view elsif elem.is_a?(Class) elem = elem.new elsif elem.is_a?(TreeLayout) layout = elem elem = elem.view end if layout if element_id name_element(layout, element_id) end @child_layouts << layout elsif element_id name_element(elem, element_id) end return elem end
ruby
def initialize_element(elem, element_id) if elem.is_a?(Class) && elem < TreeLayout layout = elem.new elem = layout.view elsif elem.is_a?(Class) elem = elem.new elsif elem.is_a?(TreeLayout) layout = elem elem = elem.view end if layout if element_id name_element(layout, element_id) end @child_layouts << layout elsif element_id name_element(elem, element_id) end return elem end
[ "def", "initialize_element", "(", "elem", ",", "element_id", ")", "if", "elem", ".", "is_a?", "(", "Class", ")", "&&", "elem", "<", "TreeLayout", "layout", "=", "elem", ".", "new", "elem", "=", "layout", ".", "view", "elsif", "elem", ".", "is_a?", "(", "Class", ")", "elem", "=", "elem", ".", "new", "elsif", "elem", ".", "is_a?", "(", "TreeLayout", ")", "layout", "=", "elem", "elem", "=", "elem", ".", "view", "end", "if", "layout", "if", "element_id", "name_element", "(", "layout", ",", "element_id", ")", "end", "@child_layouts", "<<", "layout", "elsif", "element_id", "name_element", "(", "elem", ",", "element_id", ")", "end", "return", "elem", "end" ]
Initializes an instance of a view. This will need to be smarter going forward as `new` isn't always the designated initializer. Accepts a view instance, a class (which is instantiated with 'new') or a `ViewLayout`, which returns the root view.
[ "Initializes", "an", "instance", "of", "a", "view", ".", "This", "will", "need", "to", "be", "smarter", "going", "forward", "as", "new", "isn", "t", "always", "the", "designated", "initializer", "." ]
fa01dd08497b0dd01090156e58552be9d3b25ef1
https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L543-L564
19,229
motion-kit/motion-kit
lib/motion-kit/helpers/tree_layout.rb
MotionKit.TreeLayout.style_and_context
def style_and_context(element, element_id, &block) style_method = "#{element_id}_style" if parent_layout.respond_to?(style_method) || block_given? parent_layout.context(element) do if parent_layout.respond_to?(style_method) parent_layout.send(style_method) end if block_given? yield end end end end
ruby
def style_and_context(element, element_id, &block) style_method = "#{element_id}_style" if parent_layout.respond_to?(style_method) || block_given? parent_layout.context(element) do if parent_layout.respond_to?(style_method) parent_layout.send(style_method) end if block_given? yield end end end end
[ "def", "style_and_context", "(", "element", ",", "element_id", ",", "&", "block", ")", "style_method", "=", "\"#{element_id}_style\"", "if", "parent_layout", ".", "respond_to?", "(", "style_method", ")", "||", "block_given?", "parent_layout", ".", "context", "(", "element", ")", "do", "if", "parent_layout", ".", "respond_to?", "(", "style_method", ")", "parent_layout", ".", "send", "(", "style_method", ")", "end", "if", "block_given?", "yield", "end", "end", "end", "end" ]
Calls the `_style` method with the element as the context, and runs the optional block in that context. This is usually done immediately after `initialize_element`, except in the case of `add`, which adds the item to the tree before styling it.
[ "Calls", "the", "_style", "method", "with", "the", "element", "as", "the", "context", "and", "runs", "the", "optional", "block", "in", "that", "context", ".", "This", "is", "usually", "done", "immediately", "after", "initialize_element", "except", "in", "the", "case", "of", "add", "which", "adds", "the", "item", "to", "the", "tree", "before", "styling", "it", "." ]
fa01dd08497b0dd01090156e58552be9d3b25ef1
https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/tree_layout.rb#L570-L583
19,230
motion-kit/motion-kit
lib/motion-kit/helpers/base_layout.rb
MotionKit.BaseLayout.context
def context(new_target, &block) return new_target unless block # this little line is incredibly important; the context is only set on # the top-level Layout object. # mp "MOTIONKIT CONTEXT is #{new_target} meta: #{new_target.motion_kit_meta}" return parent_layout.context(new_target, &block) unless is_parent_layout? if new_target.is_a?(Symbol) new_target = self.get_view(new_target) end context_was, parent_was, delegate_was = @context, @parent, @layout_delegate prev_should_run = @should_run_deferred if @should_run_deferred.nil? @should_run_deferred = true else @should_run_deferred = false end @parent = MK::Parent.new(context_was) @context = new_target @context.motion_kit_meta[:delegate] ||= Layout.layout_for(@context.class) @layout_delegate = @context.motion_kit_meta[:delegate] if @layout_delegate @layout_delegate.set_parent_layout(parent_layout) end yield @layout_delegate, @context, @parent = delegate_was, context_was, parent_was if @should_run_deferred run_deferred(new_target) end @should_run_deferred = prev_should_run new_target end
ruby
def context(new_target, &block) return new_target unless block # this little line is incredibly important; the context is only set on # the top-level Layout object. # mp "MOTIONKIT CONTEXT is #{new_target} meta: #{new_target.motion_kit_meta}" return parent_layout.context(new_target, &block) unless is_parent_layout? if new_target.is_a?(Symbol) new_target = self.get_view(new_target) end context_was, parent_was, delegate_was = @context, @parent, @layout_delegate prev_should_run = @should_run_deferred if @should_run_deferred.nil? @should_run_deferred = true else @should_run_deferred = false end @parent = MK::Parent.new(context_was) @context = new_target @context.motion_kit_meta[:delegate] ||= Layout.layout_for(@context.class) @layout_delegate = @context.motion_kit_meta[:delegate] if @layout_delegate @layout_delegate.set_parent_layout(parent_layout) end yield @layout_delegate, @context, @parent = delegate_was, context_was, parent_was if @should_run_deferred run_deferred(new_target) end @should_run_deferred = prev_should_run new_target end
[ "def", "context", "(", "new_target", ",", "&", "block", ")", "return", "new_target", "unless", "block", "# this little line is incredibly important; the context is only set on", "# the top-level Layout object.", "# mp \"MOTIONKIT CONTEXT is #{new_target} meta: #{new_target.motion_kit_meta}\"", "return", "parent_layout", ".", "context", "(", "new_target", ",", "block", ")", "unless", "is_parent_layout?", "if", "new_target", ".", "is_a?", "(", "Symbol", ")", "new_target", "=", "self", ".", "get_view", "(", "new_target", ")", "end", "context_was", ",", "parent_was", ",", "delegate_was", "=", "@context", ",", "@parent", ",", "@layout_delegate", "prev_should_run", "=", "@should_run_deferred", "if", "@should_run_deferred", ".", "nil?", "@should_run_deferred", "=", "true", "else", "@should_run_deferred", "=", "false", "end", "@parent", "=", "MK", "::", "Parent", ".", "new", "(", "context_was", ")", "@context", "=", "new_target", "@context", ".", "motion_kit_meta", "[", ":delegate", "]", "||=", "Layout", ".", "layout_for", "(", "@context", ".", "class", ")", "@layout_delegate", "=", "@context", ".", "motion_kit_meta", "[", ":delegate", "]", "if", "@layout_delegate", "@layout_delegate", ".", "set_parent_layout", "(", "parent_layout", ")", "end", "yield", "@layout_delegate", ",", "@context", ",", "@parent", "=", "delegate_was", ",", "context_was", ",", "parent_was", "if", "@should_run_deferred", "run_deferred", "(", "new_target", ")", "end", "@should_run_deferred", "=", "prev_should_run", "new_target", "end" ]
Runs a block of code with a new object as the 'context'. Methods from the Layout classes are applied to this target object, and missing methods are delegated to a new Layout instance that is created based on the new context. This method is part of the public API, you can pass in any object to have it become the 'context'. Example: def table_view_style content = target.contentView if content context(content) do background_color UIColor.clearColor end end # usually you use 'context' automatically via method_missing, by # passing a block to a method that returns an object. That object becomes # the new context. layer do # target is now a CALayer, and methods are delegated to CALayerHelpers corner_radius 5 end end
[ "Runs", "a", "block", "of", "code", "with", "a", "new", "object", "as", "the", "context", ".", "Methods", "from", "the", "Layout", "classes", "are", "applied", "to", "this", "target", "object", "and", "missing", "methods", "are", "delegated", "to", "a", "new", "Layout", "instance", "that", "is", "created", "based", "on", "the", "new", "context", "." ]
fa01dd08497b0dd01090156e58552be9d3b25ef1
https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit/helpers/base_layout.rb#L91-L126
19,231
motion-kit/motion-kit
lib/motion-kit-osx/helpers/nsmenu_helpers.rb
MotionKit.MenuLayout.root
def root(element, element_id=nil, &block) if element && element.is_a?(NSString) element = NSMenu.alloc.initWithTitle(element) end super(element, element_id, &block) end
ruby
def root(element, element_id=nil, &block) if element && element.is_a?(NSString) element = NSMenu.alloc.initWithTitle(element) end super(element, element_id, &block) end
[ "def", "root", "(", "element", ",", "element_id", "=", "nil", ",", "&", "block", ")", "if", "element", "&&", "element", ".", "is_a?", "(", "NSString", ")", "element", "=", "NSMenu", ".", "alloc", ".", "initWithTitle", "(", "element", ")", "end", "super", "(", "element", ",", "element_id", ",", "block", ")", "end" ]
override root to allow a menu title for the top level menu
[ "override", "root", "to", "allow", "a", "menu", "title", "for", "the", "top", "level", "menu" ]
fa01dd08497b0dd01090156e58552be9d3b25ef1
https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit-osx/helpers/nsmenu_helpers.rb#L28-L33
19,232
motion-kit/motion-kit
lib/motion-kit-osx/helpers/nsmenu_helpers.rb
MotionKit.MenuLayout.add
def add(title_or_item, element_id=nil, options={}, &block) if element_id.is_a?(NSDictionary) options = element_id element_id = nil end if title_or_item.is_a?(NSMenuItem) item = title_or_item menu = nil retval = item elsif title_or_item.is_a?(NSMenu) menu = title_or_item item = self.item(menu.title, options) item.submenu = menu retval = menu else title = title_or_item item = self.item(title, options) if block menu = create(title) item.submenu = menu retval = menu else retval = item end end self.apply(:add_child, item) if menu && block menuitem_was = @menu_item @menu_item = item context(menu, &block) @menu_item = menuitem_was end if element_id create(retval, element_id) end return retval end
ruby
def add(title_or_item, element_id=nil, options={}, &block) if element_id.is_a?(NSDictionary) options = element_id element_id = nil end if title_or_item.is_a?(NSMenuItem) item = title_or_item menu = nil retval = item elsif title_or_item.is_a?(NSMenu) menu = title_or_item item = self.item(menu.title, options) item.submenu = menu retval = menu else title = title_or_item item = self.item(title, options) if block menu = create(title) item.submenu = menu retval = menu else retval = item end end self.apply(:add_child, item) if menu && block menuitem_was = @menu_item @menu_item = item context(menu, &block) @menu_item = menuitem_was end if element_id create(retval, element_id) end return retval end
[ "def", "add", "(", "title_or_item", ",", "element_id", "=", "nil", ",", "options", "=", "{", "}", ",", "&", "block", ")", "if", "element_id", ".", "is_a?", "(", "NSDictionary", ")", "options", "=", "element_id", "element_id", "=", "nil", "end", "if", "title_or_item", ".", "is_a?", "(", "NSMenuItem", ")", "item", "=", "title_or_item", "menu", "=", "nil", "retval", "=", "item", "elsif", "title_or_item", ".", "is_a?", "(", "NSMenu", ")", "menu", "=", "title_or_item", "item", "=", "self", ".", "item", "(", "menu", ".", "title", ",", "options", ")", "item", ".", "submenu", "=", "menu", "retval", "=", "menu", "else", "title", "=", "title_or_item", "item", "=", "self", ".", "item", "(", "title", ",", "options", ")", "if", "block", "menu", "=", "create", "(", "title", ")", "item", ".", "submenu", "=", "menu", "retval", "=", "menu", "else", "retval", "=", "item", "end", "end", "self", ".", "apply", "(", ":add_child", ",", "item", ")", "if", "menu", "&&", "block", "menuitem_was", "=", "@menu_item", "@menu_item", "=", "item", "context", "(", "menu", ",", "block", ")", "@menu_item", "=", "menuitem_was", "end", "if", "element_id", "create", "(", "retval", ",", "element_id", ")", "end", "return", "retval", "end" ]
override 'add'; menus are just a horse of a different color.
[ "override", "add", ";", "menus", "are", "just", "a", "horse", "of", "a", "different", "color", "." ]
fa01dd08497b0dd01090156e58552be9d3b25ef1
https://github.com/motion-kit/motion-kit/blob/fa01dd08497b0dd01090156e58552be9d3b25ef1/lib/motion-kit-osx/helpers/nsmenu_helpers.rb#L36-L78
19,233
cookpad/expeditor
lib/expeditor/command.rb
Expeditor.Command.start_with_retry
def start_with_retry(current_thread: false, **retryable_options) unless started? @retryable_options.set(retryable_options) start(current_thread: current_thread) end self end
ruby
def start_with_retry(current_thread: false, **retryable_options) unless started? @retryable_options.set(retryable_options) start(current_thread: current_thread) end self end
[ "def", "start_with_retry", "(", "current_thread", ":", "false", ",", "**", "retryable_options", ")", "unless", "started?", "@retryable_options", ".", "set", "(", "retryable_options", ")", "start", "(", "current_thread", ":", "current_thread", ")", "end", "self", "end" ]
Equivalent to retryable gem options
[ "Equivalent", "to", "retryable", "gem", "options" ]
1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e
https://github.com/cookpad/expeditor/blob/1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e/lib/expeditor/command.rb#L39-L45
19,234
cookpad/expeditor
lib/expeditor/command.rb
Expeditor.Command.on_complete
def on_complete(&block) on do |_, value, reason| block.call(reason == nil, value, reason) end end
ruby
def on_complete(&block) on do |_, value, reason| block.call(reason == nil, value, reason) end end
[ "def", "on_complete", "(", "&", "block", ")", "on", "do", "|", "_", ",", "value", ",", "reason", "|", "block", ".", "call", "(", "reason", "==", "nil", ",", "value", ",", "reason", ")", "end", "end" ]
command.on_complete do |success, value, reason| ... end
[ "command", ".", "on_complete", "do", "|success", "value", "reason|", "...", "end" ]
1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e
https://github.com/cookpad/expeditor/blob/1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e/lib/expeditor/command.rb#L88-L92
19,235
cookpad/expeditor
lib/expeditor/command.rb
Expeditor.Command.on_success
def on_success(&block) on do |_, value, reason| block.call(value) unless reason end end
ruby
def on_success(&block) on do |_, value, reason| block.call(value) unless reason end end
[ "def", "on_success", "(", "&", "block", ")", "on", "do", "|", "_", ",", "value", ",", "reason", "|", "block", ".", "call", "(", "value", ")", "unless", "reason", "end", "end" ]
command.on_success do |value| ... end
[ "command", ".", "on_success", "do", "|value|", "...", "end" ]
1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e
https://github.com/cookpad/expeditor/blob/1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e/lib/expeditor/command.rb#L97-L101
19,236
cookpad/expeditor
lib/expeditor/command.rb
Expeditor.Command.on_failure
def on_failure(&block) on do |_, _, reason| block.call(reason) if reason end end
ruby
def on_failure(&block) on do |_, _, reason| block.call(reason) if reason end end
[ "def", "on_failure", "(", "&", "block", ")", "on", "do", "|", "_", ",", "_", ",", "reason", "|", "block", ".", "call", "(", "reason", ")", "if", "reason", "end", "end" ]
command.on_failure do |e| ... end
[ "command", ".", "on_failure", "do", "|e|", "...", "end" ]
1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e
https://github.com/cookpad/expeditor/blob/1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e/lib/expeditor/command.rb#L106-L110
19,237
cookpad/expeditor
lib/expeditor/command.rb
Expeditor.Command.prepare
def prepare(executor = @service.executor) @normal_future = initial_normal(executor, &@normal_block) @normal_future.add_observer do |_, value, reason| if reason # failure if @fallback_block future = RichFuture.new(executor: executor) do success, value, reason = Concurrent::SafeTaskExecutor.new(@fallback_block, rescue_exception: true).execute(reason) if success @ivar.set(value) else @ivar.fail(reason) end end future.safe_execute else @ivar.fail(reason) end else # success @ivar.set(value) end end @dependencies.each(&:start) end
ruby
def prepare(executor = @service.executor) @normal_future = initial_normal(executor, &@normal_block) @normal_future.add_observer do |_, value, reason| if reason # failure if @fallback_block future = RichFuture.new(executor: executor) do success, value, reason = Concurrent::SafeTaskExecutor.new(@fallback_block, rescue_exception: true).execute(reason) if success @ivar.set(value) else @ivar.fail(reason) end end future.safe_execute else @ivar.fail(reason) end else # success @ivar.set(value) end end @dependencies.each(&:start) end
[ "def", "prepare", "(", "executor", "=", "@service", ".", "executor", ")", "@normal_future", "=", "initial_normal", "(", "executor", ",", "@normal_block", ")", "@normal_future", ".", "add_observer", "do", "|", "_", ",", "value", ",", "reason", "|", "if", "reason", "# failure", "if", "@fallback_block", "future", "=", "RichFuture", ".", "new", "(", "executor", ":", "executor", ")", "do", "success", ",", "value", ",", "reason", "=", "Concurrent", "::", "SafeTaskExecutor", ".", "new", "(", "@fallback_block", ",", "rescue_exception", ":", "true", ")", ".", "execute", "(", "reason", ")", "if", "success", "@ivar", ".", "set", "(", "value", ")", "else", "@ivar", ".", "fail", "(", "reason", ")", "end", "end", "future", ".", "safe_execute", "else", "@ivar", ".", "fail", "(", "reason", ")", "end", "else", "# success", "@ivar", ".", "set", "(", "value", ")", "end", "end", "@dependencies", ".", "each", "(", ":start", ")", "end" ]
set future set fallback future as an observer start dependencies
[ "set", "future", "set", "fallback", "future", "as", "an", "observer", "start", "dependencies" ]
1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e
https://github.com/cookpad/expeditor/blob/1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e/lib/expeditor/command.rb#L134-L157
19,238
cookpad/expeditor
lib/expeditor/command.rb
Expeditor.Command.initial_normal
def initial_normal(executor, &block) future = RichFuture.new(executor: executor) do args = wait_dependencies timeout_block(args, &block) end future.add_observer do |_, _, reason| metrics(reason) end future end
ruby
def initial_normal(executor, &block) future = RichFuture.new(executor: executor) do args = wait_dependencies timeout_block(args, &block) end future.add_observer do |_, _, reason| metrics(reason) end future end
[ "def", "initial_normal", "(", "executor", ",", "&", "block", ")", "future", "=", "RichFuture", ".", "new", "(", "executor", ":", "executor", ")", "do", "args", "=", "wait_dependencies", "timeout_block", "(", "args", ",", "block", ")", "end", "future", ".", "add_observer", "do", "|", "_", ",", "_", ",", "reason", "|", "metrics", "(", "reason", ")", "end", "future", "end" ]
timeout_block do retryable_block do breakable_block do block.call end end end
[ "timeout_block", "do", "retryable_block", "do", "breakable_block", "do", "block", ".", "call", "end", "end", "end" ]
1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e
https://github.com/cookpad/expeditor/blob/1dd5bb434d7cb6bd6063ab7eb7b5c80d395be92e/lib/expeditor/command.rb#L166-L175
19,239
david942j/gdb-ruby
lib/gdb/eval_context.rb
GDB.EvalContext.invoke_pry
def invoke_pry org = Pry.config.history.file # this has no effect if gdb is launched by pry Pry.config.history.file = '~/.gdb-pry_history' $stdin.cooked { pry } Pry.config.history.file = org end
ruby
def invoke_pry org = Pry.config.history.file # this has no effect if gdb is launched by pry Pry.config.history.file = '~/.gdb-pry_history' $stdin.cooked { pry } Pry.config.history.file = org end
[ "def", "invoke_pry", "org", "=", "Pry", ".", "config", ".", "history", ".", "file", "# this has no effect if gdb is launched by pry", "Pry", ".", "config", ".", "history", ".", "file", "=", "'~/.gdb-pry_history'", "$stdin", ".", "cooked", "{", "pry", "}", "Pry", ".", "config", ".", "history", ".", "file", "=", "org", "end" ]
Invoke pry, wrapper with some settings. @return [void]
[ "Invoke", "pry", "wrapper", "with", "some", "settings", "." ]
1c6fcca14314dd8289bc3598bdf2b72235bfbb4e
https://github.com/david942j/gdb-ruby/blob/1c6fcca14314dd8289bc3598bdf2b72235bfbb4e/lib/gdb/eval_context.rb#L25-L31
19,240
david942j/gdb-ruby
lib/gdb/gdb.rb
GDB.GDB.text_base
def text_base check_alive! base = Integer(execute('info proc stat').scan(/Start of text: (.*)/).flatten.first) execute("set $text = #{base}") base end
ruby
def text_base check_alive! base = Integer(execute('info proc stat').scan(/Start of text: (.*)/).flatten.first) execute("set $text = #{base}") base end
[ "def", "text_base", "check_alive!", "base", "=", "Integer", "(", "execute", "(", "'info proc stat'", ")", ".", "scan", "(", "/", "/", ")", ".", "flatten", ".", "first", ")", "execute", "(", "\"set $text = #{base}\"", ")", "base", "end" ]
Get the process's text base. @return [Integer] The base address. @note This will also set a variable +$text+ in gdb.
[ "Get", "the", "process", "s", "text", "base", "." ]
1c6fcca14314dd8289bc3598bdf2b72235bfbb4e
https://github.com/david942j/gdb-ruby/blob/1c6fcca14314dd8289bc3598bdf2b72235bfbb4e/lib/gdb/gdb.rb#L136-L141
19,241
david942j/gdb-ruby
lib/gdb/gdb.rb
GDB.GDB.read_memory
def read_memory(addr, num_elements, options = {}, &block) check_alive! # this would set @pid options[:as] = block if block_given? MemoryIO.attach(@pid).read(addr, num_elements, **options) end
ruby
def read_memory(addr, num_elements, options = {}, &block) check_alive! # this would set @pid options[:as] = block if block_given? MemoryIO.attach(@pid).read(addr, num_elements, **options) end
[ "def", "read_memory", "(", "addr", ",", "num_elements", ",", "options", "=", "{", "}", ",", "&", "block", ")", "check_alive!", "# this would set @pid", "options", "[", ":as", "]", "=", "block", "if", "block_given?", "MemoryIO", ".", "attach", "(", "@pid", ")", ".", "read", "(", "addr", ",", "num_elements", ",", "**", "options", ")", "end" ]
Read current process's memory. @param [Integer, String] addr Address to start to read. +addr+ can be a string like 'heap+0x10'. Supported variables are names in /proc/$pid/maps such as +heap/libc/stack/ld+. @param [Integer] num_elements Number of elements to read. If +num_elements+ equals to 1, an object read will be returned. Otherwise, an array with size +num_elements+ will be returned. @option [Symbol, Class] as Types that supported by [MemoryIO](https://github.com/david942j/memory_io). @return [Object, Array<Object>] Return types are decided by value of +num_elements+ and option +as+. @yieldparam [IO] io The +IO+ object that points to +addr+, read from it. @yieldreturn [Object] Whatever you read from +io+. @example gdb = GDB::GDB.new('spec/binaries/amd64.elf') gdb.break('main') gdb.run gdb.read_memory('amd64.elf', 4) #=> "\x7fELF" @example # example of fetching argv gdb = GDB::GDB.new('spec/binaries/amd64.elf') gdb.break('main') gdb.run('pusheen the cat') gdb.read_memory(0x400000, 4) #=> "\x7fELF" argc = gdb.register(:rdi) #=> 4 args = gdb.read_memory(gdb.register(:rsi), argc, as: :u64) Array.new(3) do |i| gdb.read_memory(args[i + 1], 1) do |m| str = '' loop do c = m.read(1) break if c == "\x00" str << c end str end end #=> ["pusheen", "the", "cat"] # or, use our build-in types of gem +memory_io+. gdb.read_memory(args[1], 3, as: :c_str) #=> ["pusheen", "the", "cat"]
[ "Read", "current", "process", "s", "memory", "." ]
1c6fcca14314dd8289bc3598bdf2b72235bfbb4e
https://github.com/david942j/gdb-ruby/blob/1c6fcca14314dd8289bc3598bdf2b72235bfbb4e/lib/gdb/gdb.rb#L255-L259
19,242
david942j/gdb-ruby
lib/gdb/gdb.rb
GDB.GDB.write_memory
def write_memory(addr, objects, options = {}, &block) check_alive! # this would set @pid options[:as] = block if block_given? MemoryIO.attach(@pid).write(addr, objects, **options) end
ruby
def write_memory(addr, objects, options = {}, &block) check_alive! # this would set @pid options[:as] = block if block_given? MemoryIO.attach(@pid).write(addr, objects, **options) end
[ "def", "write_memory", "(", "addr", ",", "objects", ",", "options", "=", "{", "}", ",", "&", "block", ")", "check_alive!", "# this would set @pid", "options", "[", ":as", "]", "=", "block", "if", "block_given?", "MemoryIO", ".", "attach", "(", "@pid", ")", ".", "write", "(", "addr", ",", "objects", ",", "**", "options", ")", "end" ]
Write an object to process at specific address. @param [Integer, String] addr Target address. +addr+ can be a string like 'heap+0x10'. Supported variables are names in +/proc/$pid/maps+ such as +heap/libc/stack/ld+. @param [Objects, Array<Objects>] objects Objects to be written. @option [Symbol, Class] as See {#read_memory}. @return [void]
[ "Write", "an", "object", "to", "process", "at", "specific", "address", "." ]
1c6fcca14314dd8289bc3598bdf2b72235bfbb4e
https://github.com/david942j/gdb-ruby/blob/1c6fcca14314dd8289bc3598bdf2b72235bfbb4e/lib/gdb/gdb.rb#L275-L279
19,243
ashfurrow/danger-rubocop
lib/danger_plugin.rb
Danger.DangerRubocop.lint
def lint(config = nil) config = config.is_a?(Hash) ? config : { files: config } files = config[:files] force_exclusion = config[:force_exclusion] || false report_danger = config[:report_danger] || false inline_comment = config[:inline_comment] || false fail_on_inline_comment = config[:fail_on_inline_comment] || false files_to_lint = fetch_files_to_lint(files) files_to_report = rubocop(files_to_lint, force_exclusion) return if files_to_report.empty? return report_failures files_to_report if report_danger if inline_comment add_violation_for_each_line(files_to_report, fail_on_inline_comment) else markdown offenses_message(files_to_report) end end
ruby
def lint(config = nil) config = config.is_a?(Hash) ? config : { files: config } files = config[:files] force_exclusion = config[:force_exclusion] || false report_danger = config[:report_danger] || false inline_comment = config[:inline_comment] || false fail_on_inline_comment = config[:fail_on_inline_comment] || false files_to_lint = fetch_files_to_lint(files) files_to_report = rubocop(files_to_lint, force_exclusion) return if files_to_report.empty? return report_failures files_to_report if report_danger if inline_comment add_violation_for_each_line(files_to_report, fail_on_inline_comment) else markdown offenses_message(files_to_report) end end
[ "def", "lint", "(", "config", "=", "nil", ")", "config", "=", "config", ".", "is_a?", "(", "Hash", ")", "?", "config", ":", "{", "files", ":", "config", "}", "files", "=", "config", "[", ":files", "]", "force_exclusion", "=", "config", "[", ":force_exclusion", "]", "||", "false", "report_danger", "=", "config", "[", ":report_danger", "]", "||", "false", "inline_comment", "=", "config", "[", ":inline_comment", "]", "||", "false", "fail_on_inline_comment", "=", "config", "[", ":fail_on_inline_comment", "]", "||", "false", "files_to_lint", "=", "fetch_files_to_lint", "(", "files", ")", "files_to_report", "=", "rubocop", "(", "files_to_lint", ",", "force_exclusion", ")", "return", "if", "files_to_report", ".", "empty?", "return", "report_failures", "files_to_report", "if", "report_danger", "if", "inline_comment", "add_violation_for_each_line", "(", "files_to_report", ",", "fail_on_inline_comment", ")", "else", "markdown", "offenses_message", "(", "files_to_report", ")", "end", "end" ]
Runs Ruby files through Rubocop. Generates a `markdown` list of warnings. @param [String] files A globbed string which should return the files that you want to run through, defaults to nil. If nil, modified and added files from the diff will be used. @return [void]
[ "Runs", "Ruby", "files", "through", "Rubocop", ".", "Generates", "a", "markdown", "list", "of", "warnings", "." ]
3959cca96dca031a0740576ac22471b80f671b82
https://github.com/ashfurrow/danger-rubocop/blob/3959cca96dca031a0740576ac22471b80f671b82/lib/danger_plugin.rb#L29-L50
19,244
protobuf-ruby/beefcake
lib/beefcake/generator.rb
Beefcake.Generator.name_for
def name_for(b, mod, val) b.name_for(mod, val).to_s.gsub(/.*_/, "").downcase end
ruby
def name_for(b, mod, val) b.name_for(mod, val).to_s.gsub(/.*_/, "").downcase end
[ "def", "name_for", "(", "b", ",", "mod", ",", "val", ")", "b", ".", "name_for", "(", "mod", ",", "val", ")", ".", "to_s", ".", "gsub", "(", "/", "/", ",", "\"\"", ")", ".", "downcase", "end" ]
Determines the name for a
[ "Determines", "the", "name", "for", "a" ]
c0a97e7ca05b4d2f980509e85c4a49dfe7acbc5a
https://github.com/protobuf-ruby/beefcake/blob/c0a97e7ca05b4d2f980509e85c4a49dfe7acbc5a/lib/beefcake/generator.rb#L267-L269
19,245
imikimi/literate_randomizer
lib/literate_randomizer/source_parser.rb
LiterateRandomizer.SourceParser.scrub_sentence
def scrub_sentence(sentence) sentence.split(/([\s]|--)+/).collect {|a| scrub_word(a)}.select {|a| a.length>0} end
ruby
def scrub_sentence(sentence) sentence.split(/([\s]|--)+/).collect {|a| scrub_word(a)}.select {|a| a.length>0} end
[ "def", "scrub_sentence", "(", "sentence", ")", "sentence", ".", "split", "(", "/", "\\s", "/", ")", ".", "collect", "{", "|", "a", "|", "scrub_word", "(", "a", ")", "}", ".", "select", "{", "|", "a", "|", "a", ".", "length", ">", "0", "}", "end" ]
clean up all words in a string, returning an array of clean words
[ "clean", "up", "all", "words", "in", "a", "string", "returning", "an", "array", "of", "clean", "words" ]
55d123f230b13c62de6f815063edf0d9b7dce306
https://github.com/imikimi/literate_randomizer/blob/55d123f230b13c62de6f815063edf0d9b7dce306/lib/literate_randomizer/source_parser.rb#L44-L46
19,246
imikimi/literate_randomizer
lib/literate_randomizer/markov.rb
LiterateRandomizer.MarkovModel.next_word
def next_word(word,randomizer=@randomizer) return if !markov_chains[word] sum = @markov_weighted_sum[word] random = randomizer.rand(sum)+1 partial_sum = 0 (markov_chains[word].find do |w, count| partial_sum += count w!=word && partial_sum >= random end||[]).first end
ruby
def next_word(word,randomizer=@randomizer) return if !markov_chains[word] sum = @markov_weighted_sum[word] random = randomizer.rand(sum)+1 partial_sum = 0 (markov_chains[word].find do |w, count| partial_sum += count w!=word && partial_sum >= random end||[]).first end
[ "def", "next_word", "(", "word", ",", "randomizer", "=", "@randomizer", ")", "return", "if", "!", "markov_chains", "[", "word", "]", "sum", "=", "@markov_weighted_sum", "[", "word", "]", "random", "=", "randomizer", ".", "rand", "(", "sum", ")", "+", "1", "partial_sum", "=", "0", "(", "markov_chains", "[", "word", "]", ".", "find", "do", "|", "w", ",", "count", "|", "partial_sum", "+=", "count", "w!", "=", "word", "&&", "partial_sum", ">=", "random", "end", "||", "[", "]", ")", ".", "first", "end" ]
Initialize a new instance. Options: * :randomizer => Random.new # must respond to #rand(limit) * :source_parser => SourceParser.new options Given a word, return a weighted-randomly selected next-one.
[ "Initialize", "a", "new", "instance", "." ]
55d123f230b13c62de6f815063edf0d9b7dce306
https://github.com/imikimi/literate_randomizer/blob/55d123f230b13c62de6f815063edf0d9b7dce306/lib/literate_randomizer/markov.rb#L99-L108
19,247
imikimi/literate_randomizer
lib/literate_randomizer/randomizer.rb
LiterateRandomizer.Randomizer.extend_trailing_preposition
def extend_trailing_preposition(max_words,words) while words.length < max_words && words[-1] && words[-1][PREPOSITION_REGEX] words << model.next_word(words[-1],randomizer) end words end
ruby
def extend_trailing_preposition(max_words,words) while words.length < max_words && words[-1] && words[-1][PREPOSITION_REGEX] words << model.next_word(words[-1],randomizer) end words end
[ "def", "extend_trailing_preposition", "(", "max_words", ",", "words", ")", "while", "words", ".", "length", "<", "max_words", "&&", "words", "[", "-", "1", "]", "&&", "words", "[", "-", "1", "]", "[", "PREPOSITION_REGEX", "]", "words", "<<", "model", ".", "next_word", "(", "words", "[", "-", "1", "]", ",", "randomizer", ")", "end", "words", "end" ]
Check to see if the sentence ends in a PREPOSITION_REGEX word. If so, add more words up to max-words until it does.
[ "Check", "to", "see", "if", "the", "sentence", "ends", "in", "a", "PREPOSITION_REGEX", "word", ".", "If", "so", "add", "more", "words", "up", "to", "max", "-", "words", "until", "it", "does", "." ]
55d123f230b13c62de6f815063edf0d9b7dce306
https://github.com/imikimi/literate_randomizer/blob/55d123f230b13c62de6f815063edf0d9b7dce306/lib/literate_randomizer/randomizer.rb#L32-L37
19,248
imikimi/literate_randomizer
lib/literate_randomizer/randomizer.rb
LiterateRandomizer.Randomizer.sentence
def sentence(options={}) word = options[:first_word] || self.first_word num_words_option = options[:words] || (3..15) count = Util.rand_count(num_words_option,randomizer) punctuation = options[:punctuation] || self.punctuation words = count.times.collect do word.tap {word = model.next_word(word,randomizer)} end.compact words = extend_trailing_preposition(Util.max(num_words_option), words) Util.capitalize words.compact.join(" ") + punctuation end
ruby
def sentence(options={}) word = options[:first_word] || self.first_word num_words_option = options[:words] || (3..15) count = Util.rand_count(num_words_option,randomizer) punctuation = options[:punctuation] || self.punctuation words = count.times.collect do word.tap {word = model.next_word(word,randomizer)} end.compact words = extend_trailing_preposition(Util.max(num_words_option), words) Util.capitalize words.compact.join(" ") + punctuation end
[ "def", "sentence", "(", "options", "=", "{", "}", ")", "word", "=", "options", "[", ":first_word", "]", "||", "self", ".", "first_word", "num_words_option", "=", "options", "[", ":words", "]", "||", "(", "3", "..", "15", ")", "count", "=", "Util", ".", "rand_count", "(", "num_words_option", ",", "randomizer", ")", "punctuation", "=", "options", "[", ":punctuation", "]", "||", "self", ".", "punctuation", "words", "=", "count", ".", "times", ".", "collect", "do", "word", ".", "tap", "{", "word", "=", "model", ".", "next_word", "(", "word", ",", "randomizer", ")", "}", "end", ".", "compact", "words", "=", "extend_trailing_preposition", "(", "Util", ".", "max", "(", "num_words_option", ")", ",", "words", ")", "Util", ".", "capitalize", "words", ".", "compact", ".", "join", "(", "\" \"", ")", "+", "punctuation", "end" ]
return a random sentence Options: * :first_word => nil - the start word * :words => range or int - number of words in sentence * :punctuation => nil - punction to end the sentence with (nil == randomly selected from punctuation_distribution)
[ "return", "a", "random", "sentence" ]
55d123f230b13c62de6f815063edf0d9b7dce306
https://github.com/imikimi/literate_randomizer/blob/55d123f230b13c62de6f815063edf0d9b7dce306/lib/literate_randomizer/randomizer.rb#L96-L109
19,249
imikimi/literate_randomizer
lib/literate_randomizer/randomizer.rb
LiterateRandomizer.Randomizer.paragraph
def paragraph(options={}) count = Util.rand_count(options[:sentences] || (5..15),randomizer) count.times.collect do |i| op = options.clone op.delete :punctuation unless i==count-1 op.delete :first_word unless i==0 sentence op end.join(" ") end
ruby
def paragraph(options={}) count = Util.rand_count(options[:sentences] || (5..15),randomizer) count.times.collect do |i| op = options.clone op.delete :punctuation unless i==count-1 op.delete :first_word unless i==0 sentence op end.join(" ") end
[ "def", "paragraph", "(", "options", "=", "{", "}", ")", "count", "=", "Util", ".", "rand_count", "(", "options", "[", ":sentences", "]", "||", "(", "5", "..", "15", ")", ",", "randomizer", ")", "count", ".", "times", ".", "collect", "do", "|", "i", "|", "op", "=", "options", ".", "clone", "op", ".", "delete", ":punctuation", "unless", "i", "==", "count", "-", "1", "op", ".", "delete", ":first_word", "unless", "i", "==", "0", "sentence", "op", "end", ".", "join", "(", "\" \"", ")", "end" ]
return a random paragraph Options: * :first_word => nil - the first word of the paragraph * :words => range or int - number of words in sentence * :sentences => range or int - number of sentences in paragraph * :punctuation => nil - punction to end the paragraph with (nil == randomly selected from punctuation_distribution)
[ "return", "a", "random", "paragraph" ]
55d123f230b13c62de6f815063edf0d9b7dce306
https://github.com/imikimi/literate_randomizer/blob/55d123f230b13c62de6f815063edf0d9b7dce306/lib/literate_randomizer/randomizer.rb#L119-L128
19,250
imikimi/literate_randomizer
lib/literate_randomizer/randomizer.rb
LiterateRandomizer.Randomizer.paragraphs
def paragraphs(options={}) count = Util.rand_count(options[:paragraphs] || (3..5),randomizer) join_str = options[:join] res = count.times.collect do |i| op = options.clone op.delete :punctuation unless i==count-1 op.delete :first_word unless i==0 paragraph op end join_str!=false ? res.join(join_str || "\n\n") : res end
ruby
def paragraphs(options={}) count = Util.rand_count(options[:paragraphs] || (3..5),randomizer) join_str = options[:join] res = count.times.collect do |i| op = options.clone op.delete :punctuation unless i==count-1 op.delete :first_word unless i==0 paragraph op end join_str!=false ? res.join(join_str || "\n\n") : res end
[ "def", "paragraphs", "(", "options", "=", "{", "}", ")", "count", "=", "Util", ".", "rand_count", "(", "options", "[", ":paragraphs", "]", "||", "(", "3", "..", "5", ")", ",", "randomizer", ")", "join_str", "=", "options", "[", ":join", "]", "res", "=", "count", ".", "times", ".", "collect", "do", "|", "i", "|", "op", "=", "options", ".", "clone", "op", ".", "delete", ":punctuation", "unless", "i", "==", "count", "-", "1", "op", ".", "delete", ":first_word", "unless", "i", "==", "0", "paragraph", "op", "end", "join_str!", "=", "false", "?", "res", ".", "join", "(", "join_str", "||", "\"\\n\\n\"", ")", ":", "res", "end" ]
return random paragraphs Options: * :first_word => nil - the first word of the paragraph * :words => range or int - number of words in sentence * :sentences => range or int - number of sentences in paragraph * :paragraphs => range or int - number of paragraphs in paragraph * :join => "\n\n" - join the paragraphs. if :join => false, returns an array of the paragraphs * :punctuation => nil - punction to end the paragraph with (nil == randomly selected from punctuation_distribution)
[ "return", "random", "paragraphs" ]
55d123f230b13c62de6f815063edf0d9b7dce306
https://github.com/imikimi/literate_randomizer/blob/55d123f230b13c62de6f815063edf0d9b7dce306/lib/literate_randomizer/randomizer.rb#L140-L152
19,251
mvz/gir_ffi
lib/ffi-glib/array_methods.rb
GLib.ArrayMethods.index
def index(idx) unless (0...length).cover? idx raise IndexError, "Index #{idx} outside of bounds 0..#{length - 1}" end ptr = GirFFI::InOutPointer.new element_type, data_ptr + idx * element_size ptr.to_ruby_value end
ruby
def index(idx) unless (0...length).cover? idx raise IndexError, "Index #{idx} outside of bounds 0..#{length - 1}" end ptr = GirFFI::InOutPointer.new element_type, data_ptr + idx * element_size ptr.to_ruby_value end
[ "def", "index", "(", "idx", ")", "unless", "(", "0", "...", "length", ")", ".", "cover?", "idx", "raise", "IndexError", ",", "\"Index #{idx} outside of bounds 0..#{length - 1}\"", "end", "ptr", "=", "GirFFI", "::", "InOutPointer", ".", "new", "element_type", ",", "data_ptr", "+", "idx", "*", "element_size", "ptr", ".", "to_ruby_value", "end" ]
Re-implementation of the g_array_index and g_ptr_array_index macros
[ "Re", "-", "implementation", "of", "the", "g_array_index", "and", "g_ptr_array_index", "macros" ]
917cd2a5feda2ed9c06404d63b463794761d896f
https://github.com/mvz/gir_ffi/blob/917cd2a5feda2ed9c06404d63b463794761d896f/lib/ffi-glib/array_methods.rb#L7-L14
19,252
opentracing-contrib/ruby-rack-tracer
lib/rack/tracer.rb
Rack.Tracer.call
def call(env) method = env[REQUEST_METHOD] context = @tracer.extract(OpenTracing::FORMAT_RACK, env) if @trust_incoming_span scope = @tracer.start_active_span( method, child_of: context, tags: { 'component' => 'rack', 'span.kind' => 'server', 'http.method' => method, 'http.url' => env[REQUEST_URI] } ) span = scope.span @on_start_span.call(span) if @on_start_span env['rack.span'] = span @app.call(env).tap do |status_code, _headers, _body| span.set_tag('http.status_code', status_code) route = route_from_env(env) span.operation_name = route if route end rescue *@errors => e span.set_tag('error', true) span.log_kv( event: 'error', :'error.kind' => e.class.to_s, :'error.object' => e, message: e.message, stack: e.backtrace.join("\n") ) raise ensure begin scope.close ensure @on_finish_span.call(span) if @on_finish_span end end
ruby
def call(env) method = env[REQUEST_METHOD] context = @tracer.extract(OpenTracing::FORMAT_RACK, env) if @trust_incoming_span scope = @tracer.start_active_span( method, child_of: context, tags: { 'component' => 'rack', 'span.kind' => 'server', 'http.method' => method, 'http.url' => env[REQUEST_URI] } ) span = scope.span @on_start_span.call(span) if @on_start_span env['rack.span'] = span @app.call(env).tap do |status_code, _headers, _body| span.set_tag('http.status_code', status_code) route = route_from_env(env) span.operation_name = route if route end rescue *@errors => e span.set_tag('error', true) span.log_kv( event: 'error', :'error.kind' => e.class.to_s, :'error.object' => e, message: e.message, stack: e.backtrace.join("\n") ) raise ensure begin scope.close ensure @on_finish_span.call(span) if @on_finish_span end end
[ "def", "call", "(", "env", ")", "method", "=", "env", "[", "REQUEST_METHOD", "]", "context", "=", "@tracer", ".", "extract", "(", "OpenTracing", "::", "FORMAT_RACK", ",", "env", ")", "if", "@trust_incoming_span", "scope", "=", "@tracer", ".", "start_active_span", "(", "method", ",", "child_of", ":", "context", ",", "tags", ":", "{", "'component'", "=>", "'rack'", ",", "'span.kind'", "=>", "'server'", ",", "'http.method'", "=>", "method", ",", "'http.url'", "=>", "env", "[", "REQUEST_URI", "]", "}", ")", "span", "=", "scope", ".", "span", "@on_start_span", ".", "call", "(", "span", ")", "if", "@on_start_span", "env", "[", "'rack.span'", "]", "=", "span", "@app", ".", "call", "(", "env", ")", ".", "tap", "do", "|", "status_code", ",", "_headers", ",", "_body", "|", "span", ".", "set_tag", "(", "'http.status_code'", ",", "status_code", ")", "route", "=", "route_from_env", "(", "env", ")", "span", ".", "operation_name", "=", "route", "if", "route", "end", "rescue", "@errors", "=>", "e", "span", ".", "set_tag", "(", "'error'", ",", "true", ")", "span", ".", "log_kv", "(", "event", ":", "'error'", ",", ":'", "'", "=>", "e", ".", "class", ".", "to_s", ",", ":'", "'", "=>", "e", ",", "message", ":", "e", ".", "message", ",", "stack", ":", "e", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", ")", "raise", "ensure", "begin", "scope", ".", "close", "ensure", "@on_finish_span", ".", "call", "(", "span", ")", "if", "@on_finish_span", "end", "end" ]
Create a new Rack Tracer middleware. @param app The Rack application/middlewares stack. @param tracer [OpenTracing::Tracer] A tracer to be used when start_span, and extract is called. @param on_start_span [Proc, nil] A callback evaluated after a new span is created. @param on_finish_span [Proc, nil] A callback evaluated after a span is finished. @param errors [Array<Class>] An array of error classes to be captured by the tracer as errors. Errors are **not** muted by the middleware, they're re-raised afterwards.
[ "Create", "a", "new", "Rack", "Tracer", "middleware", "." ]
e0259589a85e3453751806f6fa7425f1c506f399
https://github.com/opentracing-contrib/ruby-rack-tracer/blob/e0259589a85e3453751806f6fa7425f1c506f399/lib/rack/tracer.rb#L33-L75
19,253
electric-it/minimart
lib/minimart/cli.rb
Minimart.Cli.mirror
def mirror Minimart::Commands::Mirror.new(options).execute! rescue Minimart::Error::BaseError => e Minimart::Error.handle_exception(e) end
ruby
def mirror Minimart::Commands::Mirror.new(options).execute! rescue Minimart::Error::BaseError => e Minimart::Error.handle_exception(e) end
[ "def", "mirror", "Minimart", "::", "Commands", "::", "Mirror", ".", "new", "(", "options", ")", ".", "execute!", "rescue", "Minimart", "::", "Error", "::", "BaseError", "=>", "e", "Minimart", "::", "Error", ".", "handle_exception", "(", "e", ")", "end" ]
Mirror cookbooks specified in an inventory file.
[ "Mirror", "cookbooks", "specified", "in", "an", "inventory", "file", "." ]
ca64bdc6ebf63a8ae27832ee914f815a160b65dd
https://github.com/electric-it/minimart/blob/ca64bdc6ebf63a8ae27832ee914f815a160b65dd/lib/minimart/cli.rb#L69-L74
19,254
electric-it/minimart
lib/minimart/cli.rb
Minimart.Cli.web
def web Minimart::Commands::Web.new(options).execute! rescue Minimart::Error::BaseError => e Minimart::Error.handle_exception(e) end
ruby
def web Minimart::Commands::Web.new(options).execute! rescue Minimart::Error::BaseError => e Minimart::Error.handle_exception(e) end
[ "def", "web", "Minimart", "::", "Commands", "::", "Web", ".", "new", "(", "options", ")", ".", "execute!", "rescue", "Minimart", "::", "Error", "::", "BaseError", "=>", "e", "Minimart", "::", "Error", ".", "handle_exception", "(", "e", ")", "end" ]
Generate a web interface to download any mirrored cookbooks.
[ "Generate", "a", "web", "interface", "to", "download", "any", "mirrored", "cookbooks", "." ]
ca64bdc6ebf63a8ae27832ee914f815a160b65dd
https://github.com/electric-it/minimart/blob/ca64bdc6ebf63a8ae27832ee914f815a160b65dd/lib/minimart/cli.rb#L103-L108
19,255
yob/em-ftpd
lib/em-ftpd/authentication.rb
EM::FTPD.Authentication.cmd_pass
def cmd_pass(param) send_response "202 User already logged in" and return unless @user.nil? send_param_required and return if param.nil? send_response "530 password with no username" and return if @requested_user.nil? # return an error message if: # - the specified username isn't in our system # - the password is wrong @driver.authenticate(@requested_user, param) do |result| if result @name_prefix = "/" @user = @requested_user @requested_user = nil send_response "230 OK, password correct" else @user = nil send_response "530 incorrect login. not logged in." end end end
ruby
def cmd_pass(param) send_response "202 User already logged in" and return unless @user.nil? send_param_required and return if param.nil? send_response "530 password with no username" and return if @requested_user.nil? # return an error message if: # - the specified username isn't in our system # - the password is wrong @driver.authenticate(@requested_user, param) do |result| if result @name_prefix = "/" @user = @requested_user @requested_user = nil send_response "230 OK, password correct" else @user = nil send_response "530 incorrect login. not logged in." end end end
[ "def", "cmd_pass", "(", "param", ")", "send_response", "\"202 User already logged in\"", "and", "return", "unless", "@user", ".", "nil?", "send_param_required", "and", "return", "if", "param", ".", "nil?", "send_response", "\"530 password with no username\"", "and", "return", "if", "@requested_user", ".", "nil?", "# return an error message if:", "# - the specified username isn't in our system", "# - the password is wrong", "@driver", ".", "authenticate", "(", "@requested_user", ",", "param", ")", "do", "|", "result", "|", "if", "result", "@name_prefix", "=", "\"/\"", "@user", "=", "@requested_user", "@requested_user", "=", "nil", "send_response", "\"230 OK, password correct\"", "else", "@user", "=", "nil", "send_response", "\"530 incorrect login. not logged in.\"", "end", "end", "end" ]
handle the PASS FTP command. This is the second stage of a user logging in
[ "handle", "the", "PASS", "FTP", "command", ".", "This", "is", "the", "second", "stage", "of", "a", "user", "logging", "in" ]
27565d7d8ddab17e6538936355c56a9184a97a95
https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/authentication.rb#L25-L45
19,256
yob/em-ftpd
lib/em-ftpd/files.rb
EM::FTPD.Files.cmd_dele
def cmd_dele(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? path = build_path(param) @driver.delete_file(path) do |result| if result send_response "250 File deleted" else send_action_not_taken end end end
ruby
def cmd_dele(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? path = build_path(param) @driver.delete_file(path) do |result| if result send_response "250 File deleted" else send_action_not_taken end end end
[ "def", "cmd_dele", "(", "param", ")", "send_unauthorised", "and", "return", "unless", "logged_in?", "send_param_required", "and", "return", "if", "param", ".", "nil?", "path", "=", "build_path", "(", "param", ")", "@driver", ".", "delete_file", "(", "path", ")", "do", "|", "result", "|", "if", "result", "send_response", "\"250 File deleted\"", "else", "send_action_not_taken", "end", "end", "end" ]
delete a file
[ "delete", "a", "file" ]
27565d7d8ddab17e6538936355c56a9184a97a95
https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/files.rb#L7-L20
19,257
yob/em-ftpd
lib/em-ftpd/files.rb
EM::FTPD.Files.cmd_retr
def cmd_retr(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? path = build_path(param) @driver.get_file(path) do |data| if data send_response "150 Data transfer starting #{data.size} bytes" send_outofband_data(data, @restart_pos || 0) else send_response "551 file not available" end end end
ruby
def cmd_retr(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? path = build_path(param) @driver.get_file(path) do |data| if data send_response "150 Data transfer starting #{data.size} bytes" send_outofband_data(data, @restart_pos || 0) else send_response "551 file not available" end end end
[ "def", "cmd_retr", "(", "param", ")", "send_unauthorised", "and", "return", "unless", "logged_in?", "send_param_required", "and", "return", "if", "param", ".", "nil?", "path", "=", "build_path", "(", "param", ")", "@driver", ".", "get_file", "(", "path", ")", "do", "|", "data", "|", "if", "data", "send_response", "\"150 Data transfer starting #{data.size} bytes\"", "send_outofband_data", "(", "data", ",", "@restart_pos", "||", "0", ")", "else", "send_response", "\"551 file not available\"", "end", "end", "end" ]
send a file to the client
[ "send", "a", "file", "to", "the", "client" ]
27565d7d8ddab17e6538936355c56a9184a97a95
https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/files.rb#L33-L47
19,258
yob/em-ftpd
lib/em-ftpd/files.rb
EM::FTPD.Files.cmd_size
def cmd_size(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? @driver.bytes(build_path(param)) do |bytes| if bytes send_response "213 #{bytes}" else send_response "450 file not available" end end end
ruby
def cmd_size(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? @driver.bytes(build_path(param)) do |bytes| if bytes send_response "213 #{bytes}" else send_response "450 file not available" end end end
[ "def", "cmd_size", "(", "param", ")", "send_unauthorised", "and", "return", "unless", "logged_in?", "send_param_required", "and", "return", "if", "param", ".", "nil?", "@driver", ".", "bytes", "(", "build_path", "(", "param", ")", ")", "do", "|", "bytes", "|", "if", "bytes", "send_response", "\"213 #{bytes}\"", "else", "send_response", "\"450 file not available\"", "end", "end", "end" ]
return the size of a file in bytes
[ "return", "the", "size", "of", "a", "file", "in", "bytes" ]
27565d7d8ddab17e6538936355c56a9184a97a95
https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/files.rb#L73-L84
19,259
yob/em-ftpd
lib/em-ftpd/files.rb
EM::FTPD.Files.cmd_stor
def cmd_stor(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? path = build_path(param) if @driver.respond_to?(:put_file_streamed) cmd_stor_streamed(path) elsif @driver.respond_to?(:put_file) cmd_stor_tempfile(path) else raise "driver MUST respond to put_file OR put_file_streamed" end end
ruby
def cmd_stor(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? path = build_path(param) if @driver.respond_to?(:put_file_streamed) cmd_stor_streamed(path) elsif @driver.respond_to?(:put_file) cmd_stor_tempfile(path) else raise "driver MUST respond to put_file OR put_file_streamed" end end
[ "def", "cmd_stor", "(", "param", ")", "send_unauthorised", "and", "return", "unless", "logged_in?", "send_param_required", "and", "return", "if", "param", ".", "nil?", "path", "=", "build_path", "(", "param", ")", "if", "@driver", ".", "respond_to?", "(", ":put_file_streamed", ")", "cmd_stor_streamed", "(", "path", ")", "elsif", "@driver", ".", "respond_to?", "(", ":put_file", ")", "cmd_stor_tempfile", "(", "path", ")", "else", "raise", "\"driver MUST respond to put_file OR put_file_streamed\"", "end", "end" ]
save a file from a client
[ "save", "a", "file", "from", "a", "client" ]
27565d7d8ddab17e6538936355c56a9184a97a95
https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/files.rb#L87-L100
19,260
yob/em-ftpd
lib/em-ftpd/directories.rb
EM::FTPD.Directories.cmd_nlst
def cmd_nlst(param) send_unauthorised and return unless logged_in? send_response "150 Opening ASCII mode data connection for file list" @driver.dir_contents(build_path(param)) do |files| send_outofband_data(files.map(&:name)) end end
ruby
def cmd_nlst(param) send_unauthorised and return unless logged_in? send_response "150 Opening ASCII mode data connection for file list" @driver.dir_contents(build_path(param)) do |files| send_outofband_data(files.map(&:name)) end end
[ "def", "cmd_nlst", "(", "param", ")", "send_unauthorised", "and", "return", "unless", "logged_in?", "send_response", "\"150 Opening ASCII mode data connection for file list\"", "@driver", ".", "dir_contents", "(", "build_path", "(", "param", ")", ")", "do", "|", "files", "|", "send_outofband_data", "(", "files", ".", "map", "(", ":name", ")", ")", "end", "end" ]
return a listing of the current directory, one per line, each line separated by the standard FTP EOL sequence. The listing is returned to the client over a data socket.
[ "return", "a", "listing", "of", "the", "current", "directory", "one", "per", "line", "each", "line", "separated", "by", "the", "standard", "FTP", "EOL", "sequence", ".", "The", "listing", "is", "returned", "to", "the", "client", "over", "a", "data", "socket", "." ]
27565d7d8ddab17e6538936355c56a9184a97a95
https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/directories.rb#L49-L56
19,261
yob/em-ftpd
lib/em-ftpd/directories.rb
EM::FTPD.Directories.cmd_list
def cmd_list(param) send_unauthorised and return unless logged_in? send_response "150 Opening ASCII mode data connection for file list" param = '' if param.to_s == '-a' @driver.dir_contents(build_path(param)) do |files| now = Time.now lines = files.map { |item| sizestr = (item.size || 0).to_s.rjust(12) "#{item.directory ? 'd' : '-'}#{item.permissions || 'rwxrwxrwx'} 1 #{item.owner || 'owner'} #{item.group || 'group'} #{sizestr} #{(item.time || now).strftime("%b %d %H:%M")} #{item.name}" } send_outofband_data(lines) end end
ruby
def cmd_list(param) send_unauthorised and return unless logged_in? send_response "150 Opening ASCII mode data connection for file list" param = '' if param.to_s == '-a' @driver.dir_contents(build_path(param)) do |files| now = Time.now lines = files.map { |item| sizestr = (item.size || 0).to_s.rjust(12) "#{item.directory ? 'd' : '-'}#{item.permissions || 'rwxrwxrwx'} 1 #{item.owner || 'owner'} #{item.group || 'group'} #{sizestr} #{(item.time || now).strftime("%b %d %H:%M")} #{item.name}" } send_outofband_data(lines) end end
[ "def", "cmd_list", "(", "param", ")", "send_unauthorised", "and", "return", "unless", "logged_in?", "send_response", "\"150 Opening ASCII mode data connection for file list\"", "param", "=", "''", "if", "param", ".", "to_s", "==", "'-a'", "@driver", ".", "dir_contents", "(", "build_path", "(", "param", ")", ")", "do", "|", "files", "|", "now", "=", "Time", ".", "now", "lines", "=", "files", ".", "map", "{", "|", "item", "|", "sizestr", "=", "(", "item", ".", "size", "||", "0", ")", ".", "to_s", ".", "rjust", "(", "12", ")", "\"#{item.directory ? 'd' : '-'}#{item.permissions || 'rwxrwxrwx'} 1 #{item.owner || 'owner'} #{item.group || 'group'} #{sizestr} #{(item.time || now).strftime(\"%b %d %H:%M\")} #{item.name}\"", "}", "send_outofband_data", "(", "lines", ")", "end", "end" ]
return a detailed list of files and directories
[ "return", "a", "detailed", "list", "of", "files", "and", "directories" ]
27565d7d8ddab17e6538936355c56a9184a97a95
https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/directories.rb#L67-L81
19,262
yob/em-ftpd
lib/em-ftpd/directories.rb
EM::FTPD.Directories.cmd_rmd
def cmd_rmd(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? @driver.delete_dir(build_path(param)) do |result| if result send_response "250 Directory deleted." else send_action_not_taken end end end
ruby
def cmd_rmd(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? @driver.delete_dir(build_path(param)) do |result| if result send_response "250 Directory deleted." else send_action_not_taken end end end
[ "def", "cmd_rmd", "(", "param", ")", "send_unauthorised", "and", "return", "unless", "logged_in?", "send_param_required", "and", "return", "if", "param", ".", "nil?", "@driver", ".", "delete_dir", "(", "build_path", "(", "param", ")", ")", "do", "|", "result", "|", "if", "result", "send_response", "\"250 Directory deleted.\"", "else", "send_action_not_taken", "end", "end", "end" ]
delete a directory
[ "delete", "a", "directory" ]
27565d7d8ddab17e6538936355c56a9184a97a95
https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/directories.rb#L93-L104
19,263
yob/em-ftpd
lib/em-ftpd/server.rb
EM::FTPD.Server.parse_request
def parse_request(data) data.strip! space = data.index(" ") if space cmd = data[0, space] param = data[space+1, data.length - space] param = nil if param.strip.size == 0 else cmd = data param = nil end [cmd.downcase, param] end
ruby
def parse_request(data) data.strip! space = data.index(" ") if space cmd = data[0, space] param = data[space+1, data.length - space] param = nil if param.strip.size == 0 else cmd = data param = nil end [cmd.downcase, param] end
[ "def", "parse_request", "(", "data", ")", "data", ".", "strip!", "space", "=", "data", ".", "index", "(", "\" \"", ")", "if", "space", "cmd", "=", "data", "[", "0", ",", "space", "]", "param", "=", "data", "[", "space", "+", "1", ",", "data", ".", "length", "-", "space", "]", "param", "=", "nil", "if", "param", ".", "strip", ".", "size", "==", "0", "else", "cmd", "=", "data", "param", "=", "nil", "end", "[", "cmd", ".", "downcase", ",", "param", "]", "end" ]
split a client's request into command and parameter components
[ "split", "a", "client", "s", "request", "into", "command", "and", "parameter", "components" ]
27565d7d8ddab17e6538936355c56a9184a97a95
https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/server.rb#L76-L89
19,264
yob/em-ftpd
lib/em-ftpd/server.rb
EM::FTPD.Server.cmd_help
def cmd_help(param) send_response "214- The following commands are recognized." commands = COMMANDS str = "" commands.sort.each_slice(3) { |slice| str += " " + slice.join("\t\t") + LBRK } send_response str, true send_response "214 End of list." end
ruby
def cmd_help(param) send_response "214- The following commands are recognized." commands = COMMANDS str = "" commands.sort.each_slice(3) { |slice| str += " " + slice.join("\t\t") + LBRK } send_response str, true send_response "214 End of list." end
[ "def", "cmd_help", "(", "param", ")", "send_response", "\"214- The following commands are recognized.\"", "commands", "=", "COMMANDS", "str", "=", "\"\"", "commands", ".", "sort", ".", "each_slice", "(", "3", ")", "{", "|", "slice", "|", "str", "+=", "\" \"", "+", "slice", ".", "join", "(", "\"\\t\\t\"", ")", "+", "LBRK", "}", "send_response", "str", ",", "true", "send_response", "\"214 End of list.\"", "end" ]
handle the HELP FTP command by sending a list of available commands.
[ "handle", "the", "HELP", "FTP", "command", "by", "sending", "a", "list", "of", "available", "commands", "." ]
27565d7d8ddab17e6538936355c56a9184a97a95
https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/server.rb#L109-L118
19,265
yob/em-ftpd
lib/em-ftpd/server.rb
EM::FTPD.Server.cmd_pasv
def cmd_pasv(param) send_unauthorised and return unless logged_in? host, port = start_passive_socket p1, p2 = *port.divmod(256) send_response "227 Entering Passive Mode (" + host.split(".").join(",") + ",#{p1},#{p2})" end
ruby
def cmd_pasv(param) send_unauthorised and return unless logged_in? host, port = start_passive_socket p1, p2 = *port.divmod(256) send_response "227 Entering Passive Mode (" + host.split(".").join(",") + ",#{p1},#{p2})" end
[ "def", "cmd_pasv", "(", "param", ")", "send_unauthorised", "and", "return", "unless", "logged_in?", "host", ",", "port", "=", "start_passive_socket", "p1", ",", "p2", "=", "port", ".", "divmod", "(", "256", ")", "send_response", "\"227 Entering Passive Mode (\"", "+", "host", ".", "split", "(", "\".\"", ")", ".", "join", "(", "\",\"", ")", "+", "\",#{p1},#{p2})\"", "end" ]
Passive FTP. At the clients request, listen on a port for an incoming data connection. The listening socket is opened on a random port, so the host and port is sent back to the client on the control socket.
[ "Passive", "FTP", ".", "At", "the", "clients", "request", "listen", "on", "a", "port", "for", "an", "incoming", "data", "connection", ".", "The", "listening", "socket", "is", "opened", "on", "a", "random", "port", "so", "the", "host", "and", "port", "is", "sent", "back", "to", "the", "client", "on", "the", "control", "socket", "." ]
27565d7d8ddab17e6538936355c56a9184a97a95
https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/server.rb#L156-L164
19,266
yob/em-ftpd
lib/em-ftpd/server.rb
EM::FTPD.Server.cmd_port
def cmd_port(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? nums = param.split(',') port = nums[4].to_i * 256 + nums[5].to_i host = nums[0..3].join('.') close_datasocket puts "connecting to client #{host} on #{port}" @datasocket = ActiveSocket.open(host, port) puts "Opened active connection at #{host}:#{port}" send_response "200 Connection established (#{port})" rescue puts "Error opening data connection to #{host}:#{port}" send_response "425 Data connection failed" end
ruby
def cmd_port(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? nums = param.split(',') port = nums[4].to_i * 256 + nums[5].to_i host = nums[0..3].join('.') close_datasocket puts "connecting to client #{host} on #{port}" @datasocket = ActiveSocket.open(host, port) puts "Opened active connection at #{host}:#{port}" send_response "200 Connection established (#{port})" rescue puts "Error opening data connection to #{host}:#{port}" send_response "425 Data connection failed" end
[ "def", "cmd_port", "(", "param", ")", "send_unauthorised", "and", "return", "unless", "logged_in?", "send_param_required", "and", "return", "if", "param", ".", "nil?", "nums", "=", "param", ".", "split", "(", "','", ")", "port", "=", "nums", "[", "4", "]", ".", "to_i", "*", "256", "+", "nums", "[", "5", "]", ".", "to_i", "host", "=", "nums", "[", "0", "..", "3", "]", ".", "join", "(", "'.'", ")", "close_datasocket", "puts", "\"connecting to client #{host} on #{port}\"", "@datasocket", "=", "ActiveSocket", ".", "open", "(", "host", ",", "port", ")", "puts", "\"Opened active connection at #{host}:#{port}\"", "send_response", "\"200 Connection established (#{port})\"", "rescue", "puts", "\"Error opening data connection to #{host}:#{port}\"", "send_response", "\"425 Data connection failed\"", "end" ]
Active FTP. An alternative to Passive FTP. The client has a listening socket open, waiting for us to connect and establish a data socket. Attempt to open a connection to the host and port they specify and save the connection, ready for either end to send something down it.
[ "Active", "FTP", ".", "An", "alternative", "to", "Passive", "FTP", ".", "The", "client", "has", "a", "listening", "socket", "open", "waiting", "for", "us", "to", "connect", "and", "establish", "a", "data", "socket", ".", "Attempt", "to", "open", "a", "connection", "to", "the", "host", "and", "port", "they", "specify", "and", "save", "the", "connection", "ready", "for", "either", "end", "to", "send", "something", "down", "it", "." ]
27565d7d8ddab17e6538936355c56a9184a97a95
https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/server.rb#L178-L195
19,267
yob/em-ftpd
lib/em-ftpd/server.rb
EM::FTPD.Server.cmd_type
def cmd_type(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? if param.upcase.eql?("A") send_response "200 Type set to ASCII" elsif param.upcase.eql?("I") send_response "200 Type set to binary" else send_response "500 Invalid type" end end
ruby
def cmd_type(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? if param.upcase.eql?("A") send_response "200 Type set to ASCII" elsif param.upcase.eql?("I") send_response "200 Type set to binary" else send_response "500 Invalid type" end end
[ "def", "cmd_type", "(", "param", ")", "send_unauthorised", "and", "return", "unless", "logged_in?", "send_param_required", "and", "return", "if", "param", ".", "nil?", "if", "param", ".", "upcase", ".", "eql?", "(", "\"A\"", ")", "send_response", "\"200 Type set to ASCII\"", "elsif", "param", ".", "upcase", ".", "eql?", "(", "\"I\"", ")", "send_response", "\"200 Type set to binary\"", "else", "send_response", "\"500 Invalid type\"", "end", "end" ]
like the MODE and STRU commands, TYPE dates back to a time when the FTP protocol was more aware of the content of the files it was transferring, and would sometimes be expected to translate things like EOL markers on the fly. Valid options were A(SCII), I(mage), E(BCDIC) or LN (for local type). Since we plan to just accept bytes from the client unchanged, I think Image mode is adequate. The RFC requires we accept ASCII mode however, so accept it, but ignore it.
[ "like", "the", "MODE", "and", "STRU", "commands", "TYPE", "dates", "back", "to", "a", "time", "when", "the", "FTP", "protocol", "was", "more", "aware", "of", "the", "content", "of", "the", "files", "it", "was", "transferring", "and", "would", "sometimes", "be", "expected", "to", "translate", "things", "like", "EOL", "markers", "on", "the", "fly", "." ]
27565d7d8ddab17e6538936355c56a9184a97a95
https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/server.rb#L260-L270
19,268
yob/em-ftpd
lib/em-ftpd/server.rb
EM::FTPD.Server.send_outofband_data
def send_outofband_data(data, restart_pos = 0) wait_for_datasocket do |datasocket| if datasocket.nil? send_response "425 Error establishing connection" else if data.is_a?(Array) data = data.join(LBRK) << LBRK end data = StringIO.new(data) if data.kind_of?(String) data.seek(restart_pos) if EM.reactor_running? # send the data out in chunks, as fast as the client can recieve it -- not blocking the reactor in the process streamer = IOStreamer.new(datasocket, data) finalize = Proc.new { close_datasocket data.close if data.respond_to?(:close) && !data.closed? } streamer.callback { send_response "226 Closing data connection, sent #{streamer.bytes_streamed} bytes" finalize.call } streamer.errback { |ex| send_response "425 Error while streaming data, sent #{streamer.bytes_streamed} bytes" finalize.call raise ex } else # blocks until all data is sent begin bytes = 0 data.each do |line| datasocket.send_data(line) bytes += line.bytesize end send_response "226 Closing data connection, sent #{bytes} bytes" ensure close_datasocket data.close if data.respond_to?(:close) end end end end end
ruby
def send_outofband_data(data, restart_pos = 0) wait_for_datasocket do |datasocket| if datasocket.nil? send_response "425 Error establishing connection" else if data.is_a?(Array) data = data.join(LBRK) << LBRK end data = StringIO.new(data) if data.kind_of?(String) data.seek(restart_pos) if EM.reactor_running? # send the data out in chunks, as fast as the client can recieve it -- not blocking the reactor in the process streamer = IOStreamer.new(datasocket, data) finalize = Proc.new { close_datasocket data.close if data.respond_to?(:close) && !data.closed? } streamer.callback { send_response "226 Closing data connection, sent #{streamer.bytes_streamed} bytes" finalize.call } streamer.errback { |ex| send_response "425 Error while streaming data, sent #{streamer.bytes_streamed} bytes" finalize.call raise ex } else # blocks until all data is sent begin bytes = 0 data.each do |line| datasocket.send_data(line) bytes += line.bytesize end send_response "226 Closing data connection, sent #{bytes} bytes" ensure close_datasocket data.close if data.respond_to?(:close) end end end end end
[ "def", "send_outofband_data", "(", "data", ",", "restart_pos", "=", "0", ")", "wait_for_datasocket", "do", "|", "datasocket", "|", "if", "datasocket", ".", "nil?", "send_response", "\"425 Error establishing connection\"", "else", "if", "data", ".", "is_a?", "(", "Array", ")", "data", "=", "data", ".", "join", "(", "LBRK", ")", "<<", "LBRK", "end", "data", "=", "StringIO", ".", "new", "(", "data", ")", "if", "data", ".", "kind_of?", "(", "String", ")", "data", ".", "seek", "(", "restart_pos", ")", "if", "EM", ".", "reactor_running?", "# send the data out in chunks, as fast as the client can recieve it -- not blocking the reactor in the process", "streamer", "=", "IOStreamer", ".", "new", "(", "datasocket", ",", "data", ")", "finalize", "=", "Proc", ".", "new", "{", "close_datasocket", "data", ".", "close", "if", "data", ".", "respond_to?", "(", ":close", ")", "&&", "!", "data", ".", "closed?", "}", "streamer", ".", "callback", "{", "send_response", "\"226 Closing data connection, sent #{streamer.bytes_streamed} bytes\"", "finalize", ".", "call", "}", "streamer", ".", "errback", "{", "|", "ex", "|", "send_response", "\"425 Error while streaming data, sent #{streamer.bytes_streamed} bytes\"", "finalize", ".", "call", "raise", "ex", "}", "else", "# blocks until all data is sent", "begin", "bytes", "=", "0", "data", ".", "each", "do", "|", "line", "|", "datasocket", ".", "send_data", "(", "line", ")", "bytes", "+=", "line", ".", "bytesize", "end", "send_response", "\"226 Closing data connection, sent #{bytes} bytes\"", "ensure", "close_datasocket", "data", ".", "close", "if", "data", ".", "respond_to?", "(", ":close", ")", "end", "end", "end", "end", "end" ]
send data to the client across the data socket. The data socket is NOT guaranteed to be setup by the time this method runs. If it isn't ready yet, exit the method and try again on the next reactor tick. This is particularly likely with some clients that operate in passive mode. They get a message on the control port with the data port details, so they start up a new data connection AND send they command that will use it in close succession. The data port setup needs to complete a TCP handshake before it will be ready to use, so it may take a few RTTs after the command is received at the server before the data socket is ready.
[ "send", "data", "to", "the", "client", "across", "the", "data", "socket", "." ]
27565d7d8ddab17e6538936355c56a9184a97a95
https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/server.rb#L285-L329
19,269
yob/em-ftpd
lib/em-ftpd/server.rb
EM::FTPD.Server.wait_for_datasocket
def wait_for_datasocket(interval = 0.1, &block) if @datasocket.nil? && interval < 25 if EM.reactor_running? EventMachine.add_timer(interval) { wait_for_datasocket(interval * 2, &block) } else sleep interval wait_for_datasocket(interval * 2, &block) end return end yield @datasocket end
ruby
def wait_for_datasocket(interval = 0.1, &block) if @datasocket.nil? && interval < 25 if EM.reactor_running? EventMachine.add_timer(interval) { wait_for_datasocket(interval * 2, &block) } else sleep interval wait_for_datasocket(interval * 2, &block) end return end yield @datasocket end
[ "def", "wait_for_datasocket", "(", "interval", "=", "0.1", ",", "&", "block", ")", "if", "@datasocket", ".", "nil?", "&&", "interval", "<", "25", "if", "EM", ".", "reactor_running?", "EventMachine", ".", "add_timer", "(", "interval", ")", "{", "wait_for_datasocket", "(", "interval", "*", "2", ",", "block", ")", "}", "else", "sleep", "interval", "wait_for_datasocket", "(", "interval", "*", "2", ",", "block", ")", "end", "return", "end", "yield", "@datasocket", "end" ]
waits for the data socket to be established
[ "waits", "for", "the", "data", "socket", "to", "be", "established" ]
27565d7d8ddab17e6538936355c56a9184a97a95
https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/server.rb#L332-L343
19,270
yob/em-ftpd
lib/em-ftpd/server.rb
EM::FTPD.Server.receive_outofband_data
def receive_outofband_data(&block) wait_for_datasocket do |datasocket| if datasocket.nil? send_response "425 Error establishing connection" yield false else # let the client know we're ready to start send_response "150 Data transfer starting" datasocket.callback do |data| block.call(data) end end end end
ruby
def receive_outofband_data(&block) wait_for_datasocket do |datasocket| if datasocket.nil? send_response "425 Error establishing connection" yield false else # let the client know we're ready to start send_response "150 Data transfer starting" datasocket.callback do |data| block.call(data) end end end end
[ "def", "receive_outofband_data", "(", "&", "block", ")", "wait_for_datasocket", "do", "|", "datasocket", "|", "if", "datasocket", ".", "nil?", "send_response", "\"425 Error establishing connection\"", "yield", "false", "else", "# let the client know we're ready to start", "send_response", "\"150 Data transfer starting\"", "datasocket", ".", "callback", "do", "|", "data", "|", "block", ".", "call", "(", "data", ")", "end", "end", "end", "end" ]
receive a file data from the client across the data socket. The data socket is NOT guaranteed to be setup by the time this method runs. If this happens, exit the method early and try again later. See the method comments to send_outofband_data for further explanation.
[ "receive", "a", "file", "data", "from", "the", "client", "across", "the", "data", "socket", "." ]
27565d7d8ddab17e6538936355c56a9184a97a95
https://github.com/yob/em-ftpd/blob/27565d7d8ddab17e6538936355c56a9184a97a95/lib/em-ftpd/server.rb#L351-L366
19,271
tyrauber/census_api
lib/census_api/client.rb
CensusApi.Client.where
def where(options={}) options.merge!(key: @api_key, vintage: @api_vintage) fail "Client requires a dataset (#{DATASETS})." if @dataset.nil? [:fields, :level].each do |f| fail ArgumentError, "#{f} is a requied parameter" if options[f].nil? end options[:within] = [options[:within]] unless options[:within].nil? Request.find(dataset, options) end
ruby
def where(options={}) options.merge!(key: @api_key, vintage: @api_vintage) fail "Client requires a dataset (#{DATASETS})." if @dataset.nil? [:fields, :level].each do |f| fail ArgumentError, "#{f} is a requied parameter" if options[f].nil? end options[:within] = [options[:within]] unless options[:within].nil? Request.find(dataset, options) end
[ "def", "where", "(", "options", "=", "{", "}", ")", "options", ".", "merge!", "(", "key", ":", "@api_key", ",", "vintage", ":", "@api_vintage", ")", "fail", "\"Client requires a dataset (#{DATASETS}).\"", "if", "@dataset", ".", "nil?", "[", ":fields", ",", ":level", "]", ".", "each", "do", "|", "f", "|", "fail", "ArgumentError", ",", "\"#{f} is a requied parameter\"", "if", "options", "[", "f", "]", ".", "nil?", "end", "options", "[", ":within", "]", "=", "[", "options", "[", ":within", "]", "]", "unless", "options", "[", ":within", "]", ".", "nil?", "Request", ".", "find", "(", "dataset", ",", "options", ")", "end" ]
can add more datasets as support becomes available
[ "can", "add", "more", "datasets", "as", "support", "becomes", "available" ]
0b31e7617287c055afc5ed732e4aadf9213fc8b0
https://github.com/tyrauber/census_api/blob/0b31e7617287c055afc5ed732e4aadf9213fc8b0/lib/census_api/client.rb#L26-L34
19,272
chrislee35/dnsbl-client
lib/dnsbl/client.rb
DNSBL.Client.add_dnsbl
def add_dnsbl(name,domain,type='ip',codes={"0"=>"OK","127.0.0.2"=>"Blacklisted"}) @dnsbls[name] = codes @dnsbls[name]['domain'] = domain @dnsbls[name]['type'] = type end
ruby
def add_dnsbl(name,domain,type='ip',codes={"0"=>"OK","127.0.0.2"=>"Blacklisted"}) @dnsbls[name] = codes @dnsbls[name]['domain'] = domain @dnsbls[name]['type'] = type end
[ "def", "add_dnsbl", "(", "name", ",", "domain", ",", "type", "=", "'ip'", ",", "codes", "=", "{", "\"0\"", "=>", "\"OK\"", ",", "\"127.0.0.2\"", "=>", "\"Blacklisted\"", "}", ")", "@dnsbls", "[", "name", "]", "=", "codes", "@dnsbls", "[", "name", "]", "[", "'domain'", "]", "=", "domain", "@dnsbls", "[", "name", "]", "[", "'type'", "]", "=", "type", "end" ]
allows the adding of a new DNSBL to the set of configured DNSBLs
[ "allows", "the", "adding", "of", "a", "new", "DNSBL", "to", "the", "set", "of", "configured", "DNSBLs" ]
d88bb5eae3dfd03c418f67ae5767234a862a92b8
https://github.com/chrislee35/dnsbl-client/blob/d88bb5eae3dfd03c418f67ae5767234a862a92b8/lib/dnsbl/client.rb#L96-L100
19,273
chrislee35/dnsbl-client
lib/dnsbl/client.rb
DNSBL.Client._encode_query
def _encode_query(item,itemtype,domain,apikey=nil) label = nil if itemtype == 'ip' label = item.split(/\./).reverse.join(".") elsif itemtype == 'domain' label = normalize(item) end lookup = "#{label}.#{domain}" if apikey lookup = "#{apikey}.#{lookup}" end txid = lookup.sum message = Resolv::DNS::Message.new(txid) message.rd = 1 message.add_question(lookup,Resolv::DNS::Resource::IN::A) message.encode end
ruby
def _encode_query(item,itemtype,domain,apikey=nil) label = nil if itemtype == 'ip' label = item.split(/\./).reverse.join(".") elsif itemtype == 'domain' label = normalize(item) end lookup = "#{label}.#{domain}" if apikey lookup = "#{apikey}.#{lookup}" end txid = lookup.sum message = Resolv::DNS::Message.new(txid) message.rd = 1 message.add_question(lookup,Resolv::DNS::Resource::IN::A) message.encode end
[ "def", "_encode_query", "(", "item", ",", "itemtype", ",", "domain", ",", "apikey", "=", "nil", ")", "label", "=", "nil", "if", "itemtype", "==", "'ip'", "label", "=", "item", ".", "split", "(", "/", "\\.", "/", ")", ".", "reverse", ".", "join", "(", "\".\"", ")", "elsif", "itemtype", "==", "'domain'", "label", "=", "normalize", "(", "item", ")", "end", "lookup", "=", "\"#{label}.#{domain}\"", "if", "apikey", "lookup", "=", "\"#{apikey}.#{lookup}\"", "end", "txid", "=", "lookup", ".", "sum", "message", "=", "Resolv", "::", "DNS", "::", "Message", ".", "new", "(", "txid", ")", "message", ".", "rd", "=", "1", "message", ".", "add_question", "(", "lookup", ",", "Resolv", "::", "DNS", "::", "Resource", "::", "IN", "::", "A", ")", "message", ".", "encode", "end" ]
converts an ip or a hostname into the DNS query packet requires to lookup the result
[ "converts", "an", "ip", "or", "a", "hostname", "into", "the", "DNS", "query", "packet", "requires", "to", "lookup", "the", "result" ]
d88bb5eae3dfd03c418f67ae5767234a862a92b8
https://github.com/chrislee35/dnsbl-client/blob/d88bb5eae3dfd03c418f67ae5767234a862a92b8/lib/dnsbl/client.rb#L108-L124
19,274
chrislee35/dnsbl-client
lib/dnsbl/client.rb
DNSBL.Client.lookup
def lookup(item) # if item is an array, use it, otherwise make it one items = item if item.is_a? String items = [item] end # place the results in the results array results = [] # for each ip or hostname items.each do |item| # sent is used to determine when we have all the answers sent = 0 # record the start time @starttime = Time.now.to_f # determine the type of query itemtype = (item =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) ? 'ip' : 'domain' # for each dnsbl that supports our type, create the DNS query packet and send it # rotate across our configured name servers and increment sent @dnsbls.each do |name,config| next if config['disabled'] next unless config['type'] == itemtype begin msg = _encode_query(item,itemtype,config['domain'],config['apikey']) @sockets[@socket_index].send(msg,0) @socket_index += 1 @socket_index %= @sockets.length sent += 1 rescue Exception => e puts e puts e.backtrace.join("\n") end end # while we still expect answers while sent > 0 # wait on the socket for maximally 1.5 seconds r,_,_ = IO.select(@sockets,nil,nil,1.5) # if we time out, break out of the loop break unless r # for each reply, decode it and receive results, decrement the pending answers r.each do |s| begin response = _decode_response(s.recv(4096)) results += response rescue Exception => e puts e puts e.backtrace.join("\n") end sent -= 1 end end end results end
ruby
def lookup(item) # if item is an array, use it, otherwise make it one items = item if item.is_a? String items = [item] end # place the results in the results array results = [] # for each ip or hostname items.each do |item| # sent is used to determine when we have all the answers sent = 0 # record the start time @starttime = Time.now.to_f # determine the type of query itemtype = (item =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) ? 'ip' : 'domain' # for each dnsbl that supports our type, create the DNS query packet and send it # rotate across our configured name servers and increment sent @dnsbls.each do |name,config| next if config['disabled'] next unless config['type'] == itemtype begin msg = _encode_query(item,itemtype,config['domain'],config['apikey']) @sockets[@socket_index].send(msg,0) @socket_index += 1 @socket_index %= @sockets.length sent += 1 rescue Exception => e puts e puts e.backtrace.join("\n") end end # while we still expect answers while sent > 0 # wait on the socket for maximally 1.5 seconds r,_,_ = IO.select(@sockets,nil,nil,1.5) # if we time out, break out of the loop break unless r # for each reply, decode it and receive results, decrement the pending answers r.each do |s| begin response = _decode_response(s.recv(4096)) results += response rescue Exception => e puts e puts e.backtrace.join("\n") end sent -= 1 end end end results end
[ "def", "lookup", "(", "item", ")", "# if item is an array, use it, otherwise make it one", "items", "=", "item", "if", "item", ".", "is_a?", "String", "items", "=", "[", "item", "]", "end", "# place the results in the results array", "results", "=", "[", "]", "# for each ip or hostname", "items", ".", "each", "do", "|", "item", "|", "# sent is used to determine when we have all the answers", "sent", "=", "0", "# record the start time", "@starttime", "=", "Time", ".", "now", ".", "to_f", "# determine the type of query", "itemtype", "=", "(", "item", "=~", "/", "\\d", "\\.", "\\d", "\\.", "\\d", "\\.", "\\d", "/", ")", "?", "'ip'", ":", "'domain'", "# for each dnsbl that supports our type, create the DNS query packet and send it", "# rotate across our configured name servers and increment sent", "@dnsbls", ".", "each", "do", "|", "name", ",", "config", "|", "next", "if", "config", "[", "'disabled'", "]", "next", "unless", "config", "[", "'type'", "]", "==", "itemtype", "begin", "msg", "=", "_encode_query", "(", "item", ",", "itemtype", ",", "config", "[", "'domain'", "]", ",", "config", "[", "'apikey'", "]", ")", "@sockets", "[", "@socket_index", "]", ".", "send", "(", "msg", ",", "0", ")", "@socket_index", "+=", "1", "@socket_index", "%=", "@sockets", ".", "length", "sent", "+=", "1", "rescue", "Exception", "=>", "e", "puts", "e", "puts", "e", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", "end", "end", "# while we still expect answers", "while", "sent", ">", "0", "# wait on the socket for maximally 1.5 seconds", "r", ",", "_", ",", "_", "=", "IO", ".", "select", "(", "@sockets", ",", "nil", ",", "nil", ",", "1.5", ")", "# if we time out, break out of the loop", "break", "unless", "r", "# for each reply, decode it and receive results, decrement the pending answers", "r", ".", "each", "do", "|", "s", "|", "begin", "response", "=", "_decode_response", "(", "s", ".", "recv", "(", "4096", ")", ")", "results", "+=", "response", "rescue", "Exception", "=>", "e", "puts", "e", "puts", "e", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", "end", "sent", "-=", "1", "end", "end", "end", "results", "end" ]
lookup performs the sending of DNS queries for the given items returns an array of DNSBLResult
[ "lookup", "performs", "the", "sending", "of", "DNS", "queries", "for", "the", "given", "items", "returns", "an", "array", "of", "DNSBLResult" ]
d88bb5eae3dfd03c418f67ae5767234a862a92b8
https://github.com/chrislee35/dnsbl-client/blob/d88bb5eae3dfd03c418f67ae5767234a862a92b8/lib/dnsbl/client.rb#L129-L181
19,275
chrislee35/dnsbl-client
lib/dnsbl/client.rb
DNSBL.Client._decode_response
def _decode_response(buf) reply = Resolv::DNS::Message.decode(buf) results = [] reply.each_answer do |name,ttl,data| if name.to_s =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(.+)$/ ip = [$4,$3,$2,$1].join(".") domain = $5 @dnsbls.each do |dnsblname, config| next unless data.is_a? Resolv::DNS::Resource::IN::A if domain == config['domain'] meaning = config[data.address.to_s] || data.address.to_s results << DNSBLResult.new(dnsblname, ip, name.to_s, data.address.to_s, meaning, Time.now.to_f - @starttime) break end end else @dnsbls.each do |dnsblname, config| if name.to_s.end_with?(config['domain']) meaning = nil if config['decoder'] meaning = self.send(("__"+config['decoder']).to_sym, data.address.to_s) elsif config[data.address.to_s] meaning = config[data.address.to_s] else meaning = data.address.to_s end results << DNSBLResult.new(dnsblname, name.to_s.gsub("."+config['domain'],''), name.to_s, data.address.to_s, meaning, Time.now.to_f - @starttime) break end end end end results end
ruby
def _decode_response(buf) reply = Resolv::DNS::Message.decode(buf) results = [] reply.each_answer do |name,ttl,data| if name.to_s =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(.+)$/ ip = [$4,$3,$2,$1].join(".") domain = $5 @dnsbls.each do |dnsblname, config| next unless data.is_a? Resolv::DNS::Resource::IN::A if domain == config['domain'] meaning = config[data.address.to_s] || data.address.to_s results << DNSBLResult.new(dnsblname, ip, name.to_s, data.address.to_s, meaning, Time.now.to_f - @starttime) break end end else @dnsbls.each do |dnsblname, config| if name.to_s.end_with?(config['domain']) meaning = nil if config['decoder'] meaning = self.send(("__"+config['decoder']).to_sym, data.address.to_s) elsif config[data.address.to_s] meaning = config[data.address.to_s] else meaning = data.address.to_s end results << DNSBLResult.new(dnsblname, name.to_s.gsub("."+config['domain'],''), name.to_s, data.address.to_s, meaning, Time.now.to_f - @starttime) break end end end end results end
[ "def", "_decode_response", "(", "buf", ")", "reply", "=", "Resolv", "::", "DNS", "::", "Message", ".", "decode", "(", "buf", ")", "results", "=", "[", "]", "reply", ".", "each_answer", "do", "|", "name", ",", "ttl", ",", "data", "|", "if", "name", ".", "to_s", "=~", "/", "\\d", "\\.", "\\d", "\\.", "\\d", "\\.", "\\d", "\\.", "/", "ip", "=", "[", "$4", ",", "$3", ",", "$2", ",", "$1", "]", ".", "join", "(", "\".\"", ")", "domain", "=", "$5", "@dnsbls", ".", "each", "do", "|", "dnsblname", ",", "config", "|", "next", "unless", "data", ".", "is_a?", "Resolv", "::", "DNS", "::", "Resource", "::", "IN", "::", "A", "if", "domain", "==", "config", "[", "'domain'", "]", "meaning", "=", "config", "[", "data", ".", "address", ".", "to_s", "]", "||", "data", ".", "address", ".", "to_s", "results", "<<", "DNSBLResult", ".", "new", "(", "dnsblname", ",", "ip", ",", "name", ".", "to_s", ",", "data", ".", "address", ".", "to_s", ",", "meaning", ",", "Time", ".", "now", ".", "to_f", "-", "@starttime", ")", "break", "end", "end", "else", "@dnsbls", ".", "each", "do", "|", "dnsblname", ",", "config", "|", "if", "name", ".", "to_s", ".", "end_with?", "(", "config", "[", "'domain'", "]", ")", "meaning", "=", "nil", "if", "config", "[", "'decoder'", "]", "meaning", "=", "self", ".", "send", "(", "(", "\"__\"", "+", "config", "[", "'decoder'", "]", ")", ".", "to_sym", ",", "data", ".", "address", ".", "to_s", ")", "elsif", "config", "[", "data", ".", "address", ".", "to_s", "]", "meaning", "=", "config", "[", "data", ".", "address", ".", "to_s", "]", "else", "meaning", "=", "data", ".", "address", ".", "to_s", "end", "results", "<<", "DNSBLResult", ".", "new", "(", "dnsblname", ",", "name", ".", "to_s", ".", "gsub", "(", "\".\"", "+", "config", "[", "'domain'", "]", ",", "''", ")", ",", "name", ".", "to_s", ",", "data", ".", "address", ".", "to_s", ",", "meaning", ",", "Time", ".", "now", ".", "to_f", "-", "@starttime", ")", "break", "end", "end", "end", "end", "results", "end" ]
takes a DNS response and converts it into a DNSBLResult
[ "takes", "a", "DNS", "response", "and", "converts", "it", "into", "a", "DNSBLResult" ]
d88bb5eae3dfd03c418f67ae5767234a862a92b8
https://github.com/chrislee35/dnsbl-client/blob/d88bb5eae3dfd03c418f67ae5767234a862a92b8/lib/dnsbl/client.rb#L186-L219
19,276
chrislee35/dnsbl-client
lib/dnsbl/client.rb
DNSBL.Client.__phpot_decoder
def __phpot_decoder(ip) octets = ip.split(/\./) if octets.length != 4 or octets[0] != "127" return "invalid response" elsif octets[3] == "0" search_engines = ["undocumented", "AltaVista", "Ask", "Baidu", "Excite", "Google", "Looksmart", "Lycos", "MSN", "Yahoo", "Cuil", "InfoSeek", "Miscellaneous"] sindex = octets[2].to_i if sindex >= search_engines.length return "type=search engine,engine=unknown" else return "type=search engine,engine=#{search_engines[sindex]}" end else days, threatscore, flags = octets[1,3] flags = flags.to_i types = [] if (flags & 0x1) == 0x1 types << "suspicious" end if (flags & 0x2) == 0x2 types << "harvester" end if (flags & 0x4) == 0x4 types << "comment spammer" end if (flags & 0xf8) > 0 types << "reserved" end type = types.join(",") return "days=#{days},score=#{threatscore},type=#{type}" end end
ruby
def __phpot_decoder(ip) octets = ip.split(/\./) if octets.length != 4 or octets[0] != "127" return "invalid response" elsif octets[3] == "0" search_engines = ["undocumented", "AltaVista", "Ask", "Baidu", "Excite", "Google", "Looksmart", "Lycos", "MSN", "Yahoo", "Cuil", "InfoSeek", "Miscellaneous"] sindex = octets[2].to_i if sindex >= search_engines.length return "type=search engine,engine=unknown" else return "type=search engine,engine=#{search_engines[sindex]}" end else days, threatscore, flags = octets[1,3] flags = flags.to_i types = [] if (flags & 0x1) == 0x1 types << "suspicious" end if (flags & 0x2) == 0x2 types << "harvester" end if (flags & 0x4) == 0x4 types << "comment spammer" end if (flags & 0xf8) > 0 types << "reserved" end type = types.join(",") return "days=#{days},score=#{threatscore},type=#{type}" end end
[ "def", "__phpot_decoder", "(", "ip", ")", "octets", "=", "ip", ".", "split", "(", "/", "\\.", "/", ")", "if", "octets", ".", "length", "!=", "4", "or", "octets", "[", "0", "]", "!=", "\"127\"", "return", "\"invalid response\"", "elsif", "octets", "[", "3", "]", "==", "\"0\"", "search_engines", "=", "[", "\"undocumented\"", ",", "\"AltaVista\"", ",", "\"Ask\"", ",", "\"Baidu\"", ",", "\"Excite\"", ",", "\"Google\"", ",", "\"Looksmart\"", ",", "\"Lycos\"", ",", "\"MSN\"", ",", "\"Yahoo\"", ",", "\"Cuil\"", ",", "\"InfoSeek\"", ",", "\"Miscellaneous\"", "]", "sindex", "=", "octets", "[", "2", "]", ".", "to_i", "if", "sindex", ">=", "search_engines", ".", "length", "return", "\"type=search engine,engine=unknown\"", "else", "return", "\"type=search engine,engine=#{search_engines[sindex]}\"", "end", "else", "days", ",", "threatscore", ",", "flags", "=", "octets", "[", "1", ",", "3", "]", "flags", "=", "flags", ".", "to_i", "types", "=", "[", "]", "if", "(", "flags", "&", "0x1", ")", "==", "0x1", "types", "<<", "\"suspicious\"", "end", "if", "(", "flags", "&", "0x2", ")", "==", "0x2", "types", "<<", "\"harvester\"", "end", "if", "(", "flags", "&", "0x4", ")", "==", "0x4", "types", "<<", "\"comment spammer\"", "end", "if", "(", "flags", "&", "0xf8", ")", ">", "0", "types", "<<", "\"reserved\"", "end", "type", "=", "types", ".", "join", "(", "\",\"", ")", "return", "\"days=#{days},score=#{threatscore},type=#{type}\"", "end", "end" ]
decodes the response from Project Honey Pot's service
[ "decodes", "the", "response", "from", "Project", "Honey", "Pot", "s", "service" ]
d88bb5eae3dfd03c418f67ae5767234a862a92b8
https://github.com/chrislee35/dnsbl-client/blob/d88bb5eae3dfd03c418f67ae5767234a862a92b8/lib/dnsbl/client.rb#L222-L253
19,277
jgoizueta/flt
lib/flt/support/flag_values.rb
Flt.Support.FlagValues
def FlagValues(*params) if params.size==1 && params.first.kind_of?(FlagValues) params.first else FlagValues.new(*params) end end
ruby
def FlagValues(*params) if params.size==1 && params.first.kind_of?(FlagValues) params.first else FlagValues.new(*params) end end
[ "def", "FlagValues", "(", "*", "params", ")", "if", "params", ".", "size", "==", "1", "&&", "params", ".", "first", ".", "kind_of?", "(", "FlagValues", ")", "params", ".", "first", "else", "FlagValues", ".", "new", "(", "params", ")", "end", "end" ]
Constructor for FlagValues
[ "Constructor", "for", "FlagValues" ]
068869cfb81fe339658348490f4ea1294facfffa
https://github.com/jgoizueta/flt/blob/068869cfb81fe339658348490f4ea1294facfffa/lib/flt/support/flag_values.rb#L322-L328
19,278
jgoizueta/flt
lib/flt/support/flag_values.rb
Flt.Support.Flags
def Flags(*params) if params.size==1 && params.first.kind_of?(Flags) params.first else Flags.new(*params) end end
ruby
def Flags(*params) if params.size==1 && params.first.kind_of?(Flags) params.first else Flags.new(*params) end end
[ "def", "Flags", "(", "*", "params", ")", "if", "params", ".", "size", "==", "1", "&&", "params", ".", "first", ".", "kind_of?", "(", "Flags", ")", "params", ".", "first", "else", "Flags", ".", "new", "(", "params", ")", "end", "end" ]
Constructor for Flags
[ "Constructor", "for", "Flags" ]
068869cfb81fe339658348490f4ea1294facfffa
https://github.com/jgoizueta/flt/blob/068869cfb81fe339658348490f4ea1294facfffa/lib/flt/support/flag_values.rb#L331-L337
19,279
jgoizueta/flt
lib/flt/tolerance.rb
Flt.Tolerance.integer
def integer(x) # return integer?(x) ? x.round : nil r = x.round ((x-r).abs <= relative_to(x)) ? r : nil end
ruby
def integer(x) # return integer?(x) ? x.round : nil r = x.round ((x-r).abs <= relative_to(x)) ? r : nil end
[ "def", "integer", "(", "x", ")", "# return integer?(x) ? x.round : nil", "r", "=", "x", ".", "round", "(", "(", "x", "-", "r", ")", ".", "abs", "<=", "relative_to", "(", "x", ")", ")", "?", "r", ":", "nil", "end" ]
If the argument is close to an integer it rounds it
[ "If", "the", "argument", "is", "close", "to", "an", "integer", "it", "rounds", "it" ]
068869cfb81fe339658348490f4ea1294facfffa
https://github.com/jgoizueta/flt/blob/068869cfb81fe339658348490f4ea1294facfffa/lib/flt/tolerance.rb#L135-L139
19,280
muffinista/gopher2000
lib/gopher2000/dsl.rb
Gopher.DSL.mount
def mount(path, opts = {}) route, folder = path.first # # if path has more than the one option (:route => :folder), # then incorporate the rest of the hash into our opts # if path.size > 1 other_opts = path.dup other_opts.delete(route) opts = opts.merge(other_opts) end application.mount(route, opts.merge({:path => folder})) end
ruby
def mount(path, opts = {}) route, folder = path.first # # if path has more than the one option (:route => :folder), # then incorporate the rest of the hash into our opts # if path.size > 1 other_opts = path.dup other_opts.delete(route) opts = opts.merge(other_opts) end application.mount(route, opts.merge({:path => folder})) end
[ "def", "mount", "(", "path", ",", "opts", "=", "{", "}", ")", "route", ",", "folder", "=", "path", ".", "first", "#", "# if path has more than the one option (:route => :folder),", "# then incorporate the rest of the hash into our opts", "#", "if", "path", ".", "size", ">", "1", "other_opts", "=", "path", ".", "dup", "other_opts", ".", "delete", "(", "route", ")", "opts", "=", "opts", ".", "merge", "(", "other_opts", ")", "end", "application", ".", "mount", "(", "route", ",", "opts", ".", "merge", "(", "{", ":path", "=>", "folder", "}", ")", ")", "end" ]
mount a folder for browsing
[ "mount", "a", "folder", "for", "browsing" ]
0b5333c368b307772a41b4bc77b208d5c3f9196b
https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/dsl.rb#L43-L57
19,281
muffinista/gopher2000
lib/gopher2000/response.rb
Gopher.Response.size
def size case self.body when String then self.body.length when StringIO then self.body.length when File then self.body.size else 0 end end
ruby
def size case self.body when String then self.body.length when StringIO then self.body.length when File then self.body.size else 0 end end
[ "def", "size", "case", "self", ".", "body", "when", "String", "then", "self", ".", "body", ".", "length", "when", "StringIO", "then", "self", ".", "body", ".", "length", "when", "File", "then", "self", ".", "body", ".", "size", "else", "0", "end", "end" ]
get the size, in bytes, of the response. used for logging @return [Integer] size
[ "get", "the", "size", "in", "bytes", "of", "the", "response", ".", "used", "for", "logging" ]
0b5333c368b307772a41b4bc77b208d5c3f9196b
https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/response.rb#L16-L23
19,282
muffinista/gopher2000
lib/gopher2000/server.rb
Gopher.Server.run!
def run! EventMachine::run do Signal.trap("INT") { puts "It's a trap!" EventMachine.stop } Signal.trap("TERM") { puts "It's a trap!" EventMachine.stop } EventMachine.kqueue = true if EventMachine.kqueue? EventMachine.epoll = true if EventMachine.epoll? STDERR.puts "start server at #{host} #{port}" if @app.non_blocking? STDERR.puts "Not blocking on requests" end EventMachine::start_server(host, port, Gopher::Dispatcher) do |conn| # # check if we should reload any scripts before moving along # @app.reload_stale # # roughly matching sinatra's style of duping the app to respond # to requests, @see http://www.sinatrarb.com/intro#Request/Instance%20Scope # # this essentially means we have 'one instance per request' # conn.app = @app.dup end end end
ruby
def run! EventMachine::run do Signal.trap("INT") { puts "It's a trap!" EventMachine.stop } Signal.trap("TERM") { puts "It's a trap!" EventMachine.stop } EventMachine.kqueue = true if EventMachine.kqueue? EventMachine.epoll = true if EventMachine.epoll? STDERR.puts "start server at #{host} #{port}" if @app.non_blocking? STDERR.puts "Not blocking on requests" end EventMachine::start_server(host, port, Gopher::Dispatcher) do |conn| # # check if we should reload any scripts before moving along # @app.reload_stale # # roughly matching sinatra's style of duping the app to respond # to requests, @see http://www.sinatrarb.com/intro#Request/Instance%20Scope # # this essentially means we have 'one instance per request' # conn.app = @app.dup end end end
[ "def", "run!", "EventMachine", "::", "run", "do", "Signal", ".", "trap", "(", "\"INT\"", ")", "{", "puts", "\"It's a trap!\"", "EventMachine", ".", "stop", "}", "Signal", ".", "trap", "(", "\"TERM\"", ")", "{", "puts", "\"It's a trap!\"", "EventMachine", ".", "stop", "}", "EventMachine", ".", "kqueue", "=", "true", "if", "EventMachine", ".", "kqueue?", "EventMachine", ".", "epoll", "=", "true", "if", "EventMachine", ".", "epoll?", "STDERR", ".", "puts", "\"start server at #{host} #{port}\"", "if", "@app", ".", "non_blocking?", "STDERR", ".", "puts", "\"Not blocking on requests\"", "end", "EventMachine", "::", "start_server", "(", "host", ",", "port", ",", "Gopher", "::", "Dispatcher", ")", "do", "|", "conn", "|", "#", "# check if we should reload any scripts before moving along", "#", "@app", ".", "reload_stale", "#", "# roughly matching sinatra's style of duping the app to respond", "# to requests, @see http://www.sinatrarb.com/intro#Request/Instance%20Scope", "#", "# this essentially means we have 'one instance per request'", "#", "conn", ".", "app", "=", "@app", ".", "dup", "end", "end", "end" ]
main app loop. called via at_exit block defined in DSL
[ "main", "app", "loop", ".", "called", "via", "at_exit", "block", "defined", "in", "DSL" ]
0b5333c368b307772a41b4bc77b208d5c3f9196b
https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/server.rb#L34-L70
19,283
muffinista/gopher2000
lib/gopher2000/base.rb
Gopher.Application.should_reload?
def should_reload? ! last_reload.nil? && self.scripts.any? do |f| File.mtime(f) > last_reload end end
ruby
def should_reload? ! last_reload.nil? && self.scripts.any? do |f| File.mtime(f) > last_reload end end
[ "def", "should_reload?", "!", "last_reload", ".", "nil?", "&&", "self", ".", "scripts", ".", "any?", "do", "|", "f", "|", "File", ".", "mtime", "(", "f", ")", ">", "last_reload", "end", "end" ]
check if our script has been updated since the last reload
[ "check", "if", "our", "script", "has", "been", "updated", "since", "the", "last", "reload" ]
0b5333c368b307772a41b4bc77b208d5c3f9196b
https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L68-L72
19,284
muffinista/gopher2000
lib/gopher2000/base.rb
Gopher.Application.reload_stale
def reload_stale reload_check = should_reload? self.last_reload = Time.now return if ! reload_check reset! self.scripts.each do |f| debug_log "reload #{f}" load f end end
ruby
def reload_stale reload_check = should_reload? self.last_reload = Time.now return if ! reload_check reset! self.scripts.each do |f| debug_log "reload #{f}" load f end end
[ "def", "reload_stale", "reload_check", "=", "should_reload?", "self", ".", "last_reload", "=", "Time", ".", "now", "return", "if", "!", "reload_check", "reset!", "self", ".", "scripts", ".", "each", "do", "|", "f", "|", "debug_log", "\"reload #{f}\"", "load", "f", "end", "end" ]
reload scripts if needed
[ "reload", "scripts", "if", "needed" ]
0b5333c368b307772a41b4bc77b208d5c3f9196b
https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L77-L88
19,285
muffinista/gopher2000
lib/gopher2000/base.rb
Gopher.Application.mount
def mount(path, opts = {}, klass = Gopher::Handlers::DirectoryHandler) debug_log "MOUNT #{path} #{opts.inspect}" opts[:mount_point] = path handler = klass.new(opts) handler.application = self # # add a route for the mounted class # route(globify(path)) do # when we call, pass the params and request object for this # particular request handler.call(params, request) end end
ruby
def mount(path, opts = {}, klass = Gopher::Handlers::DirectoryHandler) debug_log "MOUNT #{path} #{opts.inspect}" opts[:mount_point] = path handler = klass.new(opts) handler.application = self # # add a route for the mounted class # route(globify(path)) do # when we call, pass the params and request object for this # particular request handler.call(params, request) end end
[ "def", "mount", "(", "path", ",", "opts", "=", "{", "}", ",", "klass", "=", "Gopher", "::", "Handlers", "::", "DirectoryHandler", ")", "debug_log", "\"MOUNT #{path} #{opts.inspect}\"", "opts", "[", ":mount_point", "]", "=", "path", "handler", "=", "klass", ".", "new", "(", "opts", ")", "handler", ".", "application", "=", "self", "#", "# add a route for the mounted class", "#", "route", "(", "globify", "(", "path", ")", ")", "do", "# when we call, pass the params and request object for this", "# particular request", "handler", ".", "call", "(", "params", ",", "request", ")", "end", "end" ]
mount a directory for browsing via gopher @param [Hash] path A hash specifying the path your route will answer to, and the filesystem path to use '/route' => '/home/path/etc' @param [Hash] opts a hash of options for the mount. Primarily this is a filter, which will restrict the list files outputted. example: :filter => '*.jpg' @param [Class] klass The class that should be used to handle this mount. You could write and use a custom handler if desired @example mount the directory '/home/user/foo' at the gopher path '/files', and only show JPG files: mount '/files' => '/home/user/foo', :filter => '*.jpg'
[ "mount", "a", "directory", "for", "browsing", "via", "gopher" ]
0b5333c368b307772a41b4bc77b208d5c3f9196b
https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L101-L116
19,286
muffinista/gopher2000
lib/gopher2000/base.rb
Gopher.Application.lookup
def lookup(selector) unless routes.nil? routes.each do |pattern, keys, block| if match = pattern.match(selector) match = match.to_a url = match.shift params = to_params_hash(keys, match) # # @todo think about this # @params = params return params, block end end end unless @default_route.nil? return {}, @default_route end raise Gopher::NotFoundError end
ruby
def lookup(selector) unless routes.nil? routes.each do |pattern, keys, block| if match = pattern.match(selector) match = match.to_a url = match.shift params = to_params_hash(keys, match) # # @todo think about this # @params = params return params, block end end end unless @default_route.nil? return {}, @default_route end raise Gopher::NotFoundError end
[ "def", "lookup", "(", "selector", ")", "unless", "routes", ".", "nil?", "routes", ".", "each", "do", "|", "pattern", ",", "keys", ",", "block", "|", "if", "match", "=", "pattern", ".", "match", "(", "selector", ")", "match", "=", "match", ".", "to_a", "url", "=", "match", ".", "shift", "params", "=", "to_params_hash", "(", "keys", ",", "match", ")", "#", "# @todo think about this", "#", "@params", "=", "params", "return", "params", ",", "block", "end", "end", "end", "unless", "@default_route", ".", "nil?", "return", "{", "}", ",", "@default_route", "end", "raise", "Gopher", "::", "NotFoundError", "end" ]
lookup an incoming path @param [String] selector the selector path of the incoming request
[ "lookup", "an", "incoming", "path" ]
0b5333c368b307772a41b4bc77b208d5c3f9196b
https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L163-L188
19,287
muffinista/gopher2000
lib/gopher2000/base.rb
Gopher.Application.dispatch
def dispatch(req) debug_log(req) response = Response.new @request = req if ! @request.valid? response.body = handle_invalid_request response.code = :error else begin debug_log("do lookup for #{@request.selector}") @params, block = lookup(@request.selector) # # call the block that handles this lookup # response.body = block.bind(self).call response.code = :success rescue Gopher::NotFoundError => e debug_log("#{@request.selector} -- not found") response.body = handle_not_found response.code = :missing rescue Exception => e debug_log("#{@request.selector} -- error") debug_log(e.inspect) debug_log(e.backtrace) response.body = handle_error(e) response.code = :error end end access_log(req, response) response end
ruby
def dispatch(req) debug_log(req) response = Response.new @request = req if ! @request.valid? response.body = handle_invalid_request response.code = :error else begin debug_log("do lookup for #{@request.selector}") @params, block = lookup(@request.selector) # # call the block that handles this lookup # response.body = block.bind(self).call response.code = :success rescue Gopher::NotFoundError => e debug_log("#{@request.selector} -- not found") response.body = handle_not_found response.code = :missing rescue Exception => e debug_log("#{@request.selector} -- error") debug_log(e.inspect) debug_log(e.backtrace) response.body = handle_error(e) response.code = :error end end access_log(req, response) response end
[ "def", "dispatch", "(", "req", ")", "debug_log", "(", "req", ")", "response", "=", "Response", ".", "new", "@request", "=", "req", "if", "!", "@request", ".", "valid?", "response", ".", "body", "=", "handle_invalid_request", "response", ".", "code", "=", ":error", "else", "begin", "debug_log", "(", "\"do lookup for #{@request.selector}\"", ")", "@params", ",", "block", "=", "lookup", "(", "@request", ".", "selector", ")", "#", "# call the block that handles this lookup", "#", "response", ".", "body", "=", "block", ".", "bind", "(", "self", ")", ".", "call", "response", ".", "code", "=", ":success", "rescue", "Gopher", "::", "NotFoundError", "=>", "e", "debug_log", "(", "\"#{@request.selector} -- not found\"", ")", "response", ".", "body", "=", "handle_not_found", "response", ".", "code", "=", ":missing", "rescue", "Exception", "=>", "e", "debug_log", "(", "\"#{@request.selector} -- error\"", ")", "debug_log", "(", "e", ".", "inspect", ")", "debug_log", "(", "e", ".", "backtrace", ")", "response", ".", "body", "=", "handle_error", "(", "e", ")", "response", ".", "code", "=", ":error", "end", "end", "access_log", "(", "req", ",", "response", ")", "response", "end" ]
find and run the first route which matches the incoming request @param [Request] req Gopher::Request object
[ "find", "and", "run", "the", "first", "route", "which", "matches", "the", "incoming", "request" ]
0b5333c368b307772a41b4bc77b208d5c3f9196b
https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L195-L230
19,288
muffinista/gopher2000
lib/gopher2000/base.rb
Gopher.Application.find_template
def find_template(t) x = menus[t] if x return x, Gopher::Rendering::Menu end x = text_templates[t] if x return x, Gopher::Rendering::Text end end
ruby
def find_template(t) x = menus[t] if x return x, Gopher::Rendering::Menu end x = text_templates[t] if x return x, Gopher::Rendering::Text end end
[ "def", "find_template", "(", "t", ")", "x", "=", "menus", "[", "t", "]", "if", "x", "return", "x", ",", "Gopher", "::", "Rendering", "::", "Menu", "end", "x", "=", "text_templates", "[", "t", "]", "if", "x", "return", "x", ",", "Gopher", "::", "Rendering", "::", "Text", "end", "end" ]
find a template @param [String/Symbol] t name of the template @return template block and the class context it should use
[ "find", "a", "template" ]
0b5333c368b307772a41b4bc77b208d5c3f9196b
https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L301-L310
19,289
muffinista/gopher2000
lib/gopher2000/base.rb
Gopher.Application.render
def render(template, *arguments) # # find the right renderer we need # block, handler = find_template(template) raise TemplateNotFound if block.nil? ctx = handler.new(self) ctx.params = @params ctx.request = @request ctx.instance_exec(*arguments, &block) end
ruby
def render(template, *arguments) # # find the right renderer we need # block, handler = find_template(template) raise TemplateNotFound if block.nil? ctx = handler.new(self) ctx.params = @params ctx.request = @request ctx.instance_exec(*arguments, &block) end
[ "def", "render", "(", "template", ",", "*", "arguments", ")", "#", "# find the right renderer we need", "#", "block", ",", "handler", "=", "find_template", "(", "template", ")", "raise", "TemplateNotFound", "if", "block", ".", "nil?", "ctx", "=", "handler", ".", "new", "(", "self", ")", "ctx", ".", "params", "=", "@params", "ctx", ".", "request", "=", "@request", "ctx", ".", "instance_exec", "(", "arguments", ",", "block", ")", "end" ]
Find the desired template and call it within the proper context @param [String/Symbol] template name of the template to render @param [Array] arguments optional arguments to be passed to template @return result of rendering
[ "Find", "the", "desired", "template", "and", "call", "it", "within", "the", "proper", "context" ]
0b5333c368b307772a41b4bc77b208d5c3f9196b
https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L318-L331
19,290
muffinista/gopher2000
lib/gopher2000/base.rb
Gopher.Application.compile!
def compile!(path, &block) method_name = path route_method = Application.generate_method(method_name, &block) pattern, keys = compile path [ pattern, keys, route_method ] end
ruby
def compile!(path, &block) method_name = path route_method = Application.generate_method(method_name, &block) pattern, keys = compile path [ pattern, keys, route_method ] end
[ "def", "compile!", "(", "path", ",", "&", "block", ")", "method_name", "=", "path", "route_method", "=", "Application", ".", "generate_method", "(", "method_name", ",", "block", ")", "pattern", ",", "keys", "=", "compile", "path", "[", "pattern", ",", "keys", ",", "route_method", "]", "end" ]
compile a route
[ "compile", "a", "route" ]
0b5333c368b307772a41b4bc77b208d5c3f9196b
https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L402-L408
19,291
muffinista/gopher2000
lib/gopher2000/base.rb
Gopher.Application.init_access_log
def init_access_log return if access_log_dest.nil? log = ::Logging.logger['access_log'] pattern = ::Logging.layouts.pattern(:pattern => ACCESS_LOG_PATTERN) log.add_appenders( ::Logging.appenders.rolling_file(access_log_dest, :level => :debug, :age => 'daily', :layout => pattern) ) log end
ruby
def init_access_log return if access_log_dest.nil? log = ::Logging.logger['access_log'] pattern = ::Logging.layouts.pattern(:pattern => ACCESS_LOG_PATTERN) log.add_appenders( ::Logging.appenders.rolling_file(access_log_dest, :level => :debug, :age => 'daily', :layout => pattern) ) log end
[ "def", "init_access_log", "return", "if", "access_log_dest", ".", "nil?", "log", "=", "::", "Logging", ".", "logger", "[", "'access_log'", "]", "pattern", "=", "::", "Logging", ".", "layouts", ".", "pattern", "(", ":pattern", "=>", "ACCESS_LOG_PATTERN", ")", "log", ".", "add_appenders", "(", "::", "Logging", ".", "appenders", ".", "rolling_file", "(", "access_log_dest", ",", ":level", "=>", ":debug", ",", ":age", "=>", "'daily'", ",", ":layout", "=>", "pattern", ")", ")", "log", "end" ]
initialize a Logger for tracking hits to the server
[ "initialize", "a", "Logger", "for", "tracking", "hits", "to", "the", "server" ]
0b5333c368b307772a41b4bc77b208d5c3f9196b
https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L514-L528
19,292
muffinista/gopher2000
lib/gopher2000/base.rb
Gopher.Application.access_log
def access_log(request, response) return if access_log_dest.nil? @@access_logger ||= init_access_log code = response.respond_to?(:code) ? response.code.to_s : "success" size = response.respond_to?(:size) ? response.size : response.length output = [request.ip_address, request.selector, request.input, code.to_s, size].join("\t") @@access_logger.debug output end
ruby
def access_log(request, response) return if access_log_dest.nil? @@access_logger ||= init_access_log code = response.respond_to?(:code) ? response.code.to_s : "success" size = response.respond_to?(:size) ? response.size : response.length output = [request.ip_address, request.selector, request.input, code.to_s, size].join("\t") @@access_logger.debug output end
[ "def", "access_log", "(", "request", ",", "response", ")", "return", "if", "access_log_dest", ".", "nil?", "@@access_logger", "||=", "init_access_log", "code", "=", "response", ".", "respond_to?", "(", ":code", ")", "?", "response", ".", "code", ".", "to_s", ":", "\"success\"", "size", "=", "response", ".", "respond_to?", "(", ":size", ")", "?", "response", ".", "size", ":", "response", ".", "length", "output", "=", "[", "request", ".", "ip_address", ",", "request", ".", "selector", ",", "request", ".", "input", ",", "code", ".", "to_s", ",", "size", "]", ".", "join", "(", "\"\\t\"", ")", "@@access_logger", ".", "debug", "output", "end" ]
write out an entry to our access log
[ "write", "out", "an", "entry", "to", "our", "access", "log" ]
0b5333c368b307772a41b4bc77b208d5c3f9196b
https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L533-L542
19,293
muffinista/gopher2000
lib/gopher2000/base.rb
Gopher.Application.to_params_hash
def to_params_hash(keys,values) hash = {} keys.size.times { |i| hash[ keys[i].to_sym ] = values[i] } hash end
ruby
def to_params_hash(keys,values) hash = {} keys.size.times { |i| hash[ keys[i].to_sym ] = values[i] } hash end
[ "def", "to_params_hash", "(", "keys", ",", "values", ")", "hash", "=", "{", "}", "keys", ".", "size", ".", "times", "{", "|", "i", "|", "hash", "[", "keys", "[", "i", "]", ".", "to_sym", "]", "=", "values", "[", "i", "]", "}", "hash", "end" ]
zip up two arrays of keys and values from an incoming request
[ "zip", "up", "two", "arrays", "of", "keys", "and", "values", "from", "an", "incoming", "request" ]
0b5333c368b307772a41b4bc77b208d5c3f9196b
https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/base.rb#L548-L552
19,294
muffinista/gopher2000
lib/gopher2000/dispatcher.rb
Gopher.Dispatcher.call!
def call!(request) operation = proc { app.dispatch(request) } callback = proc {|result| send_response result close_connection_after_writing } # # if we don't want to block on slow calls, use EM#defer # @see http://eventmachine.rubyforge.org/EventMachine.html#M000486 # if app.non_blocking? EventMachine.defer( operation, callback ) else callback.call(operation.call) end end
ruby
def call!(request) operation = proc { app.dispatch(request) } callback = proc {|result| send_response result close_connection_after_writing } # # if we don't want to block on slow calls, use EM#defer # @see http://eventmachine.rubyforge.org/EventMachine.html#M000486 # if app.non_blocking? EventMachine.defer( operation, callback ) else callback.call(operation.call) end end
[ "def", "call!", "(", "request", ")", "operation", "=", "proc", "{", "app", ".", "dispatch", "(", "request", ")", "}", "callback", "=", "proc", "{", "|", "result", "|", "send_response", "result", "close_connection_after_writing", "}", "#", "# if we don't want to block on slow calls, use EM#defer", "# @see http://eventmachine.rubyforge.org/EventMachine.html#M000486", "#", "if", "app", ".", "non_blocking?", "EventMachine", ".", "defer", "(", "operation", ",", "callback", ")", "else", "callback", ".", "call", "(", "operation", ".", "call", ")", "end", "end" ]
generate a request object from an incoming selector, and dispatch it to the app @param [Request] request Request object to handle @return Response object
[ "generate", "a", "request", "object", "from", "an", "incoming", "selector", "and", "dispatch", "it", "to", "the", "app" ]
0b5333c368b307772a41b4bc77b208d5c3f9196b
https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/dispatcher.rb#L46-L64
19,295
muffinista/gopher2000
lib/gopher2000/dispatcher.rb
Gopher.Dispatcher.send_response
def send_response(response) case response when Gopher::Response then send_response(response.body) when String then send_data(response + end_of_transmission) when StringIO then send_data(response.read + end_of_transmission) when File while chunk = response.read(8192) do send_data(chunk) end response.close end end
ruby
def send_response(response) case response when Gopher::Response then send_response(response.body) when String then send_data(response + end_of_transmission) when StringIO then send_data(response.read + end_of_transmission) when File while chunk = response.read(8192) do send_data(chunk) end response.close end end
[ "def", "send_response", "(", "response", ")", "case", "response", "when", "Gopher", "::", "Response", "then", "send_response", "(", "response", ".", "body", ")", "when", "String", "then", "send_data", "(", "response", "+", "end_of_transmission", ")", "when", "StringIO", "then", "send_data", "(", "response", ".", "read", "+", "end_of_transmission", ")", "when", "File", "while", "chunk", "=", "response", ".", "read", "(", "8192", ")", "do", "send_data", "(", "chunk", ")", "end", "response", ".", "close", "end", "end" ]
send the response back to the client @param [Response] response object
[ "send", "the", "response", "back", "to", "the", "client" ]
0b5333c368b307772a41b4bc77b208d5c3f9196b
https://github.com/muffinista/gopher2000/blob/0b5333c368b307772a41b4bc77b208d5c3f9196b/lib/gopher2000/dispatcher.rb#L70-L81
19,296
appsignal/appsignal-ruby
lib/appsignal/auth_check.rb
Appsignal.AuthCheck.perform_with_result
def perform_with_result status = perform result = case status when "200" "AppSignal has confirmed authorization!" when "401" "API key not valid with AppSignal..." else "Could not confirm authorization: " \ "#{status.nil? ? "nil" : status}" end [status, result] rescue => e result = "Something went wrong while trying to "\ "authenticate with AppSignal: #{e}" [nil, result] end
ruby
def perform_with_result status = perform result = case status when "200" "AppSignal has confirmed authorization!" when "401" "API key not valid with AppSignal..." else "Could not confirm authorization: " \ "#{status.nil? ? "nil" : status}" end [status, result] rescue => e result = "Something went wrong while trying to "\ "authenticate with AppSignal: #{e}" [nil, result] end
[ "def", "perform_with_result", "status", "=", "perform", "result", "=", "case", "status", "when", "\"200\"", "\"AppSignal has confirmed authorization!\"", "when", "\"401\"", "\"API key not valid with AppSignal...\"", "else", "\"Could not confirm authorization: \"", "\"#{status.nil? ? \"nil\" : status}\"", "end", "[", "status", ",", "result", "]", "rescue", "=>", "e", "result", "=", "\"Something went wrong while trying to \"", "\"authenticate with AppSignal: #{e}\"", "[", "nil", ",", "result", "]", "end" ]
Perform push api validation request and return a descriptive response tuple. @return [Array<String/nil, String>] response tuple. - First value is the response status code. - Second value is a description of the response and the exception error message if an exception occured.
[ "Perform", "push", "api", "validation", "request", "and", "return", "a", "descriptive", "response", "tuple", "." ]
23a07f6f01857a967921adb83deb98b07d160629
https://github.com/appsignal/appsignal-ruby/blob/23a07f6f01857a967921adb83deb98b07d160629/lib/appsignal/auth_check.rb#L48-L65
19,297
appsignal/appsignal-ruby
lib/appsignal/config.rb
Appsignal.Config.maintain_backwards_compatibility
def maintain_backwards_compatibility(configuration) configuration.tap do |config| DEPRECATED_CONFIG_KEY_MAPPING.each do |old_key, new_key| old_config_value = config.delete(old_key) next unless old_config_value deprecation_message \ "Old configuration key found. Please update the "\ "'#{old_key}' to '#{new_key}'.", logger next if config[new_key] # Skip if new key is already in use config[new_key] = old_config_value end if config.include?(:working_dir_path) deprecation_message \ "'working_dir_path' is deprecated, please use " \ "'working_directory_path' instead and specify the " \ "full path to the working directory", logger end end end
ruby
def maintain_backwards_compatibility(configuration) configuration.tap do |config| DEPRECATED_CONFIG_KEY_MAPPING.each do |old_key, new_key| old_config_value = config.delete(old_key) next unless old_config_value deprecation_message \ "Old configuration key found. Please update the "\ "'#{old_key}' to '#{new_key}'.", logger next if config[new_key] # Skip if new key is already in use config[new_key] = old_config_value end if config.include?(:working_dir_path) deprecation_message \ "'working_dir_path' is deprecated, please use " \ "'working_directory_path' instead and specify the " \ "full path to the working directory", logger end end end
[ "def", "maintain_backwards_compatibility", "(", "configuration", ")", "configuration", ".", "tap", "do", "|", "config", "|", "DEPRECATED_CONFIG_KEY_MAPPING", ".", "each", "do", "|", "old_key", ",", "new_key", "|", "old_config_value", "=", "config", ".", "delete", "(", "old_key", ")", "next", "unless", "old_config_value", "deprecation_message", "\"Old configuration key found. Please update the \"", "\"'#{old_key}' to '#{new_key}'.\"", ",", "logger", "next", "if", "config", "[", "new_key", "]", "# Skip if new key is already in use", "config", "[", "new_key", "]", "=", "old_config_value", "end", "if", "config", ".", "include?", "(", ":working_dir_path", ")", "deprecation_message", "\"'working_dir_path' is deprecated, please use \"", "\"'working_directory_path' instead and specify the \"", "\"full path to the working directory\"", ",", "logger", "end", "end", "end" ]
Maintain backwards compatibility with config files generated by earlier versions of the gem Used by {#load_from_disk}. No compatibility for env variables or initial config currently.
[ "Maintain", "backwards", "compatibility", "with", "config", "files", "generated", "by", "earlier", "versions", "of", "the", "gem" ]
23a07f6f01857a967921adb83deb98b07d160629
https://github.com/appsignal/appsignal-ruby/blob/23a07f6f01857a967921adb83deb98b07d160629/lib/appsignal/config.rb#L283-L305
19,298
appsignal/appsignal-ruby
lib/appsignal/transaction.rb
Appsignal.Transaction.background_queue_start
def background_queue_start env = environment return unless env queue_start = env[:queue_start] return unless queue_start (queue_start.to_f * 1000.0).to_i end
ruby
def background_queue_start env = environment return unless env queue_start = env[:queue_start] return unless queue_start (queue_start.to_f * 1000.0).to_i end
[ "def", "background_queue_start", "env", "=", "environment", "return", "unless", "env", "queue_start", "=", "env", "[", ":queue_start", "]", "return", "unless", "queue_start", "(", "queue_start", ".", "to_f", "*", "1000.0", ")", ".", "to_i", "end" ]
Returns calculated background queue start time in milliseconds, based on environment values. @return [nil] if no {#environment} is present. @return [nil] if there is no `:queue_start` in the {#environment}. @return [Integer]
[ "Returns", "calculated", "background", "queue", "start", "time", "in", "milliseconds", "based", "on", "environment", "values", "." ]
23a07f6f01857a967921adb83deb98b07d160629
https://github.com/appsignal/appsignal-ruby/blob/23a07f6f01857a967921adb83deb98b07d160629/lib/appsignal/transaction.rb#L340-L347
19,299
appsignal/appsignal-ruby
lib/appsignal/transaction.rb
Appsignal.Transaction.http_queue_start
def http_queue_start env = environment return unless env env_var = env["HTTP_X_QUEUE_START".freeze] || env["HTTP_X_REQUEST_START".freeze] return unless env_var cleaned_value = env_var.tr("^0-9".freeze, "".freeze) return if cleaned_value.empty? value = cleaned_value.to_i if value > 4_102_441_200_000 # Value is in microseconds. Transform to milliseconds. value / 1_000 elsif value < 946_681_200_000 # Value is too low to be plausible nil else # Value is in milliseconds value end end
ruby
def http_queue_start env = environment return unless env env_var = env["HTTP_X_QUEUE_START".freeze] || env["HTTP_X_REQUEST_START".freeze] return unless env_var cleaned_value = env_var.tr("^0-9".freeze, "".freeze) return if cleaned_value.empty? value = cleaned_value.to_i if value > 4_102_441_200_000 # Value is in microseconds. Transform to milliseconds. value / 1_000 elsif value < 946_681_200_000 # Value is too low to be plausible nil else # Value is in milliseconds value end end
[ "def", "http_queue_start", "env", "=", "environment", "return", "unless", "env", "env_var", "=", "env", "[", "\"HTTP_X_QUEUE_START\"", ".", "freeze", "]", "||", "env", "[", "\"HTTP_X_REQUEST_START\"", ".", "freeze", "]", "return", "unless", "env_var", "cleaned_value", "=", "env_var", ".", "tr", "(", "\"^0-9\"", ".", "freeze", ",", "\"\"", ".", "freeze", ")", "return", "if", "cleaned_value", ".", "empty?", "value", "=", "cleaned_value", ".", "to_i", "if", "value", ">", "4_102_441_200_000", "# Value is in microseconds. Transform to milliseconds.", "value", "/", "1_000", "elsif", "value", "<", "946_681_200_000", "# Value is too low to be plausible", "nil", "else", "# Value is in milliseconds", "value", "end", "end" ]
Returns HTTP queue start time in milliseconds. @return [nil] if no queue start time is found. @return [nil] if begin time is too low to be plausible. @return [Integer] queue start in milliseconds.
[ "Returns", "HTTP", "queue", "start", "time", "in", "milliseconds", "." ]
23a07f6f01857a967921adb83deb98b07d160629
https://github.com/appsignal/appsignal-ruby/blob/23a07f6f01857a967921adb83deb98b07d160629/lib/appsignal/transaction.rb#L354-L373