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
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
4,500
netskin/ceph-ruby
lib/ceph-ruby/cluster.rb
CephRuby.Cluster.connect
def connect log("connect") ret = Lib::Rados.rados_connect(handle) raise SystemCallError.new("connect to cluster failed", -ret) if ret < 0 end
ruby
def connect log("connect") ret = Lib::Rados.rados_connect(handle) raise SystemCallError.new("connect to cluster failed", -ret) if ret < 0 end
[ "def", "connect", "log", "(", "\"connect\"", ")", "ret", "=", "Lib", "::", "Rados", ".", "rados_connect", "(", "handle", ")", "raise", "SystemCallError", ".", "new", "(", "\"connect to cluster failed\"", ",", "-", "ret", ")", "if", "ret", "<", "0", "end" ]
helper methods below
[ "helper", "methods", "below" ]
bf2023b450ffb8ba7b12e5847e475f0f8796d0c7
https://github.com/netskin/ceph-ruby/blob/bf2023b450ffb8ba7b12e5847e475f0f8796d0c7/lib/ceph-ruby/cluster.rb#L38-L42
4,501
stereobooster/jshintrb
lib/jshintrb/jshinttask.rb
Jshintrb.JshintTask.define
def define # :nodoc: actual_name = Hash === name ? name.keys.first : name unless ::Rake.application.last_comment desc "Run JShint" end task name do unless js_file_list.empty? result = Jshintrb::report(js_file_list, @options, @globals, STDERR) if result.size > 0 abort("JSHint check failed") if fail_on_error end end end self end
ruby
def define # :nodoc: actual_name = Hash === name ? name.keys.first : name unless ::Rake.application.last_comment desc "Run JShint" end task name do unless js_file_list.empty? result = Jshintrb::report(js_file_list, @options, @globals, STDERR) if result.size > 0 abort("JSHint check failed") if fail_on_error end end end self end
[ "def", "define", "# :nodoc:", "actual_name", "=", "Hash", "===", "name", "?", "name", ".", "keys", ".", "first", ":", "name", "unless", "::", "Rake", ".", "application", ".", "last_comment", "desc", "\"Run JShint\"", "end", "task", "name", "do", "unless", "js_file_list", ".", "empty?", "result", "=", "Jshintrb", "::", "report", "(", "js_file_list", ",", "@options", ",", "@globals", ",", "STDERR", ")", "if", "result", ".", "size", ">", "0", "abort", "(", "\"JSHint check failed\"", ")", "if", "fail_on_error", "end", "end", "end", "self", "end" ]
Defines a new task, using the name +name+.
[ "Defines", "a", "new", "task", "using", "the", "name", "+", "name", "+", "." ]
5ee7051e3c6df584ea7e020bcffd712ffbdb1b31
https://github.com/stereobooster/jshintrb/blob/5ee7051e3c6df584ea7e020bcffd712ffbdb1b31/lib/jshintrb/jshinttask.rb#L52-L68
4,502
SSSaaS/sssa-ruby
lib/utils.rb
SSSA.Utils.split_ints
def split_ints(secret) result = [] secret.split('').map { |x| data = x.unpack("H*")[0] "0"*(data.size % 2) + data }.join("").scan(/.{1,64}/) { |segment| result.push (segment+"0"*(64-segment.size)).hex } return result end
ruby
def split_ints(secret) result = [] secret.split('').map { |x| data = x.unpack("H*")[0] "0"*(data.size % 2) + data }.join("").scan(/.{1,64}/) { |segment| result.push (segment+"0"*(64-segment.size)).hex } return result end
[ "def", "split_ints", "(", "secret", ")", "result", "=", "[", "]", "secret", ".", "split", "(", "''", ")", ".", "map", "{", "|", "x", "|", "data", "=", "x", ".", "unpack", "(", "\"H*\"", ")", "[", "0", "]", "\"0\"", "*", "(", "data", ".", "size", "%", "2", ")", "+", "data", "}", ".", "join", "(", "\"\"", ")", ".", "scan", "(", "/", "/", ")", "{", "|", "segment", "|", "result", ".", "push", "(", "segment", "+", "\"0\"", "*", "(", "64", "-", "segment", ".", "size", ")", ")", ".", "hex", "}", "return", "result", "end" ]
split_ints and merge_ints converts between string and integer array, where the integer is right-padded until it fits a 256 bit integer.
[ "split_ints", "and", "merge_ints", "converts", "between", "string", "and", "integer", "array", "where", "the", "integer", "is", "right", "-", "padded", "until", "it", "fits", "a", "256", "bit", "integer", "." ]
df65db5785d591630e4acdff7d2a65b52d2d9581
https://github.com/SSSaaS/sssa-ruby/blob/df65db5785d591630e4acdff7d2a65b52d2d9581/lib/utils.rb#L19-L30
4,503
appirits/comable
core/app/models/comable/order.rb
Comable.Order.inherit!
def inherit!(order) self.bill_address ||= order.bill_address self.ship_address ||= order.ship_address self.payment ||= order.payment self.shipments = order.shipments if shipments.empty? stated?(order.state) ? save! : next_state! end
ruby
def inherit!(order) self.bill_address ||= order.bill_address self.ship_address ||= order.ship_address self.payment ||= order.payment self.shipments = order.shipments if shipments.empty? stated?(order.state) ? save! : next_state! end
[ "def", "inherit!", "(", "order", ")", "self", ".", "bill_address", "||=", "order", ".", "bill_address", "self", ".", "ship_address", "||=", "order", ".", "ship_address", "self", ".", "payment", "||=", "order", ".", "payment", "self", ".", "shipments", "=", "order", ".", "shipments", "if", "shipments", ".", "empty?", "stated?", "(", "order", ".", "state", ")", "?", "save!", ":", "next_state!", "end" ]
Inherit from other Order
[ "Inherit", "from", "other", "Order" ]
b0cf028da35ea9def1c675680e5e5293a969bebc
https://github.com/appirits/comable/blob/b0cf028da35ea9def1c675680e5e5293a969bebc/core/app/models/comable/order.rb#L98-L105
4,504
thelabtech/questionnaire
app/models/qe/element.rb
Qe.Element.duplicate
def duplicate(page, parent = nil) new_element = self.class.new(self.attributes) case parent.class.to_s when ChoiceField new_element.conditional_id = parent.id when QuestionGrid, QuestionGridWithTotal new_element.question_grid_id = parent.id end new_element.save(:validate => false) PageElement.create(:element => new_element, :page => page) unless parent # duplicate children if respond_to?(:elements) && elements.present? elements.each {|e| e.duplicate(page, new_element)} end new_element end
ruby
def duplicate(page, parent = nil) new_element = self.class.new(self.attributes) case parent.class.to_s when ChoiceField new_element.conditional_id = parent.id when QuestionGrid, QuestionGridWithTotal new_element.question_grid_id = parent.id end new_element.save(:validate => false) PageElement.create(:element => new_element, :page => page) unless parent # duplicate children if respond_to?(:elements) && elements.present? elements.each {|e| e.duplicate(page, new_element)} end new_element end
[ "def", "duplicate", "(", "page", ",", "parent", "=", "nil", ")", "new_element", "=", "self", ".", "class", ".", "new", "(", "self", ".", "attributes", ")", "case", "parent", ".", "class", ".", "to_s", "when", "ChoiceField", "new_element", ".", "conditional_id", "=", "parent", ".", "id", "when", "QuestionGrid", ",", "QuestionGridWithTotal", "new_element", ".", "question_grid_id", "=", "parent", ".", "id", "end", "new_element", ".", "save", "(", ":validate", "=>", "false", ")", "PageElement", ".", "create", "(", ":element", "=>", "new_element", ",", ":page", "=>", "page", ")", "unless", "parent", "# duplicate children", "if", "respond_to?", "(", ":elements", ")", "&&", "elements", ".", "present?", "elements", ".", "each", "{", "|", "e", "|", "e", ".", "duplicate", "(", "page", ",", "new_element", ")", "}", "end", "new_element", "end" ]
copy an item and all it's children
[ "copy", "an", "item", "and", "all", "it", "s", "children" ]
02eb47cbcda8cca28a5db78e18623d0957aa2c9b
https://github.com/thelabtech/questionnaire/blob/02eb47cbcda8cca28a5db78e18623d0957aa2c9b/app/models/qe/element.rb#L116-L133
4,505
nazoking/rehtml
lib/rehtml/tokenizer.rb
REHTML.Tokenizer.decode
def decode(html) html.gsub(ENTITIES::REGEXP){ if $1 if ENTITIES::MAP[$1] ENTITIES::MAP[$1] else $& end elsif $2 [$2.to_i(10)].pack('U') elsif $3 [$3.to_i(16)].pack('U') else $& end } end
ruby
def decode(html) html.gsub(ENTITIES::REGEXP){ if $1 if ENTITIES::MAP[$1] ENTITIES::MAP[$1] else $& end elsif $2 [$2.to_i(10)].pack('U') elsif $3 [$3.to_i(16)].pack('U') else $& end } end
[ "def", "decode", "(", "html", ")", "html", ".", "gsub", "(", "ENTITIES", "::", "REGEXP", ")", "{", "if", "$1", "if", "ENTITIES", "::", "MAP", "[", "$1", "]", "ENTITIES", "::", "MAP", "[", "$1", "]", "else", "$&", "end", "elsif", "$2", "[", "$2", ".", "to_i", "(", "10", ")", "]", ".", "pack", "(", "'U'", ")", "elsif", "$3", "[", "$3", ".", "to_i", "(", "16", ")", "]", ".", "pack", "(", "'U'", ")", "else", "$&", "end", "}", "end" ]
decode html entity
[ "decode", "html", "entity" ]
4bf9016f5325becd955db777d832a2c90f3407ac
https://github.com/nazoking/rehtml/blob/4bf9016f5325becd955db777d832a2c90f3407ac/lib/rehtml/tokenizer.rb#L42-L58
4,506
thelabtech/questionnaire
app/models/qe/notifier.rb
Qe.Notifier.notification
def notification(p_recipients, p_from, template_name, template_params = {}, options = {}) email_template = EmailTemplate.find_by_name(template_name) if email_template.nil? raise "Email Template #{template_name} could not be found" else @recipients = p_recipients @from = p_from @subject = Liquid::Template.parse(email_template.subject).render(template_params) @body = Liquid::Template.parse(email_template.content).render(template_params) end end
ruby
def notification(p_recipients, p_from, template_name, template_params = {}, options = {}) email_template = EmailTemplate.find_by_name(template_name) if email_template.nil? raise "Email Template #{template_name} could not be found" else @recipients = p_recipients @from = p_from @subject = Liquid::Template.parse(email_template.subject).render(template_params) @body = Liquid::Template.parse(email_template.content).render(template_params) end end
[ "def", "notification", "(", "p_recipients", ",", "p_from", ",", "template_name", ",", "template_params", "=", "{", "}", ",", "options", "=", "{", "}", ")", "email_template", "=", "EmailTemplate", ".", "find_by_name", "(", "template_name", ")", "if", "email_template", ".", "nil?", "raise", "\"Email Template #{template_name} could not be found\"", "else", "@recipients", "=", "p_recipients", "@from", "=", "p_from", "@subject", "=", "Liquid", "::", "Template", ".", "parse", "(", "email_template", ".", "subject", ")", ".", "render", "(", "template_params", ")", "@body", "=", "Liquid", "::", "Template", ".", "parse", "(", "email_template", ".", "content", ")", ".", "render", "(", "template_params", ")", "end", "end" ]
call Notifier.deliver_notification
[ "call", "Notifier", ".", "deliver_notification" ]
02eb47cbcda8cca28a5db78e18623d0957aa2c9b
https://github.com/thelabtech/questionnaire/blob/02eb47cbcda8cca28a5db78e18623d0957aa2c9b/app/models/qe/notifier.rb#L5-L16
4,507
vchs/ruby_vcloud_sdk
lib/ruby_vcloud_sdk/catalog.rb
VCloudSdk.Catalog.find_item
def find_item(name, item_type = nil) link = find_item_link(name) item = VCloudSdk::CatalogItem.new(@session, link) check_item_type(item, item_type) item end
ruby
def find_item(name, item_type = nil) link = find_item_link(name) item = VCloudSdk::CatalogItem.new(@session, link) check_item_type(item, item_type) item end
[ "def", "find_item", "(", "name", ",", "item_type", "=", "nil", ")", "link", "=", "find_item_link", "(", "name", ")", "item", "=", "VCloudSdk", "::", "CatalogItem", ".", "new", "(", "@session", ",", "link", ")", "check_item_type", "(", "item", ",", "item_type", ")", "item", "end" ]
Find catalog item from catalog by name and type. If item_type is set to nil, returns catalog item as long as its name match. Raises an exception if catalog is not found. Raises ObjectNotFoundError if an item matching the name and type is not found. Otherwise, returns the catalog item.
[ "Find", "catalog", "item", "from", "catalog", "by", "name", "and", "type", ".", "If", "item_type", "is", "set", "to", "nil", "returns", "catalog", "item", "as", "long", "as", "its", "name", "match", ".", "Raises", "an", "exception", "if", "catalog", "is", "not", "found", ".", "Raises", "ObjectNotFoundError", "if", "an", "item", "matching", "the", "name", "and", "type", "is", "not", "found", ".", "Otherwise", "returns", "the", "catalog", "item", "." ]
92d56db4fea4321068ab300ca60bcc6cec3e459b
https://github.com/vchs/ruby_vcloud_sdk/blob/92d56db4fea4321068ab300ca60bcc6cec3e459b/lib/ruby_vcloud_sdk/catalog.rb#L40-L45
4,508
qw3/getnet_api
lib/getnet_api/configure.rb
GetnetApi.Configure.set_endpoint
def set_endpoint if ambiente == :producao return GetnetApi::Configure::URL[:producao] elsif ambiente == :homologacao return GetnetApi::Configure::URL[:homologacao] else return GetnetApi::Configure::URL[:sandbox] end end
ruby
def set_endpoint if ambiente == :producao return GetnetApi::Configure::URL[:producao] elsif ambiente == :homologacao return GetnetApi::Configure::URL[:homologacao] else return GetnetApi::Configure::URL[:sandbox] end end
[ "def", "set_endpoint", "if", "ambiente", "==", ":producao", "return", "GetnetApi", "::", "Configure", "::", "URL", "[", ":producao", "]", "elsif", "ambiente", "==", ":homologacao", "return", "GetnetApi", "::", "Configure", "::", "URL", "[", ":homologacao", "]", "else", "return", "GetnetApi", "::", "Configure", "::", "URL", "[", ":sandbox", "]", "end", "end" ]
Retornar a url conforme o ambiente
[ "Retornar", "a", "url", "conforme", "o", "ambiente" ]
94cbda66aab03d83ea38bc5325ea2a02a639e922
https://github.com/qw3/getnet_api/blob/94cbda66aab03d83ea38bc5325ea2a02a639e922/lib/getnet_api/configure.rb#L90-L98
4,509
kissmetrics/uri_signer
lib/uri_signer/request_signature.rb
UriSigner.RequestSignature.signature
def signature core_signature = [self.http_method, self.encoded_base_uri] core_signature << self.encoded_query_params if self.query_params? core_signature.join(self.separator) end
ruby
def signature core_signature = [self.http_method, self.encoded_base_uri] core_signature << self.encoded_query_params if self.query_params? core_signature.join(self.separator) end
[ "def", "signature", "core_signature", "=", "[", "self", ".", "http_method", ",", "self", ".", "encoded_base_uri", "]", "core_signature", "<<", "self", ".", "encoded_query_params", "if", "self", ".", "query_params?", "core_signature", ".", "join", "(", "self", ".", "separator", ")", "end" ]
Create a new RequestSignature instance @param http_method [String] The HTTP method from the request (GET, POST, PUT, or DELETE) @param base_uri [String] The base URI of the request. This is everything except the query string params @param query_params [Hash] A hash of the provided query string params It's required that you provide at least the http_method and base_uri. Params are optional @return [void] Returns the full signature string @return [String]
[ "Create", "a", "new", "RequestSignature", "instance" ]
3169df476c7f8ed88c5af6ade2c826ad3e5fa2a3
https://github.com/kissmetrics/uri_signer/blob/3169df476c7f8ed88c5af6ade2c826ad3e5fa2a3/lib/uri_signer/request_signature.rb#L57-L61
4,510
kissmetrics/uri_signer
lib/uri_signer/query_hash_parser.rb
UriSigner.QueryHashParser.to_s
def to_s parts = @query_hash.sort.inject([]) do |arr, (key,value)| if value.kind_of?(Array) value.each do |nested| arr << "%s=%s" % [key, nested] end else arr << "%s=%s" % [key, value] end arr end parts.join('&') end
ruby
def to_s parts = @query_hash.sort.inject([]) do |arr, (key,value)| if value.kind_of?(Array) value.each do |nested| arr << "%s=%s" % [key, nested] end else arr << "%s=%s" % [key, value] end arr end parts.join('&') end
[ "def", "to_s", "parts", "=", "@query_hash", ".", "sort", ".", "inject", "(", "[", "]", ")", "do", "|", "arr", ",", "(", "key", ",", "value", ")", "|", "if", "value", ".", "kind_of?", "(", "Array", ")", "value", ".", "each", "do", "|", "nested", "|", "arr", "<<", "\"%s=%s\"", "%", "[", "key", ",", "nested", "]", "end", "else", "arr", "<<", "\"%s=%s\"", "%", "[", "key", ",", "value", "]", "end", "arr", "end", "parts", ".", "join", "(", "'&'", ")", "end" ]
Creates a new QueryHashParser instance @param query_hash [Hash] A hash of key/values to turn into a query stringo @return [void] Returns the hash (key/values) as an ordered query string. This joins the keys and values, and then joins it all with the ampersand. This is not escaped @return [String]
[ "Creates", "a", "new", "QueryHashParser", "instance" ]
3169df476c7f8ed88c5af6ade2c826ad3e5fa2a3
https://github.com/kissmetrics/uri_signer/blob/3169df476c7f8ed88c5af6ade2c826ad3e5fa2a3/lib/uri_signer/query_hash_parser.rb#L28-L40
4,511
plexus/macros
lib/macros/sexp.rb
Macros.Sexp.sfind
def sfind(sexp, specs) specs.inject(sexp) do |node, spec| return NotFound if node.nil? if spec.is_a?(Symbol) && node.type == spec node elsif spec.is_a?(Integer) && node.children.length > spec node.children[spec] elsif spec.is_a?(Array) node.children.grep(AST::Node) .flat_map { |child| sfind(child, spec) } .reject { |child| child == NotFound } else return NotFound end end end
ruby
def sfind(sexp, specs) specs.inject(sexp) do |node, spec| return NotFound if node.nil? if spec.is_a?(Symbol) && node.type == spec node elsif spec.is_a?(Integer) && node.children.length > spec node.children[spec] elsif spec.is_a?(Array) node.children.grep(AST::Node) .flat_map { |child| sfind(child, spec) } .reject { |child| child == NotFound } else return NotFound end end end
[ "def", "sfind", "(", "sexp", ",", "specs", ")", "specs", ".", "inject", "(", "sexp", ")", "do", "|", "node", ",", "spec", "|", "return", "NotFound", "if", "node", ".", "nil?", "if", "spec", ".", "is_a?", "(", "Symbol", ")", "&&", "node", ".", "type", "==", "spec", "node", "elsif", "spec", ".", "is_a?", "(", "Integer", ")", "&&", "node", ".", "children", ".", "length", ">", "spec", "node", ".", "children", "[", "spec", "]", "elsif", "spec", ".", "is_a?", "(", "Array", ")", "node", ".", "children", ".", "grep", "(", "AST", "::", "Node", ")", ".", "flat_map", "{", "|", "child", "|", "sfind", "(", "child", ",", "spec", ")", "}", ".", "reject", "{", "|", "child", "|", "child", "==", "NotFound", "}", "else", "return", "NotFound", "end", "end", "end" ]
Traverse into sexp by type and child position
[ "Traverse", "into", "sexp", "by", "type", "and", "child", "position" ]
5a45c8f452695643727383d6e3c0004eb3a1146e
https://github.com/plexus/macros/blob/5a45c8f452695643727383d6e3c0004eb3a1146e/lib/macros/sexp.rb#L11-L27
4,512
sleewoo/minispec
lib/minispec/api/class/helpers.rb
MiniSpec.ClassAPI.helper
def helper helper, opts = {}, &proc proc || raise(ArgumentError, 'block is missing') helpers[helper] = [proc, opts] end
ruby
def helper helper, opts = {}, &proc proc || raise(ArgumentError, 'block is missing') helpers[helper] = [proc, opts] end
[ "def", "helper", "helper", ",", "opts", "=", "{", "}", ",", "&", "proc", "proc", "||", "raise", "(", "ArgumentError", ",", "'block is missing'", ")", "helpers", "[", "helper", "]", "=", "[", "proc", ",", "opts", "]", "end" ]
define custom assertion helpers. @note helpers can be overridden by name, that's it, if some spec inherits `:a_duck?` helper you can use `helper(:a_duck?) { ... }` to override it. @note tested object are passed to helper via first argument. any arguments passed to helper are sent after tested object. @note if a block used on left side, it will be passed as last argument and the helper is responsible to call it. please note that block will be passed as usual argument rather than a block. @note if you need the current context to be passed into helper use `:with_context` option. when doing so, the context will come as last argument. @example describe SomeTest do helper :a_pizza? do |food| does(food) =~ /cheese/ does(food) =~ /olives/ end testing :foods do food = Cook.some_food(with: 'cheese', and: 'olives') is(food).a_pizza? #=> passed food = Cook.some_food(with: 'potatoes') is(food).a_pizza? #=> failed end end @example any other arguments are sent after tested object describe SomeTest do helper :a_pizza? do |food, ingredients| does(food) =~ /dough/ does(ingredients).include? 'cheese' does(ingredients).include? 'olives' end testing :foods do ingredients = ['cheese', 'olives'] food = Cook.some_food(ingredients) is(food).a_pizza? ingredients end end @example given block passed as last argument # block comes as a usual argument rather than a block helper :is_invalid do |attr, block| e = assert(&block).raise(FormulaValidationError) assert(e.attr) == attr end test 'validates name' do assert(:name).is_invalid do formula "name with spaces" do url "foo" version "1.0" end end end @example using `with_context` option to get context as last argument describe SomeTest do helper :a_pizza?, with_context: true do |subject, ingredients, context| # context is a Hash containing :left_method, left_object, :left_proc and :negation keys end testing :foods do is(:smth).a_pizza? ['some', 'ingredients'] # helper's context will look like: # {left_method: :is, left_object: :smth, left_proc: nil, negation: nil} is { smth }.a_pizza? ['some', 'ingredients'] # helper's context will look like: # {left_method: :is, left_object: nil, left_proc: 'the -> { smth } proc', negation: nil} end end
[ "define", "custom", "assertion", "helpers", "." ]
6dcdacd041cc031c21f2fe70b6e5b22c6af636c5
https://github.com/sleewoo/minispec/blob/6dcdacd041cc031c21f2fe70b6e5b22c6af636c5/lib/minispec/api/class/helpers.rb#L92-L95
4,513
sleewoo/minispec
lib/minispec/utils/throw.rb
MiniSpec.Utils.symbol_thrown?
def symbol_thrown? expected_symbol, expected_value, context, &block thrown_symbol, thrown_value = catch_symbol(expected_symbol, &block) if context[:right_proc] expected_symbol && raise(ArgumentError, 'Both arguments and block given. Please use either one.') return MiniSpec::ThrowInspector.thrown_as_expected_by_proc?(thrown_symbol, context) end MiniSpec::ThrowInspector.thrown_as_expected?(expected_symbol, expected_value, thrown_symbol, thrown_value, context) end
ruby
def symbol_thrown? expected_symbol, expected_value, context, &block thrown_symbol, thrown_value = catch_symbol(expected_symbol, &block) if context[:right_proc] expected_symbol && raise(ArgumentError, 'Both arguments and block given. Please use either one.') return MiniSpec::ThrowInspector.thrown_as_expected_by_proc?(thrown_symbol, context) end MiniSpec::ThrowInspector.thrown_as_expected?(expected_symbol, expected_value, thrown_symbol, thrown_value, context) end
[ "def", "symbol_thrown?", "expected_symbol", ",", "expected_value", ",", "context", ",", "&", "block", "thrown_symbol", ",", "thrown_value", "=", "catch_symbol", "(", "expected_symbol", ",", "block", ")", "if", "context", "[", ":right_proc", "]", "expected_symbol", "&&", "raise", "(", "ArgumentError", ",", "'Both arguments and block given. Please use either one.'", ")", "return", "MiniSpec", "::", "ThrowInspector", ".", "thrown_as_expected_by_proc?", "(", "thrown_symbol", ",", "context", ")", "end", "MiniSpec", "::", "ThrowInspector", ".", "thrown_as_expected?", "(", "expected_symbol", ",", "expected_value", ",", "thrown_symbol", ",", "thrown_value", ",", "context", ")", "end" ]
checks whether given block throws a symbol and if yes compare it with expected one. if a optional value given it will be compared to thrown one. @param expected_symbol @param expected_value @param [Proc] &proc @return a failure [ThrowError] if expectation not met. true if expectations met.
[ "checks", "whether", "given", "block", "throws", "a", "symbol", "and", "if", "yes", "compare", "it", "with", "expected", "one", ".", "if", "a", "optional", "value", "given", "it", "will", "be", "compared", "to", "thrown", "one", "." ]
6dcdacd041cc031c21f2fe70b6e5b22c6af636c5
https://github.com/sleewoo/minispec/blob/6dcdacd041cc031c21f2fe70b6e5b22c6af636c5/lib/minispec/utils/throw.rb#L17-L26
4,514
sleewoo/minispec
lib/minispec/utils/throw.rb
MiniSpec.Utils.catch_symbol
def catch_symbol expected_symbol, &block thrown_symbol, thrown_value = nil begin if expected_symbol thrown_value = catch :__ms__nothing_thrown do catch expected_symbol do block.call throw :__ms__nothing_thrown, :__ms__nothing_thrown end end thrown_symbol = expected_symbol unless thrown_value == :__ms__nothing_thrown else block.call end rescue => e raise(e) unless thrown_symbol = extract_thrown_symbol(e) end [thrown_symbol, thrown_value] end
ruby
def catch_symbol expected_symbol, &block thrown_symbol, thrown_value = nil begin if expected_symbol thrown_value = catch :__ms__nothing_thrown do catch expected_symbol do block.call throw :__ms__nothing_thrown, :__ms__nothing_thrown end end thrown_symbol = expected_symbol unless thrown_value == :__ms__nothing_thrown else block.call end rescue => e raise(e) unless thrown_symbol = extract_thrown_symbol(e) end [thrown_symbol, thrown_value] end
[ "def", "catch_symbol", "expected_symbol", ",", "&", "block", "thrown_symbol", ",", "thrown_value", "=", "nil", "begin", "if", "expected_symbol", "thrown_value", "=", "catch", ":__ms__nothing_thrown", "do", "catch", "expected_symbol", "do", "block", ".", "call", "throw", ":__ms__nothing_thrown", ",", ":__ms__nothing_thrown", "end", "end", "thrown_symbol", "=", "expected_symbol", "unless", "thrown_value", "==", ":__ms__nothing_thrown", "else", "block", ".", "call", "end", "rescue", "=>", "e", "raise", "(", "e", ")", "unless", "thrown_symbol", "=", "extract_thrown_symbol", "(", "e", ")", "end", "[", "thrown_symbol", ",", "thrown_value", "]", "end" ]
calling given block and catching thrown symbol, if any. @param expected_symbol @param [Proc] &block
[ "calling", "given", "block", "and", "catching", "thrown", "symbol", "if", "any", "." ]
6dcdacd041cc031c21f2fe70b6e5b22c6af636c5
https://github.com/sleewoo/minispec/blob/6dcdacd041cc031c21f2fe70b6e5b22c6af636c5/lib/minispec/utils/throw.rb#L33-L51
4,515
sleewoo/minispec
lib/minispec/utils/throw.rb
MiniSpec.Utils.extract_thrown_symbol
def extract_thrown_symbol exception return unless exception.is_a?(Exception) return unless s = exception.message.scan(/uncaught throw\W+(\w+)/).flatten[0] s.to_sym end
ruby
def extract_thrown_symbol exception return unless exception.is_a?(Exception) return unless s = exception.message.scan(/uncaught throw\W+(\w+)/).flatten[0] s.to_sym end
[ "def", "extract_thrown_symbol", "exception", "return", "unless", "exception", ".", "is_a?", "(", "Exception", ")", "return", "unless", "s", "=", "exception", ".", "message", ".", "scan", "(", "/", "\\W", "\\w", "/", ")", ".", "flatten", "[", "0", "]", "s", ".", "to_sym", "end" ]
extract thrown symbol from given exception @param exception
[ "extract", "thrown", "symbol", "from", "given", "exception" ]
6dcdacd041cc031c21f2fe70b6e5b22c6af636c5
https://github.com/sleewoo/minispec/blob/6dcdacd041cc031c21f2fe70b6e5b22c6af636c5/lib/minispec/utils/throw.rb#L57-L61
4,516
pjotrp/bioruby-table
lib/bio-table/table.rb
BioTable.Table.find_fields
def find_fields rowname row = row_by_name(rowname) fields = (row ? row.fields : []) # fill fields with nil to match header length # say header=5 fields=2 fill=2 (skip rowname) fields.fill(nil,fields.size,header.size-1-fields.size) end
ruby
def find_fields rowname row = row_by_name(rowname) fields = (row ? row.fields : []) # fill fields with nil to match header length # say header=5 fields=2 fill=2 (skip rowname) fields.fill(nil,fields.size,header.size-1-fields.size) end
[ "def", "find_fields", "rowname", "row", "=", "row_by_name", "(", "rowname", ")", "fields", "=", "(", "row", "?", "row", ".", "fields", ":", "[", "]", ")", "# fill fields with nil to match header length", "# say header=5 fields=2 fill=2 (skip rowname)", "fields", ".", "fill", "(", "nil", ",", "fields", ".", "size", ",", "header", ".", "size", "-", "1", "-", "fields", ".", "size", ")", "end" ]
Find a record by rowname and return the fields. Empty fields are nils.
[ "Find", "a", "record", "by", "rowname", "and", "return", "the", "fields", ".", "Empty", "fields", "are", "nils", "." ]
e7cc97bb598743e7d69e63f16f76a2ce0ed9006d
https://github.com/pjotrp/bioruby-table/blob/e7cc97bb598743e7d69e63f16f76a2ce0ed9006d/lib/bio-table/table.rb#L97-L103
4,517
inre/fibre
lib/fibre/fiber_pool.rb
Fibre.FiberPool.checkout
def checkout(&b) spec = { block: b, parent: ::Fiber.current } if @pool.empty? raise "The fiber queue has been overflowed" if @queue.size > @pool_queue_size @queue.push spec return end @pool.shift.tap do |fiber| @reserved[fiber.object_id] = spec fiber.resume(spec) end self end
ruby
def checkout(&b) spec = { block: b, parent: ::Fiber.current } if @pool.empty? raise "The fiber queue has been overflowed" if @queue.size > @pool_queue_size @queue.push spec return end @pool.shift.tap do |fiber| @reserved[fiber.object_id] = spec fiber.resume(spec) end self end
[ "def", "checkout", "(", "&", "b", ")", "spec", "=", "{", "block", ":", "b", ",", "parent", ":", "::", "Fiber", ".", "current", "}", "if", "@pool", ".", "empty?", "raise", "\"The fiber queue has been overflowed\"", "if", "@queue", ".", "size", ">", "@pool_queue_size", "@queue", ".", "push", "spec", "return", "end", "@pool", ".", "shift", ".", "tap", "do", "|", "fiber", "|", "@reserved", "[", "fiber", ".", "object_id", "]", "=", "spec", "fiber", ".", "resume", "(", "spec", ")", "end", "self", "end" ]
Initialize fiber's pool Borrow fiber from the pool and call the block inside
[ "Initialize", "fiber", "s", "pool", "Borrow", "fiber", "from", "the", "pool", "and", "call", "the", "block", "inside" ]
6b4155b1b0042345154984c088007b63b3b69f20
https://github.com/inre/fibre/blob/6b4155b1b0042345154984c088007b63b3b69f20/lib/fibre/fiber_pool.rb#L31-L46
4,518
inre/fibre
lib/fibre/fiber_pool.rb
Fibre.FiberPool.fiber_entry
def fiber_entry(spec) loop do raise "wrong spec in fiber block" unless spec.is_a?(Hash) begin before!(spec) spec[:block].call# *Fiber.current.args after!(spec) # catch ArgumentError, IOError, EOFError, IndexError, LocalJumpError, NameError, NoMethodError # RangeError, FloatDomainError, RegexpError, RuntimeError, SecurityError, SystemCallError # SystemStackError, ThreadError, TypeError, ZeroDivisionError rescue StandardError => e if error.empty? raise Fibre::FiberError.new(e) else error!(e) end # catch NoMemoryError, ScriptError, SignalException, SystemExit, fatal etc #rescue Exception end unless @queue.empty? spec = @queue.shift next end spec = checkin end end
ruby
def fiber_entry(spec) loop do raise "wrong spec in fiber block" unless spec.is_a?(Hash) begin before!(spec) spec[:block].call# *Fiber.current.args after!(spec) # catch ArgumentError, IOError, EOFError, IndexError, LocalJumpError, NameError, NoMethodError # RangeError, FloatDomainError, RegexpError, RuntimeError, SecurityError, SystemCallError # SystemStackError, ThreadError, TypeError, ZeroDivisionError rescue StandardError => e if error.empty? raise Fibre::FiberError.new(e) else error!(e) end # catch NoMemoryError, ScriptError, SignalException, SystemExit, fatal etc #rescue Exception end unless @queue.empty? spec = @queue.shift next end spec = checkin end end
[ "def", "fiber_entry", "(", "spec", ")", "loop", "do", "raise", "\"wrong spec in fiber block\"", "unless", "spec", ".", "is_a?", "(", "Hash", ")", "begin", "before!", "(", "spec", ")", "spec", "[", ":block", "]", ".", "call", "# *Fiber.current.args", "after!", "(", "spec", ")", "# catch ArgumentError, IOError, EOFError, IndexError, LocalJumpError, NameError, NoMethodError", "# RangeError, FloatDomainError, RegexpError, RuntimeError, SecurityError, SystemCallError", "# SystemStackError, ThreadError, TypeError, ZeroDivisionError", "rescue", "StandardError", "=>", "e", "if", "error", ".", "empty?", "raise", "Fibre", "::", "FiberError", ".", "new", "(", "e", ")", "else", "error!", "(", "e", ")", "end", "# catch NoMemoryError, ScriptError, SignalException, SystemExit, fatal etc", "#rescue Exception", "end", "unless", "@queue", ".", "empty?", "spec", "=", "@queue", ".", "shift", "next", "end", "spec", "=", "checkin", "end", "end" ]
There is entrypoint running fibers
[ "There", "is", "entrypoint", "running", "fibers" ]
6b4155b1b0042345154984c088007b63b3b69f20
https://github.com/inre/fibre/blob/6b4155b1b0042345154984c088007b63b3b69f20/lib/fibre/fiber_pool.rb#L51-L80
4,519
inre/fibre
lib/fibre/fiber_pool.rb
Fibre.FiberPool.checkin
def checkin(result=nil) @reserved.delete ::Fiber.current.object_id @pool.unshift ::Fiber.current ::Fiber.yield end
ruby
def checkin(result=nil) @reserved.delete ::Fiber.current.object_id @pool.unshift ::Fiber.current ::Fiber.yield end
[ "def", "checkin", "(", "result", "=", "nil", ")", "@reserved", ".", "delete", "::", "Fiber", ".", "current", ".", "object_id", "@pool", ".", "unshift", "::", "Fiber", ".", "current", "::", "Fiber", ".", "yield", "end" ]
Return the fiber into the pool
[ "Return", "the", "fiber", "into", "the", "pool" ]
6b4155b1b0042345154984c088007b63b3b69f20
https://github.com/inre/fibre/blob/6b4155b1b0042345154984c088007b63b3b69f20/lib/fibre/fiber_pool.rb#L83-L87
4,520
lloeki/sprockets-less
lib/sprockets/less/functions.rb
Less.Tree.anonymous_function
def anonymous_function(block) lambda do |*args| # args: (this, node) v8 >= 0.10, otherwise (node) raise ArgumentError, "missing node" if args.empty? @tree[:Anonymous].new block.call(@tree, args.last) end end
ruby
def anonymous_function(block) lambda do |*args| # args: (this, node) v8 >= 0.10, otherwise (node) raise ArgumentError, "missing node" if args.empty? @tree[:Anonymous].new block.call(@tree, args.last) end end
[ "def", "anonymous_function", "(", "block", ")", "lambda", "do", "|", "*", "args", "|", "# args: (this, node) v8 >= 0.10, otherwise (node)", "raise", "ArgumentError", ",", "\"missing node\"", "if", "args", ".", "empty?", "@tree", "[", ":Anonymous", "]", ".", "new", "block", ".", "call", "(", "@tree", ",", "args", ".", "last", ")", "end", "end" ]
Creates a JavaScript anonymous function from a Ruby block
[ "Creates", "a", "JavaScript", "anonymous", "function", "from", "a", "Ruby", "block" ]
f8cd973dd4dd5111bbda44e6c3fd8f445ab477f7
https://github.com/lloeki/sprockets-less/blob/f8cd973dd4dd5111bbda44e6c3fd8f445ab477f7/lib/sprockets/less/functions.rb#L111-L117
4,521
lloeki/sprockets-less
lib/sprockets/less/functions.rb
Less.Tree.extend_js
def extend_js(mod) extend mod mod.public_instance_methods.each do |method_name| add_function(sym_to_css(method_name)) { |tree, cxt| send method_name.to_sym, unquote(cxt.toCSS()) } end end
ruby
def extend_js(mod) extend mod mod.public_instance_methods.each do |method_name| add_function(sym_to_css(method_name)) { |tree, cxt| send method_name.to_sym, unquote(cxt.toCSS()) } end end
[ "def", "extend_js", "(", "mod", ")", "extend", "mod", "mod", ".", "public_instance_methods", ".", "each", "do", "|", "method_name", "|", "add_function", "(", "sym_to_css", "(", "method_name", ")", ")", "{", "|", "tree", ",", "cxt", "|", "send", "method_name", ".", "to_sym", ",", "unquote", "(", "cxt", ".", "toCSS", "(", ")", ")", "}", "end", "end" ]
Adds all of a module's public instance methods as Less functions
[ "Adds", "all", "of", "a", "module", "s", "public", "instance", "methods", "as", "Less", "functions" ]
f8cd973dd4dd5111bbda44e6c3fd8f445ab477f7
https://github.com/lloeki/sprockets-less/blob/f8cd973dd4dd5111bbda44e6c3fd8f445ab477f7/lib/sprockets/less/functions.rb#L130-L137
4,522
nazoking/rehtml
lib/rehtml/builder.rb
REHTML.REXMLBuilder.append
def append(node) if node.is_a?(EndTag) return if empty_tag?(node.name) po = @pos while po.parent and po.name != node.name po = po.parent end if po.name == node.name @pos = po.parent end else rexml = to_rexml(node) # if node is second root element, add root element wrap html tag if rexml.is_a?(REXML::Element) and @pos == @doc and @doc.root if @doc.root.name != 'html' html = REXML::Element.new html.name = "html" i = @doc.root.index_in_parent-1 while pos = @doc.delete_at(i) @doc.delete_element(pos) if pos.is_a?(REXML::Element) html << pos end @doc << html @pos = html end @pos = @doc.root end @pos << rexml if rexml.is_a?(REXML::Element) and !empty_tag?(node.name) and !node.empty? @pos = rexml end end end
ruby
def append(node) if node.is_a?(EndTag) return if empty_tag?(node.name) po = @pos while po.parent and po.name != node.name po = po.parent end if po.name == node.name @pos = po.parent end else rexml = to_rexml(node) # if node is second root element, add root element wrap html tag if rexml.is_a?(REXML::Element) and @pos == @doc and @doc.root if @doc.root.name != 'html' html = REXML::Element.new html.name = "html" i = @doc.root.index_in_parent-1 while pos = @doc.delete_at(i) @doc.delete_element(pos) if pos.is_a?(REXML::Element) html << pos end @doc << html @pos = html end @pos = @doc.root end @pos << rexml if rexml.is_a?(REXML::Element) and !empty_tag?(node.name) and !node.empty? @pos = rexml end end end
[ "def", "append", "(", "node", ")", "if", "node", ".", "is_a?", "(", "EndTag", ")", "return", "if", "empty_tag?", "(", "node", ".", "name", ")", "po", "=", "@pos", "while", "po", ".", "parent", "and", "po", ".", "name", "!=", "node", ".", "name", "po", "=", "po", ".", "parent", "end", "if", "po", ".", "name", "==", "node", ".", "name", "@pos", "=", "po", ".", "parent", "end", "else", "rexml", "=", "to_rexml", "(", "node", ")", "# if node is second root element, add root element wrap html tag", "if", "rexml", ".", "is_a?", "(", "REXML", "::", "Element", ")", "and", "@pos", "==", "@doc", "and", "@doc", ".", "root", "if", "@doc", ".", "root", ".", "name", "!=", "'html'", "html", "=", "REXML", "::", "Element", ".", "new", "html", ".", "name", "=", "\"html\"", "i", "=", "@doc", ".", "root", ".", "index_in_parent", "-", "1", "while", "pos", "=", "@doc", ".", "delete_at", "(", "i", ")", "@doc", ".", "delete_element", "(", "pos", ")", "if", "pos", ".", "is_a?", "(", "REXML", "::", "Element", ")", "html", "<<", "pos", "end", "@doc", "<<", "html", "@pos", "=", "html", "end", "@pos", "=", "@doc", ".", "root", "end", "@pos", "<<", "rexml", "if", "rexml", ".", "is_a?", "(", "REXML", "::", "Element", ")", "and", "!", "empty_tag?", "(", "node", ".", "name", ")", "and", "!", "node", ".", "empty?", "@pos", "=", "rexml", "end", "end", "end" ]
append node to document
[ "append", "node", "to", "document" ]
4bf9016f5325becd955db777d832a2c90f3407ac
https://github.com/nazoking/rehtml/blob/4bf9016f5325becd955db777d832a2c90f3407ac/lib/rehtml/builder.rb#L19-L52
4,523
qw3/getnet_api
lib/getnet_api/payment.rb
GetnetApi.Payment.to_request
def to_request obj, type payment = { seller_id: GetnetApi.seller_id.to_s, amount: self.amount.to_i, currency: self.currency.to_s, order: self.order.to_request, customer: self.customer.to_request(:payment), } if type == :boleto payment.merge!({"boleto" => obj.to_request,}) elsif :credit payment.merge!({"credit" => obj.to_request,}) end return payment end
ruby
def to_request obj, type payment = { seller_id: GetnetApi.seller_id.to_s, amount: self.amount.to_i, currency: self.currency.to_s, order: self.order.to_request, customer: self.customer.to_request(:payment), } if type == :boleto payment.merge!({"boleto" => obj.to_request,}) elsif :credit payment.merge!({"credit" => obj.to_request,}) end return payment end
[ "def", "to_request", "obj", ",", "type", "payment", "=", "{", "seller_id", ":", "GetnetApi", ".", "seller_id", ".", "to_s", ",", "amount", ":", "self", ".", "amount", ".", "to_i", ",", "currency", ":", "self", ".", "currency", ".", "to_s", ",", "order", ":", "self", ".", "order", ".", "to_request", ",", "customer", ":", "self", ".", "customer", ".", "to_request", "(", ":payment", ")", ",", "}", "if", "type", "==", ":boleto", "payment", ".", "merge!", "(", "{", "\"boleto\"", "=>", "obj", ".", "to_request", ",", "}", ")", "elsif", ":credit", "payment", ".", "merge!", "(", "{", "\"credit\"", "=>", "obj", ".", "to_request", ",", "}", ")", "end", "return", "payment", "end" ]
Nova instancia da classe Cliente @param [Hash] campos Montar o Hash de dados do usuario no padrão utilizado pela Getnet
[ "Nova", "instancia", "da", "classe", "Cliente" ]
94cbda66aab03d83ea38bc5325ea2a02a639e922
https://github.com/qw3/getnet_api/blob/94cbda66aab03d83ea38bc5325ea2a02a639e922/lib/getnet_api/payment.rb#L75-L91
4,524
codefoundry/svn
lib/svn/revisions.rb
Svn.Revision.diff
def diff( path, options={} ) raise Svn::Error, "cannot diff directory #{path}@#{to_s}" if dir? path other = options[:with] if options[:with].is_a? Root other = repo.revision(options[:with]) if options[:with].is_a? Numeric other ||= repo.revision(to_i - 1) return other.diff( path, :with => self ) if other < self content = "" begin content = file_content_stream( path ).to_counted_string rescue Svn::Error => err raise if options[:raise_errors] end other_content = "" begin other_content= other.file_content_stream( path ).to_counted_string rescue Svn::Error => err raise if options[:raise_errors] end Diff.string_diff( content, other_content ).unified( :original_header => "#{path}@#{to_s}", :modified_header => "#{path}@#{other}" ) end
ruby
def diff( path, options={} ) raise Svn::Error, "cannot diff directory #{path}@#{to_s}" if dir? path other = options[:with] if options[:with].is_a? Root other = repo.revision(options[:with]) if options[:with].is_a? Numeric other ||= repo.revision(to_i - 1) return other.diff( path, :with => self ) if other < self content = "" begin content = file_content_stream( path ).to_counted_string rescue Svn::Error => err raise if options[:raise_errors] end other_content = "" begin other_content= other.file_content_stream( path ).to_counted_string rescue Svn::Error => err raise if options[:raise_errors] end Diff.string_diff( content, other_content ).unified( :original_header => "#{path}@#{to_s}", :modified_header => "#{path}@#{other}" ) end
[ "def", "diff", "(", "path", ",", "options", "=", "{", "}", ")", "raise", "Svn", "::", "Error", ",", "\"cannot diff directory #{path}@#{to_s}\"", "if", "dir?", "path", "other", "=", "options", "[", ":with", "]", "if", "options", "[", ":with", "]", ".", "is_a?", "Root", "other", "=", "repo", ".", "revision", "(", "options", "[", ":with", "]", ")", "if", "options", "[", ":with", "]", ".", "is_a?", "Numeric", "other", "||=", "repo", ".", "revision", "(", "to_i", "-", "1", ")", "return", "other", ".", "diff", "(", "path", ",", ":with", "=>", "self", ")", "if", "other", "<", "self", "content", "=", "\"\"", "begin", "content", "=", "file_content_stream", "(", "path", ")", ".", "to_counted_string", "rescue", "Svn", "::", "Error", "=>", "err", "raise", "if", "options", "[", ":raise_errors", "]", "end", "other_content", "=", "\"\"", "begin", "other_content", "=", "other", ".", "file_content_stream", "(", "path", ")", ".", "to_counted_string", "rescue", "Svn", "::", "Error", "=>", "err", "raise", "if", "options", "[", ":raise_errors", "]", "end", "Diff", ".", "string_diff", "(", "content", ",", "other_content", ")", ".", "unified", "(", ":original_header", "=>", "\"#{path}@#{to_s}\"", ",", ":modified_header", "=>", "\"#{path}@#{other}\"", ")", "end" ]
diffs +path+ with another revision. if no revision is specified, the previous revision is used.
[ "diffs", "+", "path", "+", "with", "another", "revision", ".", "if", "no", "revision", "is", "specified", "the", "previous", "revision", "is", "used", "." ]
930a8da65fbecf3ffed50655e1cb10fcbc484be4
https://github.com/codefoundry/svn/blob/930a8da65fbecf3ffed50655e1cb10fcbc484be4/lib/svn/revisions.rb#L98-L125
4,525
Nakilon/reddit_bot
lib/reddit_bot.rb
RedditBot.Bot.resp_with_token
def resp_with_token mtd, path, form fail unless path.start_with? ?/ timeout = 5 begin reddit_resp mtd, "https://oauth.reddit.com" + path, form, { "Authorization" => "bearer #{token}", "User-Agent" => "bot/#{@user_agent || @name}/#{RedditBot::VERSION} by /u/nakilon", } rescue NetHTTPUtils::Error => e sleep timeout Module.nesting[1].logger.info "sleeping #{timeout} seconds because of #{e.code}" timeout *= 2 raise unless e.code == 401 @token_cached = nil retry end end
ruby
def resp_with_token mtd, path, form fail unless path.start_with? ?/ timeout = 5 begin reddit_resp mtd, "https://oauth.reddit.com" + path, form, { "Authorization" => "bearer #{token}", "User-Agent" => "bot/#{@user_agent || @name}/#{RedditBot::VERSION} by /u/nakilon", } rescue NetHTTPUtils::Error => e sleep timeout Module.nesting[1].logger.info "sleeping #{timeout} seconds because of #{e.code}" timeout *= 2 raise unless e.code == 401 @token_cached = nil retry end end
[ "def", "resp_with_token", "mtd", ",", "path", ",", "form", "fail", "unless", "path", ".", "start_with?", "?/", "timeout", "=", "5", "begin", "reddit_resp", "mtd", ",", "\"https://oauth.reddit.com\"", "+", "path", ",", "form", ",", "{", "\"Authorization\"", "=>", "\"bearer #{token}\"", ",", "\"User-Agent\"", "=>", "\"bot/#{@user_agent || @name}/#{RedditBot::VERSION} by /u/nakilon\"", ",", "}", "rescue", "NetHTTPUtils", "::", "Error", "=>", "e", "sleep", "timeout", "Module", ".", "nesting", "[", "1", "]", ".", "logger", ".", "info", "\"sleeping #{timeout} seconds because of #{e.code}\"", "timeout", "*=", "2", "raise", "unless", "e", ".", "code", "==", "401", "@token_cached", "=", "nil", "retry", "end", "end" ]
def update_captcha return if @ignore_captcha pp iden_json = json(:post, "/api/new_captcha") iden = iden_json["json"]["data"]["iden"] # return @iden_and_captcha = [iden, "\n"] if @ignore_captcha # pp resp_with_token(:get, "/captcha/#{iden_json["json"]["data"]["iden"]}", {}) puts "CAPTCHA: https://reddit.com/captcha/#{iden}" @iden_and_captcha = [iden, gets.strip] end
[ "def", "update_captcha", "return", "if" ]
e18e498b807b81a49b5ea87b9b294a14b96f9f78
https://github.com/Nakilon/reddit_bot/blob/e18e498b807b81a49b5ea87b9b294a14b96f9f78/lib/reddit_bot.rb#L228-L244
4,526
kennym/ideone-ruby-api
lib/ideone.rb
Ideone.Client.languages
def languages unless @languages_cache response = call_request(:get_languages) languages = response.to_hash[:get_languages_response][:return][:item][1][:value][:item] # Create a sorted hash @languages_cache = Hash[create_dict(languages).sort_by{|k,v| k.to_i}] end return @languages_cache end
ruby
def languages unless @languages_cache response = call_request(:get_languages) languages = response.to_hash[:get_languages_response][:return][:item][1][:value][:item] # Create a sorted hash @languages_cache = Hash[create_dict(languages).sort_by{|k,v| k.to_i}] end return @languages_cache end
[ "def", "languages", "unless", "@languages_cache", "response", "=", "call_request", "(", ":get_languages", ")", "languages", "=", "response", ".", "to_hash", "[", ":get_languages_response", "]", "[", ":return", "]", "[", ":item", "]", "[", "1", "]", "[", ":value", "]", "[", ":item", "]", "# Create a sorted hash", "@languages_cache", "=", "Hash", "[", "create_dict", "(", "languages", ")", ".", "sort_by", "{", "|", "k", ",", "v", "|", "k", ".", "to_i", "}", "]", "end", "return", "@languages_cache", "end" ]
Get a list of supported languages and cache it.
[ "Get", "a", "list", "of", "supported", "languages", "and", "cache", "it", "." ]
d682c8a1c673579c399b834bff7dbcbba648fb81
https://github.com/kennym/ideone-ruby-api/blob/d682c8a1c673579c399b834bff7dbcbba648fb81/lib/ideone.rb#L79-L88
4,527
qw3/getnet_api
lib/getnet_api/boleto.rb
GetnetApi.Boleto.to_request
def to_request boleto = { our_number: self.our_number, document_number: self.document_number, expiration_date: self.expiration_date, instructions: self.instructions, provider: self.provider } return boleto end
ruby
def to_request boleto = { our_number: self.our_number, document_number: self.document_number, expiration_date: self.expiration_date, instructions: self.instructions, provider: self.provider } return boleto end
[ "def", "to_request", "boleto", "=", "{", "our_number", ":", "self", ".", "our_number", ",", "document_number", ":", "self", ".", "document_number", ",", "expiration_date", ":", "self", ".", "expiration_date", ",", "instructions", ":", "self", ".", "instructions", ",", "provider", ":", "self", ".", "provider", "}", "return", "boleto", "end" ]
Nova instancia da classe Boleto @param [Hash] campos Montar o Hash de dados do pagamento no padrão utilizado pela Getnet
[ "Nova", "instancia", "da", "classe", "Boleto" ]
94cbda66aab03d83ea38bc5325ea2a02a639e922
https://github.com/qw3/getnet_api/blob/94cbda66aab03d83ea38bc5325ea2a02a639e922/lib/getnet_api/boleto.rb#L49-L59
4,528
rkday/ruby-diameter
lib/diameter/message.rb
Diameter.Message.all_avps_by_name
def all_avps_by_name(name) code, _type, vendor = Internals::AVPNames.get(name) all_avps_by_code(code, vendor) end
ruby
def all_avps_by_name(name) code, _type, vendor = Internals::AVPNames.get(name) all_avps_by_code(code, vendor) end
[ "def", "all_avps_by_name", "(", "name", ")", "code", ",", "_type", ",", "vendor", "=", "Internals", "::", "AVPNames", ".", "get", "(", "name", ")", "all_avps_by_code", "(", "code", ",", "vendor", ")", "end" ]
Returns all AVPs with the given name. Only covers "top-level" AVPs - it won't look inside Grouped AVPs. @param name [String] The AVP name, either one predefined in {Constants::AVAILABLE_AVPS} or user-defined with {AVP.define} @return [Array<AVP>]
[ "Returns", "all", "AVPs", "with", "the", "given", "name", ".", "Only", "covers", "top", "-", "level", "AVPs", "-", "it", "won", "t", "look", "inside", "Grouped", "AVPs", "." ]
83def68f67cf660aa227eac4c74719dc98aacab2
https://github.com/rkday/ruby-diameter/blob/83def68f67cf660aa227eac4c74719dc98aacab2/lib/diameter/message.rb#L113-L116
4,529
johnl/web-page-parser
lib/web-page-parser/base_parser.rb
WebPageParser.BaseRegexpParser.encode
def encode(s) return s if s.nil? return s if s.valid_encoding? if s.force_encoding("iso-8859-1").valid_encoding? return s.encode('utf-8', 'iso-8859-1') end s end
ruby
def encode(s) return s if s.nil? return s if s.valid_encoding? if s.force_encoding("iso-8859-1").valid_encoding? return s.encode('utf-8', 'iso-8859-1') end s end
[ "def", "encode", "(", "s", ")", "return", "s", "if", "s", ".", "nil?", "return", "s", "if", "s", ".", "valid_encoding?", "if", "s", ".", "force_encoding", "(", "\"iso-8859-1\"", ")", ".", "valid_encoding?", "return", "s", ".", "encode", "(", "'utf-8'", ",", "'iso-8859-1'", ")", "end", "s", "end" ]
Handle any string encoding
[ "Handle", "any", "string", "encoding" ]
105cbe6fda569c6c6667ed655ea6c6771c1d9037
https://github.com/johnl/web-page-parser/blob/105cbe6fda569c6c6667ed655ea6c6771c1d9037/lib/web-page-parser/base_parser.rb#L103-L110
4,530
johnl/web-page-parser
lib/web-page-parser/base_parser.rb
WebPageParser.BaseRegexpParser.retrieve_page
def retrieve_page(rurl = nil) durl = rurl || url return nil unless durl durl = filter_url(durl) if self.respond_to?(:filter_url) self.class.retrieve_session ||= WebPageParser::HTTP::Session.new encode(self.class.retrieve_session.get(durl)) end
ruby
def retrieve_page(rurl = nil) durl = rurl || url return nil unless durl durl = filter_url(durl) if self.respond_to?(:filter_url) self.class.retrieve_session ||= WebPageParser::HTTP::Session.new encode(self.class.retrieve_session.get(durl)) end
[ "def", "retrieve_page", "(", "rurl", "=", "nil", ")", "durl", "=", "rurl", "||", "url", "return", "nil", "unless", "durl", "durl", "=", "filter_url", "(", "durl", ")", "if", "self", ".", "respond_to?", "(", ":filter_url", ")", "self", ".", "class", ".", "retrieve_session", "||=", "WebPageParser", "::", "HTTP", "::", "Session", ".", "new", "encode", "(", "self", ".", "class", ".", "retrieve_session", ".", "get", "(", "durl", ")", ")", "end" ]
request the page from the server and return the raw contents
[ "request", "the", "page", "from", "the", "server", "and", "return", "the", "raw", "contents" ]
105cbe6fda569c6c6667ed655ea6c6771c1d9037
https://github.com/johnl/web-page-parser/blob/105cbe6fda569c6c6667ed655ea6c6771c1d9037/lib/web-page-parser/base_parser.rb#L118-L124
4,531
johnl/web-page-parser
lib/web-page-parser/base_parser.rb
WebPageParser.BaseRegexpParser.title
def title return @title if @title if matches = class_const(:TITLE_RE).match(page) @title = matches[1].to_s.strip title_processor @title = decode_entities(@title) end end
ruby
def title return @title if @title if matches = class_const(:TITLE_RE).match(page) @title = matches[1].to_s.strip title_processor @title = decode_entities(@title) end end
[ "def", "title", "return", "@title", "if", "@title", "if", "matches", "=", "class_const", "(", ":TITLE_RE", ")", ".", "match", "(", "page", ")", "@title", "=", "matches", "[", "1", "]", ".", "to_s", ".", "strip", "title_processor", "@title", "=", "decode_entities", "(", "@title", ")", "end", "end" ]
The title method returns the title of the web page. It does the basic extraction using the TITLE_RE regular expression and handles text encoding. More advanced parsing can be done by overriding the title_processor method.
[ "The", "title", "method", "returns", "the", "title", "of", "the", "web", "page", "." ]
105cbe6fda569c6c6667ed655ea6c6771c1d9037
https://github.com/johnl/web-page-parser/blob/105cbe6fda569c6c6667ed655ea6c6771c1d9037/lib/web-page-parser/base_parser.rb#L131-L138
4,532
johnl/web-page-parser
lib/web-page-parser/base_parser.rb
WebPageParser.BaseRegexpParser.content
def content return @content if @content matches = class_const(:CONTENT_RE).match(page) if matches @content = class_const(:KILL_CHARS_RE).gsub(matches[1].to_s, '') content_processor @content.collect! { |p| decode_entities(p.strip) } @content.delete_if { |p| p == '' or p.nil? } end @content = [] if @content.nil? @content end
ruby
def content return @content if @content matches = class_const(:CONTENT_RE).match(page) if matches @content = class_const(:KILL_CHARS_RE).gsub(matches[1].to_s, '') content_processor @content.collect! { |p| decode_entities(p.strip) } @content.delete_if { |p| p == '' or p.nil? } end @content = [] if @content.nil? @content end
[ "def", "content", "return", "@content", "if", "@content", "matches", "=", "class_const", "(", ":CONTENT_RE", ")", ".", "match", "(", "page", ")", "if", "matches", "@content", "=", "class_const", "(", ":KILL_CHARS_RE", ")", ".", "gsub", "(", "matches", "[", "1", "]", ".", "to_s", ",", "''", ")", "content_processor", "@content", ".", "collect!", "{", "|", "p", "|", "decode_entities", "(", "p", ".", "strip", ")", "}", "@content", ".", "delete_if", "{", "|", "p", "|", "p", "==", "''", "or", "p", ".", "nil?", "}", "end", "@content", "=", "[", "]", "if", "@content", ".", "nil?", "@content", "end" ]
The content method returns the important body text of the web page. It does basic extraction and pre-processing of the page content and then calls the content_processor method for any other more custom processing work that needs doing. Lastly, it does some basic post processing and returns the content as a string. When writing a new parser, the CONTENT_RE constant should be defined in the subclass. The KILL_CHARS_RE constant can be overridden if necessary.
[ "The", "content", "method", "returns", "the", "important", "body", "text", "of", "the", "web", "page", "." ]
105cbe6fda569c6c6667ed655ea6c6771c1d9037
https://github.com/johnl/web-page-parser/blob/105cbe6fda569c6c6667ed655ea6c6771c1d9037/lib/web-page-parser/base_parser.rb#L165-L176
4,533
brainmap/nifti
lib/nifti/n_image.rb
NIFTI.NImage.[]
def [](index) # Dealing with Ranges is useful when the image represents a tensor if (index.is_a?(Fixnum) && index >= self.shape[0]) || (index.is_a?(Range) && index.last >= self.shape[0]) raise IndexError.new("Index over bounds") elsif self.shape.count == 1 if index.is_a?(Range) value = [] index.each { |i| value << self.array_image[get_index_value(i)] } value else self.array_image[get_index_value(index)] end else NImage.new(self.array_image, self.dim, self.previous_indexes.clone << index) end end
ruby
def [](index) # Dealing with Ranges is useful when the image represents a tensor if (index.is_a?(Fixnum) && index >= self.shape[0]) || (index.is_a?(Range) && index.last >= self.shape[0]) raise IndexError.new("Index over bounds") elsif self.shape.count == 1 if index.is_a?(Range) value = [] index.each { |i| value << self.array_image[get_index_value(i)] } value else self.array_image[get_index_value(index)] end else NImage.new(self.array_image, self.dim, self.previous_indexes.clone << index) end end
[ "def", "[]", "(", "index", ")", "# Dealing with Ranges is useful when the image represents a tensor", "if", "(", "index", ".", "is_a?", "(", "Fixnum", ")", "&&", "index", ">=", "self", ".", "shape", "[", "0", "]", ")", "||", "(", "index", ".", "is_a?", "(", "Range", ")", "&&", "index", ".", "last", ">=", "self", ".", "shape", "[", "0", "]", ")", "raise", "IndexError", ".", "new", "(", "\"Index over bounds\"", ")", "elsif", "self", ".", "shape", ".", "count", "==", "1", "if", "index", ".", "is_a?", "(", "Range", ")", "value", "=", "[", "]", "index", ".", "each", "{", "|", "i", "|", "value", "<<", "self", ".", "array_image", "[", "get_index_value", "(", "i", ")", "]", "}", "value", "else", "self", ".", "array_image", "[", "get_index_value", "(", "index", ")", "]", "end", "else", "NImage", ".", "new", "(", "self", ".", "array_image", ",", "self", ".", "dim", ",", "self", ".", "previous_indexes", ".", "clone", "<<", "index", ")", "end", "end" ]
Creates an NImage instance. The NImages instance provides a user friendly interface to the NIFTI Image A NImage is typically built by NObject instance === Parameters * <tt>array_image</tt> -- The NIFTI image contained on and one dimensional array * <tt>dim</tt> -- The dimensions array from the NIFTI header. === Examples # Creates an NImage to deal with an 9 position array that represents a 3x3 matrix img = Nimage.new(Array.new(9,0.0), [2,3,3]) Retrieves an element or partition of the dataset === Parameters * <tt>index</tt> -- The desired index on the dataset === Options === Examples img[0][0] img[0][0..1]
[ "Creates", "an", "NImage", "instance", "." ]
a252ee91b4964116a72373aa5008f218fd695e57
https://github.com/brainmap/nifti/blob/a252ee91b4964116a72373aa5008f218fd695e57/lib/nifti/n_image.rb#L41-L56
4,534
brainmap/nifti
lib/nifti/n_image.rb
NIFTI.NImage.[]=
def []=(index,value) if self.shape.count != 1 or index >= self.shape[0] raise IndexError.new("You can only set values for array values") else @array_image[get_index_value(index)] = value end end
ruby
def []=(index,value) if self.shape.count != 1 or index >= self.shape[0] raise IndexError.new("You can only set values for array values") else @array_image[get_index_value(index)] = value end end
[ "def", "[]=", "(", "index", ",", "value", ")", "if", "self", ".", "shape", ".", "count", "!=", "1", "or", "index", ">=", "self", ".", "shape", "[", "0", "]", "raise", "IndexError", ".", "new", "(", "\"You can only set values for array values\"", ")", "else", "@array_image", "[", "get_index_value", "(", "index", ")", "]", "=", "value", "end", "end" ]
Set the value for an element of the dataset === Parameters * <tt>index</tt> -- The desired index on the dataset * <tt>value</tt> -- The value that the will be set === Options === Examples img[0][0] = 1.0
[ "Set", "the", "value", "for", "an", "element", "of", "the", "dataset" ]
a252ee91b4964116a72373aa5008f218fd695e57
https://github.com/brainmap/nifti/blob/a252ee91b4964116a72373aa5008f218fd695e57/lib/nifti/n_image.rb#L71-L77
4,535
thelabtech/questionnaire
app/models/qe/question_set.rb
Qe.QuestionSet.post
def post(params, answer_sheet) questions_indexed = @questions.index_by {|q| q.id} # loop over form values params ||= {} params.each do |question_id, response| next if questions_indexed[question_id.to_i].nil? # the rare case where a question was removed after the app was opened. # update each question with the posted response questions_indexed[question_id.to_i].set_response(posted_values(response), answer_sheet) end end
ruby
def post(params, answer_sheet) questions_indexed = @questions.index_by {|q| q.id} # loop over form values params ||= {} params.each do |question_id, response| next if questions_indexed[question_id.to_i].nil? # the rare case where a question was removed after the app was opened. # update each question with the posted response questions_indexed[question_id.to_i].set_response(posted_values(response), answer_sheet) end end
[ "def", "post", "(", "params", ",", "answer_sheet", ")", "questions_indexed", "=", "@questions", ".", "index_by", "{", "|", "q", "|", "q", ".", "id", "}", "# loop over form values", "params", "||=", "{", "}", "params", ".", "each", "do", "|", "question_id", ",", "response", "|", "next", "if", "questions_indexed", "[", "question_id", ".", "to_i", "]", ".", "nil?", "# the rare case where a question was removed after the app was opened.", "# update each question with the posted response", "questions_indexed", "[", "question_id", ".", "to_i", "]", ".", "set_response", "(", "posted_values", "(", "response", ")", ",", "answer_sheet", ")", "end", "end" ]
associate answers from database with a set of elements update with responses from form
[ "associate", "answers", "from", "database", "with", "a", "set", "of", "elements", "update", "with", "responses", "from", "form" ]
02eb47cbcda8cca28a5db78e18623d0957aa2c9b
https://github.com/thelabtech/questionnaire/blob/02eb47cbcda8cca28a5db78e18623d0957aa2c9b/app/models/qe/question_set.rb#L24-L34
4,536
thelabtech/questionnaire
app/models/qe/question_set.rb
Qe.QuestionSet.posted_values
def posted_values(param) if param.kind_of?(Hash) and param.has_key?('year') and param.has_key?('month') year = param['year'] month = param['month'] if month.blank? or year.blank? values = '' else values = [Date.new(year.to_i, month.to_i, 1).strftime('%m/%d/%Y')] # for mm/yy drop downs end elsif param.kind_of?(Hash) # from Hash with multiple answers per question values = param.values.map {|v| CGI.unescape(v)} elsif param.kind_of?(String) values = [CGI.unescape(param)] end # Hash may contain empty string to force post for no checkboxes # values = values.reject {|r| r == ''} end
ruby
def posted_values(param) if param.kind_of?(Hash) and param.has_key?('year') and param.has_key?('month') year = param['year'] month = param['month'] if month.blank? or year.blank? values = '' else values = [Date.new(year.to_i, month.to_i, 1).strftime('%m/%d/%Y')] # for mm/yy drop downs end elsif param.kind_of?(Hash) # from Hash with multiple answers per question values = param.values.map {|v| CGI.unescape(v)} elsif param.kind_of?(String) values = [CGI.unescape(param)] end # Hash may contain empty string to force post for no checkboxes # values = values.reject {|r| r == ''} end
[ "def", "posted_values", "(", "param", ")", "if", "param", ".", "kind_of?", "(", "Hash", ")", "and", "param", ".", "has_key?", "(", "'year'", ")", "and", "param", ".", "has_key?", "(", "'month'", ")", "year", "=", "param", "[", "'year'", "]", "month", "=", "param", "[", "'month'", "]", "if", "month", ".", "blank?", "or", "year", ".", "blank?", "values", "=", "''", "else", "values", "=", "[", "Date", ".", "new", "(", "year", ".", "to_i", ",", "month", ".", "to_i", ",", "1", ")", ".", "strftime", "(", "'%m/%d/%Y'", ")", "]", "# for mm/yy drop downs", "end", "elsif", "param", ".", "kind_of?", "(", "Hash", ")", "# from Hash with multiple answers per question", "values", "=", "param", ".", "values", ".", "map", "{", "|", "v", "|", "CGI", ".", "unescape", "(", "v", ")", "}", "elsif", "param", ".", "kind_of?", "(", "String", ")", "values", "=", "[", "CGI", ".", "unescape", "(", "param", ")", "]", "end", "# Hash may contain empty string to force post for no checkboxes", "# values = values.reject {|r| r == ''}", "end" ]
convert posted response to a question into Array of values
[ "convert", "posted", "response", "to", "a", "question", "into", "Array", "of", "values" ]
02eb47cbcda8cca28a5db78e18623d0957aa2c9b
https://github.com/thelabtech/questionnaire/blob/02eb47cbcda8cca28a5db78e18623d0957aa2c9b/app/models/qe/question_set.rb#L60-L79
4,537
sleewoo/minispec
lib/minispec/api/instance/mocks/mocks.rb
MiniSpec.InstanceAPI.mock
def mock object, method, visibility = nil, &proc if method.is_a?(Hash) proc && raise(ArgumentError, 'Both Hash and block given. Please use either one.') method.each_pair {|m,r| mock(object, m, visibility, &proc {r})} return MiniSpec::Mocks::HashedStub end visibility ||= MiniSpec::Utils.method_visibility(object, method) || :public # IMPORTANT! stub should be defined before expectation stub = stub(object, method, visibility, &proc) expect(object).to_receive(method) stub end
ruby
def mock object, method, visibility = nil, &proc if method.is_a?(Hash) proc && raise(ArgumentError, 'Both Hash and block given. Please use either one.') method.each_pair {|m,r| mock(object, m, visibility, &proc {r})} return MiniSpec::Mocks::HashedStub end visibility ||= MiniSpec::Utils.method_visibility(object, method) || :public # IMPORTANT! stub should be defined before expectation stub = stub(object, method, visibility, &proc) expect(object).to_receive(method) stub end
[ "def", "mock", "object", ",", "method", ",", "visibility", "=", "nil", ",", "&", "proc", "if", "method", ".", "is_a?", "(", "Hash", ")", "proc", "&&", "raise", "(", "ArgumentError", ",", "'Both Hash and block given. Please use either one.'", ")", "method", ".", "each_pair", "{", "|", "m", ",", "r", "|", "mock", "(", "object", ",", "m", ",", "visibility", ",", "proc", "{", "r", "}", ")", "}", "return", "MiniSpec", "::", "Mocks", "::", "HashedStub", "end", "visibility", "||=", "MiniSpec", "::", "Utils", ".", "method_visibility", "(", "object", ",", "method", ")", "||", ":public", "# IMPORTANT! stub should be defined before expectation", "stub", "=", "stub", "(", "object", ",", "method", ",", "visibility", ",", "proc", ")", "expect", "(", "object", ")", ".", "to_receive", "(", "method", ")", "stub", "end" ]
the mock is basically a stub with difference it will also add a expectation. that's it, a mock will stub a method on a object and will expect that stub to be called before test finished. the `mock` method will return the actual stub so you can build chained constraints on it. @note if mocked method exists it's visibility will be kept @example make `some_object` to respond to `:some_method` and expect `:some_method` to be called before current test finished. also make `:some_method` to behave differently depending on given arguments. so if called with [:a, :b] arguments it will return 'called with a, b'. called with [:x, :y] arguments it will return 'called with x, y'. called with any other arguments or without arguments at all it returns 'whatever'. mock(some_object, :some_method). with(:a, :b) { 'called with a, b' }. with(:x, :y) { 'called with x, y' }. with_any { 'whatever' }
[ "the", "mock", "is", "basically", "a", "stub", "with", "difference", "it", "will", "also", "add", "a", "expectation", ".", "that", "s", "it", "a", "mock", "will", "stub", "a", "method", "on", "a", "object", "and", "will", "expect", "that", "stub", "to", "be", "called", "before", "test", "finished", "." ]
6dcdacd041cc031c21f2fe70b6e5b22c6af636c5
https://github.com/sleewoo/minispec/blob/6dcdacd041cc031c21f2fe70b6e5b22c6af636c5/lib/minispec/api/instance/mocks/mocks.rb#L25-L36
4,538
sleewoo/minispec
lib/minispec/api/instance/mocks/mocks.rb
MiniSpec.InstanceAPI.proxy
def proxy object, method_name # do not proxify doubles return if object.respond_to?(:__ms__double_instance) # do not proxify stubs return if (x = @__ms__stubs__originals) && (x = x[object]) && x[method_name] proxies = (@__ms__proxies[object] ||= []) return if proxies.include?(method_name) proxies << method_name # method exists and it is a singleton. # `nil?` method can be overridden only through a singleton if method_name == :nil? || object.singleton_methods.include?(method_name) return __ms__mocks__define_singleton_proxy(object, method_name) end # method exists and it is not a singleton, define a regular proxy if visibility = MiniSpec::Utils.method_visibility(object, method_name) return __ms__mocks__define_regular_proxy(object, method_name, visibility) end raise(NoMethodError, '%s does not respond to %s. Can not proxify an un-existing method.' % [ object.inspect, method_name.inspect ]) end
ruby
def proxy object, method_name # do not proxify doubles return if object.respond_to?(:__ms__double_instance) # do not proxify stubs return if (x = @__ms__stubs__originals) && (x = x[object]) && x[method_name] proxies = (@__ms__proxies[object] ||= []) return if proxies.include?(method_name) proxies << method_name # method exists and it is a singleton. # `nil?` method can be overridden only through a singleton if method_name == :nil? || object.singleton_methods.include?(method_name) return __ms__mocks__define_singleton_proxy(object, method_name) end # method exists and it is not a singleton, define a regular proxy if visibility = MiniSpec::Utils.method_visibility(object, method_name) return __ms__mocks__define_regular_proxy(object, method_name, visibility) end raise(NoMethodError, '%s does not respond to %s. Can not proxify an un-existing method.' % [ object.inspect, method_name.inspect ]) end
[ "def", "proxy", "object", ",", "method_name", "# do not proxify doubles", "return", "if", "object", ".", "respond_to?", "(", ":__ms__double_instance", ")", "# do not proxify stubs", "return", "if", "(", "x", "=", "@__ms__stubs__originals", ")", "&&", "(", "x", "=", "x", "[", "object", "]", ")", "&&", "x", "[", "method_name", "]", "proxies", "=", "(", "@__ms__proxies", "[", "object", "]", "||=", "[", "]", ")", "return", "if", "proxies", ".", "include?", "(", "method_name", ")", "proxies", "<<", "method_name", "# method exists and it is a singleton.", "# `nil?` method can be overridden only through a singleton", "if", "method_name", "==", ":nil?", "||", "object", ".", "singleton_methods", ".", "include?", "(", "method_name", ")", "return", "__ms__mocks__define_singleton_proxy", "(", "object", ",", "method_name", ")", "end", "# method exists and it is not a singleton, define a regular proxy", "if", "visibility", "=", "MiniSpec", "::", "Utils", ".", "method_visibility", "(", "object", ",", "method_name", ")", "return", "__ms__mocks__define_regular_proxy", "(", "object", ",", "method_name", ",", "visibility", ")", "end", "raise", "(", "NoMethodError", ",", "'%s does not respond to %s. Can not proxify an un-existing method.'", "%", "[", "object", ".", "inspect", ",", "method_name", ".", "inspect", "]", ")", "end" ]
overriding given method of given object with a proxy so MiniSpec can later check whether given method was called. if given method does not exists a NoMethodError raised @note doubles and stubs will be skipped as they are already proxified @example proxy(obj, :a) assert(obj).received(:a) # checking whether obj received :a message @param object @param method_name
[ "overriding", "given", "method", "of", "given", "object", "with", "a", "proxy", "so", "MiniSpec", "can", "later", "check", "whether", "given", "method", "was", "called", "." ]
6dcdacd041cc031c21f2fe70b6e5b22c6af636c5
https://github.com/sleewoo/minispec/blob/6dcdacd041cc031c21f2fe70b6e5b22c6af636c5/lib/minispec/api/instance/mocks/mocks.rb#L87-L112
4,539
thelabtech/questionnaire
app/controllers/qe/answer_sheets_controller.rb
Qe.AnswerSheetsController.index
def index # TODO dynamically reference this # @answer_sheets = answer_sheet_type.find(:all, :order => 'created_at') @answer_sheets = AnswerSheet.find(:all, :order => 'created_at') # drop down of sheets to capture data for @question_sheets = QuestionSheet.find(:all, :order => 'label').map {|s| [s.label, s.id]} end
ruby
def index # TODO dynamically reference this # @answer_sheets = answer_sheet_type.find(:all, :order => 'created_at') @answer_sheets = AnswerSheet.find(:all, :order => 'created_at') # drop down of sheets to capture data for @question_sheets = QuestionSheet.find(:all, :order => 'label').map {|s| [s.label, s.id]} end
[ "def", "index", "# TODO dynamically reference this", "# @answer_sheets = answer_sheet_type.find(:all, :order => 'created_at')", "@answer_sheets", "=", "AnswerSheet", ".", "find", "(", ":all", ",", ":order", "=>", "'created_at'", ")", "# drop down of sheets to capture data for", "@question_sheets", "=", "QuestionSheet", ".", "find", "(", ":all", ",", ":order", "=>", "'label'", ")", ".", "map", "{", "|", "s", "|", "[", "s", ".", "label", ",", "s", ".", "id", "]", "}", "end" ]
list existing answer sheets
[ "list", "existing", "answer", "sheets" ]
02eb47cbcda8cca28a5db78e18623d0957aa2c9b
https://github.com/thelabtech/questionnaire/blob/02eb47cbcda8cca28a5db78e18623d0957aa2c9b/app/controllers/qe/answer_sheets_controller.rb#L11-L19
4,540
Telestream/telestream-cloud-ruby-sdk
qc/lib/telestream_cloud_qc/api/qc_api.rb
TelestreamCloud::Qc.QcApi.create_job
def create_job(project_id, data, opts = {}) data, _status_code, _headers = create_job_with_http_info(project_id, data, opts) return data end
ruby
def create_job(project_id, data, opts = {}) data, _status_code, _headers = create_job_with_http_info(project_id, data, opts) return data end
[ "def", "create_job", "(", "project_id", ",", "data", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "create_job_with_http_info", "(", "project_id", ",", "data", ",", "opts", ")", "return", "data", "end" ]
Create a new job @param project_id A unique identifier of a Project. @param data @param [Hash] opts the optional parameters @return [Job]
[ "Create", "a", "new", "job" ]
c232427aa3e84688ba41ec28e5bef1cc72832bf4
https://github.com/Telestream/telestream-cloud-ruby-sdk/blob/c232427aa3e84688ba41ec28e5bef1cc72832bf4/qc/lib/telestream_cloud_qc/api/qc_api.rb#L89-L92
4,541
Telestream/telestream-cloud-ruby-sdk
qc/lib/telestream_cloud_qc/api/qc_api.rb
TelestreamCloud::Qc.QcApi.get_job
def get_job(project_id, job_id, opts = {}) data, _status_code, _headers = get_job_with_http_info(project_id, job_id, opts) return data end
ruby
def get_job(project_id, job_id, opts = {}) data, _status_code, _headers = get_job_with_http_info(project_id, job_id, opts) return data end
[ "def", "get_job", "(", "project_id", ",", "job_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_job_with_http_info", "(", "project_id", ",", "job_id", ",", "opts", ")", "return", "data", "end" ]
Get QC job @param project_id A unique identifier of a Project. @param job_id A unique identifier of a Job. @param [Hash] opts the optional parameters @return [Job]
[ "Get", "QC", "job" ]
c232427aa3e84688ba41ec28e5bef1cc72832bf4
https://github.com/Telestream/telestream-cloud-ruby-sdk/blob/c232427aa3e84688ba41ec28e5bef1cc72832bf4/qc/lib/telestream_cloud_qc/api/qc_api.rb#L201-L204
4,542
Telestream/telestream-cloud-ruby-sdk
qc/lib/telestream_cloud_qc/api/qc_api.rb
TelestreamCloud::Qc.QcApi.get_project
def get_project(project_id, opts = {}) data, _status_code, _headers = get_project_with_http_info(project_id, opts) return data end
ruby
def get_project(project_id, opts = {}) data, _status_code, _headers = get_project_with_http_info(project_id, opts) return data end
[ "def", "get_project", "(", "project_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_project_with_http_info", "(", "project_id", ",", "opts", ")", "return", "data", "end" ]
Get project by Id @param project_id A unique identifier of a Project. @param [Hash] opts the optional parameters @return [Project]
[ "Get", "project", "by", "Id" ]
c232427aa3e84688ba41ec28e5bef1cc72832bf4
https://github.com/Telestream/telestream-cloud-ruby-sdk/blob/c232427aa3e84688ba41ec28e5bef1cc72832bf4/qc/lib/telestream_cloud_qc/api/qc_api.rb#L261-L264
4,543
Telestream/telestream-cloud-ruby-sdk
qc/lib/telestream_cloud_qc/api/qc_api.rb
TelestreamCloud::Qc.QcApi.list_jobs
def list_jobs(project_id, opts = {}) data, _status_code, _headers = list_jobs_with_http_info(project_id, opts) return data end
ruby
def list_jobs(project_id, opts = {}) data, _status_code, _headers = list_jobs_with_http_info(project_id, opts) return data end
[ "def", "list_jobs", "(", "project_id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "list_jobs_with_http_info", "(", "project_id", ",", "opts", ")", "return", "data", "end" ]
Get jobs form projects @param project_id A unique identifier of a Project. @param [Hash] opts the optional parameters @option opts [BOOLEAN] :expand Expand details of job @option opts [String] :status Filter jobs by status @option opts [Integer] :per_page Limit number of listed jobs (default to 30) @option opts [Integer] :page Index of jobs page to be listed @return [JobsCollection]
[ "Get", "jobs", "form", "projects" ]
c232427aa3e84688ba41ec28e5bef1cc72832bf4
https://github.com/Telestream/telestream-cloud-ruby-sdk/blob/c232427aa3e84688ba41ec28e5bef1cc72832bf4/qc/lib/telestream_cloud_qc/api/qc_api.rb#L320-L323
4,544
mlomnicki/automatic_foreign_key
lib/automatic_foreign_key/active_record/connection_adapters/table_definition.rb
AutomaticForeignKey::ActiveRecord::ConnectionAdapters.TableDefinition.belongs_to
def belongs_to(table, options = {}) options = options.merge(:references => table) options[:on_delete] = options.delete(:dependent) if options.has_key?(:dependent) column("#{table.to_s.singularize}_id".to_sym, :integer, options) end
ruby
def belongs_to(table, options = {}) options = options.merge(:references => table) options[:on_delete] = options.delete(:dependent) if options.has_key?(:dependent) column("#{table.to_s.singularize}_id".to_sym, :integer, options) end
[ "def", "belongs_to", "(", "table", ",", "options", "=", "{", "}", ")", "options", "=", "options", ".", "merge", "(", ":references", "=>", "table", ")", "options", "[", ":on_delete", "]", "=", "options", ".", "delete", "(", ":dependent", ")", "if", "options", ".", "has_key?", "(", ":dependent", ")", "column", "(", "\"#{table.to_s.singularize}_id\"", ".", "to_sym", ",", ":integer", ",", "options", ")", "end" ]
Some people liked this; personally I've decided against using it but I'll keep it nonetheless
[ "Some", "people", "liked", "this", ";", "personally", "I", "ve", "decided", "against", "using", "it", "but", "I", "ll", "keep", "it", "nonetheless" ]
c87676f8ebca0a1326c5b5c48ae166fdefd3fd2a
https://github.com/mlomnicki/automatic_foreign_key/blob/c87676f8ebca0a1326c5b5c48ae166fdefd3fd2a/lib/automatic_foreign_key/active_record/connection_adapters/table_definition.rb#L40-L44
4,545
codefoundry/svn
lib/svn/streams.rb
Svn.Stream.read_all
def read_all content = String.new while bytes = read and !bytes.empty? content << bytes end content end
ruby
def read_all content = String.new while bytes = read and !bytes.empty? content << bytes end content end
[ "def", "read_all", "content", "=", "String", ".", "new", "while", "bytes", "=", "read", "and", "!", "bytes", ".", "empty?", "content", "<<", "bytes", "end", "content", "end" ]
reads the stream contents into a String object
[ "reads", "the", "stream", "contents", "into", "a", "String", "object" ]
930a8da65fbecf3ffed50655e1cb10fcbc484be4
https://github.com/codefoundry/svn/blob/930a8da65fbecf3ffed50655e1cb10fcbc484be4/lib/svn/streams.rb#L118-L124
4,546
codefoundry/svn
lib/svn/streams.rb
Svn.Stream.to_string_io
def to_string_io content = StringIO.new while bytes = read and !bytes.empty? content.write( bytes ) end content.rewind content end
ruby
def to_string_io content = StringIO.new while bytes = read and !bytes.empty? content.write( bytes ) end content.rewind content end
[ "def", "to_string_io", "content", "=", "StringIO", ".", "new", "while", "bytes", "=", "read", "and", "!", "bytes", ".", "empty?", "content", ".", "write", "(", "bytes", ")", "end", "content", ".", "rewind", "content", "end" ]
reads the stream contents into a StringIO object
[ "reads", "the", "stream", "contents", "into", "a", "StringIO", "object" ]
930a8da65fbecf3ffed50655e1cb10fcbc484be4
https://github.com/codefoundry/svn/blob/930a8da65fbecf3ffed50655e1cb10fcbc484be4/lib/svn/streams.rb#L138-L145
4,547
brainmap/nifti
lib/nifti/stream.rb
NIFTI.Stream.decode
def decode(length, type) # Check if values are valid: if (@index + length) > @string.length # The index number is bigger then the length of the binary string. # We have reached the end and will return nil. value = nil else if type == "AT" value = decode_tag else # Decode the binary string and return value: value = @string.slice(@index, length).unpack(vr_to_str(type)) # If the result is an array of one element, return the element instead of the array. # If result is contained in a multi-element array, the original array is returned. if value.length == 1 value = value[0] # If value is a string, strip away possible trailing whitespace: # Do this using gsub instead of ruby-core #strip to keep trailing carriage # returns, etc., because that is valid whitespace that we want to have included # (i.e. in extended header data, AFNI writes a \n at the end of it's xml info, # and that must be kept in order to not change the file on writing back out). value.gsub!(/\000*$/, "") if value.respond_to? :gsub! end # Update our position in the string: skip(length) end end return value end
ruby
def decode(length, type) # Check if values are valid: if (@index + length) > @string.length # The index number is bigger then the length of the binary string. # We have reached the end and will return nil. value = nil else if type == "AT" value = decode_tag else # Decode the binary string and return value: value = @string.slice(@index, length).unpack(vr_to_str(type)) # If the result is an array of one element, return the element instead of the array. # If result is contained in a multi-element array, the original array is returned. if value.length == 1 value = value[0] # If value is a string, strip away possible trailing whitespace: # Do this using gsub instead of ruby-core #strip to keep trailing carriage # returns, etc., because that is valid whitespace that we want to have included # (i.e. in extended header data, AFNI writes a \n at the end of it's xml info, # and that must be kept in order to not change the file on writing back out). value.gsub!(/\000*$/, "") if value.respond_to? :gsub! end # Update our position in the string: skip(length) end end return value end
[ "def", "decode", "(", "length", ",", "type", ")", "# Check if values are valid:", "if", "(", "@index", "+", "length", ")", ">", "@string", ".", "length", "# The index number is bigger then the length of the binary string.", "# We have reached the end and will return nil.", "value", "=", "nil", "else", "if", "type", "==", "\"AT\"", "value", "=", "decode_tag", "else", "# Decode the binary string and return value:", "value", "=", "@string", ".", "slice", "(", "@index", ",", "length", ")", ".", "unpack", "(", "vr_to_str", "(", "type", ")", ")", "# If the result is an array of one element, return the element instead of the array.", "# If result is contained in a multi-element array, the original array is returned.", "if", "value", ".", "length", "==", "1", "value", "=", "value", "[", "0", "]", "# If value is a string, strip away possible trailing whitespace:", "# Do this using gsub instead of ruby-core #strip to keep trailing carriage", "# returns, etc., because that is valid whitespace that we want to have included", "# (i.e. in extended header data, AFNI writes a \\n at the end of it's xml info, ", "# and that must be kept in order to not change the file on writing back out).", "value", ".", "gsub!", "(", "/", "\\000", "/", ",", "\"\"", ")", "if", "value", ".", "respond_to?", ":gsub!", "end", "# Update our position in the string:", "skip", "(", "length", ")", "end", "end", "return", "value", "end" ]
Creates a Stream instance. === Parameters * <tt>binary</tt> -- A binary string. * <tt>string_endian</tt> -- Boolean. The endianness of the instance string (true for big endian, false for small endian). * <tt>options</tt> -- A hash of parameters. === Options * <tt>:index</tt> -- Fixnum. A position (offset) in the instance string where reading will start. Decodes a section of the instance string and returns the formatted data. The instance index is offset in accordance with the length read. === Notes * If multiple numbers are decoded, these are returned in an array. === Parameters * <tt>length</tt> -- Fixnum. The string length which will be decoded. * <tt>type</tt> -- String. The type (vr) of data to decode.
[ "Creates", "a", "Stream", "instance", "." ]
a252ee91b4964116a72373aa5008f218fd695e57
https://github.com/brainmap/nifti/blob/a252ee91b4964116a72373aa5008f218fd695e57/lib/nifti/stream.rb#L53-L81
4,548
brainmap/nifti
lib/nifti/stream.rb
NIFTI.Stream.encode
def encode(value, type) value = [value] unless value.is_a?(Array) return value.pack(vr_to_str(type)) end
ruby
def encode(value, type) value = [value] unless value.is_a?(Array) return value.pack(vr_to_str(type)) end
[ "def", "encode", "(", "value", ",", "type", ")", "value", "=", "[", "value", "]", "unless", "value", ".", "is_a?", "(", "Array", ")", "return", "value", ".", "pack", "(", "vr_to_str", "(", "type", ")", ")", "end" ]
Encodes a value and returns the resulting binary string. === Parameters * <tt>value</tt> -- A custom value (String, Fixnum, etc..) or an array of numbers. * <tt>type</tt> -- String. The type (vr) of data to encode.
[ "Encodes", "a", "value", "and", "returns", "the", "resulting", "binary", "string", "." ]
a252ee91b4964116a72373aa5008f218fd695e57
https://github.com/brainmap/nifti/blob/a252ee91b4964116a72373aa5008f218fd695e57/lib/nifti/stream.rb#L200-L203
4,549
pjotrp/bioruby-table
lib/bio-table/table_apply.rb
BioTable.TableApply.parse_row
def parse_row(line_num, line, header, column_idx, prev_fields, options) fields = LineParser::parse(line, options[:in_format], options[:split_on]) return nil,nil if fields.compact == [] if options[:pad_fields] and fields.size < header.size fields += [''] * (header.size - fields.size) end fields = Formatter::strip_quotes(fields) if @strip_quotes fields = Formatter::transform_row_ids(@transform_ids, fields) if @transform_ids fields = Filter::apply_column_filter(fields,column_idx) return nil,nil if fields.compact == [] rowname = fields[0] data_fields = fields[@first_column..-1] if data_fields.size > 0 return nil,nil if not Validator::valid_row?(line_num, data_fields, prev_fields) return nil,nil if not Filter::numeric(@num_filter,data_fields,header) return nil,nil if not Filter::generic(@filter,data_fields,header) (rowname, data_fields) = Rewrite::rewrite(@rewrite,rowname,data_fields) end return rowname, data_fields end
ruby
def parse_row(line_num, line, header, column_idx, prev_fields, options) fields = LineParser::parse(line, options[:in_format], options[:split_on]) return nil,nil if fields.compact == [] if options[:pad_fields] and fields.size < header.size fields += [''] * (header.size - fields.size) end fields = Formatter::strip_quotes(fields) if @strip_quotes fields = Formatter::transform_row_ids(@transform_ids, fields) if @transform_ids fields = Filter::apply_column_filter(fields,column_idx) return nil,nil if fields.compact == [] rowname = fields[0] data_fields = fields[@first_column..-1] if data_fields.size > 0 return nil,nil if not Validator::valid_row?(line_num, data_fields, prev_fields) return nil,nil if not Filter::numeric(@num_filter,data_fields,header) return nil,nil if not Filter::generic(@filter,data_fields,header) (rowname, data_fields) = Rewrite::rewrite(@rewrite,rowname,data_fields) end return rowname, data_fields end
[ "def", "parse_row", "(", "line_num", ",", "line", ",", "header", ",", "column_idx", ",", "prev_fields", ",", "options", ")", "fields", "=", "LineParser", "::", "parse", "(", "line", ",", "options", "[", ":in_format", "]", ",", "options", "[", ":split_on", "]", ")", "return", "nil", ",", "nil", "if", "fields", ".", "compact", "==", "[", "]", "if", "options", "[", ":pad_fields", "]", "and", "fields", ".", "size", "<", "header", ".", "size", "fields", "+=", "[", "''", "]", "*", "(", "header", ".", "size", "-", "fields", ".", "size", ")", "end", "fields", "=", "Formatter", "::", "strip_quotes", "(", "fields", ")", "if", "@strip_quotes", "fields", "=", "Formatter", "::", "transform_row_ids", "(", "@transform_ids", ",", "fields", ")", "if", "@transform_ids", "fields", "=", "Filter", "::", "apply_column_filter", "(", "fields", ",", "column_idx", ")", "return", "nil", ",", "nil", "if", "fields", ".", "compact", "==", "[", "]", "rowname", "=", "fields", "[", "0", "]", "data_fields", "=", "fields", "[", "@first_column", "..", "-", "1", "]", "if", "data_fields", ".", "size", ">", "0", "return", "nil", ",", "nil", "if", "not", "Validator", "::", "valid_row?", "(", "line_num", ",", "data_fields", ",", "prev_fields", ")", "return", "nil", ",", "nil", "if", "not", "Filter", "::", "numeric", "(", "@num_filter", ",", "data_fields", ",", "header", ")", "return", "nil", ",", "nil", "if", "not", "Filter", "::", "generic", "(", "@filter", ",", "data_fields", ",", "header", ")", "(", "rowname", ",", "data_fields", ")", "=", "Rewrite", "::", "rewrite", "(", "@rewrite", ",", "rowname", ",", "data_fields", ")", "end", "return", "rowname", ",", "data_fields", "end" ]
Take a line as a string and return it as a tuple of rowname and datafields
[ "Take", "a", "line", "as", "a", "string", "and", "return", "it", "as", "a", "tuple", "of", "rowname", "and", "datafields" ]
e7cc97bb598743e7d69e63f16f76a2ce0ed9006d
https://github.com/pjotrp/bioruby-table/blob/e7cc97bb598743e7d69e63f16f76a2ce0ed9006d/lib/bio-table/table_apply.rb#L55-L74
4,550
flydata/elastic-mapreduce
lib/json/lexer.rb
JSON.Lexer.nextclean
def nextclean while true c = self.nextchar() if (c == '/') case self.nextchar() when '/' c = self.nextchar() while c != "\n" && c != "\r" && c != "\0" c = self.nextchar() end when '*' while true c = self.nextchar() raise "unclosed comment" if (c == "\0") if (c == '*') break if (self.nextchar() == '/') self.back() end end else self.back() return '/'; end elsif c == "\0" || c[0] > " "[0] return(c) end end end
ruby
def nextclean while true c = self.nextchar() if (c == '/') case self.nextchar() when '/' c = self.nextchar() while c != "\n" && c != "\r" && c != "\0" c = self.nextchar() end when '*' while true c = self.nextchar() raise "unclosed comment" if (c == "\0") if (c == '*') break if (self.nextchar() == '/') self.back() end end else self.back() return '/'; end elsif c == "\0" || c[0] > " "[0] return(c) end end end
[ "def", "nextclean", "while", "true", "c", "=", "self", ".", "nextchar", "(", ")", "if", "(", "c", "==", "'/'", ")", "case", "self", ".", "nextchar", "(", ")", "when", "'/'", "c", "=", "self", ".", "nextchar", "(", ")", "while", "c", "!=", "\"\\n\"", "&&", "c", "!=", "\"\\r\"", "&&", "c", "!=", "\"\\0\"", "c", "=", "self", ".", "nextchar", "(", ")", "end", "when", "'*'", "while", "true", "c", "=", "self", ".", "nextchar", "(", ")", "raise", "\"unclosed comment\"", "if", "(", "c", "==", "\"\\0\"", ")", "if", "(", "c", "==", "'*'", ")", "break", "if", "(", "self", ".", "nextchar", "(", ")", "==", "'/'", ")", "self", ".", "back", "(", ")", "end", "end", "else", "self", ".", "back", "(", ")", "return", "'/'", ";", "end", "elsif", "c", "==", "\"\\0\"", "||", "c", "[", "0", "]", ">", "\" \"", "[", "0", "]", "return", "(", "c", ")", "end", "end", "end" ]
Read the next n characters from the string with escape sequence processing.
[ "Read", "the", "next", "n", "characters", "from", "the", "string", "with", "escape", "sequence", "processing", "." ]
fc96593d27c7e4797aef67ff4f8c76ee35609d57
https://github.com/flydata/elastic-mapreduce/blob/fc96593d27c7e4797aef67ff4f8c76ee35609d57/lib/json/lexer.rb#L78-L105
4,551
flydata/elastic-mapreduce
lib/json/lexer.rb
JSON.Lexer.utf8str
def utf8str(code) if (code & ~(0x7f)) == 0 # UCS-4 range 0x00000000 - 0x0000007F return(code.chr) end buf = "" if (code & ~(0x7ff)) == 0 # UCS-4 range 0x00000080 - 0x000007FF buf << (0b11000000 | (code >> 6)).chr buf << (0b10000000 | (code & 0b00111111)).chr return(buf) end if (code & ~(0x000ffff)) == 0 # UCS-4 range 0x00000800 - 0x0000FFFF buf << (0b11100000 | (code >> 12)).chr buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr buf << (0b10000000 | (code & 0b0011111)).chr return(buf) end # Not used -- JSON only has UCS-2, but for the sake # of completeness if (code & ~(0x1FFFFF)) == 0 # UCS-4 range 0x00010000 - 0x001FFFFF buf << (0b11110000 | (code >> 18)).chr buf << (0b10000000 | ((code >> 12) & 0b00111111)).chr buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr buf << (0b10000000 | (code & 0b0011111)).chr return(buf) end if (code & ~(0x03FFFFFF)) == 0 # UCS-4 range 0x00200000 - 0x03FFFFFF buf << (0b11110000 | (code >> 24)).chr buf << (0b10000000 | ((code >> 18) & 0b00111111)).chr buf << (0b10000000 | ((code >> 12) & 0b00111111)).chr buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr buf << (0b10000000 | (code & 0b0011111)).chr return(buf) end # UCS-4 range 0x04000000 - 0x7FFFFFFF buf << (0b11111000 | (code >> 30)).chr buf << (0b10000000 | ((code >> 24) & 0b00111111)).chr buf << (0b10000000 | ((code >> 18) & 0b00111111)).chr buf << (0b10000000 | ((code >> 12) & 0b00111111)).chr buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr buf << (0b10000000 | (code & 0b0011111)).chr return(buf) end
ruby
def utf8str(code) if (code & ~(0x7f)) == 0 # UCS-4 range 0x00000000 - 0x0000007F return(code.chr) end buf = "" if (code & ~(0x7ff)) == 0 # UCS-4 range 0x00000080 - 0x000007FF buf << (0b11000000 | (code >> 6)).chr buf << (0b10000000 | (code & 0b00111111)).chr return(buf) end if (code & ~(0x000ffff)) == 0 # UCS-4 range 0x00000800 - 0x0000FFFF buf << (0b11100000 | (code >> 12)).chr buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr buf << (0b10000000 | (code & 0b0011111)).chr return(buf) end # Not used -- JSON only has UCS-2, but for the sake # of completeness if (code & ~(0x1FFFFF)) == 0 # UCS-4 range 0x00010000 - 0x001FFFFF buf << (0b11110000 | (code >> 18)).chr buf << (0b10000000 | ((code >> 12) & 0b00111111)).chr buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr buf << (0b10000000 | (code & 0b0011111)).chr return(buf) end if (code & ~(0x03FFFFFF)) == 0 # UCS-4 range 0x00200000 - 0x03FFFFFF buf << (0b11110000 | (code >> 24)).chr buf << (0b10000000 | ((code >> 18) & 0b00111111)).chr buf << (0b10000000 | ((code >> 12) & 0b00111111)).chr buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr buf << (0b10000000 | (code & 0b0011111)).chr return(buf) end # UCS-4 range 0x04000000 - 0x7FFFFFFF buf << (0b11111000 | (code >> 30)).chr buf << (0b10000000 | ((code >> 24) & 0b00111111)).chr buf << (0b10000000 | ((code >> 18) & 0b00111111)).chr buf << (0b10000000 | ((code >> 12) & 0b00111111)).chr buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr buf << (0b10000000 | (code & 0b0011111)).chr return(buf) end
[ "def", "utf8str", "(", "code", ")", "if", "(", "code", "&", "~", "(", "0x7f", ")", ")", "==", "0", "# UCS-4 range 0x00000000 - 0x0000007F", "return", "(", "code", ".", "chr", ")", "end", "buf", "=", "\"\"", "if", "(", "code", "&", "~", "(", "0x7ff", ")", ")", "==", "0", "# UCS-4 range 0x00000080 - 0x000007FF", "buf", "<<", "(", "0b11000000", "|", "(", "code", ">>", "6", ")", ")", ".", "chr", "buf", "<<", "(", "0b10000000", "|", "(", "code", "&", "0b00111111", ")", ")", ".", "chr", "return", "(", "buf", ")", "end", "if", "(", "code", "&", "~", "(", "0x000ffff", ")", ")", "==", "0", "# UCS-4 range 0x00000800 - 0x0000FFFF", "buf", "<<", "(", "0b11100000", "|", "(", "code", ">>", "12", ")", ")", ".", "chr", "buf", "<<", "(", "0b10000000", "|", "(", "(", "code", ">>", "6", ")", "&", "0b00111111", ")", ")", ".", "chr", "buf", "<<", "(", "0b10000000", "|", "(", "code", "&", "0b0011111", ")", ")", ".", "chr", "return", "(", "buf", ")", "end", "# Not used -- JSON only has UCS-2, but for the sake", "# of completeness", "if", "(", "code", "&", "~", "(", "0x1FFFFF", ")", ")", "==", "0", "# UCS-4 range 0x00010000 - 0x001FFFFF", "buf", "<<", "(", "0b11110000", "|", "(", "code", ">>", "18", ")", ")", ".", "chr", "buf", "<<", "(", "0b10000000", "|", "(", "(", "code", ">>", "12", ")", "&", "0b00111111", ")", ")", ".", "chr", "buf", "<<", "(", "0b10000000", "|", "(", "(", "code", ">>", "6", ")", "&", "0b00111111", ")", ")", ".", "chr", "buf", "<<", "(", "0b10000000", "|", "(", "code", "&", "0b0011111", ")", ")", ".", "chr", "return", "(", "buf", ")", "end", "if", "(", "code", "&", "~", "(", "0x03FFFFFF", ")", ")", "==", "0", "# UCS-4 range 0x00200000 - 0x03FFFFFF", "buf", "<<", "(", "0b11110000", "|", "(", "code", ">>", "24", ")", ")", ".", "chr", "buf", "<<", "(", "0b10000000", "|", "(", "(", "code", ">>", "18", ")", "&", "0b00111111", ")", ")", ".", "chr", "buf", "<<", "(", "0b10000000", "|", "(", "(", "code", ">>", "12", ")", "&", "0b00111111", ")", ")", ".", "chr", "buf", "<<", "(", "0b10000000", "|", "(", "(", "code", ">>", "6", ")", "&", "0b00111111", ")", ")", ".", "chr", "buf", "<<", "(", "0b10000000", "|", "(", "code", "&", "0b0011111", ")", ")", ".", "chr", "return", "(", "buf", ")", "end", "# UCS-4 range 0x04000000 - 0x7FFFFFFF", "buf", "<<", "(", "0b11111000", "|", "(", "code", ">>", "30", ")", ")", ".", "chr", "buf", "<<", "(", "0b10000000", "|", "(", "(", "code", ">>", "24", ")", "&", "0b00111111", ")", ")", ".", "chr", "buf", "<<", "(", "0b10000000", "|", "(", "(", "code", ">>", "18", ")", "&", "0b00111111", ")", ")", ".", "chr", "buf", "<<", "(", "0b10000000", "|", "(", "(", "code", ">>", "12", ")", "&", "0b00111111", ")", ")", ".", "chr", "buf", "<<", "(", "0b10000000", "|", "(", "(", "code", ">>", "6", ")", "&", "0b00111111", ")", ")", ".", "chr", "buf", "<<", "(", "0b10000000", "|", "(", "code", "&", "0b0011111", ")", ")", ".", "chr", "return", "(", "buf", ")", "end" ]
Given a Unicode code point, return a string giving its UTF-8 representation based on RFC 2279.
[ "Given", "a", "Unicode", "code", "point", "return", "a", "string", "giving", "its", "UTF", "-", "8", "representation", "based", "on", "RFC", "2279", "." ]
fc96593d27c7e4797aef67ff4f8c76ee35609d57
https://github.com/flydata/elastic-mapreduce/blob/fc96593d27c7e4797aef67ff4f8c76ee35609d57/lib/json/lexer.rb#L109-L160
4,552
flydata/elastic-mapreduce
lib/json/lexer.rb
JSON.Lexer.nextto
def nextto(regex) buf = "" while (true) c = self.nextchar() if !(regex =~ c).nil? || c == '\0' || c == '\n' || c == '\r' self.back() if (c != '\0') return(buf.chomp()) end buf += c end end
ruby
def nextto(regex) buf = "" while (true) c = self.nextchar() if !(regex =~ c).nil? || c == '\0' || c == '\n' || c == '\r' self.back() if (c != '\0') return(buf.chomp()) end buf += c end end
[ "def", "nextto", "(", "regex", ")", "buf", "=", "\"\"", "while", "(", "true", ")", "c", "=", "self", ".", "nextchar", "(", ")", "if", "!", "(", "regex", "=~", "c", ")", ".", "nil?", "||", "c", "==", "'\\0'", "||", "c", "==", "'\\n'", "||", "c", "==", "'\\r'", "self", ".", "back", "(", ")", "if", "(", "c", "!=", "'\\0'", ")", "return", "(", "buf", ".", "chomp", "(", ")", ")", "end", "buf", "+=", "c", "end", "end" ]
Reads the next group of characters that match a regular expresion.
[ "Reads", "the", "next", "group", "of", "characters", "that", "match", "a", "regular", "expresion", "." ]
fc96593d27c7e4797aef67ff4f8c76ee35609d57
https://github.com/flydata/elastic-mapreduce/blob/fc96593d27c7e4797aef67ff4f8c76ee35609d57/lib/json/lexer.rb#L200-L210
4,553
flydata/elastic-mapreduce
lib/json/lexer.rb
JSON.Lexer.nextvalue
def nextvalue c = self.nextclean s = "" case c when /\"|\'/ return(self.nextstring(c)) when '{' self.back() return(Hash.new.from_json(self)) when '[' self.back() return(Array.new.from_json(self)) else buf = "" while ((c =~ /"| |:|,|\]|\}|\/|\0/).nil?) buf += c c = self.nextchar() end self.back() s = buf.chomp case s when "true" return(true) when "false" return(false) when "null" return(nil) when /^[0-9]|\.|-|\+/ if s =~ /[.]/ then return Float(s) else return Integer(s) end end if (s == "") s = nil end return(s) end end
ruby
def nextvalue c = self.nextclean s = "" case c when /\"|\'/ return(self.nextstring(c)) when '{' self.back() return(Hash.new.from_json(self)) when '[' self.back() return(Array.new.from_json(self)) else buf = "" while ((c =~ /"| |:|,|\]|\}|\/|\0/).nil?) buf += c c = self.nextchar() end self.back() s = buf.chomp case s when "true" return(true) when "false" return(false) when "null" return(nil) when /^[0-9]|\.|-|\+/ if s =~ /[.]/ then return Float(s) else return Integer(s) end end if (s == "") s = nil end return(s) end end
[ "def", "nextvalue", "c", "=", "self", ".", "nextclean", "s", "=", "\"\"", "case", "c", "when", "/", "\\\"", "\\'", "/", "return", "(", "self", ".", "nextstring", "(", "c", ")", ")", "when", "'{'", "self", ".", "back", "(", ")", "return", "(", "Hash", ".", "new", ".", "from_json", "(", "self", ")", ")", "when", "'['", "self", ".", "back", "(", ")", "return", "(", "Array", ".", "new", ".", "from_json", "(", "self", ")", ")", "else", "buf", "=", "\"\"", "while", "(", "(", "c", "=~", "/", "\\]", "\\}", "\\/", "\\0", "/", ")", ".", "nil?", ")", "buf", "+=", "c", "c", "=", "self", ".", "nextchar", "(", ")", "end", "self", ".", "back", "(", ")", "s", "=", "buf", ".", "chomp", "case", "s", "when", "\"true\"", "return", "(", "true", ")", "when", "\"false\"", "return", "(", "false", ")", "when", "\"null\"", "return", "(", "nil", ")", "when", "/", "\\.", "\\+", "/", "if", "s", "=~", "/", "/", "then", "return", "Float", "(", "s", ")", "else", "return", "Integer", "(", "s", ")", "end", "end", "if", "(", "s", "==", "\"\"", ")", "s", "=", "nil", "end", "return", "(", "s", ")", "end", "end" ]
Reads the next value from the string. This can return either a string, a FixNum, a floating point value, a JSON array, or a JSON object.
[ "Reads", "the", "next", "value", "from", "the", "string", ".", "This", "can", "return", "either", "a", "string", "a", "FixNum", "a", "floating", "point", "value", "a", "JSON", "array", "or", "a", "JSON", "object", "." ]
fc96593d27c7e4797aef67ff4f8c76ee35609d57
https://github.com/flydata/elastic-mapreduce/blob/fc96593d27c7e4797aef67ff4f8c76ee35609d57/lib/json/lexer.rb#L215-L255
4,554
rossmeissl/bombshell
lib/bombshell/completor.rb
Bombshell.Completor.complete
def complete(fragment) self.class.filter(shell.instance_methods).grep Regexp.new(Regexp.quote(fragment)) end
ruby
def complete(fragment) self.class.filter(shell.instance_methods).grep Regexp.new(Regexp.quote(fragment)) end
[ "def", "complete", "(", "fragment", ")", "self", ".", "class", ".", "filter", "(", "shell", ".", "instance_methods", ")", ".", "grep", "Regexp", ".", "new", "(", "Regexp", ".", "quote", "(", "fragment", ")", ")", "end" ]
Provide completion for a given fragment. @param [String] fragment the fragment to complete for
[ "Provide", "completion", "for", "a", "given", "fragment", "." ]
542c855eb741095b1e88cc1bbfa1c1bacfcd9ebd
https://github.com/rossmeissl/bombshell/blob/542c855eb741095b1e88cc1bbfa1c1bacfcd9ebd/lib/bombshell/completor.rb#L13-L15
4,555
puppetlabs/beaker-openstack
lib/beaker/hypervisor/openstack.rb
Beaker.Openstack.flavor
def flavor f @logger.debug "OpenStack: Looking up flavor '#{f}'" @compute_client.flavors.find { |x| x.name == f } || raise("Couldn't find flavor: #{f}") end
ruby
def flavor f @logger.debug "OpenStack: Looking up flavor '#{f}'" @compute_client.flavors.find { |x| x.name == f } || raise("Couldn't find flavor: #{f}") end
[ "def", "flavor", "f", "@logger", ".", "debug", "\"OpenStack: Looking up flavor '#{f}'\"", "@compute_client", ".", "flavors", ".", "find", "{", "|", "x", "|", "x", ".", "name", "==", "f", "}", "||", "raise", "(", "\"Couldn't find flavor: #{f}\"", ")", "end" ]
Create a new instance of the OpenStack hypervisor object @param [<Host>] openstack_hosts The array of OpenStack hosts to provision @param [Hash{Symbol=>String}] options The options hash containing configuration values @option options [String] :openstack_api_key The key to access the OpenStack instance with (required) @option options [String] :openstack_username The username to access the OpenStack instance with (required) @option options [String] :openstack_auth_url The URL to access the OpenStack instance with (required) @option options [String] :openstack_tenant The tenant to access the OpenStack instance with (required) @option options [String] :openstack_region The region that each OpenStack instance should be provisioned on (optional) @option options [String] :openstack_network The network that each OpenStack instance should be contacted through (required) @option options [String] :openstack_keyname The name of an existing key pair that should be auto-loaded onto each @option options [Hash] :security_group An array of security groups to associate with the instance OpenStack instance (optional) @option options [String] :jenkins_build_url Added as metadata to each OpenStack instance @option options [String] :department Added as metadata to each OpenStack instance @option options [String] :project Added as metadata to each OpenStack instance @option options [Integer] :timeout The amount of time to attempt execution before quiting and exiting with failure Provided a flavor name return the OpenStack id for that flavor @param [String] f The flavor name @return [String] Openstack id for provided flavor name
[ "Create", "a", "new", "instance", "of", "the", "OpenStack", "hypervisor", "object" ]
129227e23f3fbc412d5b9f6e46ced3b059af9e19
https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L76-L79
4,556
puppetlabs/beaker-openstack
lib/beaker/hypervisor/openstack.rb
Beaker.Openstack.image
def image i @logger.debug "OpenStack: Looking up image '#{i}'" @compute_client.images.find { |x| x.name == i } || raise("Couldn't find image: #{i}") end
ruby
def image i @logger.debug "OpenStack: Looking up image '#{i}'" @compute_client.images.find { |x| x.name == i } || raise("Couldn't find image: #{i}") end
[ "def", "image", "i", "@logger", ".", "debug", "\"OpenStack: Looking up image '#{i}'\"", "@compute_client", ".", "images", ".", "find", "{", "|", "x", "|", "x", ".", "name", "==", "i", "}", "||", "raise", "(", "\"Couldn't find image: #{i}\"", ")", "end" ]
Provided an image name return the OpenStack id for that image @param [String] i The image name @return [String] Openstack id for provided image name
[ "Provided", "an", "image", "name", "return", "the", "OpenStack", "id", "for", "that", "image" ]
129227e23f3fbc412d5b9f6e46ced3b059af9e19
https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L84-L87
4,557
puppetlabs/beaker-openstack
lib/beaker/hypervisor/openstack.rb
Beaker.Openstack.network
def network n @logger.debug "OpenStack: Looking up network '#{n}'" @network_client.networks.find { |x| x.name == n } || raise("Couldn't find network: #{n}") end
ruby
def network n @logger.debug "OpenStack: Looking up network '#{n}'" @network_client.networks.find { |x| x.name == n } || raise("Couldn't find network: #{n}") end
[ "def", "network", "n", "@logger", ".", "debug", "\"OpenStack: Looking up network '#{n}'\"", "@network_client", ".", "networks", ".", "find", "{", "|", "x", "|", "x", ".", "name", "==", "n", "}", "||", "raise", "(", "\"Couldn't find network: #{n}\"", ")", "end" ]
Provided a network name return the OpenStack id for that network @param [String] n The network name @return [String] Openstack id for provided network name
[ "Provided", "a", "network", "name", "return", "the", "OpenStack", "id", "for", "that", "network" ]
129227e23f3fbc412d5b9f6e46ced3b059af9e19
https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L92-L95
4,558
puppetlabs/beaker-openstack
lib/beaker/hypervisor/openstack.rb
Beaker.Openstack.security_groups
def security_groups sgs for sg in sgs @logger.debug "Openstack: Looking up security group '#{sg}'" @compute_client.security_groups.find { |x| x.name == sg } || raise("Couldn't find security group: #{sg}") sgs end end
ruby
def security_groups sgs for sg in sgs @logger.debug "Openstack: Looking up security group '#{sg}'" @compute_client.security_groups.find { |x| x.name == sg } || raise("Couldn't find security group: #{sg}") sgs end end
[ "def", "security_groups", "sgs", "for", "sg", "in", "sgs", "@logger", ".", "debug", "\"Openstack: Looking up security group '#{sg}'\"", "@compute_client", ".", "security_groups", ".", "find", "{", "|", "x", "|", "x", ".", "name", "==", "sg", "}", "||", "raise", "(", "\"Couldn't find security group: #{sg}\"", ")", "sgs", "end", "end" ]
Provided an array of security groups return that array if all security groups are present @param [Array] sgs The array of security group names @return [Array] The array of security group names
[ "Provided", "an", "array", "of", "security", "groups", "return", "that", "array", "if", "all", "security", "groups", "are", "present" ]
129227e23f3fbc412d5b9f6e46ced3b059af9e19
https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L101-L107
4,559
puppetlabs/beaker-openstack
lib/beaker/hypervisor/openstack.rb
Beaker.Openstack.provision_storage
def provision_storage host, vm volumes = get_volumes(host) if !volumes.empty? # Lazily create the volume client if needed volume_client_create volumes.keys.each_with_index do |volume, index| @logger.debug "Creating volume #{volume} for OpenStack host #{host.name}" # The node defintion file defines volume sizes in MB (due to precedent # with the vagrant virtualbox implementation) however OpenStack requires # this translating into GB openstack_size = volumes[volume]['size'].to_i / 1000 # Set up the volume creation arguments args = { :size => openstack_size, :description => "Beaker volume: host=#{host.name} volume=#{volume}", } # Between version 1 and subsequent versions the API was updated to # rename 'display_name' to just 'name' for better consistency if get_volume_api_version == 1 args[:display_name] = volume else args[:name] = volume end # Create the volume and wait for it to become available vol = @volume_client.volumes.create(**args) vol.wait_for { ready? } # Fog needs a device name to attach as, so invent one. The guest # doesn't pay any attention to this device = "/dev/vd#{('b'.ord + index).chr}" vm.attach_volume(vol.id, device) end end end
ruby
def provision_storage host, vm volumes = get_volumes(host) if !volumes.empty? # Lazily create the volume client if needed volume_client_create volumes.keys.each_with_index do |volume, index| @logger.debug "Creating volume #{volume} for OpenStack host #{host.name}" # The node defintion file defines volume sizes in MB (due to precedent # with the vagrant virtualbox implementation) however OpenStack requires # this translating into GB openstack_size = volumes[volume]['size'].to_i / 1000 # Set up the volume creation arguments args = { :size => openstack_size, :description => "Beaker volume: host=#{host.name} volume=#{volume}", } # Between version 1 and subsequent versions the API was updated to # rename 'display_name' to just 'name' for better consistency if get_volume_api_version == 1 args[:display_name] = volume else args[:name] = volume end # Create the volume and wait for it to become available vol = @volume_client.volumes.create(**args) vol.wait_for { ready? } # Fog needs a device name to attach as, so invent one. The guest # doesn't pay any attention to this device = "/dev/vd#{('b'.ord + index).chr}" vm.attach_volume(vol.id, device) end end end
[ "def", "provision_storage", "host", ",", "vm", "volumes", "=", "get_volumes", "(", "host", ")", "if", "!", "volumes", ".", "empty?", "# Lazily create the volume client if needed", "volume_client_create", "volumes", ".", "keys", ".", "each_with_index", "do", "|", "volume", ",", "index", "|", "@logger", ".", "debug", "\"Creating volume #{volume} for OpenStack host #{host.name}\"", "# The node defintion file defines volume sizes in MB (due to precedent", "# with the vagrant virtualbox implementation) however OpenStack requires", "# this translating into GB", "openstack_size", "=", "volumes", "[", "volume", "]", "[", "'size'", "]", ".", "to_i", "/", "1000", "# Set up the volume creation arguments", "args", "=", "{", ":size", "=>", "openstack_size", ",", ":description", "=>", "\"Beaker volume: host=#{host.name} volume=#{volume}\"", ",", "}", "# Between version 1 and subsequent versions the API was updated to", "# rename 'display_name' to just 'name' for better consistency", "if", "get_volume_api_version", "==", "1", "args", "[", ":display_name", "]", "=", "volume", "else", "args", "[", ":name", "]", "=", "volume", "end", "# Create the volume and wait for it to become available", "vol", "=", "@volume_client", ".", "volumes", ".", "create", "(", "**", "args", ")", "vol", ".", "wait_for", "{", "ready?", "}", "# Fog needs a device name to attach as, so invent one. The guest", "# doesn't pay any attention to this", "device", "=", "\"/dev/vd#{('b'.ord + index).chr}\"", "vm", ".", "attach_volume", "(", "vol", ".", "id", ",", "device", ")", "end", "end", "end" ]
Create and attach dynamic volumes Creates an array of volumes and attaches them to the current host. The host bus type is determined by the image type, so by default devices appear as /dev/vdb, /dev/vdc etc. Setting the glance properties hw_disk_bus=scsi, hw_scsi_model=virtio-scsi will present them as /dev/sdb, /dev/sdc (or 2:0:0:1, 2:0:0:2 in SCSI addresses) @param host [Hash] thet current host defined in the nodeset @param vm [Fog::Compute::OpenStack::Server] the server to attach to
[ "Create", "and", "attach", "dynamic", "volumes" ]
129227e23f3fbc412d5b9f6e46ced3b059af9e19
https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L148-L185
4,560
puppetlabs/beaker-openstack
lib/beaker/hypervisor/openstack.rb
Beaker.Openstack.cleanup_storage
def cleanup_storage vm vm.volumes.each do |vol| @logger.debug "Deleting volume #{vol.name} for OpenStack host #{vm.name}" vm.detach_volume(vol.id) vol.wait_for { ready? } vol.destroy end end
ruby
def cleanup_storage vm vm.volumes.each do |vol| @logger.debug "Deleting volume #{vol.name} for OpenStack host #{vm.name}" vm.detach_volume(vol.id) vol.wait_for { ready? } vol.destroy end end
[ "def", "cleanup_storage", "vm", "vm", ".", "volumes", ".", "each", "do", "|", "vol", "|", "@logger", ".", "debug", "\"Deleting volume #{vol.name} for OpenStack host #{vm.name}\"", "vm", ".", "detach_volume", "(", "vol", ".", "id", ")", "vol", ".", "wait_for", "{", "ready?", "}", "vol", ".", "destroy", "end", "end" ]
Detach and delete guest volumes @param vm [Fog::Compute::OpenStack::Server] the server to detach from
[ "Detach", "and", "delete", "guest", "volumes" ]
129227e23f3fbc412d5b9f6e46ced3b059af9e19
https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L189-L196
4,561
puppetlabs/beaker-openstack
lib/beaker/hypervisor/openstack.rb
Beaker.Openstack.get_ip
def get_ip begin @logger.debug "Creating IP" ip = @compute_client.addresses.create rescue Fog::Compute::OpenStack::NotFound # If there are no more floating IP addresses, allocate a # new one and try again. @compute_client.allocate_address(@options[:floating_ip_pool]) ip = @compute_client.addresses.find { |ip| ip.instance_id.nil? } end raise 'Could not find or allocate an address' if not ip ip end
ruby
def get_ip begin @logger.debug "Creating IP" ip = @compute_client.addresses.create rescue Fog::Compute::OpenStack::NotFound # If there are no more floating IP addresses, allocate a # new one and try again. @compute_client.allocate_address(@options[:floating_ip_pool]) ip = @compute_client.addresses.find { |ip| ip.instance_id.nil? } end raise 'Could not find or allocate an address' if not ip ip end
[ "def", "get_ip", "begin", "@logger", ".", "debug", "\"Creating IP\"", "ip", "=", "@compute_client", ".", "addresses", ".", "create", "rescue", "Fog", "::", "Compute", "::", "OpenStack", "::", "NotFound", "# If there are no more floating IP addresses, allocate a", "# new one and try again. ", "@compute_client", ".", "allocate_address", "(", "@options", "[", ":floating_ip_pool", "]", ")", "ip", "=", "@compute_client", ".", "addresses", ".", "find", "{", "|", "ip", "|", "ip", ".", "instance_id", ".", "nil?", "}", "end", "raise", "'Could not find or allocate an address'", "if", "not", "ip", "ip", "end" ]
Get a floating IP address to associate with the instance, try to allocate a new one from the specified pool if none are available
[ "Get", "a", "floating", "IP", "address", "to", "associate", "with", "the", "instance", "try", "to", "allocate", "a", "new", "one", "from", "the", "specified", "pool", "if", "none", "are", "available" ]
129227e23f3fbc412d5b9f6e46ced3b059af9e19
https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L200-L212
4,562
puppetlabs/beaker-openstack
lib/beaker/hypervisor/openstack.rb
Beaker.Openstack.provision
def provision @logger.notify "Provisioning OpenStack" @hosts.each do |host| ip = get_ip hostname = ip.ip.gsub('.','-') host[:vmhostname] = hostname + '.rfc1918.puppetlabs.net' create_or_associate_keypair(host, hostname) @logger.debug "Provisioning #{host.name} (#{host[:vmhostname]})" options = { :flavor_ref => flavor(host[:flavor]).id, :image_ref => image(host[:image]).id, :nics => [ {'net_id' => network(@options[:openstack_network]).id } ], :name => host[:vmhostname], :hostname => host[:vmhostname], :user_data => host[:user_data] || "#cloud-config\nmanage_etc_hosts: true\n", :key_name => host[:keyname], } options[:security_groups] = security_groups(@options[:security_group]) unless @options[:security_group].nil? vm = @compute_client.servers.create(options) #wait for the new instance to start up try = 1 attempts = @options[:timeout].to_i / SLEEPWAIT while try <= attempts begin vm.wait_for(5) { ready? } break rescue Fog::Errors::TimeoutError => e if try >= attempts @logger.debug "Failed to connect to new OpenStack instance #{host.name} (#{host[:vmhostname]})" raise e end @logger.debug "Timeout connecting to instance #{host.name} (#{host[:vmhostname]}), trying again..." end sleep SLEEPWAIT try += 1 end # Associate a public IP to the server ip.server = vm host[:ip] = ip.ip @logger.debug "OpenStack host #{host.name} (#{host[:vmhostname]}) assigned ip: #{host[:ip]}" #set metadata vm.metadata.update({:jenkins_build_url => @options[:jenkins_build_url].to_s, :department => @options[:department].to_s, :project => @options[:project].to_s }) @vms << vm # Wait for the host to accept ssh logins host.wait_for_port(22) #enable root if user is not root enable_root(host) provision_storage(host, vm) if @options[:openstack_volume_support] @logger.notify "OpenStack Volume Support Disabled, can't provision volumes" if not @options[:openstack_volume_support] end hack_etc_hosts @hosts, @options end
ruby
def provision @logger.notify "Provisioning OpenStack" @hosts.each do |host| ip = get_ip hostname = ip.ip.gsub('.','-') host[:vmhostname] = hostname + '.rfc1918.puppetlabs.net' create_or_associate_keypair(host, hostname) @logger.debug "Provisioning #{host.name} (#{host[:vmhostname]})" options = { :flavor_ref => flavor(host[:flavor]).id, :image_ref => image(host[:image]).id, :nics => [ {'net_id' => network(@options[:openstack_network]).id } ], :name => host[:vmhostname], :hostname => host[:vmhostname], :user_data => host[:user_data] || "#cloud-config\nmanage_etc_hosts: true\n", :key_name => host[:keyname], } options[:security_groups] = security_groups(@options[:security_group]) unless @options[:security_group].nil? vm = @compute_client.servers.create(options) #wait for the new instance to start up try = 1 attempts = @options[:timeout].to_i / SLEEPWAIT while try <= attempts begin vm.wait_for(5) { ready? } break rescue Fog::Errors::TimeoutError => e if try >= attempts @logger.debug "Failed to connect to new OpenStack instance #{host.name} (#{host[:vmhostname]})" raise e end @logger.debug "Timeout connecting to instance #{host.name} (#{host[:vmhostname]}), trying again..." end sleep SLEEPWAIT try += 1 end # Associate a public IP to the server ip.server = vm host[:ip] = ip.ip @logger.debug "OpenStack host #{host.name} (#{host[:vmhostname]}) assigned ip: #{host[:ip]}" #set metadata vm.metadata.update({:jenkins_build_url => @options[:jenkins_build_url].to_s, :department => @options[:department].to_s, :project => @options[:project].to_s }) @vms << vm # Wait for the host to accept ssh logins host.wait_for_port(22) #enable root if user is not root enable_root(host) provision_storage(host, vm) if @options[:openstack_volume_support] @logger.notify "OpenStack Volume Support Disabled, can't provision volumes" if not @options[:openstack_volume_support] end hack_etc_hosts @hosts, @options end
[ "def", "provision", "@logger", ".", "notify", "\"Provisioning OpenStack\"", "@hosts", ".", "each", "do", "|", "host", "|", "ip", "=", "get_ip", "hostname", "=", "ip", ".", "ip", ".", "gsub", "(", "'.'", ",", "'-'", ")", "host", "[", ":vmhostname", "]", "=", "hostname", "+", "'.rfc1918.puppetlabs.net'", "create_or_associate_keypair", "(", "host", ",", "hostname", ")", "@logger", ".", "debug", "\"Provisioning #{host.name} (#{host[:vmhostname]})\"", "options", "=", "{", ":flavor_ref", "=>", "flavor", "(", "host", "[", ":flavor", "]", ")", ".", "id", ",", ":image_ref", "=>", "image", "(", "host", "[", ":image", "]", ")", ".", "id", ",", ":nics", "=>", "[", "{", "'net_id'", "=>", "network", "(", "@options", "[", ":openstack_network", "]", ")", ".", "id", "}", "]", ",", ":name", "=>", "host", "[", ":vmhostname", "]", ",", ":hostname", "=>", "host", "[", ":vmhostname", "]", ",", ":user_data", "=>", "host", "[", ":user_data", "]", "||", "\"#cloud-config\\nmanage_etc_hosts: true\\n\"", ",", ":key_name", "=>", "host", "[", ":keyname", "]", ",", "}", "options", "[", ":security_groups", "]", "=", "security_groups", "(", "@options", "[", ":security_group", "]", ")", "unless", "@options", "[", ":security_group", "]", ".", "nil?", "vm", "=", "@compute_client", ".", "servers", ".", "create", "(", "options", ")", "#wait for the new instance to start up", "try", "=", "1", "attempts", "=", "@options", "[", ":timeout", "]", ".", "to_i", "/", "SLEEPWAIT", "while", "try", "<=", "attempts", "begin", "vm", ".", "wait_for", "(", "5", ")", "{", "ready?", "}", "break", "rescue", "Fog", "::", "Errors", "::", "TimeoutError", "=>", "e", "if", "try", ">=", "attempts", "@logger", ".", "debug", "\"Failed to connect to new OpenStack instance #{host.name} (#{host[:vmhostname]})\"", "raise", "e", "end", "@logger", ".", "debug", "\"Timeout connecting to instance #{host.name} (#{host[:vmhostname]}), trying again...\"", "end", "sleep", "SLEEPWAIT", "try", "+=", "1", "end", "# Associate a public IP to the server", "ip", ".", "server", "=", "vm", "host", "[", ":ip", "]", "=", "ip", ".", "ip", "@logger", ".", "debug", "\"OpenStack host #{host.name} (#{host[:vmhostname]}) assigned ip: #{host[:ip]}\"", "#set metadata", "vm", ".", "metadata", ".", "update", "(", "{", ":jenkins_build_url", "=>", "@options", "[", ":jenkins_build_url", "]", ".", "to_s", ",", ":department", "=>", "@options", "[", ":department", "]", ".", "to_s", ",", ":project", "=>", "@options", "[", ":project", "]", ".", "to_s", "}", ")", "@vms", "<<", "vm", "# Wait for the host to accept ssh logins", "host", ".", "wait_for_port", "(", "22", ")", "#enable root if user is not root", "enable_root", "(", "host", ")", "provision_storage", "(", "host", ",", "vm", ")", "if", "@options", "[", ":openstack_volume_support", "]", "@logger", ".", "notify", "\"OpenStack Volume Support Disabled, can't provision volumes\"", "if", "not", "@options", "[", ":openstack_volume_support", "]", "end", "hack_etc_hosts", "@hosts", ",", "@options", "end" ]
Create new instances in OpenStack
[ "Create", "new", "instances", "in", "OpenStack" ]
129227e23f3fbc412d5b9f6e46ced3b059af9e19
https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L215-L279
4,563
puppetlabs/beaker-openstack
lib/beaker/hypervisor/openstack.rb
Beaker.Openstack.cleanup
def cleanup @logger.notify "Cleaning up OpenStack" @vms.each do |vm| cleanup_storage(vm) if @options[:openstack_volume_support] @logger.debug "Release floating IPs for OpenStack host #{vm.name}" floating_ips = vm.all_addresses # fetch and release its floating IPs floating_ips.each do |address| @compute_client.disassociate_address(vm.id, address['ip']) @compute_client.release_address(address['id']) end @logger.debug "Destroying OpenStack host #{vm.name}" vm.destroy if @options[:openstack_keyname].nil? @logger.debug "Deleting random keypair" @compute_client.delete_key_pair vm.key_name end end end
ruby
def cleanup @logger.notify "Cleaning up OpenStack" @vms.each do |vm| cleanup_storage(vm) if @options[:openstack_volume_support] @logger.debug "Release floating IPs for OpenStack host #{vm.name}" floating_ips = vm.all_addresses # fetch and release its floating IPs floating_ips.each do |address| @compute_client.disassociate_address(vm.id, address['ip']) @compute_client.release_address(address['id']) end @logger.debug "Destroying OpenStack host #{vm.name}" vm.destroy if @options[:openstack_keyname].nil? @logger.debug "Deleting random keypair" @compute_client.delete_key_pair vm.key_name end end end
[ "def", "cleanup", "@logger", ".", "notify", "\"Cleaning up OpenStack\"", "@vms", ".", "each", "do", "|", "vm", "|", "cleanup_storage", "(", "vm", ")", "if", "@options", "[", ":openstack_volume_support", "]", "@logger", ".", "debug", "\"Release floating IPs for OpenStack host #{vm.name}\"", "floating_ips", "=", "vm", ".", "all_addresses", "# fetch and release its floating IPs", "floating_ips", ".", "each", "do", "|", "address", "|", "@compute_client", ".", "disassociate_address", "(", "vm", ".", "id", ",", "address", "[", "'ip'", "]", ")", "@compute_client", ".", "release_address", "(", "address", "[", "'id'", "]", ")", "end", "@logger", ".", "debug", "\"Destroying OpenStack host #{vm.name}\"", "vm", ".", "destroy", "if", "@options", "[", ":openstack_keyname", "]", ".", "nil?", "@logger", ".", "debug", "\"Deleting random keypair\"", "@compute_client", ".", "delete_key_pair", "vm", ".", "key_name", "end", "end", "end" ]
Destroy any OpenStack instances
[ "Destroy", "any", "OpenStack", "instances" ]
129227e23f3fbc412d5b9f6e46ced3b059af9e19
https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L282-L299
4,564
puppetlabs/beaker-openstack
lib/beaker/hypervisor/openstack.rb
Beaker.Openstack.create_or_associate_keypair
def create_or_associate_keypair(host, keyname) if @options[:openstack_keyname] @logger.debug "Adding optional key_name #{@options[:openstack_keyname]} to #{host.name} (#{host[:vmhostname]})" keyname = @options[:openstack_keyname] else @logger.debug "Generate a new rsa key" # There is apparently an error that can occur when generating RSA keys, probably # due to some timing issue, probably similar to the issue described here: # https://github.com/negativecode/vines/issues/34 # In order to mitigate this error, we will simply try again up to three times, and # then fail if we continue to error out. begin retries ||= 0 key = OpenSSL::PKey::RSA.new 2048 rescue OpenSSL::PKey::RSAError => e retries += 1 if retries > 2 @logger.notify "error generating RSA key #{retries} times, exiting" raise e end retry end type = key.ssh_type data = [ key.to_blob ].pack('m0') @logger.debug "Creating Openstack keypair '#{keyname}' for public key '#{type} #{data}'" @compute_client.create_key_pair keyname, "#{type} #{data}" host['ssh'][:key_data] = [ key.to_pem ] end host[:keyname] = keyname end
ruby
def create_or_associate_keypair(host, keyname) if @options[:openstack_keyname] @logger.debug "Adding optional key_name #{@options[:openstack_keyname]} to #{host.name} (#{host[:vmhostname]})" keyname = @options[:openstack_keyname] else @logger.debug "Generate a new rsa key" # There is apparently an error that can occur when generating RSA keys, probably # due to some timing issue, probably similar to the issue described here: # https://github.com/negativecode/vines/issues/34 # In order to mitigate this error, we will simply try again up to three times, and # then fail if we continue to error out. begin retries ||= 0 key = OpenSSL::PKey::RSA.new 2048 rescue OpenSSL::PKey::RSAError => e retries += 1 if retries > 2 @logger.notify "error generating RSA key #{retries} times, exiting" raise e end retry end type = key.ssh_type data = [ key.to_blob ].pack('m0') @logger.debug "Creating Openstack keypair '#{keyname}' for public key '#{type} #{data}'" @compute_client.create_key_pair keyname, "#{type} #{data}" host['ssh'][:key_data] = [ key.to_pem ] end host[:keyname] = keyname end
[ "def", "create_or_associate_keypair", "(", "host", ",", "keyname", ")", "if", "@options", "[", ":openstack_keyname", "]", "@logger", ".", "debug", "\"Adding optional key_name #{@options[:openstack_keyname]} to #{host.name} (#{host[:vmhostname]})\"", "keyname", "=", "@options", "[", ":openstack_keyname", "]", "else", "@logger", ".", "debug", "\"Generate a new rsa key\"", "# There is apparently an error that can occur when generating RSA keys, probably", "# due to some timing issue, probably similar to the issue described here:", "# https://github.com/negativecode/vines/issues/34", "# In order to mitigate this error, we will simply try again up to three times, and", "# then fail if we continue to error out.", "begin", "retries", "||=", "0", "key", "=", "OpenSSL", "::", "PKey", "::", "RSA", ".", "new", "2048", "rescue", "OpenSSL", "::", "PKey", "::", "RSAError", "=>", "e", "retries", "+=", "1", "if", "retries", ">", "2", "@logger", ".", "notify", "\"error generating RSA key #{retries} times, exiting\"", "raise", "e", "end", "retry", "end", "type", "=", "key", ".", "ssh_type", "data", "=", "[", "key", ".", "to_blob", "]", ".", "pack", "(", "'m0'", ")", "@logger", ".", "debug", "\"Creating Openstack keypair '#{keyname}' for public key '#{type} #{data}'\"", "@compute_client", ".", "create_key_pair", "keyname", ",", "\"#{type} #{data}\"", "host", "[", "'ssh'", "]", "[", ":key_data", "]", "=", "[", "key", ".", "to_pem", "]", "end", "host", "[", ":keyname", "]", "=", "keyname", "end" ]
Get key_name from options or generate a new rsa key and add it to OpenStack keypairs @param [Host] host The OpenStack host to provision @api private
[ "Get", "key_name", "from", "options", "or", "generate", "a", "new", "rsa", "key", "and", "add", "it", "to", "OpenStack", "keypairs" ]
129227e23f3fbc412d5b9f6e46ced3b059af9e19
https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L329-L361
4,565
ryw/pinboard
lib/pinboard/client.rb
Pinboard.Client.get
def get(params = {}) params[:dt] = params[:dt].to_date.to_s if params.is_a? Time params[:meta] = params[:meta] ? 'yes' : 'no' if params.has_key?(:meta) options = create_params(params) posts = self.class.get('/posts/get', options)['posts']['post'] posts = [] if posts.nil? posts = [posts] if posts.class != Array posts.map { |p| Post.new(Util.symbolize_keys(p)) } end
ruby
def get(params = {}) params[:dt] = params[:dt].to_date.to_s if params.is_a? Time params[:meta] = params[:meta] ? 'yes' : 'no' if params.has_key?(:meta) options = create_params(params) posts = self.class.get('/posts/get', options)['posts']['post'] posts = [] if posts.nil? posts = [posts] if posts.class != Array posts.map { |p| Post.new(Util.symbolize_keys(p)) } end
[ "def", "get", "(", "params", "=", "{", "}", ")", "params", "[", ":dt", "]", "=", "params", "[", ":dt", "]", ".", "to_date", ".", "to_s", "if", "params", ".", "is_a?", "Time", "params", "[", ":meta", "]", "=", "params", "[", ":meta", "]", "?", "'yes'", ":", "'no'", "if", "params", ".", "has_key?", "(", ":meta", ")", "options", "=", "create_params", "(", "params", ")", "posts", "=", "self", ".", "class", ".", "get", "(", "'/posts/get'", ",", "options", ")", "[", "'posts'", "]", "[", "'post'", "]", "posts", "=", "[", "]", "if", "posts", ".", "nil?", "posts", "=", "[", "posts", "]", "if", "posts", ".", "class", "!=", "Array", "posts", ".", "map", "{", "|", "p", "|", "Post", ".", "new", "(", "Util", ".", "symbolize_keys", "(", "p", ")", ")", "}", "end" ]
Returns one or more posts on a single day matching the arguments. If no date or url is given, date of most recent bookmark will be used. @option params [String] :tag filter by up to three tags @option params [Time] :dt return results bookmarked on this day @option params [String] :url return bookmark for this URL @option params [Boolean] :meta include a change detection signature in a meta attribute @return [Array<Post>] the list of bookmarks
[ "Returns", "one", "or", "more", "posts", "on", "a", "single", "day", "matching", "the", "arguments", ".", "If", "no", "date", "or", "url", "is", "given", "date", "of", "most", "recent", "bookmark", "will", "be", "used", "." ]
65d3b2f38b56d0f9f236d0041f4a697157905cf9
https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L57-L65
4,566
ryw/pinboard
lib/pinboard/client.rb
Pinboard.Client.suggest
def suggest(url) options = create_params({url: url}) suggested = self.class.get('/posts/suggest', options)['suggested'] popular = suggested['popular'] popular = [] if popular.nil? popular = [popular] if popular.class != Array recommended = suggested['recommended'] recommended = [] if recommended.nil? recommended = [recommended] if recommended.class != Array {:popular => popular, :recommended => recommended} end
ruby
def suggest(url) options = create_params({url: url}) suggested = self.class.get('/posts/suggest', options)['suggested'] popular = suggested['popular'] popular = [] if popular.nil? popular = [popular] if popular.class != Array recommended = suggested['recommended'] recommended = [] if recommended.nil? recommended = [recommended] if recommended.class != Array {:popular => popular, :recommended => recommended} end
[ "def", "suggest", "(", "url", ")", "options", "=", "create_params", "(", "{", "url", ":", "url", "}", ")", "suggested", "=", "self", ".", "class", ".", "get", "(", "'/posts/suggest'", ",", "options", ")", "[", "'suggested'", "]", "popular", "=", "suggested", "[", "'popular'", "]", "popular", "=", "[", "]", "if", "popular", ".", "nil?", "popular", "=", "[", "popular", "]", "if", "popular", ".", "class", "!=", "Array", "recommended", "=", "suggested", "[", "'recommended'", "]", "recommended", "=", "[", "]", "if", "recommended", ".", "nil?", "recommended", "=", "[", "recommended", "]", "if", "recommended", ".", "class", "!=", "Array", "{", ":popular", "=>", "popular", ",", ":recommended", "=>", "recommended", "}", "end" ]
Returns a list of popular tags and recommended tags for a given URL. Popular tags are tags used site-wide for the url; recommended tags are drawn from the user's own tags. @param [String] url @return [Hash<String, Array>]
[ "Returns", "a", "list", "of", "popular", "tags", "and", "recommended", "tags", "for", "a", "given", "URL", ".", "Popular", "tags", "are", "tags", "used", "site", "-", "wide", "for", "the", "url", ";", "recommended", "tags", "are", "drawn", "from", "the", "user", "s", "own", "tags", "." ]
65d3b2f38b56d0f9f236d0041f4a697157905cf9
https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L73-L85
4,567
ryw/pinboard
lib/pinboard/client.rb
Pinboard.Client.recent
def recent(params={}) options = create_params(params) posts = self.class.get('/posts/recent', options)['posts']['post'] posts = [] if posts.nil? posts = [*posts] posts.map { |p| Post.new(Util.symbolize_keys(p)) } end
ruby
def recent(params={}) options = create_params(params) posts = self.class.get('/posts/recent', options)['posts']['post'] posts = [] if posts.nil? posts = [*posts] posts.map { |p| Post.new(Util.symbolize_keys(p)) } end
[ "def", "recent", "(", "params", "=", "{", "}", ")", "options", "=", "create_params", "(", "params", ")", "posts", "=", "self", ".", "class", ".", "get", "(", "'/posts/recent'", ",", "options", ")", "[", "'posts'", "]", "[", "'post'", "]", "posts", "=", "[", "]", "if", "posts", ".", "nil?", "posts", "=", "[", "posts", "]", "posts", ".", "map", "{", "|", "p", "|", "Post", ".", "new", "(", "Util", ".", "symbolize_keys", "(", "p", ")", ")", "}", "end" ]
Returns a list of the user's most recent posts, filtered by tag. @param <Hash> params the options to filter current posts @option params [String] :tag filter by up to three tags @option params [String] :count Number of results to return. Default is 15, max is 100 @return [Array<Post>] the list of recent posts
[ "Returns", "a", "list", "of", "the", "user", "s", "most", "recent", "posts", "filtered", "by", "tag", "." ]
65d3b2f38b56d0f9f236d0041f4a697157905cf9
https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L150-L156
4,568
ryw/pinboard
lib/pinboard/client.rb
Pinboard.Client.dates
def dates(tag=nil) params = {} params[:tag] = tag if tag options = create_params(params) dates = self.class.get('/posts/dates', options)['dates']['date'] dates = [] if dates.nil? dates = [*dates] dates.each_with_object({}) { |value, hash| hash[value["date"]] = value["count"].to_i } end
ruby
def dates(tag=nil) params = {} params[:tag] = tag if tag options = create_params(params) dates = self.class.get('/posts/dates', options)['dates']['date'] dates = [] if dates.nil? dates = [*dates] dates.each_with_object({}) { |value, hash| hash[value["date"]] = value["count"].to_i } end
[ "def", "dates", "(", "tag", "=", "nil", ")", "params", "=", "{", "}", "params", "[", ":tag", "]", "=", "tag", "if", "tag", "options", "=", "create_params", "(", "params", ")", "dates", "=", "self", ".", "class", ".", "get", "(", "'/posts/dates'", ",", "options", ")", "[", "'dates'", "]", "[", "'date'", "]", "dates", "=", "[", "]", "if", "dates", ".", "nil?", "dates", "=", "[", "dates", "]", "dates", ".", "each_with_object", "(", "{", "}", ")", "{", "|", "value", ",", "hash", "|", "hash", "[", "value", "[", "\"date\"", "]", "]", "=", "value", "[", "\"count\"", "]", ".", "to_i", "}", "end" ]
Returns a list of dates with the number of posts at each date @param [String] tag Filter by up to three tags @return [Hash<String,Fixnum>] List of dates with number of posts at each date
[ "Returns", "a", "list", "of", "dates", "with", "the", "number", "of", "posts", "at", "each", "date" ]
65d3b2f38b56d0f9f236d0041f4a697157905cf9
https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L164-L175
4,569
ryw/pinboard
lib/pinboard/client.rb
Pinboard.Client.tags_get
def tags_get(params={}) options = create_params(params) tags = self.class.get('/tags/get', options)['tags']['tag'] tags = [] if tags.nil? tags = [*tags] tags.map { |p| Tag.new(Util.symbolize_keys(p)) } end
ruby
def tags_get(params={}) options = create_params(params) tags = self.class.get('/tags/get', options)['tags']['tag'] tags = [] if tags.nil? tags = [*tags] tags.map { |p| Tag.new(Util.symbolize_keys(p)) } end
[ "def", "tags_get", "(", "params", "=", "{", "}", ")", "options", "=", "create_params", "(", "params", ")", "tags", "=", "self", ".", "class", ".", "get", "(", "'/tags/get'", ",", "options", ")", "[", "'tags'", "]", "[", "'tag'", "]", "tags", "=", "[", "]", "if", "tags", ".", "nil?", "tags", "=", "[", "tags", "]", "tags", ".", "map", "{", "|", "p", "|", "Tag", ".", "new", "(", "Util", ".", "symbolize_keys", "(", "p", ")", ")", "}", "end" ]
Returns a full list of the user's tags along with the number of times they were used. @return [Array<Tag>] List of all tags
[ "Returns", "a", "full", "list", "of", "the", "user", "s", "tags", "along", "with", "the", "number", "of", "times", "they", "were", "used", "." ]
65d3b2f38b56d0f9f236d0041f4a697157905cf9
https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L198-L204
4,570
ryw/pinboard
lib/pinboard/client.rb
Pinboard.Client.tags_rename
def tags_rename(old_tag, new_tag=nil) params = {} params[:old] = old_tag params[:new] = new_tag if new_tag options = create_params(params) result_code = self.class.get('/tags/rename', options).parsed_response["result"] raise Error.new(result_code) if result_code != "done" result_code end
ruby
def tags_rename(old_tag, new_tag=nil) params = {} params[:old] = old_tag params[:new] = new_tag if new_tag options = create_params(params) result_code = self.class.get('/tags/rename', options).parsed_response["result"] raise Error.new(result_code) if result_code != "done" result_code end
[ "def", "tags_rename", "(", "old_tag", ",", "new_tag", "=", "nil", ")", "params", "=", "{", "}", "params", "[", ":old", "]", "=", "old_tag", "params", "[", ":new", "]", "=", "new_tag", "if", "new_tag", "options", "=", "create_params", "(", "params", ")", "result_code", "=", "self", ".", "class", ".", "get", "(", "'/tags/rename'", ",", "options", ")", ".", "parsed_response", "[", "\"result\"", "]", "raise", "Error", ".", "new", "(", "result_code", ")", "if", "result_code", "!=", "\"done\"", "result_code", "end" ]
Rename an tag or fold it into an existing tag @param [String] old_tag Tag to rename (not case sensitive) @param [String] new_tag New tag (if empty nothing will happen) @return [String] "done" when everything went as expected @raise [Error] if result code is not "done"
[ "Rename", "an", "tag", "or", "fold", "it", "into", "an", "existing", "tag" ]
65d3b2f38b56d0f9f236d0041f4a697157905cf9
https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L213-L224
4,571
ryw/pinboard
lib/pinboard/client.rb
Pinboard.Client.tags_delete
def tags_delete(tag) params = { tag: tag } options = create_params(params) self.class.get('/tags/delete', options) nil end
ruby
def tags_delete(tag) params = { tag: tag } options = create_params(params) self.class.get('/tags/delete', options) nil end
[ "def", "tags_delete", "(", "tag", ")", "params", "=", "{", "tag", ":", "tag", "}", "options", "=", "create_params", "(", "params", ")", "self", ".", "class", ".", "get", "(", "'/tags/delete'", ",", "options", ")", "nil", "end" ]
Delete an existing tag @param [String] tag Tag to delete @return [nil]
[ "Delete", "an", "existing", "tag" ]
65d3b2f38b56d0f9f236d0041f4a697157905cf9
https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L230-L236
4,572
ryw/pinboard
lib/pinboard/client.rb
Pinboard.Client.notes_list
def notes_list options = create_params({}) notes = self.class.get('/notes/list', options)['notes']['note'] notes = [] if notes.nil? notes = [*notes] notes.map { |p| Note.new(Util.symbolize_keys(p)) } end
ruby
def notes_list options = create_params({}) notes = self.class.get('/notes/list', options)['notes']['note'] notes = [] if notes.nil? notes = [*notes] notes.map { |p| Note.new(Util.symbolize_keys(p)) } end
[ "def", "notes_list", "options", "=", "create_params", "(", "{", "}", ")", "notes", "=", "self", ".", "class", ".", "get", "(", "'/notes/list'", ",", "options", ")", "[", "'notes'", "]", "[", "'note'", "]", "notes", "=", "[", "]", "if", "notes", ".", "nil?", "notes", "=", "[", "notes", "]", "notes", ".", "map", "{", "|", "p", "|", "Note", ".", "new", "(", "Util", ".", "symbolize_keys", "(", "p", ")", ")", "}", "end" ]
Returns a list of the user's notes @return [Array<Note>] list of notes
[ "Returns", "a", "list", "of", "the", "user", "s", "notes" ]
65d3b2f38b56d0f9f236d0041f4a697157905cf9
https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L256-L262
4,573
ryw/pinboard
lib/pinboard/client.rb
Pinboard.Client.notes_get
def notes_get(id) options = create_params({}) note = self.class.get("/notes/#{id}", options)['note'] return nil unless note # Complete hack, because the API is still broken content = '__content__' Note.new({ id: note['id'], # Remove whitespace around the title, # because of missing xml tag around title: note[content].gsub(/\n| +/, ''), length: note['length'][content].to_i, text: note['text'][content] }) end
ruby
def notes_get(id) options = create_params({}) note = self.class.get("/notes/#{id}", options)['note'] return nil unless note # Complete hack, because the API is still broken content = '__content__' Note.new({ id: note['id'], # Remove whitespace around the title, # because of missing xml tag around title: note[content].gsub(/\n| +/, ''), length: note['length'][content].to_i, text: note['text'][content] }) end
[ "def", "notes_get", "(", "id", ")", "options", "=", "create_params", "(", "{", "}", ")", "note", "=", "self", ".", "class", ".", "get", "(", "\"/notes/#{id}\"", ",", "options", ")", "[", "'note'", "]", "return", "nil", "unless", "note", "# Complete hack, because the API is still broken", "content", "=", "'__content__'", "Note", ".", "new", "(", "{", "id", ":", "note", "[", "'id'", "]", ",", "# Remove whitespace around the title,", "# because of missing xml tag around", "title", ":", "note", "[", "content", "]", ".", "gsub", "(", "/", "\\n", "/", ",", "''", ")", ",", "length", ":", "note", "[", "'length'", "]", "[", "content", "]", ".", "to_i", ",", "text", ":", "note", "[", "'text'", "]", "[", "content", "]", "}", ")", "end" ]
Returns an individual user note. The hash property is a 20 character long sha1 hash of the note text. @return [Note] the note
[ "Returns", "an", "individual", "user", "note", ".", "The", "hash", "property", "is", "a", "20", "character", "long", "sha1", "hash", "of", "the", "note", "text", "." ]
65d3b2f38b56d0f9f236d0041f4a697157905cf9
https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L268-L284
4,574
ryw/pinboard
lib/pinboard/client.rb
Pinboard.Client.create_params
def create_params params options = {} options[:query] = params if @auth_token options[:query].merge!(auth_token: @auth_token) else options[:basic_auth] = @auth end options end
ruby
def create_params params options = {} options[:query] = params if @auth_token options[:query].merge!(auth_token: @auth_token) else options[:basic_auth] = @auth end options end
[ "def", "create_params", "params", "options", "=", "{", "}", "options", "[", ":query", "]", "=", "params", "if", "@auth_token", "options", "[", ":query", "]", ".", "merge!", "(", "auth_token", ":", "@auth_token", ")", "else", "options", "[", ":basic_auth", "]", "=", "@auth", "end", "options", "end" ]
Construct params hash for HTTP request @param [Hash] params Query arguments to include in request @return [Hash] Options hash for request
[ "Construct", "params", "hash", "for", "HTTP", "request" ]
65d3b2f38b56d0f9f236d0041f4a697157905cf9
https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L291-L302
4,575
vchs/ruby_vcloud_sdk
lib/ruby_vcloud_sdk/vm.rb
VCloudSdk.VM.memory
def memory m = entity_xml .hardware_section .memory allocation_units = m.get_rasd_content(Xml::RASD_TYPES[:ALLOCATION_UNITS]) bytes = eval_memory_allocation_units(allocation_units) virtual_quantity = m.get_rasd_content(Xml::RASD_TYPES[:VIRTUAL_QUANTITY]).to_i memory_mb = virtual_quantity * bytes / BYTES_PER_MEGABYTE fail CloudError, "Size of memory is less than 1 MB." if memory_mb == 0 memory_mb end
ruby
def memory m = entity_xml .hardware_section .memory allocation_units = m.get_rasd_content(Xml::RASD_TYPES[:ALLOCATION_UNITS]) bytes = eval_memory_allocation_units(allocation_units) virtual_quantity = m.get_rasd_content(Xml::RASD_TYPES[:VIRTUAL_QUANTITY]).to_i memory_mb = virtual_quantity * bytes / BYTES_PER_MEGABYTE fail CloudError, "Size of memory is less than 1 MB." if memory_mb == 0 memory_mb end
[ "def", "memory", "m", "=", "entity_xml", ".", "hardware_section", ".", "memory", "allocation_units", "=", "m", ".", "get_rasd_content", "(", "Xml", "::", "RASD_TYPES", "[", ":ALLOCATION_UNITS", "]", ")", "bytes", "=", "eval_memory_allocation_units", "(", "allocation_units", ")", "virtual_quantity", "=", "m", ".", "get_rasd_content", "(", "Xml", "::", "RASD_TYPES", "[", ":VIRTUAL_QUANTITY", "]", ")", ".", "to_i", "memory_mb", "=", "virtual_quantity", "*", "bytes", "/", "BYTES_PER_MEGABYTE", "fail", "CloudError", ",", "\"Size of memory is less than 1 MB.\"", "if", "memory_mb", "==", "0", "memory_mb", "end" ]
returns size of memory in megabytes
[ "returns", "size", "of", "memory", "in", "megabytes" ]
92d56db4fea4321068ab300ca60bcc6cec3e459b
https://github.com/vchs/ruby_vcloud_sdk/blob/92d56db4fea4321068ab300ca60bcc6cec3e459b/lib/ruby_vcloud_sdk/vm.rb#L25-L37
4,576
vchs/ruby_vcloud_sdk
lib/ruby_vcloud_sdk/vm.rb
VCloudSdk.VM.memory=
def memory=(size) fail(CloudError, "Invalid vm memory size #{size}MB") if size <= 0 Config .logger .info "Changing the vm memory to #{size}MB." payload = entity_xml payload.change_memory(size) task = connection.post(payload.reconfigure_link.href, payload, Xml::MEDIA_TYPE[:VM]) monitor_task(task) self end
ruby
def memory=(size) fail(CloudError, "Invalid vm memory size #{size}MB") if size <= 0 Config .logger .info "Changing the vm memory to #{size}MB." payload = entity_xml payload.change_memory(size) task = connection.post(payload.reconfigure_link.href, payload, Xml::MEDIA_TYPE[:VM]) monitor_task(task) self end
[ "def", "memory", "=", "(", "size", ")", "fail", "(", "CloudError", ",", "\"Invalid vm memory size #{size}MB\"", ")", "if", "size", "<=", "0", "Config", ".", "logger", ".", "info", "\"Changing the vm memory to #{size}MB.\"", "payload", "=", "entity_xml", "payload", ".", "change_memory", "(", "size", ")", "task", "=", "connection", ".", "post", "(", "payload", ".", "reconfigure_link", ".", "href", ",", "payload", ",", "Xml", "::", "MEDIA_TYPE", "[", ":VM", "]", ")", "monitor_task", "(", "task", ")", "self", "end" ]
sets size of memory in megabytes
[ "sets", "size", "of", "memory", "in", "megabytes" ]
92d56db4fea4321068ab300ca60bcc6cec3e459b
https://github.com/vchs/ruby_vcloud_sdk/blob/92d56db4fea4321068ab300ca60bcc6cec3e459b/lib/ruby_vcloud_sdk/vm.rb#L40-L56
4,577
vchs/ruby_vcloud_sdk
lib/ruby_vcloud_sdk/vm.rb
VCloudSdk.VM.vcpu
def vcpu cpus = entity_xml .hardware_section .cpu .get_rasd_content(Xml::RASD_TYPES[:VIRTUAL_QUANTITY]) fail CloudError, "Uable to retrieve number of virtual cpus of VM #{name}" if cpus.nil? cpus.to_i end
ruby
def vcpu cpus = entity_xml .hardware_section .cpu .get_rasd_content(Xml::RASD_TYPES[:VIRTUAL_QUANTITY]) fail CloudError, "Uable to retrieve number of virtual cpus of VM #{name}" if cpus.nil? cpus.to_i end
[ "def", "vcpu", "cpus", "=", "entity_xml", ".", "hardware_section", ".", "cpu", ".", "get_rasd_content", "(", "Xml", "::", "RASD_TYPES", "[", ":VIRTUAL_QUANTITY", "]", ")", "fail", "CloudError", ",", "\"Uable to retrieve number of virtual cpus of VM #{name}\"", "if", "cpus", ".", "nil?", "cpus", ".", "to_i", "end" ]
returns number of virtual cpus of VM
[ "returns", "number", "of", "virtual", "cpus", "of", "VM" ]
92d56db4fea4321068ab300ca60bcc6cec3e459b
https://github.com/vchs/ruby_vcloud_sdk/blob/92d56db4fea4321068ab300ca60bcc6cec3e459b/lib/ruby_vcloud_sdk/vm.rb#L59-L68
4,578
vchs/ruby_vcloud_sdk
lib/ruby_vcloud_sdk/vm.rb
VCloudSdk.VM.vcpu=
def vcpu=(count) fail(CloudError, "Invalid virtual CPU count #{count}") if count <= 0 Config .logger .info "Changing the virtual CPU count to #{count}." payload = entity_xml payload.change_cpu_count(count) task = connection.post(payload.reconfigure_link.href, payload, Xml::MEDIA_TYPE[:VM]) monitor_task(task) self end
ruby
def vcpu=(count) fail(CloudError, "Invalid virtual CPU count #{count}") if count <= 0 Config .logger .info "Changing the virtual CPU count to #{count}." payload = entity_xml payload.change_cpu_count(count) task = connection.post(payload.reconfigure_link.href, payload, Xml::MEDIA_TYPE[:VM]) monitor_task(task) self end
[ "def", "vcpu", "=", "(", "count", ")", "fail", "(", "CloudError", ",", "\"Invalid virtual CPU count #{count}\"", ")", "if", "count", "<=", "0", "Config", ".", "logger", ".", "info", "\"Changing the virtual CPU count to #{count}.\"", "payload", "=", "entity_xml", "payload", ".", "change_cpu_count", "(", "count", ")", "task", "=", "connection", ".", "post", "(", "payload", ".", "reconfigure_link", ".", "href", ",", "payload", ",", "Xml", "::", "MEDIA_TYPE", "[", ":VM", "]", ")", "monitor_task", "(", "task", ")", "self", "end" ]
sets number of virtual cpus of VM
[ "sets", "number", "of", "virtual", "cpus", "of", "VM" ]
92d56db4fea4321068ab300ca60bcc6cec3e459b
https://github.com/vchs/ruby_vcloud_sdk/blob/92d56db4fea4321068ab300ca60bcc6cec3e459b/lib/ruby_vcloud_sdk/vm.rb#L71-L87
4,579
maxivak/simple_search_filter
lib/simple_search_filter/filter.rb
SimpleSearchFilter.Filter.get_order_dir_for_column
def get_order_dir_for_column(name) name = name.to_s current_column = get_order_column return nil unless current_column==name dir = get_order_dir return nil if dir.nil? dir end
ruby
def get_order_dir_for_column(name) name = name.to_s current_column = get_order_column return nil unless current_column==name dir = get_order_dir return nil if dir.nil? dir end
[ "def", "get_order_dir_for_column", "(", "name", ")", "name", "=", "name", ".", "to_s", "current_column", "=", "get_order_column", "return", "nil", "unless", "current_column", "==", "name", "dir", "=", "get_order_dir", "return", "nil", "if", "dir", ".", "nil?", "dir", "end" ]
return nil if not sorted by this column return order dir if sorted by this column
[ "return", "nil", "if", "not", "sorted", "by", "this", "column", "return", "order", "dir", "if", "sorted", "by", "this", "column" ]
3bece03360f9895b037ca11a9a98fd0e9665e37c
https://github.com/maxivak/simple_search_filter/blob/3bece03360f9895b037ca11a9a98fd0e9665e37c/lib/simple_search_filter/filter.rb#L348-L358
4,580
raulanatol/el_finder_s3
lib/el_finder_s3/connector.rb
ElFinderS3.Connector.run
def run(params) @adapter = ElFinderS3::Adapter.new(@options[:server], @options[:cache_connector]) @root = ElFinderS3::Pathname.new(adapter, @options[:root]) #Change - Pass the root dir here begin @params = params.dup @headers = {} @response = {} @response[:errorData] = {} if VALID_COMMANDS.include?(@params[:cmd]) if @options[:thumbs] @thumb_directory = @root + @options[:thumbs_directory] @thumb_directory.mkdir unless @thumb_directory.exist? raise(RuntimeError, "Unable to create thumbs directory") unless @thumb_directory.directory? end @current = @params[:current] ? from_hash(@params[:current]) : nil @target = (@params[:target] and !@params[:target].empty?) ? from_hash(@params[:target]) : nil if params[:targets] @targets = @params[:targets].map { |t| from_hash(t) } end begin send("_#{@params[:cmd]}") rescue Exception => exception puts exception.message puts exception.backtrace.inspect @response[:error] = 'Access Denied' end else invalid_request end @response.delete(:errorData) if @response[:errorData].empty? return @headers, @response ensure adapter.close end end
ruby
def run(params) @adapter = ElFinderS3::Adapter.new(@options[:server], @options[:cache_connector]) @root = ElFinderS3::Pathname.new(adapter, @options[:root]) #Change - Pass the root dir here begin @params = params.dup @headers = {} @response = {} @response[:errorData] = {} if VALID_COMMANDS.include?(@params[:cmd]) if @options[:thumbs] @thumb_directory = @root + @options[:thumbs_directory] @thumb_directory.mkdir unless @thumb_directory.exist? raise(RuntimeError, "Unable to create thumbs directory") unless @thumb_directory.directory? end @current = @params[:current] ? from_hash(@params[:current]) : nil @target = (@params[:target] and !@params[:target].empty?) ? from_hash(@params[:target]) : nil if params[:targets] @targets = @params[:targets].map { |t| from_hash(t) } end begin send("_#{@params[:cmd]}") rescue Exception => exception puts exception.message puts exception.backtrace.inspect @response[:error] = 'Access Denied' end else invalid_request end @response.delete(:errorData) if @response[:errorData].empty? return @headers, @response ensure adapter.close end end
[ "def", "run", "(", "params", ")", "@adapter", "=", "ElFinderS3", "::", "Adapter", ".", "new", "(", "@options", "[", ":server", "]", ",", "@options", "[", ":cache_connector", "]", ")", "@root", "=", "ElFinderS3", "::", "Pathname", ".", "new", "(", "adapter", ",", "@options", "[", ":root", "]", ")", "#Change - Pass the root dir here", "begin", "@params", "=", "params", ".", "dup", "@headers", "=", "{", "}", "@response", "=", "{", "}", "@response", "[", ":errorData", "]", "=", "{", "}", "if", "VALID_COMMANDS", ".", "include?", "(", "@params", "[", ":cmd", "]", ")", "if", "@options", "[", ":thumbs", "]", "@thumb_directory", "=", "@root", "+", "@options", "[", ":thumbs_directory", "]", "@thumb_directory", ".", "mkdir", "unless", "@thumb_directory", ".", "exist?", "raise", "(", "RuntimeError", ",", "\"Unable to create thumbs directory\"", ")", "unless", "@thumb_directory", ".", "directory?", "end", "@current", "=", "@params", "[", ":current", "]", "?", "from_hash", "(", "@params", "[", ":current", "]", ")", ":", "nil", "@target", "=", "(", "@params", "[", ":target", "]", "and", "!", "@params", "[", ":target", "]", ".", "empty?", ")", "?", "from_hash", "(", "@params", "[", ":target", "]", ")", ":", "nil", "if", "params", "[", ":targets", "]", "@targets", "=", "@params", "[", ":targets", "]", ".", "map", "{", "|", "t", "|", "from_hash", "(", "t", ")", "}", "end", "begin", "send", "(", "\"_#{@params[:cmd]}\"", ")", "rescue", "Exception", "=>", "exception", "puts", "exception", ".", "message", "puts", "exception", ".", "backtrace", ".", "inspect", "@response", "[", ":error", "]", "=", "'Access Denied'", "end", "else", "invalid_request", "end", "@response", ".", "delete", "(", ":errorData", ")", "if", "@response", "[", ":errorData", "]", ".", "empty?", "return", "@headers", ",", "@response", "ensure", "adapter", ".", "close", "end", "end" ]
Runs request-response cycle. @param [Hash] params Request parameters. :cmd option is required. @option params [String] :cmd Command to be performed. @see VALID_COMMANDS
[ "Runs", "request", "-", "response", "cycle", "." ]
df7e9d5792949f466cafecdbac9b6289ebbe4224
https://github.com/raulanatol/el_finder_s3/blob/df7e9d5792949f466cafecdbac9b6289ebbe4224/lib/el_finder_s3/connector.rb#L78-L120
4,581
rkday/ruby-diameter
lib/diameter/stack.rb
Diameter.Stack.add_handler
def add_handler(app_id, opts={}, &blk) vendor = opts.fetch(:vendor, 0) auth = opts.fetch(:auth, false) acct = opts.fetch(:acct, false) raise ArgumentError.new("Must specify at least one of auth or acct") unless auth or acct @acct_apps << [app_id, vendor] if acct @auth_apps << [app_id, vendor] if auth @handlers[app_id] = blk end
ruby
def add_handler(app_id, opts={}, &blk) vendor = opts.fetch(:vendor, 0) auth = opts.fetch(:auth, false) acct = opts.fetch(:acct, false) raise ArgumentError.new("Must specify at least one of auth or acct") unless auth or acct @acct_apps << [app_id, vendor] if acct @auth_apps << [app_id, vendor] if auth @handlers[app_id] = blk end
[ "def", "add_handler", "(", "app_id", ",", "opts", "=", "{", "}", ",", "&", "blk", ")", "vendor", "=", "opts", ".", "fetch", "(", ":vendor", ",", "0", ")", "auth", "=", "opts", ".", "fetch", "(", ":auth", ",", "false", ")", "acct", "=", "opts", ".", "fetch", "(", ":acct", ",", "false", ")", "raise", "ArgumentError", ".", "new", "(", "\"Must specify at least one of auth or acct\"", ")", "unless", "auth", "or", "acct", "@acct_apps", "<<", "[", "app_id", ",", "vendor", "]", "if", "acct", "@auth_apps", "<<", "[", "app_id", ",", "vendor", "]", "if", "auth", "@handlers", "[", "app_id", "]", "=", "blk", "end" ]
Adds a handler for a specific Diameter application. @note If you expect to only send requests for this application, not receive them, the block can be a no-op (e.g. `{ nil }`) @param app_id [Fixnum] The Diameter application ID. @option opts [true, false] auth Whether we should advertise support for this application in the Auth-Application-ID AVP. Note that at least one of auth or acct must be specified. @option opts [true, false] acct Whether we should advertise support for this application in the Acct-Application-ID AVP. Note that at least one of auth or acct must be specified. @option opts [Fixnum] vendor If we should advertise support for this application in a Vendor-Specific-Application-Id AVP, this specifies the associated Vendor-Id. @yield [req, cxn] Passes a Diameter message (and its originating connection) for application-specific handling. @yieldparam [Message] req The parsed Diameter message from the peer. @yieldparam [Socket] cxn The TCP connection to the peer, to be passed to {Stack#send_answer}.
[ "Adds", "a", "handler", "for", "a", "specific", "Diameter", "application", "." ]
83def68f67cf660aa227eac4c74719dc98aacab2
https://github.com/rkday/ruby-diameter/blob/83def68f67cf660aa227eac4c74719dc98aacab2/lib/diameter/stack.rb#L91-L102
4,582
rkday/ruby-diameter
lib/diameter/stack.rb
Diameter.Stack.connect_to_peer
def connect_to_peer(peer_uri, peer_host, realm) peer = Peer.new(peer_host, realm) @peer_table[peer_host] = peer @peer_table[peer_host].state = :WAITING # Will move to :UP when the CEA is received uri = URI(peer_uri) cxn = @tcp_helper.setup_new_connection(uri.host, uri.port) @peer_table[peer_host].cxn = cxn avps = [AVP.create('Origin-Host', @local_host), AVP.create('Origin-Realm', @local_realm), AVP.create('Host-IP-Address', IPAddr.new('127.0.0.1')), AVP.create('Vendor-Id', 100), AVP.create('Product-Name', 'ruby-diameter') ] avps += app_avps cer_bytes = Message.new(version: 1, command_code: 257, app_id: 0, request: true, proxyable: false, retransmitted: false, error: false, avps: avps).to_wire @tcp_helper.send(cer_bytes, cxn) peer end
ruby
def connect_to_peer(peer_uri, peer_host, realm) peer = Peer.new(peer_host, realm) @peer_table[peer_host] = peer @peer_table[peer_host].state = :WAITING # Will move to :UP when the CEA is received uri = URI(peer_uri) cxn = @tcp_helper.setup_new_connection(uri.host, uri.port) @peer_table[peer_host].cxn = cxn avps = [AVP.create('Origin-Host', @local_host), AVP.create('Origin-Realm', @local_realm), AVP.create('Host-IP-Address', IPAddr.new('127.0.0.1')), AVP.create('Vendor-Id', 100), AVP.create('Product-Name', 'ruby-diameter') ] avps += app_avps cer_bytes = Message.new(version: 1, command_code: 257, app_id: 0, request: true, proxyable: false, retransmitted: false, error: false, avps: avps).to_wire @tcp_helper.send(cer_bytes, cxn) peer end
[ "def", "connect_to_peer", "(", "peer_uri", ",", "peer_host", ",", "realm", ")", "peer", "=", "Peer", ".", "new", "(", "peer_host", ",", "realm", ")", "@peer_table", "[", "peer_host", "]", "=", "peer", "@peer_table", "[", "peer_host", "]", ".", "state", "=", ":WAITING", "# Will move to :UP when the CEA is received", "uri", "=", "URI", "(", "peer_uri", ")", "cxn", "=", "@tcp_helper", ".", "setup_new_connection", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "@peer_table", "[", "peer_host", "]", ".", "cxn", "=", "cxn", "avps", "=", "[", "AVP", ".", "create", "(", "'Origin-Host'", ",", "@local_host", ")", ",", "AVP", ".", "create", "(", "'Origin-Realm'", ",", "@local_realm", ")", ",", "AVP", ".", "create", "(", "'Host-IP-Address'", ",", "IPAddr", ".", "new", "(", "'127.0.0.1'", ")", ")", ",", "AVP", ".", "create", "(", "'Vendor-Id'", ",", "100", ")", ",", "AVP", ".", "create", "(", "'Product-Name'", ",", "'ruby-diameter'", ")", "]", "avps", "+=", "app_avps", "cer_bytes", "=", "Message", ".", "new", "(", "version", ":", "1", ",", "command_code", ":", "257", ",", "app_id", ":", "0", ",", "request", ":", "true", ",", "proxyable", ":", "false", ",", "retransmitted", ":", "false", ",", "error", ":", "false", ",", "avps", ":", "avps", ")", ".", "to_wire", "@tcp_helper", ".", "send", "(", "cer_bytes", ",", "cxn", ")", "peer", "end" ]
Creates a Peer connection to a Diameter agent at the specific network location indicated by peer_uri. @param peer_uri [URI] The aaa:// URI identifying the peer. Should contain a hostname/IP; may contain a port (default 3868). @param peer_host [String] The DiameterIdentity of this peer, which will uniquely identify it in the peer table. @param realm [String] The Diameter realm of this peer. @return [Peer] The Diameter peer chosen.
[ "Creates", "a", "Peer", "connection", "to", "a", "Diameter", "agent", "at", "the", "specific", "network", "location", "indicated", "by", "peer_uri", "." ]
83def68f67cf660aa227eac4c74719dc98aacab2
https://github.com/rkday/ruby-diameter/blob/83def68f67cf660aa227eac4c74719dc98aacab2/lib/diameter/stack.rb#L161-L182
4,583
qw3/getnet_api
lib/getnet_api/credit.rb
GetnetApi.Credit.to_request
def to_request credit = { delayed: self.delayed, authenticated: self.authenticated, pre_authorization: self.pre_authorization, save_card_data: self.save_card_data, transaction_type: self.transaction_type, number_installments: self.number_installments.to_i, soft_descriptor: self.soft_descriptor, dynamic_mcc: self.dynamic_mcc, card: self.card.to_request, } return credit end
ruby
def to_request credit = { delayed: self.delayed, authenticated: self.authenticated, pre_authorization: self.pre_authorization, save_card_data: self.save_card_data, transaction_type: self.transaction_type, number_installments: self.number_installments.to_i, soft_descriptor: self.soft_descriptor, dynamic_mcc: self.dynamic_mcc, card: self.card.to_request, } return credit end
[ "def", "to_request", "credit", "=", "{", "delayed", ":", "self", ".", "delayed", ",", "authenticated", ":", "self", ".", "authenticated", ",", "pre_authorization", ":", "self", ".", "pre_authorization", ",", "save_card_data", ":", "self", ".", "save_card_data", ",", "transaction_type", ":", "self", ".", "transaction_type", ",", "number_installments", ":", "self", ".", "number_installments", ".", "to_i", ",", "soft_descriptor", ":", "self", ".", "soft_descriptor", ",", "dynamic_mcc", ":", "self", ".", "dynamic_mcc", ",", "card", ":", "self", ".", "card", ".", "to_request", ",", "}", "return", "credit", "end" ]
Nova instancia da classe Credit @param [Hash] campos Montar o Hash de dados do pagamento no padrão utilizado pela Getnet
[ "Nova", "instancia", "da", "classe", "Credit" ]
94cbda66aab03d83ea38bc5325ea2a02a639e922
https://github.com/qw3/getnet_api/blob/94cbda66aab03d83ea38bc5325ea2a02a639e922/lib/getnet_api/credit.rb#L71-L85
4,584
chrismagnacca/newegg-api
lib/newegg/api.rb
Newegg.Api.stores
def stores return self._stores if not self._stores.empty? response = api_get("Stores.egg") stores = JSON.parse(response.body) stores.each do |store| self._stores << Newegg::Store.new(store['Title'], store['StoreDepa'], store['StoreID'], store['ShowSeeAllDeals']) end self._stores end
ruby
def stores return self._stores if not self._stores.empty? response = api_get("Stores.egg") stores = JSON.parse(response.body) stores.each do |store| self._stores << Newegg::Store.new(store['Title'], store['StoreDepa'], store['StoreID'], store['ShowSeeAllDeals']) end self._stores end
[ "def", "stores", "return", "self", ".", "_stores", "if", "not", "self", ".", "_stores", ".", "empty?", "response", "=", "api_get", "(", "\"Stores.egg\"", ")", "stores", "=", "JSON", ".", "parse", "(", "response", ".", "body", ")", "stores", ".", "each", "do", "|", "store", "|", "self", ".", "_stores", "<<", "Newegg", "::", "Store", ".", "new", "(", "store", "[", "'Title'", "]", ",", "store", "[", "'StoreDepa'", "]", ",", "store", "[", "'StoreID'", "]", ",", "store", "[", "'ShowSeeAllDeals'", "]", ")", "end", "self", ".", "_stores", "end" ]
retrieve and populate a list of available stores
[ "retrieve", "and", "populate", "a", "list", "of", "available", "stores" ]
c362058eef09a8966625a88d6b3e25c4345f757c
https://github.com/chrismagnacca/newegg-api/blob/c362058eef09a8966625a88d6b3e25c4345f757c/lib/newegg/api.rb#L32-L40
4,585
chrismagnacca/newegg-api
lib/newegg/api.rb
Newegg.Api.categories
def categories(store_id) return [] if store_id.nil? response = api_get("Stores.egg", "Categories", store_id) categories = JSON.parse(response.body) categories = categories.collect do |category| Newegg::Category.new(category['Description'], category['CategoryType'], category['CategoryID'], category['StoreID'], category['ShowSeeAllDeals'], category['NodeId']) end categories end
ruby
def categories(store_id) return [] if store_id.nil? response = api_get("Stores.egg", "Categories", store_id) categories = JSON.parse(response.body) categories = categories.collect do |category| Newegg::Category.new(category['Description'], category['CategoryType'], category['CategoryID'], category['StoreID'], category['ShowSeeAllDeals'], category['NodeId']) end categories end
[ "def", "categories", "(", "store_id", ")", "return", "[", "]", "if", "store_id", ".", "nil?", "response", "=", "api_get", "(", "\"Stores.egg\"", ",", "\"Categories\"", ",", "store_id", ")", "categories", "=", "JSON", ".", "parse", "(", "response", ".", "body", ")", "categories", "=", "categories", ".", "collect", "do", "|", "category", "|", "Newegg", "::", "Category", ".", "new", "(", "category", "[", "'Description'", "]", ",", "category", "[", "'CategoryType'", "]", ",", "category", "[", "'CategoryID'", "]", ",", "category", "[", "'StoreID'", "]", ",", "category", "[", "'ShowSeeAllDeals'", "]", ",", "category", "[", "'NodeId'", "]", ")", "end", "categories", "end" ]
retrieve and populate list of categories for a given store_id @param [Integer] store_id of the store
[ "retrieve", "and", "populate", "list", "of", "categories", "for", "a", "given", "store_id" ]
c362058eef09a8966625a88d6b3e25c4345f757c
https://github.com/chrismagnacca/newegg-api/blob/c362058eef09a8966625a88d6b3e25c4345f757c/lib/newegg/api.rb#L47-L58
4,586
chrismagnacca/newegg-api
lib/newegg/api.rb
Newegg.Api.store_content
def store_content(store_id, category_id = -1, node_id = -1, store_type = 4, page_number = 1) params = { 'storeId' => store_id, 'categoryId' => category_id, 'nodeId' => node_id, 'storeType' => store_type, 'pageNumber' => page_number } JSON.parse(api_get('Stores.egg', 'Content', nil, params).body) end
ruby
def store_content(store_id, category_id = -1, node_id = -1, store_type = 4, page_number = 1) params = { 'storeId' => store_id, 'categoryId' => category_id, 'nodeId' => node_id, 'storeType' => store_type, 'pageNumber' => page_number } JSON.parse(api_get('Stores.egg', 'Content', nil, params).body) end
[ "def", "store_content", "(", "store_id", ",", "category_id", "=", "-", "1", ",", "node_id", "=", "-", "1", ",", "store_type", "=", "4", ",", "page_number", "=", "1", ")", "params", "=", "{", "'storeId'", "=>", "store_id", ",", "'categoryId'", "=>", "category_id", ",", "'nodeId'", "=>", "node_id", ",", "'storeType'", "=>", "store_type", ",", "'pageNumber'", "=>", "page_number", "}", "JSON", ".", "parse", "(", "api_get", "(", "'Stores.egg'", ",", "'Content'", ",", "nil", ",", "params", ")", ".", "body", ")", "end" ]
retrieves store content
[ "retrieves", "store", "content" ]
c362058eef09a8966625a88d6b3e25c4345f757c
https://github.com/chrismagnacca/newegg-api/blob/c362058eef09a8966625a88d6b3e25c4345f757c/lib/newegg/api.rb#L75-L84
4,587
chrismagnacca/newegg-api
lib/newegg/api.rb
Newegg.Api.search
def search(options={}) options = {store_id: -1, category_id: -1, sub_category_id: -1, node_id: -1, page_number: 1, sort: "FEATURED", keywords: ""}.merge(options) request = { 'IsUPCCodeSearch' => false, 'IsSubCategorySearch' => options[:sub_category_id] > 0, 'isGuideAdvanceSearch' => false, 'StoreDepaId' => options[:store_id], 'CategoryId' => options[:category_id], 'SubCategoryId' => options[:sub_category_id], 'NodeId' => options[:node_id], 'BrandId' => -1, 'NValue' => "", 'Keyword' => options[:keywords], 'Sort' => options[:sort], 'PageNumber' => options[:page_number] } JSON.parse(api_post("Search.egg", "Advanced", request).body, {quirks_mode: true}) end
ruby
def search(options={}) options = {store_id: -1, category_id: -1, sub_category_id: -1, node_id: -1, page_number: 1, sort: "FEATURED", keywords: ""}.merge(options) request = { 'IsUPCCodeSearch' => false, 'IsSubCategorySearch' => options[:sub_category_id] > 0, 'isGuideAdvanceSearch' => false, 'StoreDepaId' => options[:store_id], 'CategoryId' => options[:category_id], 'SubCategoryId' => options[:sub_category_id], 'NodeId' => options[:node_id], 'BrandId' => -1, 'NValue' => "", 'Keyword' => options[:keywords], 'Sort' => options[:sort], 'PageNumber' => options[:page_number] } JSON.parse(api_post("Search.egg", "Advanced", request).body, {quirks_mode: true}) end
[ "def", "search", "(", "options", "=", "{", "}", ")", "options", "=", "{", "store_id", ":", "-", "1", ",", "category_id", ":", "-", "1", ",", "sub_category_id", ":", "-", "1", ",", "node_id", ":", "-", "1", ",", "page_number", ":", "1", ",", "sort", ":", "\"FEATURED\"", ",", "keywords", ":", "\"\"", "}", ".", "merge", "(", "options", ")", "request", "=", "{", "'IsUPCCodeSearch'", "=>", "false", ",", "'IsSubCategorySearch'", "=>", "options", "[", ":sub_category_id", "]", ">", "0", ",", "'isGuideAdvanceSearch'", "=>", "false", ",", "'StoreDepaId'", "=>", "options", "[", ":store_id", "]", ",", "'CategoryId'", "=>", "options", "[", ":category_id", "]", ",", "'SubCategoryId'", "=>", "options", "[", ":sub_category_id", "]", ",", "'NodeId'", "=>", "options", "[", ":node_id", "]", ",", "'BrandId'", "=>", "-", "1", ",", "'NValue'", "=>", "\"\"", ",", "'Keyword'", "=>", "options", "[", ":keywords", "]", ",", "'Sort'", "=>", "options", "[", ":sort", "]", ",", "'PageNumber'", "=>", "options", "[", ":page_number", "]", "}", "JSON", ".", "parse", "(", "api_post", "(", "\"Search.egg\"", ",", "\"Advanced\"", ",", "request", ")", ".", "body", ",", "{", "quirks_mode", ":", "true", "}", ")", "end" ]
retrieves a single page of products given a query specified by an options hash. See options below. node_id, page_number, and an optional sorting method @param [Integer] store_id, from @api.navigation, returned as StoreID @param [Integer] category_id from @api.navigation, returned as CategoryType @param [Integer] sub_category_id from @api.navigation, returned as CategoryID @param [Integer] node_id from @api.navigation, returned as NodeId @param [Integer] page_number of the paginated search results, returned as PaginationInfo from search @param [String] sort style of the returned search results, default is FEATURED (can also be RATING, PRICE, PRICED, REVIEWS) @param [String] keywords
[ "retrieves", "a", "single", "page", "of", "products", "given", "a", "query", "specified", "by", "an", "options", "hash", ".", "See", "options", "below", ".", "node_id", "page_number", "and", "an", "optional", "sorting", "method" ]
c362058eef09a8966625a88d6b3e25c4345f757c
https://github.com/chrismagnacca/newegg-api/blob/c362058eef09a8966625a88d6b3e25c4345f757c/lib/newegg/api.rb#L127-L146
4,588
chrismagnacca/newegg-api
lib/newegg/api.rb
Newegg.Api.combo_deals
def combo_deals(item_number, options={}) options = {sub_category: -1, sort_field: 0, page_number: 1}.merge(options) params = { 'SubCategory' => options[:sub_category], 'SortField' => options[:sort_field], 'PageNumber' => options[:page_number] } JSON.parse(api_get('Products.egg', item_number, 'ComboDeals', params).body) end
ruby
def combo_deals(item_number, options={}) options = {sub_category: -1, sort_field: 0, page_number: 1}.merge(options) params = { 'SubCategory' => options[:sub_category], 'SortField' => options[:sort_field], 'PageNumber' => options[:page_number] } JSON.parse(api_get('Products.egg', item_number, 'ComboDeals', params).body) end
[ "def", "combo_deals", "(", "item_number", ",", "options", "=", "{", "}", ")", "options", "=", "{", "sub_category", ":", "-", "1", ",", "sort_field", ":", "0", ",", "page_number", ":", "1", "}", ".", "merge", "(", "options", ")", "params", "=", "{", "'SubCategory'", "=>", "options", "[", ":sub_category", "]", ",", "'SortField'", "=>", "options", "[", ":sort_field", "]", ",", "'PageNumber'", "=>", "options", "[", ":page_number", "]", "}", "JSON", ".", "parse", "(", "api_get", "(", "'Products.egg'", ",", "item_number", ",", "'ComboDeals'", ",", "params", ")", ".", "body", ")", "end" ]
retrieve product combo deals given an item number @param [String] item_number of the product @param [Integer] sub_category @param [Integer] sort_field @param [Integer] page_number
[ "retrieve", "product", "combo", "deals", "given", "an", "item", "number" ]
c362058eef09a8966625a88d6b3e25c4345f757c
https://github.com/chrismagnacca/newegg-api/blob/c362058eef09a8966625a88d6b3e25c4345f757c/lib/newegg/api.rb#L262-L270
4,589
chrismagnacca/newegg-api
lib/newegg/api.rb
Newegg.Api.reviews
def reviews(item_number, page_number = 1, options={}) options = {time: 'all', rating: 'All', sort: 'date posted'}.merge(options) params = { 'filter.time' => options[:time], 'filter.rating' => options[:rating], 'sort' => options[:sort] } JSON.parse(api_get('Products.egg', item_number, "Reviewsinfo/#{page_number}", params).body) end
ruby
def reviews(item_number, page_number = 1, options={}) options = {time: 'all', rating: 'All', sort: 'date posted'}.merge(options) params = { 'filter.time' => options[:time], 'filter.rating' => options[:rating], 'sort' => options[:sort] } JSON.parse(api_get('Products.egg', item_number, "Reviewsinfo/#{page_number}", params).body) end
[ "def", "reviews", "(", "item_number", ",", "page_number", "=", "1", ",", "options", "=", "{", "}", ")", "options", "=", "{", "time", ":", "'all'", ",", "rating", ":", "'All'", ",", "sort", ":", "'date posted'", "}", ".", "merge", "(", "options", ")", "params", "=", "{", "'filter.time'", "=>", "options", "[", ":time", "]", ",", "'filter.rating'", "=>", "options", "[", ":rating", "]", ",", "'sort'", "=>", "options", "[", ":sort", "]", "}", "JSON", ".", "parse", "(", "api_get", "(", "'Products.egg'", ",", "item_number", ",", "\"Reviewsinfo/#{page_number}\"", ",", "params", ")", ".", "body", ")", "end" ]
retrieve product reviews given an item number @param [String] item_number of the product @param [Integer] page_number @param [String] time @param [String] rating default All (can also be 5, 4, 3, 2, 1) @param [String] sort default 'date posted' (can also be 'most helpful', 'highest rated', 'lowest rated', 'ownership')
[ "retrieve", "product", "reviews", "given", "an", "item", "number" ]
c362058eef09a8966625a88d6b3e25c4345f757c
https://github.com/chrismagnacca/newegg-api/blob/c362058eef09a8966625a88d6b3e25c4345f757c/lib/newegg/api.rb#L281-L289
4,590
zerowidth/camper_van
lib/camper_van/channel.rb
CamperVan.Channel.current_mode_string
def current_mode_string n = room.membership_limit s = room.open_to_guests? ? "" : "s" i = room.locked? ? "i" : "" "+#{i}l#{s}" end
ruby
def current_mode_string n = room.membership_limit s = room.open_to_guests? ? "" : "s" i = room.locked? ? "i" : "" "+#{i}l#{s}" end
[ "def", "current_mode_string", "n", "=", "room", ".", "membership_limit", "s", "=", "room", ".", "open_to_guests?", "?", "\"\"", ":", "\"s\"", "i", "=", "room", ".", "locked?", "?", "\"i\"", ":", "\"\"", "\"+#{i}l#{s}\"", "end" ]
Returns the current mode string
[ "Returns", "the", "current", "mode", "string" ]
984351a3b472e936a451f1d1cd987ca27d981d23
https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/channel.rb#L169-L174
4,591
zerowidth/camper_van
lib/camper_van/channel.rb
CamperVan.Channel.user_for_message
def user_for_message(message) if user = users[message.user_id] yield message, user else message.user do |user| yield message, user end end end
ruby
def user_for_message(message) if user = users[message.user_id] yield message, user else message.user do |user| yield message, user end end end
[ "def", "user_for_message", "(", "message", ")", "if", "user", "=", "users", "[", "message", ".", "user_id", "]", "yield", "message", ",", "user", "else", "message", ".", "user", "do", "|", "user", "|", "yield", "message", ",", "user", "end", "end", "end" ]
Retrieve the user from a message, either by finding it in the current list of known users, or by asking campfire for the user. message - the message for which to look up the user Yields the message and the user associated with the message
[ "Retrieve", "the", "user", "from", "a", "message", "either", "by", "finding", "it", "in", "the", "current", "list", "of", "known", "users", "or", "by", "asking", "campfire", "for", "the", "user", "." ]
984351a3b472e936a451f1d1cd987ca27d981d23
https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/channel.rb#L381-L389
4,592
sleewoo/minispec
lib/minispec/api/class/around.rb
MiniSpec.ClassAPI.around
def around *matchers, &proc proc || raise(ArgumentError, 'block is missing') matchers.flatten! matchers = [:*] if matchers.empty? return if around?.find {|x| x[0] == matchers && x[1].source_location == proc.source_location} around?.push([matchers, proc]) end
ruby
def around *matchers, &proc proc || raise(ArgumentError, 'block is missing') matchers.flatten! matchers = [:*] if matchers.empty? return if around?.find {|x| x[0] == matchers && x[1].source_location == proc.source_location} around?.push([matchers, proc]) end
[ "def", "around", "*", "matchers", ",", "&", "proc", "proc", "||", "raise", "(", "ArgumentError", ",", "'block is missing'", ")", "matchers", ".", "flatten!", "matchers", "=", "[", ":*", "]", "if", "matchers", ".", "empty?", "return", "if", "around?", ".", "find", "{", "|", "x", "|", "x", "[", "0", "]", "==", "matchers", "&&", "x", "[", "1", "]", ".", "source_location", "==", "proc", ".", "source_location", "}", "around?", ".", "push", "(", "[", "matchers", ",", "proc", "]", ")", "end" ]
a block to wrap each test evaluation @example describe SomeClass do around do |test| DB.connect test.run DB.disconnect end end
[ "a", "block", "to", "wrap", "each", "test", "evaluation" ]
6dcdacd041cc031c21f2fe70b6e5b22c6af636c5
https://github.com/sleewoo/minispec/blob/6dcdacd041cc031c21f2fe70b6e5b22c6af636c5/lib/minispec/api/class/around.rb#L16-L22
4,593
AssemDeghady/questionpro_rails
lib/questionpro_rails/email_list.rb
QuestionproRails.EmailList.statistics
def statistics extracted_statistics = [] unless self.qp_statistics.nil? extracted_statistics.push(EmailListStatistic.new(qp_statistics)) end return extracted_statistics end
ruby
def statistics extracted_statistics = [] unless self.qp_statistics.nil? extracted_statistics.push(EmailListStatistic.new(qp_statistics)) end return extracted_statistics end
[ "def", "statistics", "extracted_statistics", "=", "[", "]", "unless", "self", ".", "qp_statistics", ".", "nil?", "extracted_statistics", ".", "push", "(", "EmailListStatistic", ".", "new", "(", "qp_statistics", ")", ")", "end", "return", "extracted_statistics", "end" ]
Extract the email list statistics from qp_statistics attribute. @return [QuestionproRails::EmailListStatistic] Email List Statistics.
[ "Extract", "the", "email", "list", "statistics", "from", "qp_statistics", "attribute", "." ]
79f295f193b6ad593f4d56d8edfa3076a23d8e4f
https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/email_list.rb#L31-L39
4,594
ezkl/capit
lib/capit/capture.rb
CapIt.Capture.capture_command
def capture_command cmd = "#{@cutycapt_path} --url='#{@url}'" cmd += " --out='#{@folder}/#{@filename}'" cmd += " --max-wait=#{@max_wait}" cmd += " --delay=#{@delay}" if @delay cmd += " --user-agent='#{@user_agent}'" cmd += " --min-width='#{@min_width}'" cmd += " --min-height='#{@min_height}'" if determine_os == :linux and check_xvfb xvfb = 'xvfb-run --server-args="-screen 0, 1024x768x24" ' xvfb.concat(cmd) else cmd end end
ruby
def capture_command cmd = "#{@cutycapt_path} --url='#{@url}'" cmd += " --out='#{@folder}/#{@filename}'" cmd += " --max-wait=#{@max_wait}" cmd += " --delay=#{@delay}" if @delay cmd += " --user-agent='#{@user_agent}'" cmd += " --min-width='#{@min_width}'" cmd += " --min-height='#{@min_height}'" if determine_os == :linux and check_xvfb xvfb = 'xvfb-run --server-args="-screen 0, 1024x768x24" ' xvfb.concat(cmd) else cmd end end
[ "def", "capture_command", "cmd", "=", "\"#{@cutycapt_path} --url='#{@url}'\"", "cmd", "+=", "\" --out='#{@folder}/#{@filename}'\"", "cmd", "+=", "\" --max-wait=#{@max_wait}\"", "cmd", "+=", "\" --delay=#{@delay}\"", "if", "@delay", "cmd", "+=", "\" --user-agent='#{@user_agent}'\"", "cmd", "+=", "\" --min-width='#{@min_width}'\"", "cmd", "+=", "\" --min-height='#{@min_height}'\"", "if", "determine_os", "==", ":linux", "and", "check_xvfb", "xvfb", "=", "'xvfb-run --server-args=\"-screen 0, 1024x768x24\" '", "xvfb", ".", "concat", "(", "cmd", ")", "else", "cmd", "end", "end" ]
Produces the command used to run CutyCapt. @return [String]
[ "Produces", "the", "command", "used", "to", "run", "CutyCapt", "." ]
f726e1774a25c4c61f0eab1118e6cffa6ccdbd64
https://github.com/ezkl/capit/blob/f726e1774a25c4c61f0eab1118e6cffa6ccdbd64/lib/capit/capture.rb#L118-L134
4,595
sosedoff/munin-ruby
lib/munin-ruby/parser.rb
Munin.Parser.parse_config
def parse_config(data) config = {'graph' => {}, 'metrics' => {}} data.each do |l| if l =~ /^graph_/ key_name, value = l.scan(/^graph_([\w]+)\s(.*)/).flatten config['graph'][key_name] = value # according to http://munin-monitoring.org/wiki/notes_on_datasource_names elsif l =~ /^[a-zA-Z_][a-zA-Z\d_]*\./ # according to http://munin-monitoring.org/wiki/fieldnames the second one # can only be [a-z] matches = l.scan(/^([a-zA-Z_][a-zA-Z\d_]*)\.([a-z]+)\s(.*)/).flatten config['metrics'][matches[0]] ||= {} config['metrics'][matches[0]][matches[1]] = matches[2] end end # Now, lets process the args hash if config['graph'].key?('args') config['graph']['args'] = parse_config_args(config['graph']['args']) end config end
ruby
def parse_config(data) config = {'graph' => {}, 'metrics' => {}} data.each do |l| if l =~ /^graph_/ key_name, value = l.scan(/^graph_([\w]+)\s(.*)/).flatten config['graph'][key_name] = value # according to http://munin-monitoring.org/wiki/notes_on_datasource_names elsif l =~ /^[a-zA-Z_][a-zA-Z\d_]*\./ # according to http://munin-monitoring.org/wiki/fieldnames the second one # can only be [a-z] matches = l.scan(/^([a-zA-Z_][a-zA-Z\d_]*)\.([a-z]+)\s(.*)/).flatten config['metrics'][matches[0]] ||= {} config['metrics'][matches[0]][matches[1]] = matches[2] end end # Now, lets process the args hash if config['graph'].key?('args') config['graph']['args'] = parse_config_args(config['graph']['args']) end config end
[ "def", "parse_config", "(", "data", ")", "config", "=", "{", "'graph'", "=>", "{", "}", ",", "'metrics'", "=>", "{", "}", "}", "data", ".", "each", "do", "|", "l", "|", "if", "l", "=~", "/", "/", "key_name", ",", "value", "=", "l", ".", "scan", "(", "/", "\\w", "\\s", "/", ")", ".", "flatten", "config", "[", "'graph'", "]", "[", "key_name", "]", "=", "value", "# according to http://munin-monitoring.org/wiki/notes_on_datasource_names", "elsif", "l", "=~", "/", "\\d", "\\.", "/", "# according to http://munin-monitoring.org/wiki/fieldnames the second one", "# can only be [a-z]", "matches", "=", "l", ".", "scan", "(", "/", "\\d", "\\.", "\\s", "/", ")", ".", "flatten", "config", "[", "'metrics'", "]", "[", "matches", "[", "0", "]", "]", "||=", "{", "}", "config", "[", "'metrics'", "]", "[", "matches", "[", "0", "]", "]", "[", "matches", "[", "1", "]", "]", "=", "matches", "[", "2", "]", "end", "end", "# Now, lets process the args hash", "if", "config", "[", "'graph'", "]", ".", "key?", "(", "'args'", ")", "config", "[", "'graph'", "]", "[", "'args'", "]", "=", "parse_config_args", "(", "config", "[", "'graph'", "]", "[", "'args'", "]", ")", "end", "config", "end" ]
Parse 'config' request
[ "Parse", "config", "request" ]
28f65b0abb88fc40e234b6af327094992504be6a
https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/parser.rb#L27-L49
4,596
sosedoff/munin-ruby
lib/munin-ruby/parser.rb
Munin.Parser.parse_error
def parse_error(lines) if lines.size == 1 case lines.first when '# Unknown service' then raise UnknownService when '# Bad exit' then raise BadExit end end end
ruby
def parse_error(lines) if lines.size == 1 case lines.first when '# Unknown service' then raise UnknownService when '# Bad exit' then raise BadExit end end end
[ "def", "parse_error", "(", "lines", ")", "if", "lines", ".", "size", "==", "1", "case", "lines", ".", "first", "when", "'# Unknown service'", "then", "raise", "UnknownService", "when", "'# Bad exit'", "then", "raise", "BadExit", "end", "end", "end" ]
Detect error from output
[ "Detect", "error", "from", "output" ]
28f65b0abb88fc40e234b6af327094992504be6a
https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/parser.rb#L59-L66
4,597
sosedoff/munin-ruby
lib/munin-ruby/parser.rb
Munin.Parser.parse_config_args
def parse_config_args(args) result = {} args.scan(/--?([a-z\-\_]+)\s([\d]+)\s?/).each do |arg| result[arg.first] = arg.last end {'raw' => args, 'parsed' => result} end
ruby
def parse_config_args(args) result = {} args.scan(/--?([a-z\-\_]+)\s([\d]+)\s?/).each do |arg| result[arg.first] = arg.last end {'raw' => args, 'parsed' => result} end
[ "def", "parse_config_args", "(", "args", ")", "result", "=", "{", "}", "args", ".", "scan", "(", "/", "\\-", "\\_", "\\s", "\\d", "\\s", "/", ")", ".", "each", "do", "|", "arg", "|", "result", "[", "arg", ".", "first", "]", "=", "arg", ".", "last", "end", "{", "'raw'", "=>", "args", ",", "'parsed'", "=>", "result", "}", "end" ]
Parse configuration arguments
[ "Parse", "configuration", "arguments" ]
28f65b0abb88fc40e234b6af327094992504be6a
https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/parser.rb#L70-L76
4,598
ocha/devise_ott
lib/devise_ott/tokens.rb
DeviseOtt.Tokens.register
def register(token, email, granted_to_email, access_count, expire) save_config(token, {email: email, granted_to_email: granted_to_email, access_count: access_count}) @redis.expire(token, expire) token end
ruby
def register(token, email, granted_to_email, access_count, expire) save_config(token, {email: email, granted_to_email: granted_to_email, access_count: access_count}) @redis.expire(token, expire) token end
[ "def", "register", "(", "token", ",", "email", ",", "granted_to_email", ",", "access_count", ",", "expire", ")", "save_config", "(", "token", ",", "{", "email", ":", "email", ",", "granted_to_email", ":", "granted_to_email", ",", "access_count", ":", "access_count", "}", ")", "@redis", ".", "expire", "(", "token", ",", "expire", ")", "token", "end" ]
register one time token for given user in redis the generated token will have a field "email" in order to identify the associated user later
[ "register", "one", "time", "token", "for", "given", "user", "in", "redis", "the", "generated", "token", "will", "have", "a", "field", "email", "in", "order", "to", "identify", "the", "associated", "user", "later" ]
ebf39fff2ef1d4f901db11994b0ebafdfcddb0ea
https://github.com/ocha/devise_ott/blob/ebf39fff2ef1d4f901db11994b0ebafdfcddb0ea/lib/devise_ott/tokens.rb#L18-L23
4,599
ocha/devise_ott
lib/devise_ott/tokens.rb
DeviseOtt.Tokens.access
def access(token, email) config = load_config(token) return false unless config return false unless config[:email].to_s == email.to_s return false unless config[:access_count] > 0 save_config(token, config.merge(access_count: config[:access_count] - 1)) true end
ruby
def access(token, email) config = load_config(token) return false unless config return false unless config[:email].to_s == email.to_s return false unless config[:access_count] > 0 save_config(token, config.merge(access_count: config[:access_count] - 1)) true end
[ "def", "access", "(", "token", ",", "email", ")", "config", "=", "load_config", "(", "token", ")", "return", "false", "unless", "config", "return", "false", "unless", "config", "[", ":email", "]", ".", "to_s", "==", "email", ".", "to_s", "return", "false", "unless", "config", "[", ":access_count", "]", ">", "0", "save_config", "(", "token", ",", "config", ".", "merge", "(", "access_count", ":", "config", "[", ":access_count", "]", "-", "1", ")", ")", "true", "end" ]
accesses token for given email if it is allowed
[ "accesses", "token", "for", "given", "email", "if", "it", "is", "allowed" ]
ebf39fff2ef1d4f901db11994b0ebafdfcddb0ea
https://github.com/ocha/devise_ott/blob/ebf39fff2ef1d4f901db11994b0ebafdfcddb0ea/lib/devise_ott/tokens.rb#L31-L41