id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
|
|---|---|---|---|---|---|---|---|---|---|---|---|
8,900
|
kamui/kanpachi
|
lib/kanpachi/resource_list.rb
|
Kanpachi.ResourceList.named
|
def named(name)
resource = all.detect { |resource| resource.name == name }
if resource.nil?
raise UnknownResource, "Resource named #{name} doesn't exist"
else
resource
end
end
|
ruby
|
def named(name)
resource = all.detect { |resource| resource.name == name }
if resource.nil?
raise UnknownResource, "Resource named #{name} doesn't exist"
else
resource
end
end
|
[
"def",
"named",
"(",
"name",
")",
"resource",
"=",
"all",
".",
"detect",
"{",
"|",
"resource",
"|",
"resource",
".",
"name",
"==",
"name",
"}",
"if",
"resource",
".",
"nil?",
"raise",
"UnknownResource",
",",
"\"Resource named #{name} doesn't exist\"",
"else",
"resource",
"end",
"end"
] |
Returns a resource based on its name
@param [String] name The name of the resource you are looking for.
@raise [UnknownResource] if a resource with the passed name isn't found.
@return [Kanpachi::Resource] The found resource.
@api public
|
[
"Returns",
"a",
"resource",
"based",
"on",
"its",
"name"
] |
dbd09646bd8779ab874e1578b57a13f5747b0da7
|
https://github.com/kamui/kanpachi/blob/dbd09646bd8779ab874e1578b57a13f5747b0da7/lib/kanpachi/resource_list.rb#L49-L56
|
8,901
|
crapooze/em-xmpp
|
lib/em-xmpp/cert_store.rb
|
EM::Xmpp.CertStore.trusted?
|
def trusted?(pem)
if cert = OpenSSL::X509::Certificate.new(pem) rescue nil
@store.verify(cert).tap do |trusted|
@store.add_cert(cert) if trusted rescue nil
end
end
end
|
ruby
|
def trusted?(pem)
if cert = OpenSSL::X509::Certificate.new(pem) rescue nil
@store.verify(cert).tap do |trusted|
@store.add_cert(cert) if trusted rescue nil
end
end
end
|
[
"def",
"trusted?",
"(",
"pem",
")",
"if",
"cert",
"=",
"OpenSSL",
"::",
"X509",
"::",
"Certificate",
".",
"new",
"(",
"pem",
")",
"rescue",
"nil",
"@store",
".",
"verify",
"(",
"cert",
")",
".",
"tap",
"do",
"|",
"trusted",
"|",
"@store",
".",
"add_cert",
"(",
"cert",
")",
"if",
"trusted",
"rescue",
"nil",
"end",
"end",
"end"
] |
Return true if the certificate is signed by a CA certificate in the
store. If the certificate can be trusted, it's added to the store so
it can be used to trust other certs.
|
[
"Return",
"true",
"if",
"the",
"certificate",
"is",
"signed",
"by",
"a",
"CA",
"certificate",
"in",
"the",
"store",
".",
"If",
"the",
"certificate",
"can",
"be",
"trusted",
"it",
"s",
"added",
"to",
"the",
"store",
"so",
"it",
"can",
"be",
"used",
"to",
"trust",
"other",
"certs",
"."
] |
804e139944c88bc317b359754d5ad69b75f42319
|
https://github.com/crapooze/em-xmpp/blob/804e139944c88bc317b359754d5ad69b75f42319/lib/em-xmpp/cert_store.rb#L44-L50
|
8,902
|
crapooze/em-xmpp
|
lib/em-xmpp/cert_store.rb
|
EM::Xmpp.CertStore.certs
|
def certs
unless @@certs
pattern = /-{5}BEGIN CERTIFICATE-{5}\n.*?-{5}END CERTIFICATE-{5}\n/m
dir = @cert_directory
certs = Dir[File.join(dir, '*.crt')].map {|f| File.read(f) }
certs = certs.map {|c| c.scan(pattern) }.flatten
certs.map! {|c| OpenSSL::X509::Certificate.new(c) }
@@certs = certs.reject {|c| c.not_after < Time.now }
end
@@certs
end
|
ruby
|
def certs
unless @@certs
pattern = /-{5}BEGIN CERTIFICATE-{5}\n.*?-{5}END CERTIFICATE-{5}\n/m
dir = @cert_directory
certs = Dir[File.join(dir, '*.crt')].map {|f| File.read(f) }
certs = certs.map {|c| c.scan(pattern) }.flatten
certs.map! {|c| OpenSSL::X509::Certificate.new(c) }
@@certs = certs.reject {|c| c.not_after < Time.now }
end
@@certs
end
|
[
"def",
"certs",
"unless",
"@@certs",
"pattern",
"=",
"/",
"\\n",
"\\n",
"/m",
"dir",
"=",
"@cert_directory",
"certs",
"=",
"Dir",
"[",
"File",
".",
"join",
"(",
"dir",
",",
"'*.crt'",
")",
"]",
".",
"map",
"{",
"|",
"f",
"|",
"File",
".",
"read",
"(",
"f",
")",
"}",
"certs",
"=",
"certs",
".",
"map",
"{",
"|",
"c",
"|",
"c",
".",
"scan",
"(",
"pattern",
")",
"}",
".",
"flatten",
"certs",
".",
"map!",
"{",
"|",
"c",
"|",
"OpenSSL",
"::",
"X509",
"::",
"Certificate",
".",
"new",
"(",
"c",
")",
"}",
"@@certs",
"=",
"certs",
".",
"reject",
"{",
"|",
"c",
"|",
"c",
".",
"not_after",
"<",
"Time",
".",
"now",
"}",
"end",
"@@certs",
"end"
] |
Return the trusted root CA certificates installed in the @cert_directory. These
certificates are used to start the trust chain needed to validate certs
we receive from clients and servers.
|
[
"Return",
"the",
"trusted",
"root",
"CA",
"certificates",
"installed",
"in",
"the"
] |
804e139944c88bc317b359754d5ad69b75f42319
|
https://github.com/crapooze/em-xmpp/blob/804e139944c88bc317b359754d5ad69b75f42319/lib/em-xmpp/cert_store.rb#L64-L74
|
8,903
|
thriventures/storage_room_gem
|
lib/storage_room/embeddeds/image.rb
|
StorageRoom.Image.url
|
def url(name = nil)
if name
if version_identifiers.include?(name.to_s)
self[:@versions][name.to_s][:@url]
else
raise "Invalid Image Version identifier: '#{name}' (must be #{version_identifiers.join(', ')})"
end
else
self[:@url]
end
end
|
ruby
|
def url(name = nil)
if name
if version_identifiers.include?(name.to_s)
self[:@versions][name.to_s][:@url]
else
raise "Invalid Image Version identifier: '#{name}' (must be #{version_identifiers.join(', ')})"
end
else
self[:@url]
end
end
|
[
"def",
"url",
"(",
"name",
"=",
"nil",
")",
"if",
"name",
"if",
"version_identifiers",
".",
"include?",
"(",
"name",
".",
"to_s",
")",
"self",
"[",
":@versions",
"]",
"[",
"name",
".",
"to_s",
"]",
"[",
":@url",
"]",
"else",
"raise",
"\"Invalid Image Version identifier: '#{name}' (must be #{version_identifiers.join(', ')})\"",
"end",
"else",
"self",
"[",
":@url",
"]",
"end",
"end"
] |
Returns the URL of an Image or the URL of a version if a string or symbol is passed
|
[
"Returns",
"the",
"URL",
"of",
"an",
"Image",
"or",
"the",
"URL",
"of",
"a",
"version",
"if",
"a",
"string",
"or",
"symbol",
"is",
"passed"
] |
cadf132b865ff82f7b09fadfec1d294a714c6728
|
https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/embeddeds/image.rb#L10-L20
|
8,904
|
Aethelflaed/iord
|
lib/iord/fields.rb
|
Iord.Fields.field_attribute
|
def field_attribute(attr)
return 'id' if attr == :_id
# default, simply return name
return attr unless attr.is_a? Hash
# else, Hash
return attr[:object] if attr.has_key? :object
return attr[:array] if attr.has_key? :array
return attr[:value] if attr.has_key? :value
return attr[:link] if attr.has_key? :link
attr.keys[0]
end
|
ruby
|
def field_attribute(attr)
return 'id' if attr == :_id
# default, simply return name
return attr unless attr.is_a? Hash
# else, Hash
return attr[:object] if attr.has_key? :object
return attr[:array] if attr.has_key? :array
return attr[:value] if attr.has_key? :value
return attr[:link] if attr.has_key? :link
attr.keys[0]
end
|
[
"def",
"field_attribute",
"(",
"attr",
")",
"return",
"'id'",
"if",
"attr",
"==",
":_id",
"# default, simply return name",
"return",
"attr",
"unless",
"attr",
".",
"is_a?",
"Hash",
"# else, Hash",
"return",
"attr",
"[",
":object",
"]",
"if",
"attr",
".",
"has_key?",
":object",
"return",
"attr",
"[",
":array",
"]",
"if",
"attr",
".",
"has_key?",
":array",
"return",
"attr",
"[",
":value",
"]",
"if",
"attr",
".",
"has_key?",
":value",
"return",
"attr",
"[",
":link",
"]",
"if",
"attr",
".",
"has_key?",
":link",
"attr",
".",
"keys",
"[",
"0",
"]",
"end"
] |
Use for sort_if_enabled which requires the attribute name
|
[
"Use",
"for",
"sort_if_enabled",
"which",
"requires",
"the",
"attribute",
"name"
] |
5f7d5c1ddb91b6ed7f5db90f9420566477b1268a
|
https://github.com/Aethelflaed/iord/blob/5f7d5c1ddb91b6ed7f5db90f9420566477b1268a/lib/iord/fields.rb#L22-L33
|
8,905
|
webdestroya/ffaker-taxonomy
|
lib/ffaker/taxonomy.rb
|
Faker.Taxonomy.lookup
|
def lookup(code)
TAXONOMY.select {|t| t.code.eql?(code) }.first
end
|
ruby
|
def lookup(code)
TAXONOMY.select {|t| t.code.eql?(code) }.first
end
|
[
"def",
"lookup",
"(",
"code",
")",
"TAXONOMY",
".",
"select",
"{",
"|",
"t",
"|",
"t",
".",
"code",
".",
"eql?",
"(",
"code",
")",
"}",
".",
"first",
"end"
] |
Use this method if you have a taxonomy code and need to lookup the
information about that code
|
[
"Use",
"this",
"method",
"if",
"you",
"have",
"a",
"taxonomy",
"code",
"and",
"need",
"to",
"lookup",
"the",
"information",
"about",
"that",
"code"
] |
272f8cbcf4604d504f5f8e28d033b17f6c57bade
|
https://github.com/webdestroya/ffaker-taxonomy/blob/272f8cbcf4604d504f5f8e28d033b17f6c57bade/lib/ffaker/taxonomy.rb#L24-L26
|
8,906
|
kamui/kanpachi
|
lib/kanpachi/error_list.rb
|
Kanpachi.ErrorList.add
|
def add(error)
if @list.key? error.name
raise DuplicateError, "An error named #{error.name} already exists"
end
@list[error.name] = error
end
|
ruby
|
def add(error)
if @list.key? error.name
raise DuplicateError, "An error named #{error.name} already exists"
end
@list[error.name] = error
end
|
[
"def",
"add",
"(",
"error",
")",
"if",
"@list",
".",
"key?",
"error",
".",
"name",
"raise",
"DuplicateError",
",",
"\"An error named #{error.name} already exists\"",
"end",
"@list",
"[",
"error",
".",
"name",
"]",
"=",
"error",
"end"
] |
Add a error to the list
@param [Kanpachi::Error] error The error to add.
@return [Hash<Kanpachi::Error>] All the added errors.
@raise DuplicateError If a error is being duplicated.
@api public
|
[
"Add",
"a",
"error",
"to",
"the",
"list"
] |
dbd09646bd8779ab874e1578b57a13f5747b0da7
|
https://github.com/kamui/kanpachi/blob/dbd09646bd8779ab874e1578b57a13f5747b0da7/lib/kanpachi/error_list.rb#L34-L39
|
8,907
|
onurkucukkece/lotto
|
lib/lotto/draw.rb
|
Lotto.Draw.draw
|
def draw
drawns = []
@options[:include].each { |n| drawns << n } unless @options[:include].nil?
count = @options[:include] ? @options[:pick] - @options[:include].count : @options[:pick]
count.times { drawns << pick(drawns) }
drawns
end
|
ruby
|
def draw
drawns = []
@options[:include].each { |n| drawns << n } unless @options[:include].nil?
count = @options[:include] ? @options[:pick] - @options[:include].count : @options[:pick]
count.times { drawns << pick(drawns) }
drawns
end
|
[
"def",
"draw",
"drawns",
"=",
"[",
"]",
"@options",
"[",
":include",
"]",
".",
"each",
"{",
"|",
"n",
"|",
"drawns",
"<<",
"n",
"}",
"unless",
"@options",
"[",
":include",
"]",
".",
"nil?",
"count",
"=",
"@options",
"[",
":include",
"]",
"?",
"@options",
"[",
":pick",
"]",
"-",
"@options",
"[",
":include",
"]",
".",
"count",
":",
"@options",
"[",
":pick",
"]",
"count",
".",
"times",
"{",
"drawns",
"<<",
"pick",
"(",
"drawns",
")",
"}",
"drawns",
"end"
] |
Returns a set of drawn numbers
|
[
"Returns",
"a",
"set",
"of",
"drawn",
"numbers"
] |
c4236ac13c3a5b894a65d7e2fb90645e961f24c3
|
https://github.com/onurkucukkece/lotto/blob/c4236ac13c3a5b894a65d7e2fb90645e961f24c3/lib/lotto/draw.rb#L12-L18
|
8,908
|
onurkucukkece/lotto
|
lib/lotto/draw.rb
|
Lotto.Draw.basket
|
def basket
numbers = (1..@options[:of])
numbers = numbers.reject { |n| @options[:include].include? n } unless @options[:include].nil?
numbers = numbers.reject { |n| @options[:exclude].include? n } unless @options[:exclude].nil?
numbers
end
|
ruby
|
def basket
numbers = (1..@options[:of])
numbers = numbers.reject { |n| @options[:include].include? n } unless @options[:include].nil?
numbers = numbers.reject { |n| @options[:exclude].include? n } unless @options[:exclude].nil?
numbers
end
|
[
"def",
"basket",
"numbers",
"=",
"(",
"1",
"..",
"@options",
"[",
":of",
"]",
")",
"numbers",
"=",
"numbers",
".",
"reject",
"{",
"|",
"n",
"|",
"@options",
"[",
":include",
"]",
".",
"include?",
"n",
"}",
"unless",
"@options",
"[",
":include",
"]",
".",
"nil?",
"numbers",
"=",
"numbers",
".",
"reject",
"{",
"|",
"n",
"|",
"@options",
"[",
":exclude",
"]",
".",
"include?",
"n",
"}",
"unless",
"@options",
"[",
":exclude",
"]",
".",
"nil?",
"numbers",
"end"
] |
Returns the basket with numbers
|
[
"Returns",
"the",
"basket",
"with",
"numbers"
] |
c4236ac13c3a5b894a65d7e2fb90645e961f24c3
|
https://github.com/onurkucukkece/lotto/blob/c4236ac13c3a5b894a65d7e2fb90645e961f24c3/lib/lotto/draw.rb#L33-L38
|
8,909
|
checkdin/checkdin-ruby
|
lib/checkdin/activities.rb
|
Checkdin.Activities.activities
|
def activities(options={})
response = connection.get do |req|
req.url "activities", options
end
return_error_or_body(response)
end
|
ruby
|
def activities(options={})
response = connection.get do |req|
req.url "activities", options
end
return_error_or_body(response)
end
|
[
"def",
"activities",
"(",
"options",
"=",
"{",
"}",
")",
"response",
"=",
"connection",
".",
"get",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"\"activities\"",
",",
"options",
"end",
"return_error_or_body",
"(",
"response",
")",
"end"
] |
Get a list of all activities for the authenticating client.
@param [Hash] options
@option options Integer :campaign_id - Only return won rewards for this campaign.
@option options String :classification - Only return activities for users in this classification.
@option options Integer :user_id - Only return won rewards for this user.
@option options Integer :since - Only fetch updates since this time (UNIX timestamp)
@option options Integer :limit - The maximum number of records to return.
|
[
"Get",
"a",
"list",
"of",
"all",
"activities",
"for",
"the",
"authenticating",
"client",
"."
] |
c3c4b38b0f8c710e1f805100dcf3a70649215b48
|
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/activities.rb#L22-L27
|
8,910
|
henvo/digistore24
|
lib/digistore24/notification.rb
|
Digistore24.Notification.signature
|
def signature
# Remove 'sha_sign' key from request params and concatenate all
# key value pairs
params = payload.to_h
.reject { |key, value| key == :sha_sign }
.reject { |key, value| value == '' || value == false }.sort
.map { | key, value| "#{key}=#{value}#{passphrase}" }.join
# Calculate SHA512 and upcase all letters, since Digistore will
# also return upcased letters in the signature.
Digest::SHA512.hexdigest(params).upcase
end
|
ruby
|
def signature
# Remove 'sha_sign' key from request params and concatenate all
# key value pairs
params = payload.to_h
.reject { |key, value| key == :sha_sign }
.reject { |key, value| value == '' || value == false }.sort
.map { | key, value| "#{key}=#{value}#{passphrase}" }.join
# Calculate SHA512 and upcase all letters, since Digistore will
# also return upcased letters in the signature.
Digest::SHA512.hexdigest(params).upcase
end
|
[
"def",
"signature",
"# Remove 'sha_sign' key from request params and concatenate all",
"# key value pairs",
"params",
"=",
"payload",
".",
"to_h",
".",
"reject",
"{",
"|",
"key",
",",
"value",
"|",
"key",
"==",
":sha_sign",
"}",
".",
"reject",
"{",
"|",
"key",
",",
"value",
"|",
"value",
"==",
"''",
"||",
"value",
"==",
"false",
"}",
".",
"sort",
".",
"map",
"{",
"|",
"key",
",",
"value",
"|",
"\"#{key}=#{value}#{passphrase}\"",
"}",
".",
"join",
"# Calculate SHA512 and upcase all letters, since Digistore will",
"# also return upcased letters in the signature.",
"Digest",
"::",
"SHA512",
".",
"hexdigest",
"(",
"params",
")",
".",
"upcase",
"end"
] |
Initialize the notification.
@param params [Hash] The request parameters from Digistore24.
@return [Notification]
Calculate SHA512 signature for payload.
@return [String] The signature.
|
[
"Initialize",
"the",
"notification",
"."
] |
f9e43665f61af3f36e72807eda12562b9befac86
|
https://github.com/henvo/digistore24/blob/f9e43665f61af3f36e72807eda12562b9befac86/lib/digistore24/notification.rb#L25-L36
|
8,911
|
jeremyz/edoors-ruby
|
lib/edoors/board.rb
|
Edoors.Board.process_p
|
def process_p p
@viewer.receive_p p if @viewer
if p.action!=Edoors::ACT_ERROR and p.action!=Edoors::ACT_PASS_THROUGH
p2 = @postponed[p.link_value] ||= p
return if p2==p
@postponed.delete p.link_value
p,p2 = p2,p if p.action==Edoors::ACT_FOLLOW
p.merge! p2
end
@saved = p
receive_p p
_garbage if not @saved.nil?
end
|
ruby
|
def process_p p
@viewer.receive_p p if @viewer
if p.action!=Edoors::ACT_ERROR and p.action!=Edoors::ACT_PASS_THROUGH
p2 = @postponed[p.link_value] ||= p
return if p2==p
@postponed.delete p.link_value
p,p2 = p2,p if p.action==Edoors::ACT_FOLLOW
p.merge! p2
end
@saved = p
receive_p p
_garbage if not @saved.nil?
end
|
[
"def",
"process_p",
"p",
"@viewer",
".",
"receive_p",
"p",
"if",
"@viewer",
"if",
"p",
".",
"action!",
"=",
"Edoors",
"::",
"ACT_ERROR",
"and",
"p",
".",
"action!",
"=",
"Edoors",
"::",
"ACT_PASS_THROUGH",
"p2",
"=",
"@postponed",
"[",
"p",
".",
"link_value",
"]",
"||=",
"p",
"return",
"if",
"p2",
"==",
"p",
"@postponed",
".",
"delete",
"p",
".",
"link_value",
"p",
",",
"p2",
"=",
"p2",
",",
"p",
"if",
"p",
".",
"action",
"==",
"Edoors",
"::",
"ACT_FOLLOW",
"p",
".",
"merge!",
"p2",
"end",
"@saved",
"=",
"p",
"receive_p",
"p",
"_garbage",
"if",
"not",
"@saved",
".",
"nil?",
"end"
] |
process the given particle then forward it to user code
@param [Particle] p the Particle to be processed
|
[
"process",
"the",
"given",
"particle",
"then",
"forward",
"it",
"to",
"user",
"code"
] |
4f065f63125907b3a4f72fbab8722c58ccab41c1
|
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/board.rb#L71-L83
|
8,912
|
tdg5/tco_method
|
lib/tco_method/block_extractor.rb
|
TCOMethod.BlockExtractor.determine_offsets
|
def determine_offsets(block, source)
tokens = Ripper.lex(source)
start_offset, start_token = determine_start_offset(block, tokens)
expected_match = start_token == :on_kw ? :on_kw : :on_rbrace
end_offset = determine_end_offset(block, tokens, source, expected_match)
[start_offset, end_offset]
end
|
ruby
|
def determine_offsets(block, source)
tokens = Ripper.lex(source)
start_offset, start_token = determine_start_offset(block, tokens)
expected_match = start_token == :on_kw ? :on_kw : :on_rbrace
end_offset = determine_end_offset(block, tokens, source, expected_match)
[start_offset, end_offset]
end
|
[
"def",
"determine_offsets",
"(",
"block",
",",
"source",
")",
"tokens",
"=",
"Ripper",
".",
"lex",
"(",
"source",
")",
"start_offset",
",",
"start_token",
"=",
"determine_start_offset",
"(",
"block",
",",
"tokens",
")",
"expected_match",
"=",
"start_token",
"==",
":on_kw",
"?",
":on_kw",
":",
":on_rbrace",
"end_offset",
"=",
"determine_end_offset",
"(",
"block",
",",
"tokens",
",",
"source",
",",
"expected_match",
")",
"[",
"start_offset",
",",
"end_offset",
"]",
"end"
] |
Tokenizes the source of the block as determined by the `method_source` gem
and determines the beginning and end of the block.
In both cases the entire line is checked to ensure there's no unexpected
ambiguity as to the start or end of the block. See the test file for this
class for examples of ambiguous situations.
@param [Proc] block The proc for which the starting offset of its source
code should be determined.
@param [String] source The source code of the provided block.
@raise [AmbiguousSourceError] Raised when the source of the block cannot
be determined unambiguously.
@return [Array<Integer>] The start and end offsets of the block's source
code as 2-element Array.
|
[
"Tokenizes",
"the",
"source",
"of",
"the",
"block",
"as",
"determined",
"by",
"the",
"method_source",
"gem",
"and",
"determines",
"the",
"beginning",
"and",
"end",
"of",
"the",
"block",
"."
] |
fc89b884b68ce2a4bc58abb22270b1f7685efbe9
|
https://github.com/tdg5/tco_method/blob/fc89b884b68ce2a4bc58abb22270b1f7685efbe9/lib/tco_method/block_extractor.rb#L71-L77
|
8,913
|
anga/extend_at
|
lib/extend_at.rb
|
ExtendModelAt.Extention.method_missing
|
def method_missing(m, *args, &block)
column_name = m.to_s.gsub(/\=$/, '')
raise ExtendModelAt::InvalidColumn, "#{column_name} not exist" if @static == true and not (@columns.try(:keys).try(:include?, column_name.to_sym) )
# If the method don't finish with "=" is fore read
if m !~ /\=$/
self[m.to_s]
# but if finish with "=" is for wirte
else
self[column_name.to_s] = args.first
end
end
|
ruby
|
def method_missing(m, *args, &block)
column_name = m.to_s.gsub(/\=$/, '')
raise ExtendModelAt::InvalidColumn, "#{column_name} not exist" if @static == true and not (@columns.try(:keys).try(:include?, column_name.to_sym) )
# If the method don't finish with "=" is fore read
if m !~ /\=$/
self[m.to_s]
# but if finish with "=" is for wirte
else
self[column_name.to_s] = args.first
end
end
|
[
"def",
"method_missing",
"(",
"m",
",",
"*",
"args",
",",
"&",
"block",
")",
"column_name",
"=",
"m",
".",
"to_s",
".",
"gsub",
"(",
"/",
"\\=",
"/",
",",
"''",
")",
"raise",
"ExtendModelAt",
"::",
"InvalidColumn",
",",
"\"#{column_name} not exist\"",
"if",
"@static",
"==",
"true",
"and",
"not",
"(",
"@columns",
".",
"try",
"(",
":keys",
")",
".",
"try",
"(",
":include?",
",",
"column_name",
".",
"to_sym",
")",
")",
"# If the method don't finish with \"=\" is fore read",
"if",
"m",
"!~",
"/",
"\\=",
"/",
"self",
"[",
"m",
".",
"to_s",
"]",
"# but if finish with \"=\" is for wirte",
"else",
"self",
"[",
"column_name",
".",
"to_s",
"]",
"=",
"args",
".",
"first",
"end",
"end"
] |
Use the undefined method as a column
|
[
"Use",
"the",
"undefined",
"method",
"as",
"a",
"column"
] |
db77cf981108b401af0d92a8d7b1008317d9a17d
|
https://github.com/anga/extend_at/blob/db77cf981108b401af0d92a8d7b1008317d9a17d/lib/extend_at.rb#L462-L472
|
8,914
|
anga/extend_at
|
lib/extend_at.rb
|
ExtendModelAt.Extention.get_adapter
|
def get_adapter(column, value)
if @columns[column.to_sym][:type] == String
return :to_s
elsif @columns[column.to_sym][:type] == Fixnum
return :to_i if value.respond_to? :to_i
elsif @columns[column.to_sym][:type] == Float
return :to_f if value.respond_to? :to_f
elsif @columns[column.to_sym][:type] == Time
return :to_time if value.respond_to? :to_time
elsif @columns[column.to_sym][:type] == Date
return :to_date if value.respond_to? :to_date
end
nil
end
|
ruby
|
def get_adapter(column, value)
if @columns[column.to_sym][:type] == String
return :to_s
elsif @columns[column.to_sym][:type] == Fixnum
return :to_i if value.respond_to? :to_i
elsif @columns[column.to_sym][:type] == Float
return :to_f if value.respond_to? :to_f
elsif @columns[column.to_sym][:type] == Time
return :to_time if value.respond_to? :to_time
elsif @columns[column.to_sym][:type] == Date
return :to_date if value.respond_to? :to_date
end
nil
end
|
[
"def",
"get_adapter",
"(",
"column",
",",
"value",
")",
"if",
"@columns",
"[",
"column",
".",
"to_sym",
"]",
"[",
":type",
"]",
"==",
"String",
"return",
":to_s",
"elsif",
"@columns",
"[",
"column",
".",
"to_sym",
"]",
"[",
":type",
"]",
"==",
"Fixnum",
"return",
":to_i",
"if",
"value",
".",
"respond_to?",
":to_i",
"elsif",
"@columns",
"[",
"column",
".",
"to_sym",
"]",
"[",
":type",
"]",
"==",
"Float",
"return",
":to_f",
"if",
"value",
".",
"respond_to?",
":to_f",
"elsif",
"@columns",
"[",
"column",
".",
"to_sym",
"]",
"[",
":type",
"]",
"==",
"Time",
"return",
":to_time",
"if",
"value",
".",
"respond_to?",
":to_time",
"elsif",
"@columns",
"[",
"column",
".",
"to_sym",
"]",
"[",
":type",
"]",
"==",
"Date",
"return",
":to_date",
"if",
"value",
".",
"respond_to?",
":to_date",
"end",
"nil",
"end"
] |
Meta functions
Return the correct method used to transform the column value the correct Ruby class
|
[
"Meta",
"functions",
"Return",
"the",
"correct",
"method",
"used",
"to",
"transform",
"the",
"column",
"value",
"the",
"correct",
"Ruby",
"class"
] |
db77cf981108b401af0d92a8d7b1008317d9a17d
|
https://github.com/anga/extend_at/blob/db77cf981108b401af0d92a8d7b1008317d9a17d/lib/extend_at.rb#L567-L580
|
8,915
|
anga/extend_at
|
lib/extend_at.rb
|
ExtendModelAt.Extention.get_defaults_values
|
def get_defaults_values(options = {})
defaults_ = {}
options[:columns].each do |column, config|
defaults_[column.to_s] = @columns[column.to_sym][:default] || nil
end
defaults_
end
|
ruby
|
def get_defaults_values(options = {})
defaults_ = {}
options[:columns].each do |column, config|
defaults_[column.to_s] = @columns[column.to_sym][:default] || nil
end
defaults_
end
|
[
"def",
"get_defaults_values",
"(",
"options",
"=",
"{",
"}",
")",
"defaults_",
"=",
"{",
"}",
"options",
"[",
":columns",
"]",
".",
"each",
"do",
"|",
"column",
",",
"config",
"|",
"defaults_",
"[",
"column",
".",
"to_s",
"]",
"=",
"@columns",
"[",
"column",
".",
"to_sym",
"]",
"[",
":default",
"]",
"||",
"nil",
"end",
"defaults_",
"end"
] |
Get all default values
|
[
"Get",
"all",
"default",
"values"
] |
db77cf981108b401af0d92a8d7b1008317d9a17d
|
https://github.com/anga/extend_at/blob/db77cf981108b401af0d92a8d7b1008317d9a17d/lib/extend_at.rb#L594-L600
|
8,916
|
checkdin/checkdin-ruby
|
lib/checkdin/point_account_entries.rb
|
Checkdin.PointAccountEntries.point_account_entries
|
def point_account_entries(options={})
response = connection.get do |req|
req.url "point_account_entries", options
end
return_error_or_body(response)
end
|
ruby
|
def point_account_entries(options={})
response = connection.get do |req|
req.url "point_account_entries", options
end
return_error_or_body(response)
end
|
[
"def",
"point_account_entries",
"(",
"options",
"=",
"{",
"}",
")",
"response",
"=",
"connection",
".",
"get",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"\"point_account_entries\"",
",",
"options",
"end",
"return_error_or_body",
"(",
"response",
")",
"end"
] |
Get a list of point account entries.
@param [Hash] options
@option options Integer :user_id - Return entries only for this user
@option options Integer :campaign_id - Return entries only for this campaign
@option options Integer :point_account_id - Return entries only for this point account.
@option options Integer :limit - The maximum number of records to return.
|
[
"Get",
"a",
"list",
"of",
"point",
"account",
"entries",
"."
] |
c3c4b38b0f8c710e1f805100dcf3a70649215b48
|
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/point_account_entries.rb#L12-L17
|
8,917
|
bogrobotten/fetch
|
lib/fetch/request.rb
|
Fetch.Request.process!
|
def process!(body, url, effective_url)
before_process!
body = parse!(body)
@process_callback.call(body, url, effective_url) if @process_callback
after_process!
rescue => e
error!(e)
end
|
ruby
|
def process!(body, url, effective_url)
before_process!
body = parse!(body)
@process_callback.call(body, url, effective_url) if @process_callback
after_process!
rescue => e
error!(e)
end
|
[
"def",
"process!",
"(",
"body",
",",
"url",
",",
"effective_url",
")",
"before_process!",
"body",
"=",
"parse!",
"(",
"body",
")",
"@process_callback",
".",
"call",
"(",
"body",
",",
"url",
",",
"effective_url",
")",
"if",
"@process_callback",
"after_process!",
"rescue",
"=>",
"e",
"error!",
"(",
"e",
")",
"end"
] |
Runs the process callback. If it fails with an exception, it will send
the exception to the error callback.
|
[
"Runs",
"the",
"process",
"callback",
".",
"If",
"it",
"fails",
"with",
"an",
"exception",
"it",
"will",
"send",
"the",
"exception",
"to",
"the",
"error",
"callback",
"."
] |
8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f
|
https://github.com/bogrobotten/fetch/blob/8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f/lib/fetch/request.rb#L123-L130
|
8,918
|
groupdocs-signature-cloud/groupdocs-signature-cloud-ruby
|
lib/groupdocs_signature_cloud/api/signature_api.rb
|
GroupDocsSignatureCloud.SignatureApi.get_qr_codes_with_http_info
|
def get_qr_codes_with_http_info()
@api_client.config.logger.debug 'Calling API: SignatureApi.get_qr_codes ...' if @api_client.config.debugging
# resource path
local_var_path = '/signature/qrcodes'
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
header_params: header_params,
query_params: query_params,
form_params: form_params,
body: post_body,
access_token: get_access_token,
return_type: 'QRCodeCollection')
if @api_client.config.debugging
@api_client.config.logger.debug "API called:
SignatureApi#get_qr_codes\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
[data, status_code, headers]
end
|
ruby
|
def get_qr_codes_with_http_info()
@api_client.config.logger.debug 'Calling API: SignatureApi.get_qr_codes ...' if @api_client.config.debugging
# resource path
local_var_path = '/signature/qrcodes'
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
header_params: header_params,
query_params: query_params,
form_params: form_params,
body: post_body,
access_token: get_access_token,
return_type: 'QRCodeCollection')
if @api_client.config.debugging
@api_client.config.logger.debug "API called:
SignatureApi#get_qr_codes\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
[data, status_code, headers]
end
|
[
"def",
"get_qr_codes_with_http_info",
"(",
")",
"@api_client",
".",
"config",
".",
"logger",
".",
"debug",
"'Calling API: SignatureApi.get_qr_codes ...'",
"if",
"@api_client",
".",
"config",
".",
"debugging",
"# resource path",
"local_var_path",
"=",
"'/signature/qrcodes'",
"# query parameters",
"query_params",
"=",
"{",
"}",
"# header parameters",
"header_params",
"=",
"{",
"}",
"# HTTP header 'Accept' (if needed)",
"header_params",
"[",
"'Accept'",
"]",
"=",
"@api_client",
".",
"select_header_accept",
"(",
"[",
"'application/json'",
",",
"'application/xml'",
"]",
")",
"# HTTP header 'Content-Type'",
"header_params",
"[",
"'Content-Type'",
"]",
"=",
"@api_client",
".",
"select_header_content_type",
"(",
"[",
"'application/json'",
",",
"'application/xml'",
"]",
")",
"# form parameters",
"form_params",
"=",
"{",
"}",
"# http body (model)",
"post_body",
"=",
"nil",
"data",
",",
"status_code",
",",
"headers",
"=",
"@api_client",
".",
"call_api",
"(",
":GET",
",",
"local_var_path",
",",
"header_params",
":",
"header_params",
",",
"query_params",
":",
"query_params",
",",
"form_params",
":",
"form_params",
",",
"body",
":",
"post_body",
",",
"access_token",
":",
"get_access_token",
",",
"return_type",
":",
"'QRCodeCollection'",
")",
"if",
"@api_client",
".",
"config",
".",
"debugging",
"@api_client",
".",
"config",
".",
"logger",
".",
"debug",
"\"API called:\n SignatureApi#get_qr_codes\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"",
"end",
"[",
"data",
",",
"status_code",
",",
"headers",
"]",
"end"
] |
Retrieves list of supported QR-Code type names.
@return [Array<(QRCodeCollection, Fixnum, Hash)>]
QRCodeCollection data, response status code and response headers
|
[
"Retrieves",
"list",
"of",
"supported",
"QR",
"-",
"Code",
"type",
"names",
"."
] |
d16e6f4bdd6cb9196d4e28ef3fc2123da94f0ef0
|
https://github.com/groupdocs-signature-cloud/groupdocs-signature-cloud-ruby/blob/d16e6f4bdd6cb9196d4e28ef3fc2123da94f0ef0/lib/groupdocs_signature_cloud/api/signature_api.rb#L265-L299
|
8,919
|
groupdocs-signature-cloud/groupdocs-signature-cloud-ruby
|
lib/groupdocs_signature_cloud/api/signature_api.rb
|
GroupDocsSignatureCloud.SignatureApi.post_verification_collection_with_http_info
|
def post_verification_collection_with_http_info(request)
raise ArgumentError, 'Incorrect request type' unless request.is_a? PostVerificationCollectionRequest
@api_client.config.logger.debug 'Calling API: SignatureApi.post_verification_collection ...' if @api_client.config.debugging
# verify the required parameter 'name' is set
raise ArgumentError, 'Missing the required parameter name when calling SignatureApi.post_verification_collection' if @api_client.config.client_side_validation && request.name.nil?
# resource path
local_var_path = '/signature/{name}/collection/verification'
local_var_path = local_var_path.sub('{' + downcase_first_letter('Name') + '}', request.name.to_s)
# query parameters
query_params = {}
if local_var_path.include? ('{' + downcase_first_letter('Password') + '}')
local_var_path = local_var_path.sub('{' + downcase_first_letter('Password') + '}', request.password.to_s)
else
query_params[downcase_first_letter('Password')] = request.password unless request.password.nil?
end
if local_var_path.include? ('{' + downcase_first_letter('Folder') + '}')
local_var_path = local_var_path.sub('{' + downcase_first_letter('Folder') + '}', request.folder.to_s)
else
query_params[downcase_first_letter('Folder')] = request.folder unless request.folder.nil?
end
if local_var_path.include? ('{' + downcase_first_letter('Storage') + '}')
local_var_path = local_var_path.sub('{' + downcase_first_letter('Storage') + '}', request.storage.to_s)
else
query_params[downcase_first_letter('Storage')] = request.storage unless request.storage.nil?
end
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(request.verify_options_collection_data)
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
header_params: header_params,
query_params: query_params,
form_params: form_params,
body: post_body,
access_token: get_access_token,
return_type: 'VerifiedDocumentResponse')
if @api_client.config.debugging
@api_client.config.logger.debug "API called:
SignatureApi#post_verification_collection\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
[data, status_code, headers]
end
|
ruby
|
def post_verification_collection_with_http_info(request)
raise ArgumentError, 'Incorrect request type' unless request.is_a? PostVerificationCollectionRequest
@api_client.config.logger.debug 'Calling API: SignatureApi.post_verification_collection ...' if @api_client.config.debugging
# verify the required parameter 'name' is set
raise ArgumentError, 'Missing the required parameter name when calling SignatureApi.post_verification_collection' if @api_client.config.client_side_validation && request.name.nil?
# resource path
local_var_path = '/signature/{name}/collection/verification'
local_var_path = local_var_path.sub('{' + downcase_first_letter('Name') + '}', request.name.to_s)
# query parameters
query_params = {}
if local_var_path.include? ('{' + downcase_first_letter('Password') + '}')
local_var_path = local_var_path.sub('{' + downcase_first_letter('Password') + '}', request.password.to_s)
else
query_params[downcase_first_letter('Password')] = request.password unless request.password.nil?
end
if local_var_path.include? ('{' + downcase_first_letter('Folder') + '}')
local_var_path = local_var_path.sub('{' + downcase_first_letter('Folder') + '}', request.folder.to_s)
else
query_params[downcase_first_letter('Folder')] = request.folder unless request.folder.nil?
end
if local_var_path.include? ('{' + downcase_first_letter('Storage') + '}')
local_var_path = local_var_path.sub('{' + downcase_first_letter('Storage') + '}', request.storage.to_s)
else
query_params[downcase_first_letter('Storage')] = request.storage unless request.storage.nil?
end
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(request.verify_options_collection_data)
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
header_params: header_params,
query_params: query_params,
form_params: form_params,
body: post_body,
access_token: get_access_token,
return_type: 'VerifiedDocumentResponse')
if @api_client.config.debugging
@api_client.config.logger.debug "API called:
SignatureApi#post_verification_collection\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
[data, status_code, headers]
end
|
[
"def",
"post_verification_collection_with_http_info",
"(",
"request",
")",
"raise",
"ArgumentError",
",",
"'Incorrect request type'",
"unless",
"request",
".",
"is_a?",
"PostVerificationCollectionRequest",
"@api_client",
".",
"config",
".",
"logger",
".",
"debug",
"'Calling API: SignatureApi.post_verification_collection ...'",
"if",
"@api_client",
".",
"config",
".",
"debugging",
"# verify the required parameter 'name' is set",
"raise",
"ArgumentError",
",",
"'Missing the required parameter name when calling SignatureApi.post_verification_collection'",
"if",
"@api_client",
".",
"config",
".",
"client_side_validation",
"&&",
"request",
".",
"name",
".",
"nil?",
"# resource path",
"local_var_path",
"=",
"'/signature/{name}/collection/verification'",
"local_var_path",
"=",
"local_var_path",
".",
"sub",
"(",
"'{'",
"+",
"downcase_first_letter",
"(",
"'Name'",
")",
"+",
"'}'",
",",
"request",
".",
"name",
".",
"to_s",
")",
"# query parameters",
"query_params",
"=",
"{",
"}",
"if",
"local_var_path",
".",
"include?",
"(",
"'{'",
"+",
"downcase_first_letter",
"(",
"'Password'",
")",
"+",
"'}'",
")",
"local_var_path",
"=",
"local_var_path",
".",
"sub",
"(",
"'{'",
"+",
"downcase_first_letter",
"(",
"'Password'",
")",
"+",
"'}'",
",",
"request",
".",
"password",
".",
"to_s",
")",
"else",
"query_params",
"[",
"downcase_first_letter",
"(",
"'Password'",
")",
"]",
"=",
"request",
".",
"password",
"unless",
"request",
".",
"password",
".",
"nil?",
"end",
"if",
"local_var_path",
".",
"include?",
"(",
"'{'",
"+",
"downcase_first_letter",
"(",
"'Folder'",
")",
"+",
"'}'",
")",
"local_var_path",
"=",
"local_var_path",
".",
"sub",
"(",
"'{'",
"+",
"downcase_first_letter",
"(",
"'Folder'",
")",
"+",
"'}'",
",",
"request",
".",
"folder",
".",
"to_s",
")",
"else",
"query_params",
"[",
"downcase_first_letter",
"(",
"'Folder'",
")",
"]",
"=",
"request",
".",
"folder",
"unless",
"request",
".",
"folder",
".",
"nil?",
"end",
"if",
"local_var_path",
".",
"include?",
"(",
"'{'",
"+",
"downcase_first_letter",
"(",
"'Storage'",
")",
"+",
"'}'",
")",
"local_var_path",
"=",
"local_var_path",
".",
"sub",
"(",
"'{'",
"+",
"downcase_first_letter",
"(",
"'Storage'",
")",
"+",
"'}'",
",",
"request",
".",
"storage",
".",
"to_s",
")",
"else",
"query_params",
"[",
"downcase_first_letter",
"(",
"'Storage'",
")",
"]",
"=",
"request",
".",
"storage",
"unless",
"request",
".",
"storage",
".",
"nil?",
"end",
"# header parameters",
"header_params",
"=",
"{",
"}",
"# HTTP header 'Accept' (if needed)",
"header_params",
"[",
"'Accept'",
"]",
"=",
"@api_client",
".",
"select_header_accept",
"(",
"[",
"'application/json'",
",",
"'application/xml'",
"]",
")",
"# HTTP header 'Content-Type'",
"header_params",
"[",
"'Content-Type'",
"]",
"=",
"@api_client",
".",
"select_header_content_type",
"(",
"[",
"'application/json'",
",",
"'application/xml'",
"]",
")",
"# form parameters",
"form_params",
"=",
"{",
"}",
"# http body (model)",
"post_body",
"=",
"@api_client",
".",
"object_to_http_body",
"(",
"request",
".",
"verify_options_collection_data",
")",
"data",
",",
"status_code",
",",
"headers",
"=",
"@api_client",
".",
"call_api",
"(",
":POST",
",",
"local_var_path",
",",
"header_params",
":",
"header_params",
",",
"query_params",
":",
"query_params",
",",
"form_params",
":",
"form_params",
",",
"body",
":",
"post_body",
",",
"access_token",
":",
"get_access_token",
",",
"return_type",
":",
"'VerifiedDocumentResponse'",
")",
"if",
"@api_client",
".",
"config",
".",
"debugging",
"@api_client",
".",
"config",
".",
"logger",
".",
"debug",
"\"API called:\n SignatureApi#post_verification_collection\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"",
"end",
"[",
"data",
",",
"status_code",
",",
"headers",
"]",
"end"
] |
Verify the Document.
@param request PostVerificationCollectionRequest
@return [Array<(VerifiedDocumentResponse, Fixnum, Hash)>]
VerifiedDocumentResponse data, response status code and response headers
|
[
"Verify",
"the",
"Document",
"."
] |
d16e6f4bdd6cb9196d4e28ef3fc2123da94f0ef0
|
https://github.com/groupdocs-signature-cloud/groupdocs-signature-cloud-ruby/blob/d16e6f4bdd6cb9196d4e28ef3fc2123da94f0ef0/lib/groupdocs_signature_cloud/api/signature_api.rb#L1978-L2030
|
8,920
|
boof/xbel
|
lib/nokogiri/decorators/xbel.rb
|
Nokogiri::Decorators::XBEL.Entry.desc=
|
def desc=(value)
node = at './desc'
node ||= add_child Nokogiri::XML::Node.new('desc', document)
node.content = value
end
|
ruby
|
def desc=(value)
node = at './desc'
node ||= add_child Nokogiri::XML::Node.new('desc', document)
node.content = value
end
|
[
"def",
"desc",
"=",
"(",
"value",
")",
"node",
"=",
"at",
"'./desc'",
"node",
"||=",
"add_child",
"Nokogiri",
"::",
"XML",
"::",
"Node",
".",
"new",
"(",
"'desc'",
",",
"document",
")",
"node",
".",
"content",
"=",
"value",
"end"
] |
Sets description of node.
|
[
"Sets",
"description",
"of",
"node",
"."
] |
a1997a0ff61e99f390cc4f05ef9ec4757557048e
|
https://github.com/boof/xbel/blob/a1997a0ff61e99f390cc4f05ef9ec4757557048e/lib/nokogiri/decorators/xbel.rb#L47-L52
|
8,921
|
boof/xbel
|
lib/nokogiri/decorators/xbel.rb
|
Nokogiri::Decorators::XBEL.Entry.added=
|
def added=(value)
set_attribute 'added', case value
when Time; value.strftime '%Y-%m-%d'
when String; value
else
raise ArgumentError
end
end
|
ruby
|
def added=(value)
set_attribute 'added', case value
when Time; value.strftime '%Y-%m-%d'
when String; value
else
raise ArgumentError
end
end
|
[
"def",
"added",
"=",
"(",
"value",
")",
"set_attribute",
"'added'",
",",
"case",
"value",
"when",
"Time",
";",
"value",
".",
"strftime",
"'%Y-%m-%d'",
"when",
"String",
";",
"value",
"else",
"raise",
"ArgumentError",
"end",
"end"
] |
Sets addition date.
|
[
"Sets",
"addition",
"date",
"."
] |
a1997a0ff61e99f390cc4f05ef9ec4757557048e
|
https://github.com/boof/xbel/blob/a1997a0ff61e99f390cc4f05ef9ec4757557048e/lib/nokogiri/decorators/xbel.rb#L83-L90
|
8,922
|
nilsding/Empyrean
|
lib/empyrean/tweetparser.rb
|
Empyrean.TweetParser.parse
|
def parse(tweets)
retdict = {
mentions: {},
hashtags: {},
clients: {},
smileys: {},
times_of_day: [0] * 24,
tweet_count: 0,
retweet_count: 0,
selftweet_count: 0,
}
tweets.each do |tweet|
parsed_tweet = self.parse_one tweet
if parsed_tweet[:retweet] # the tweet was a retweet
# increase retweeted tweets count
retdict[:retweet_count] += 1
else
parsed_tweet[:mentions].each do |user, data| # add mentions to the mentions dict
retdict[:mentions][user] ||= { count: 0 }
retdict[:mentions][user][:count] += data[:count]
retdict[:mentions][user][:name] ||= data[:name]
retdict[:mentions][user][:examples] ||= []
retdict[:mentions][user][:examples] << data[:example]
end
parsed_tweet[:hashtags].each do |hashtag, data| # add hashtags to the hashtags dict
retdict[:hashtags][hashtag] ||= { count: 0 }
retdict[:hashtags][hashtag][:count] += data[:count]
retdict[:hashtags][hashtag][:hashtag] ||= data[:hashtag]
retdict[:hashtags][hashtag][:examples] ||= []
retdict[:hashtags][hashtag][:examples] << data[:example]
end
parsed_tweet[:smileys].each do |smile, data|
retdict[:smileys][smile] ||= { count: 0 }
retdict[:smileys][smile][:frown] ||= data[:frown]
retdict[:smileys][smile][:count] += data[:count]
retdict[:smileys][smile][:smiley] ||= data[:smiley]
retdict[:smileys][smile][:examples] ||= []
retdict[:smileys][smile][:examples] << data[:example]
end
# increase self tweeted tweets count
retdict[:selftweet_count] += 1
end
# add client to the clients dict
client_dict = parsed_tweet[:client][:name]
retdict[:clients][client_dict] ||= { count: 0 }
retdict[:clients][client_dict][:count] += 1
retdict[:clients][client_dict][:name] = parsed_tweet[:client][:name]
retdict[:clients][client_dict][:url] = parsed_tweet[:client][:url]
retdict[:times_of_day][parsed_tweet[:time_of_day]] += 1
# increase tweet count
retdict[:tweet_count] += 1
end
retdict
end
|
ruby
|
def parse(tweets)
retdict = {
mentions: {},
hashtags: {},
clients: {},
smileys: {},
times_of_day: [0] * 24,
tweet_count: 0,
retweet_count: 0,
selftweet_count: 0,
}
tweets.each do |tweet|
parsed_tweet = self.parse_one tweet
if parsed_tweet[:retweet] # the tweet was a retweet
# increase retweeted tweets count
retdict[:retweet_count] += 1
else
parsed_tweet[:mentions].each do |user, data| # add mentions to the mentions dict
retdict[:mentions][user] ||= { count: 0 }
retdict[:mentions][user][:count] += data[:count]
retdict[:mentions][user][:name] ||= data[:name]
retdict[:mentions][user][:examples] ||= []
retdict[:mentions][user][:examples] << data[:example]
end
parsed_tweet[:hashtags].each do |hashtag, data| # add hashtags to the hashtags dict
retdict[:hashtags][hashtag] ||= { count: 0 }
retdict[:hashtags][hashtag][:count] += data[:count]
retdict[:hashtags][hashtag][:hashtag] ||= data[:hashtag]
retdict[:hashtags][hashtag][:examples] ||= []
retdict[:hashtags][hashtag][:examples] << data[:example]
end
parsed_tweet[:smileys].each do |smile, data|
retdict[:smileys][smile] ||= { count: 0 }
retdict[:smileys][smile][:frown] ||= data[:frown]
retdict[:smileys][smile][:count] += data[:count]
retdict[:smileys][smile][:smiley] ||= data[:smiley]
retdict[:smileys][smile][:examples] ||= []
retdict[:smileys][smile][:examples] << data[:example]
end
# increase self tweeted tweets count
retdict[:selftweet_count] += 1
end
# add client to the clients dict
client_dict = parsed_tweet[:client][:name]
retdict[:clients][client_dict] ||= { count: 0 }
retdict[:clients][client_dict][:count] += 1
retdict[:clients][client_dict][:name] = parsed_tweet[:client][:name]
retdict[:clients][client_dict][:url] = parsed_tweet[:client][:url]
retdict[:times_of_day][parsed_tweet[:time_of_day]] += 1
# increase tweet count
retdict[:tweet_count] += 1
end
retdict
end
|
[
"def",
"parse",
"(",
"tweets",
")",
"retdict",
"=",
"{",
"mentions",
":",
"{",
"}",
",",
"hashtags",
":",
"{",
"}",
",",
"clients",
":",
"{",
"}",
",",
"smileys",
":",
"{",
"}",
",",
"times_of_day",
":",
"[",
"0",
"]",
"*",
"24",
",",
"tweet_count",
":",
"0",
",",
"retweet_count",
":",
"0",
",",
"selftweet_count",
":",
"0",
",",
"}",
"tweets",
".",
"each",
"do",
"|",
"tweet",
"|",
"parsed_tweet",
"=",
"self",
".",
"parse_one",
"tweet",
"if",
"parsed_tweet",
"[",
":retweet",
"]",
"# the tweet was a retweet",
"# increase retweeted tweets count",
"retdict",
"[",
":retweet_count",
"]",
"+=",
"1",
"else",
"parsed_tweet",
"[",
":mentions",
"]",
".",
"each",
"do",
"|",
"user",
",",
"data",
"|",
"# add mentions to the mentions dict",
"retdict",
"[",
":mentions",
"]",
"[",
"user",
"]",
"||=",
"{",
"count",
":",
"0",
"}",
"retdict",
"[",
":mentions",
"]",
"[",
"user",
"]",
"[",
":count",
"]",
"+=",
"data",
"[",
":count",
"]",
"retdict",
"[",
":mentions",
"]",
"[",
"user",
"]",
"[",
":name",
"]",
"||=",
"data",
"[",
":name",
"]",
"retdict",
"[",
":mentions",
"]",
"[",
"user",
"]",
"[",
":examples",
"]",
"||=",
"[",
"]",
"retdict",
"[",
":mentions",
"]",
"[",
"user",
"]",
"[",
":examples",
"]",
"<<",
"data",
"[",
":example",
"]",
"end",
"parsed_tweet",
"[",
":hashtags",
"]",
".",
"each",
"do",
"|",
"hashtag",
",",
"data",
"|",
"# add hashtags to the hashtags dict",
"retdict",
"[",
":hashtags",
"]",
"[",
"hashtag",
"]",
"||=",
"{",
"count",
":",
"0",
"}",
"retdict",
"[",
":hashtags",
"]",
"[",
"hashtag",
"]",
"[",
":count",
"]",
"+=",
"data",
"[",
":count",
"]",
"retdict",
"[",
":hashtags",
"]",
"[",
"hashtag",
"]",
"[",
":hashtag",
"]",
"||=",
"data",
"[",
":hashtag",
"]",
"retdict",
"[",
":hashtags",
"]",
"[",
"hashtag",
"]",
"[",
":examples",
"]",
"||=",
"[",
"]",
"retdict",
"[",
":hashtags",
"]",
"[",
"hashtag",
"]",
"[",
":examples",
"]",
"<<",
"data",
"[",
":example",
"]",
"end",
"parsed_tweet",
"[",
":smileys",
"]",
".",
"each",
"do",
"|",
"smile",
",",
"data",
"|",
"retdict",
"[",
":smileys",
"]",
"[",
"smile",
"]",
"||=",
"{",
"count",
":",
"0",
"}",
"retdict",
"[",
":smileys",
"]",
"[",
"smile",
"]",
"[",
":frown",
"]",
"||=",
"data",
"[",
":frown",
"]",
"retdict",
"[",
":smileys",
"]",
"[",
"smile",
"]",
"[",
":count",
"]",
"+=",
"data",
"[",
":count",
"]",
"retdict",
"[",
":smileys",
"]",
"[",
"smile",
"]",
"[",
":smiley",
"]",
"||=",
"data",
"[",
":smiley",
"]",
"retdict",
"[",
":smileys",
"]",
"[",
"smile",
"]",
"[",
":examples",
"]",
"||=",
"[",
"]",
"retdict",
"[",
":smileys",
"]",
"[",
"smile",
"]",
"[",
":examples",
"]",
"<<",
"data",
"[",
":example",
"]",
"end",
"# increase self tweeted tweets count",
"retdict",
"[",
":selftweet_count",
"]",
"+=",
"1",
"end",
"# add client to the clients dict",
"client_dict",
"=",
"parsed_tweet",
"[",
":client",
"]",
"[",
":name",
"]",
"retdict",
"[",
":clients",
"]",
"[",
"client_dict",
"]",
"||=",
"{",
"count",
":",
"0",
"}",
"retdict",
"[",
":clients",
"]",
"[",
"client_dict",
"]",
"[",
":count",
"]",
"+=",
"1",
"retdict",
"[",
":clients",
"]",
"[",
"client_dict",
"]",
"[",
":name",
"]",
"=",
"parsed_tweet",
"[",
":client",
"]",
"[",
":name",
"]",
"retdict",
"[",
":clients",
"]",
"[",
"client_dict",
"]",
"[",
":url",
"]",
"=",
"parsed_tweet",
"[",
":client",
"]",
"[",
":url",
"]",
"retdict",
"[",
":times_of_day",
"]",
"[",
"parsed_tweet",
"[",
":time_of_day",
"]",
"]",
"+=",
"1",
"# increase tweet count",
"retdict",
"[",
":tweet_count",
"]",
"+=",
"1",
"end",
"retdict",
"end"
] |
Parses an array of tweets
Returns a dict of things
|
[
"Parses",
"an",
"array",
"of",
"tweets"
] |
e652fb8966dfcd32968789af75e8d5a4f63134ec
|
https://github.com/nilsding/Empyrean/blob/e652fb8966dfcd32968789af75e8d5a4f63134ec/lib/empyrean/tweetparser.rb#L32-L92
|
8,923
|
Fullscreen/fb-support
|
lib/fb/http_request.rb
|
Fb.HTTPRequest.run
|
def run
if response.is_a? @expected_response
self.class.on_response.call(self, response)
response.tap do
parse_response!
end
else
raise HTTPError.new(error_message, response: response)
end
end
|
ruby
|
def run
if response.is_a? @expected_response
self.class.on_response.call(self, response)
response.tap do
parse_response!
end
else
raise HTTPError.new(error_message, response: response)
end
end
|
[
"def",
"run",
"if",
"response",
".",
"is_a?",
"@expected_response",
"self",
".",
"class",
".",
"on_response",
".",
"call",
"(",
"self",
",",
"response",
")",
"response",
".",
"tap",
"do",
"parse_response!",
"end",
"else",
"raise",
"HTTPError",
".",
"new",
"(",
"error_message",
",",
"response",
":",
"response",
")",
"end",
"end"
] |
Sends the request and returns the response with the body parsed from JSON.
@return [Net::HTTPResponse] if the request succeeds.
@raise [Fb::HTTPError] if the request fails.
|
[
"Sends",
"the",
"request",
"and",
"returns",
"the",
"response",
"with",
"the",
"body",
"parsed",
"from",
"JSON",
"."
] |
4f4633cfa06dda7bb3934acb1929cbb10a4ed018
|
https://github.com/Fullscreen/fb-support/blob/4f4633cfa06dda7bb3934acb1929cbb10a4ed018/lib/fb/http_request.rb#L58-L67
|
8,924
|
userhello/bit_magic
|
lib/bit_magic/bits.rb
|
BitMagic.Bits.read
|
def read(name, field = nil)
field ||= self.field
if name.is_a?(Integer)
field.read_field(name)
elsif bits = @field_list[name]
field.read_field(bits)
end
end
|
ruby
|
def read(name, field = nil)
field ||= self.field
if name.is_a?(Integer)
field.read_field(name)
elsif bits = @field_list[name]
field.read_field(bits)
end
end
|
[
"def",
"read",
"(",
"name",
",",
"field",
"=",
"nil",
")",
"field",
"||=",
"self",
".",
"field",
"if",
"name",
".",
"is_a?",
"(",
"Integer",
")",
"field",
".",
"read_field",
"(",
"name",
")",
"elsif",
"bits",
"=",
"@field_list",
"[",
"name",
"]",
"field",
".",
"read_field",
"(",
"bits",
")",
"end",
"end"
] |
Read a field or bit from its bit index or name
@param [Symbol, Integer] name either the name of the bit (a key in field_list)
or a integer bit position
@param [BitField optional] field a specific BitField to read from.
default: return value of #field
@example Read bit values
# The struct is just an example, normally you would define a new class
Example = Struct.new('Example', :flags)
exo = Example.new(9)
bits = Bits.new(exo, {:is_odd => 0, :amount => [1, 2, 3], :is_cool => 4})
bits.read(:is_odd) #=> 1
bits.read(:amount) #=> 4
bits.read(:is_cool) #=> 0
bits.read(:amount, BitField.new(78)) #=> 7
# Bonus: aliased as []
bits[:is_odd] #=> 1
@return [Integer] a value of the bit (0 or 1) or bits (number from 0 to
(2**bit_length) - 1) or nil if the field name is not in the list
|
[
"Read",
"a",
"field",
"or",
"bit",
"from",
"its",
"bit",
"index",
"or",
"name"
] |
78b7fc28313af9c9506220812573576d229186bb
|
https://github.com/userhello/bit_magic/blob/78b7fc28313af9c9506220812573576d229186bb/lib/bit_magic/bits.rb#L219-L227
|
8,925
|
userhello/bit_magic
|
lib/bit_magic/bits.rb
|
BitMagic.Bits.write
|
def write(name, target_value)
if name.is_a?(Symbol)
self.write(@field_list[name], target_value)
elsif name.is_a?(Integer)
self.update self.field.write_bits(name => @options[:bool_caster].call(target_value))
elsif name.respond_to?(:[]) and target_value.respond_to?(:[])
bits = {}
name.each_with_index do |bit, i|
bits[bit] = @options[:bool_caster].call(target_value[i])
end
self.update self.field.write_bits bits
end
end
|
ruby
|
def write(name, target_value)
if name.is_a?(Symbol)
self.write(@field_list[name], target_value)
elsif name.is_a?(Integer)
self.update self.field.write_bits(name => @options[:bool_caster].call(target_value))
elsif name.respond_to?(:[]) and target_value.respond_to?(:[])
bits = {}
name.each_with_index do |bit, i|
bits[bit] = @options[:bool_caster].call(target_value[i])
end
self.update self.field.write_bits bits
end
end
|
[
"def",
"write",
"(",
"name",
",",
"target_value",
")",
"if",
"name",
".",
"is_a?",
"(",
"Symbol",
")",
"self",
".",
"write",
"(",
"@field_list",
"[",
"name",
"]",
",",
"target_value",
")",
"elsif",
"name",
".",
"is_a?",
"(",
"Integer",
")",
"self",
".",
"update",
"self",
".",
"field",
".",
"write_bits",
"(",
"name",
"=>",
"@options",
"[",
":bool_caster",
"]",
".",
"call",
"(",
"target_value",
")",
")",
"elsif",
"name",
".",
"respond_to?",
"(",
":[]",
")",
"and",
"target_value",
".",
"respond_to?",
"(",
":[]",
")",
"bits",
"=",
"{",
"}",
"name",
".",
"each_with_index",
"do",
"|",
"bit",
",",
"i",
"|",
"bits",
"[",
"bit",
"]",
"=",
"@options",
"[",
":bool_caster",
"]",
".",
"call",
"(",
"target_value",
"[",
"i",
"]",
")",
"end",
"self",
".",
"update",
"self",
".",
"field",
".",
"write_bits",
"bits",
"end",
"end"
] |
Write a field or bit from its field name or index
Note: only the total bits of the field is used from the given value, so
any additional bits are ignored. eg: writing a field with one bit as value
of 4 will set the bit to 0, writing 5 sets it to 1.
@param [Symbol, Integer, Array<Integer>] name a field name, or bit position,
or array of bit positions
@param [Integer, Array<Integer>] target_value the target value for the field
(note: technically, this can be anything that responds to :[](index), but
usage in that type of context is discouraged without adapter support)
@example Write values to bit fields
# The struct is just an example, normally you would define a new class
Example = Struct.new('Example', :flags)
exo = Example.new(0)
bits = Bits.new(exo, {:is_odd => 0, :amount => [1, 2, 3], :is_cool => 4})
bits.write(:is_odd, 1) #=> 1
bits.write(:amount, 5) #=> 11
exo.flags #=> 11
# Bonus, aliased as :[]=, but note in this mode, the return value is same as given value
bits[:is_cool] = 1 #=> 1
exo.flags #=> 27
@return the return value of the updater Proc, usually is equal to the final
master value (with all the bits) after writing this bit
|
[
"Write",
"a",
"field",
"or",
"bit",
"from",
"its",
"field",
"name",
"or",
"index"
] |
78b7fc28313af9c9506220812573576d229186bb
|
https://github.com/userhello/bit_magic/blob/78b7fc28313af9c9506220812573576d229186bb/lib/bit_magic/bits.rb#L257-L271
|
8,926
|
zobar/mass_shootings
|
lib/mass_shootings/shooting.rb
|
MassShootings.Shooting.as_json
|
def as_json(_=nil)
json = {'id' => id}
json['allegedShooters'] = alleged_shooters unless alleged_shooters.nil?
json.merge(
'casualties' => casualties.stringify_keys,
'date' => date.iso8601,
'location' => location,
'references' => references.map(&:to_s))
end
|
ruby
|
def as_json(_=nil)
json = {'id' => id}
json['allegedShooters'] = alleged_shooters unless alleged_shooters.nil?
json.merge(
'casualties' => casualties.stringify_keys,
'date' => date.iso8601,
'location' => location,
'references' => references.map(&:to_s))
end
|
[
"def",
"as_json",
"(",
"_",
"=",
"nil",
")",
"json",
"=",
"{",
"'id'",
"=>",
"id",
"}",
"json",
"[",
"'allegedShooters'",
"]",
"=",
"alleged_shooters",
"unless",
"alleged_shooters",
".",
"nil?",
"json",
".",
"merge",
"(",
"'casualties'",
"=>",
"casualties",
".",
"stringify_keys",
",",
"'date'",
"=>",
"date",
".",
"iso8601",
",",
"'location'",
"=>",
"location",
",",
"'references'",
"=>",
"references",
".",
"map",
"(",
":to_s",
")",
")",
"end"
] |
Returns a hash representing the shooting.
@return [Hash{String => Object}]
|
[
"Returns",
"a",
"hash",
"representing",
"the",
"shooting",
"."
] |
dfed9c68c7216c30e7d3a9962dc7d684b28299bf
|
https://github.com/zobar/mass_shootings/blob/dfed9c68c7216c30e7d3a9962dc7d684b28299bf/lib/mass_shootings/shooting.rb#L45-L53
|
8,927
|
kmewhort/similarity_tree
|
lib/similarity_tree/similarity_tree.rb
|
SimilarityTree.SimilarityTree.prune
|
def prune(nodes)
nodes.each do |node|
node.parent.children.reject!{|n| n == node} if (node != @root) && (node.diff_score < @score_threshold)
end
end
|
ruby
|
def prune(nodes)
nodes.each do |node|
node.parent.children.reject!{|n| n == node} if (node != @root) && (node.diff_score < @score_threshold)
end
end
|
[
"def",
"prune",
"(",
"nodes",
")",
"nodes",
".",
"each",
"do",
"|",
"node",
"|",
"node",
".",
"parent",
".",
"children",
".",
"reject!",
"{",
"|",
"n",
"|",
"n",
"==",
"node",
"}",
"if",
"(",
"node",
"!=",
"@root",
")",
"&&",
"(",
"node",
".",
"diff_score",
"<",
"@score_threshold",
")",
"end",
"end"
] |
prune away nodes that don't meet the configured score threshold
|
[
"prune",
"away",
"nodes",
"that",
"don",
"t",
"meet",
"the",
"configured",
"score",
"threshold"
] |
d688c6d86e2a5a81ff71e81ef805c9af6cb8c8e7
|
https://github.com/kmewhort/similarity_tree/blob/d688c6d86e2a5a81ff71e81ef805c9af6cb8c8e7/lib/similarity_tree/similarity_tree.rb#L75-L79
|
8,928
|
aprescott/redhead
|
lib/redhead/redhead_string.rb
|
Redhead.String.headers!
|
def headers!(hash)
changing = headers.select { |header| hash.has_key?(header.key) }
# modifies its elements!
changing.each do |header|
new_values = hash[header.key]
header.raw = new_values[:raw] if new_values[:raw]
header.key = new_values[:key] if new_values[:key]
end
Redhead::HeaderSet.new(changing)
end
|
ruby
|
def headers!(hash)
changing = headers.select { |header| hash.has_key?(header.key) }
# modifies its elements!
changing.each do |header|
new_values = hash[header.key]
header.raw = new_values[:raw] if new_values[:raw]
header.key = new_values[:key] if new_values[:key]
end
Redhead::HeaderSet.new(changing)
end
|
[
"def",
"headers!",
"(",
"hash",
")",
"changing",
"=",
"headers",
".",
"select",
"{",
"|",
"header",
"|",
"hash",
".",
"has_key?",
"(",
"header",
".",
"key",
")",
"}",
"# modifies its elements!",
"changing",
".",
"each",
"do",
"|",
"header",
"|",
"new_values",
"=",
"hash",
"[",
"header",
".",
"key",
"]",
"header",
".",
"raw",
"=",
"new_values",
"[",
":raw",
"]",
"if",
"new_values",
"[",
":raw",
"]",
"header",
".",
"key",
"=",
"new_values",
"[",
":key",
"]",
"if",
"new_values",
"[",
":key",
"]",
"end",
"Redhead",
"::",
"HeaderSet",
".",
"new",
"(",
"changing",
")",
"end"
] |
Returns true if self.headers == other.headers and self.string == other.string.
Modifies the headers in the set, using the given _hash_, which has the form
{ some_header: { raw: a, key: b }, another_header: ..., ... }
Change the header with key :some_header such that its new raw name is _a_ and its new key name
is _b_. Returns a HeaderSet object containing the changed Header objects.
|
[
"Returns",
"true",
"if",
"self",
".",
"headers",
"==",
"other",
".",
"headers",
"and",
"self",
".",
"string",
"==",
"other",
".",
"string",
".",
"Modifies",
"the",
"headers",
"in",
"the",
"set",
"using",
"the",
"given",
"_hash_",
"which",
"has",
"the",
"form"
] |
4fe032029e6d3e5ebe88d61bbb0d5150fe204b3d
|
https://github.com/aprescott/redhead/blob/4fe032029e6d3e5ebe88d61bbb0d5150fe204b3d/lib/redhead/redhead_string.rb#L82-L93
|
8,929
|
fugroup/easymongo
|
lib/easymongo/document.rb
|
Easymongo.Document.method_missing
|
def method_missing(name, *args, &block)
return attr(name[0..-2], args[0]) if args.size == 1 and name[-1] == '='
end
|
ruby
|
def method_missing(name, *args, &block)
return attr(name[0..-2], args[0]) if args.size == 1 and name[-1] == '='
end
|
[
"def",
"method_missing",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"return",
"attr",
"(",
"name",
"[",
"0",
"..",
"-",
"2",
"]",
",",
"args",
"[",
"0",
"]",
")",
"if",
"args",
".",
"size",
"==",
"1",
"and",
"name",
"[",
"-",
"1",
"]",
"==",
"'='",
"end"
] |
Dynamically write value
|
[
"Dynamically",
"write",
"value"
] |
a48675248eafcd4885278d3196600c8ebda46240
|
https://github.com/fugroup/easymongo/blob/a48675248eafcd4885278d3196600c8ebda46240/lib/easymongo/document.rb#L41-L43
|
8,930
|
bcobb/and_feathers
|
lib/and_feathers/sugar.rb
|
AndFeathers.Sugar.dir
|
def dir(name, mode = 16877, &block)
name_parts = name.split(::File::SEPARATOR)
innermost_child_name = name_parts.pop
if name_parts.empty?
Directory.new(name, mode).tap do |directory|
add_directory(directory)
block.call(directory) if block
end
else
innermost_parent = name_parts.reduce(self) do |parent, child_name|
parent.dir(child_name)
end
innermost_parent.dir(innermost_child_name, &block)
end
end
|
ruby
|
def dir(name, mode = 16877, &block)
name_parts = name.split(::File::SEPARATOR)
innermost_child_name = name_parts.pop
if name_parts.empty?
Directory.new(name, mode).tap do |directory|
add_directory(directory)
block.call(directory) if block
end
else
innermost_parent = name_parts.reduce(self) do |parent, child_name|
parent.dir(child_name)
end
innermost_parent.dir(innermost_child_name, &block)
end
end
|
[
"def",
"dir",
"(",
"name",
",",
"mode",
"=",
"16877",
",",
"&",
"block",
")",
"name_parts",
"=",
"name",
".",
"split",
"(",
"::",
"File",
"::",
"SEPARATOR",
")",
"innermost_child_name",
"=",
"name_parts",
".",
"pop",
"if",
"name_parts",
".",
"empty?",
"Directory",
".",
"new",
"(",
"name",
",",
"mode",
")",
".",
"tap",
"do",
"|",
"directory",
"|",
"add_directory",
"(",
"directory",
")",
"block",
".",
"call",
"(",
"directory",
")",
"if",
"block",
"end",
"else",
"innermost_parent",
"=",
"name_parts",
".",
"reduce",
"(",
"self",
")",
"do",
"|",
"parent",
",",
"child_name",
"|",
"parent",
".",
"dir",
"(",
"child_name",
")",
"end",
"innermost_parent",
".",
"dir",
"(",
"innermost_child_name",
",",
"block",
")",
"end",
"end"
] |
Add a +Directory+ named +name+ to this entity's list of children. The
+name+ may simply be the name of the directory, or may be a path to the
directory.
In the case of the latter, +dir+ will create the +Directory+ tree
specified by the path. The block parameter yielded in this case will be
the innermost directory.
@example
archive = Directory.new
archive.dir('app') do |app|
app.name == 'app'
app.path == './app'
end
@example
archive.dir('app/controllers/concerns') do |concerns|
concerns.name == 'concerns'
concerns.path == './app/controllers/concerns'
end
@param name [String] the directory name
@param mode [Fixnum] the directory mode
@yieldparam directory [AndFeathers::Directory] the newly-created
+Directory+
|
[
"Add",
"a",
"+",
"Directory",
"+",
"named",
"+",
"name",
"+",
"to",
"this",
"entity",
"s",
"list",
"of",
"children",
".",
"The",
"+",
"name",
"+",
"may",
"simply",
"be",
"the",
"name",
"of",
"the",
"directory",
"or",
"may",
"be",
"a",
"path",
"to",
"the",
"directory",
"."
] |
f35b156f8ae6930851712bbaf502f97b3aa9a1b1
|
https://github.com/bcobb/and_feathers/blob/f35b156f8ae6930851712bbaf502f97b3aa9a1b1/lib/and_feathers/sugar.rb#L35-L53
|
8,931
|
bcobb/and_feathers
|
lib/and_feathers/sugar.rb
|
AndFeathers.Sugar.file
|
def file(name, mode = 33188, &content)
content ||= NO_CONTENT
name_parts = name.split(::File::SEPARATOR)
file_name = name_parts.pop
if name_parts.empty?
File.new(name, mode, content).tap do |file|
add_file(file)
end
else
dir(name_parts.join(::File::SEPARATOR)) do |parent|
parent.file(file_name, mode, &content)
end
end
end
|
ruby
|
def file(name, mode = 33188, &content)
content ||= NO_CONTENT
name_parts = name.split(::File::SEPARATOR)
file_name = name_parts.pop
if name_parts.empty?
File.new(name, mode, content).tap do |file|
add_file(file)
end
else
dir(name_parts.join(::File::SEPARATOR)) do |parent|
parent.file(file_name, mode, &content)
end
end
end
|
[
"def",
"file",
"(",
"name",
",",
"mode",
"=",
"33188",
",",
"&",
"content",
")",
"content",
"||=",
"NO_CONTENT",
"name_parts",
"=",
"name",
".",
"split",
"(",
"::",
"File",
"::",
"SEPARATOR",
")",
"file_name",
"=",
"name_parts",
".",
"pop",
"if",
"name_parts",
".",
"empty?",
"File",
".",
"new",
"(",
"name",
",",
"mode",
",",
"content",
")",
".",
"tap",
"do",
"|",
"file",
"|",
"add_file",
"(",
"file",
")",
"end",
"else",
"dir",
"(",
"name_parts",
".",
"join",
"(",
"::",
"File",
"::",
"SEPARATOR",
")",
")",
"do",
"|",
"parent",
"|",
"parent",
".",
"file",
"(",
"file_name",
",",
"mode",
",",
"content",
")",
"end",
"end",
"end"
] |
Add a +File+ named +name+ to this entity's list of children. The +name+
may simply be the name of the file or may be a path to the file.
In the case of the latter, +file+ will create the +Directory+ tree
which contains the +File+ specified by the path.
Either way, the +File+'s contents will be set to the result of the
given block, or to a blank string if no block is given
@example
archive = Directory.new
archive.file('README') do
"Cool"
end
@example
archive = Directory.new
archive.file('app/models/user.rb') do
"class User < ActiveRecord::Base\nend"
end
@param name [String] the file name
@param mode [Fixnum] the file mode
@yieldreturn [String] the file contents
|
[
"Add",
"a",
"+",
"File",
"+",
"named",
"+",
"name",
"+",
"to",
"this",
"entity",
"s",
"list",
"of",
"children",
".",
"The",
"+",
"name",
"+",
"may",
"simply",
"be",
"the",
"name",
"of",
"the",
"file",
"or",
"may",
"be",
"a",
"path",
"to",
"the",
"file",
"."
] |
f35b156f8ae6930851712bbaf502f97b3aa9a1b1
|
https://github.com/bcobb/and_feathers/blob/f35b156f8ae6930851712bbaf502f97b3aa9a1b1/lib/and_feathers/sugar.rb#L87-L103
|
8,932
|
dwilkie/tropo_message
|
lib/tropo_message.rb
|
Tropo.Message.request_xml
|
def request_xml
request_params = @params.dup
token = request_params.delete("token")
xml = ""
request_params.each do |key, value|
xml << "<var name=\"#{escape(key)}\" value=\"#{escape(value)}\"/>"
end
"<sessions><token>#{token}</token>#{xml}</sessions>"
end
|
ruby
|
def request_xml
request_params = @params.dup
token = request_params.delete("token")
xml = ""
request_params.each do |key, value|
xml << "<var name=\"#{escape(key)}\" value=\"#{escape(value)}\"/>"
end
"<sessions><token>#{token}</token>#{xml}</sessions>"
end
|
[
"def",
"request_xml",
"request_params",
"=",
"@params",
".",
"dup",
"token",
"=",
"request_params",
".",
"delete",
"(",
"\"token\"",
")",
"xml",
"=",
"\"\"",
"request_params",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"xml",
"<<",
"\"<var name=\\\"#{escape(key)}\\\" value=\\\"#{escape(value)}\\\"/>\"",
"end",
"\"<sessions><token>#{token}</token>#{xml}</sessions>\"",
"end"
] |
Generates xml suitable for an XML POST request to Tropo
Example:
tropo_message = Tropo::Message.new
tropo_message.to = "44122782474"
tropo_message.text = "Hi John, how r u today?"
tropo_message.token = "1234512345"
tropo_message.request_xml # =>
# <sessions>
# <token>1234512345</token>
# <var name="to" value="44122782474"/>
# <var name="text" value="Hi+John%2C+how+r+u+today%3F"/>
# </sessions>"
|
[
"Generates",
"xml",
"suitable",
"for",
"an",
"XML",
"POST",
"request",
"to",
"Tropo"
] |
a04b7ed96e8398baebbcf44d0b959c23e525d400
|
https://github.com/dwilkie/tropo_message/blob/a04b7ed96e8398baebbcf44d0b959c23e525d400/lib/tropo_message.rb#L52-L60
|
8,933
|
phallguy/shamu
|
lib/shamu/attributes.rb
|
Shamu.Attributes.to_attributes
|
def to_attributes( only: nil, except: nil )
self.class.attributes.each_with_object({}) do |(name, options), attrs|
next if ( only && !match_attribute?( only, name ) ) || ( except && match_attribute?( except, name ) )
next unless serialize_attribute?( name, options )
attrs[name] = send( name )
end
end
|
ruby
|
def to_attributes( only: nil, except: nil )
self.class.attributes.each_with_object({}) do |(name, options), attrs|
next if ( only && !match_attribute?( only, name ) ) || ( except && match_attribute?( except, name ) )
next unless serialize_attribute?( name, options )
attrs[name] = send( name )
end
end
|
[
"def",
"to_attributes",
"(",
"only",
":",
"nil",
",",
"except",
":",
"nil",
")",
"self",
".",
"class",
".",
"attributes",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"name",
",",
"options",
")",
",",
"attrs",
"|",
"next",
"if",
"(",
"only",
"&&",
"!",
"match_attribute?",
"(",
"only",
",",
"name",
")",
")",
"||",
"(",
"except",
"&&",
"match_attribute?",
"(",
"except",
",",
"name",
")",
")",
"next",
"unless",
"serialize_attribute?",
"(",
"name",
",",
"options",
")",
"attrs",
"[",
"name",
"]",
"=",
"send",
"(",
"name",
")",
"end",
"end"
] |
Project the current state of the object to a hash of attributes that can
be used to restore the attribute object at a later time.
@param [Array, Regex] only include matching attributes
@param [Array, Regex] except matching attributes
@return [Hash] of attributes
|
[
"Project",
"the",
"current",
"state",
"of",
"the",
"object",
"to",
"a",
"hash",
"of",
"attributes",
"that",
"can",
"be",
"used",
"to",
"restore",
"the",
"attribute",
"object",
"at",
"a",
"later",
"time",
"."
] |
527d5cc8ebc45a9d3f35ea43681cee6fa9255093
|
https://github.com/phallguy/shamu/blob/527d5cc8ebc45a9d3f35ea43681cee6fa9255093/lib/shamu/attributes.rb#L46-L53
|
8,934
|
mccraigmccraig/rsxml
|
lib/rsxml/namespace.rb
|
Rsxml.Namespace.compact_attr_qnames
|
def compact_attr_qnames(ns_stack, attrs)
Hash[attrs.map do |name,value|
[compact_qname(ns_stack, name), value]
end]
end
|
ruby
|
def compact_attr_qnames(ns_stack, attrs)
Hash[attrs.map do |name,value|
[compact_qname(ns_stack, name), value]
end]
end
|
[
"def",
"compact_attr_qnames",
"(",
"ns_stack",
",",
"attrs",
")",
"Hash",
"[",
"attrs",
".",
"map",
"do",
"|",
"name",
",",
"value",
"|",
"[",
"compact_qname",
"(",
"ns_stack",
",",
"name",
")",
",",
"value",
"]",
"end",
"]",
"end"
] |
compact all attribute QNames to Strings
|
[
"compact",
"all",
"attribute",
"QNames",
"to",
"Strings"
] |
3699c186f01be476a5942d64cd5c39f4d6bbe175
|
https://github.com/mccraigmccraig/rsxml/blob/3699c186f01be476a5942d64cd5c39f4d6bbe175/lib/rsxml/namespace.rb#L6-L10
|
8,935
|
mccraigmccraig/rsxml
|
lib/rsxml/namespace.rb
|
Rsxml.Namespace.find_namespace_uri
|
def find_namespace_uri(ns_stack, prefix, uri_check=nil)
tns = ns_stack.reverse.find{|ns| ns.has_key?(prefix)}
uri = tns[prefix] if tns
raise "prefix: '#{prefix}' is bound to uri: '#{uri}', but should be '#{uri_check}'" if uri_check && uri && uri!=uri_check
uri
end
|
ruby
|
def find_namespace_uri(ns_stack, prefix, uri_check=nil)
tns = ns_stack.reverse.find{|ns| ns.has_key?(prefix)}
uri = tns[prefix] if tns
raise "prefix: '#{prefix}' is bound to uri: '#{uri}', but should be '#{uri_check}'" if uri_check && uri && uri!=uri_check
uri
end
|
[
"def",
"find_namespace_uri",
"(",
"ns_stack",
",",
"prefix",
",",
"uri_check",
"=",
"nil",
")",
"tns",
"=",
"ns_stack",
".",
"reverse",
".",
"find",
"{",
"|",
"ns",
"|",
"ns",
".",
"has_key?",
"(",
"prefix",
")",
"}",
"uri",
"=",
"tns",
"[",
"prefix",
"]",
"if",
"tns",
"raise",
"\"prefix: '#{prefix}' is bound to uri: '#{uri}', but should be '#{uri_check}'\"",
"if",
"uri_check",
"&&",
"uri",
"&&",
"uri!",
"=",
"uri_check",
"uri",
"end"
] |
returns the namespace uri for a prefix, if declared in the stack
|
[
"returns",
"the",
"namespace",
"uri",
"for",
"a",
"prefix",
"if",
"declared",
"in",
"the",
"stack"
] |
3699c186f01be476a5942d64cd5c39f4d6bbe175
|
https://github.com/mccraigmccraig/rsxml/blob/3699c186f01be476a5942d64cd5c39f4d6bbe175/lib/rsxml/namespace.rb#L96-L101
|
8,936
|
mccraigmccraig/rsxml
|
lib/rsxml/namespace.rb
|
Rsxml.Namespace.undeclared_namespace_bindings
|
def undeclared_namespace_bindings(ns_stack, ns_explicit)
Hash[ns_explicit.map do |prefix,uri|
[prefix, uri] if !find_namespace_uri(ns_stack, prefix, uri)
end.compact]
end
|
ruby
|
def undeclared_namespace_bindings(ns_stack, ns_explicit)
Hash[ns_explicit.map do |prefix,uri|
[prefix, uri] if !find_namespace_uri(ns_stack, prefix, uri)
end.compact]
end
|
[
"def",
"undeclared_namespace_bindings",
"(",
"ns_stack",
",",
"ns_explicit",
")",
"Hash",
"[",
"ns_explicit",
".",
"map",
"do",
"|",
"prefix",
",",
"uri",
"|",
"[",
"prefix",
",",
"uri",
"]",
"if",
"!",
"find_namespace_uri",
"(",
"ns_stack",
",",
"prefix",
",",
"uri",
")",
"end",
".",
"compact",
"]",
"end"
] |
figure out which explicit namespaces need declaring
+ns_stack+ is the stack of namespace bindings
+ns_explicit+ is the explicit refs for a element
|
[
"figure",
"out",
"which",
"explicit",
"namespaces",
"need",
"declaring"
] |
3699c186f01be476a5942d64cd5c39f4d6bbe175
|
https://github.com/mccraigmccraig/rsxml/blob/3699c186f01be476a5942d64cd5c39f4d6bbe175/lib/rsxml/namespace.rb#L140-L144
|
8,937
|
mccraigmccraig/rsxml
|
lib/rsxml/namespace.rb
|
Rsxml.Namespace.exploded_namespace_declarations
|
def exploded_namespace_declarations(ns)
Hash[ns.map do |prefix, uri|
if prefix==""
["xmlns", uri]
else
[[prefix, "xmlns"], uri]
end
end]
end
|
ruby
|
def exploded_namespace_declarations(ns)
Hash[ns.map do |prefix, uri|
if prefix==""
["xmlns", uri]
else
[[prefix, "xmlns"], uri]
end
end]
end
|
[
"def",
"exploded_namespace_declarations",
"(",
"ns",
")",
"Hash",
"[",
"ns",
".",
"map",
"do",
"|",
"prefix",
",",
"uri",
"|",
"if",
"prefix",
"==",
"\"\"",
"[",
"\"xmlns\"",
",",
"uri",
"]",
"else",
"[",
"[",
"prefix",
",",
"\"xmlns\"",
"]",
",",
"uri",
"]",
"end",
"end",
"]",
"end"
] |
produce a Hash of namespace declaration attributes with exploded
QNames, from
a Hash of namespace prefix bindings
|
[
"produce",
"a",
"Hash",
"of",
"namespace",
"declaration",
"attributes",
"with",
"exploded",
"QNames",
"from",
"a",
"Hash",
"of",
"namespace",
"prefix",
"bindings"
] |
3699c186f01be476a5942d64cd5c39f4d6bbe175
|
https://github.com/mccraigmccraig/rsxml/blob/3699c186f01be476a5942d64cd5c39f4d6bbe175/lib/rsxml/namespace.rb#L149-L157
|
8,938
|
mccraigmccraig/rsxml
|
lib/rsxml/namespace.rb
|
Rsxml.Namespace.namespace_attributes
|
def namespace_attributes(ns)
Hash[ns.map do |prefix, uri|
if prefix==""
["xmlns", uri]
else
[["xmlns", prefix].join(":"), uri]
end
end]
end
|
ruby
|
def namespace_attributes(ns)
Hash[ns.map do |prefix, uri|
if prefix==""
["xmlns", uri]
else
[["xmlns", prefix].join(":"), uri]
end
end]
end
|
[
"def",
"namespace_attributes",
"(",
"ns",
")",
"Hash",
"[",
"ns",
".",
"map",
"do",
"|",
"prefix",
",",
"uri",
"|",
"if",
"prefix",
"==",
"\"\"",
"[",
"\"xmlns\"",
",",
"uri",
"]",
"else",
"[",
"[",
"\"xmlns\"",
",",
"prefix",
"]",
".",
"join",
"(",
"\":\"",
")",
",",
"uri",
"]",
"end",
"end",
"]",
"end"
] |
produces a Hash of compact namespace attributes from a
Hash of namespace bindings
|
[
"produces",
"a",
"Hash",
"of",
"compact",
"namespace",
"attributes",
"from",
"a",
"Hash",
"of",
"namespace",
"bindings"
] |
3699c186f01be476a5942d64cd5c39f4d6bbe175
|
https://github.com/mccraigmccraig/rsxml/blob/3699c186f01be476a5942d64cd5c39f4d6bbe175/lib/rsxml/namespace.rb#L161-L169
|
8,939
|
mccraigmccraig/rsxml
|
lib/rsxml/namespace.rb
|
Rsxml.Namespace.merge_namespace_bindings
|
def merge_namespace_bindings(ns1, ns2)
m = ns1.clone
ns2.each do |k,v|
raise "bindings clash: '#{k}'=>'#{m[k]}' , '#{k}'=>'#{v}'" if m.has_key?(k) && m[k]!=v
m[k]=v
end
m
end
|
ruby
|
def merge_namespace_bindings(ns1, ns2)
m = ns1.clone
ns2.each do |k,v|
raise "bindings clash: '#{k}'=>'#{m[k]}' , '#{k}'=>'#{v}'" if m.has_key?(k) && m[k]!=v
m[k]=v
end
m
end
|
[
"def",
"merge_namespace_bindings",
"(",
"ns1",
",",
"ns2",
")",
"m",
"=",
"ns1",
".",
"clone",
"ns2",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"raise",
"\"bindings clash: '#{k}'=>'#{m[k]}' , '#{k}'=>'#{v}'\"",
"if",
"m",
".",
"has_key?",
"(",
"k",
")",
"&&",
"m",
"[",
"k",
"]",
"!=",
"v",
"m",
"[",
"k",
"]",
"=",
"v",
"end",
"m",
"end"
] |
merges two sets of namespace bindings, raising error on clash
|
[
"merges",
"two",
"sets",
"of",
"namespace",
"bindings",
"raising",
"error",
"on",
"clash"
] |
3699c186f01be476a5942d64cd5c39f4d6bbe175
|
https://github.com/mccraigmccraig/rsxml/blob/3699c186f01be476a5942d64cd5c39f4d6bbe175/lib/rsxml/namespace.rb#L172-L179
|
8,940
|
LRDesign/Caliph
|
lib/caliph/shell.rb
|
Caliph.Shell.spawn_process
|
def spawn_process(command_line)
host_stdout, cmd_stdout = IO.pipe
host_stderr, cmd_stderr = IO.pipe
pid = Process.spawn(command_line.command_environment, command_line.command, :out => cmd_stdout, :err => cmd_stderr)
cmd_stdout.close
cmd_stderr.close
return pid, host_stdout, host_stderr
end
|
ruby
|
def spawn_process(command_line)
host_stdout, cmd_stdout = IO.pipe
host_stderr, cmd_stderr = IO.pipe
pid = Process.spawn(command_line.command_environment, command_line.command, :out => cmd_stdout, :err => cmd_stderr)
cmd_stdout.close
cmd_stderr.close
return pid, host_stdout, host_stderr
end
|
[
"def",
"spawn_process",
"(",
"command_line",
")",
"host_stdout",
",",
"cmd_stdout",
"=",
"IO",
".",
"pipe",
"host_stderr",
",",
"cmd_stderr",
"=",
"IO",
".",
"pipe",
"pid",
"=",
"Process",
".",
"spawn",
"(",
"command_line",
".",
"command_environment",
",",
"command_line",
".",
"command",
",",
":out",
"=>",
"cmd_stdout",
",",
":err",
"=>",
"cmd_stderr",
")",
"cmd_stdout",
".",
"close",
"cmd_stderr",
".",
"close",
"return",
"pid",
",",
"host_stdout",
",",
"host_stderr",
"end"
] |
Creates a process to run a command. Handles connecting pipes to stardard
streams, launching the process and returning a pid for it.
@return [pid, host_stdout, host_stderr] the process id and streams
associated with the child process
|
[
"Creates",
"a",
"process",
"to",
"run",
"a",
"command",
".",
"Handles",
"connecting",
"pipes",
"to",
"stardard",
"streams",
"launching",
"the",
"process",
"and",
"returning",
"a",
"pid",
"for",
"it",
"."
] |
9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99
|
https://github.com/LRDesign/Caliph/blob/9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99/lib/caliph/shell.rb#L77-L86
|
8,941
|
LRDesign/Caliph
|
lib/caliph/shell.rb
|
Caliph.Shell.execute
|
def execute(command_line)
result = collect_result(command_line, *spawn_process(command_line))
result.wait
result
end
|
ruby
|
def execute(command_line)
result = collect_result(command_line, *spawn_process(command_line))
result.wait
result
end
|
[
"def",
"execute",
"(",
"command_line",
")",
"result",
"=",
"collect_result",
"(",
"command_line",
",",
"spawn_process",
"(",
"command_line",
")",
")",
"result",
".",
"wait",
"result",
"end"
] |
Run the command, wait for termination, and collect the results.
Returns an instance of CommandRunResult that contains the output
and exit code of the command.
|
[
"Run",
"the",
"command",
"wait",
"for",
"termination",
"and",
"collect",
"the",
"results",
".",
"Returns",
"an",
"instance",
"of",
"CommandRunResult",
"that",
"contains",
"the",
"output",
"and",
"exit",
"code",
"of",
"the",
"command",
"."
] |
9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99
|
https://github.com/LRDesign/Caliph/blob/9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99/lib/caliph/shell.rb#L92-L96
|
8,942
|
LRDesign/Caliph
|
lib/caliph/shell.rb
|
Caliph.Shell.run_as_replacement
|
def run_as_replacement(*args, &block)
command_line = normalize_command_line(*args, &block)
report "Ceding execution to: "
report command_line.string_format
Process.exec(command_line.command_environment, command_line.command)
end
|
ruby
|
def run_as_replacement(*args, &block)
command_line = normalize_command_line(*args, &block)
report "Ceding execution to: "
report command_line.string_format
Process.exec(command_line.command_environment, command_line.command)
end
|
[
"def",
"run_as_replacement",
"(",
"*",
"args",
",",
"&",
"block",
")",
"command_line",
"=",
"normalize_command_line",
"(",
"args",
",",
"block",
")",
"report",
"\"Ceding execution to: \"",
"report",
"command_line",
".",
"string_format",
"Process",
".",
"exec",
"(",
"command_line",
".",
"command_environment",
",",
"command_line",
".",
"command",
")",
"end"
] |
Completely replace the running process with a command. Good for setting
up a command and then running it, without worrying about what happens
after that. Uses `exec` under the hood.
@macro normalized
@example Using replace_us
# The last thing we'll ever do:
shell.run_as_replacement('echo', "Everything is okay")
# don't worry, we never get here.
shell.run("sudo", "shutdown -h now")
|
[
"Completely",
"replace",
"the",
"running",
"process",
"with",
"a",
"command",
".",
"Good",
"for",
"setting",
"up",
"a",
"command",
"and",
"then",
"running",
"it",
"without",
"worrying",
"about",
"what",
"happens",
"after",
"that",
".",
"Uses",
"exec",
"under",
"the",
"hood",
"."
] |
9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99
|
https://github.com/LRDesign/Caliph/blob/9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99/lib/caliph/shell.rb#L134-L140
|
8,943
|
LRDesign/Caliph
|
lib/caliph/shell.rb
|
Caliph.Shell.run_detached
|
def run_detached(*args, &block)
command_line = normalize_command_line(*args, &block)
pid, out, err = spawn_process(command_line)
Process.detach(pid)
return collect_result(command_line, pid, out, err)
end
|
ruby
|
def run_detached(*args, &block)
command_line = normalize_command_line(*args, &block)
pid, out, err = spawn_process(command_line)
Process.detach(pid)
return collect_result(command_line, pid, out, err)
end
|
[
"def",
"run_detached",
"(",
"*",
"args",
",",
"&",
"block",
")",
"command_line",
"=",
"normalize_command_line",
"(",
"args",
",",
"block",
")",
"pid",
",",
"out",
",",
"err",
"=",
"spawn_process",
"(",
"command_line",
")",
"Process",
".",
"detach",
"(",
"pid",
")",
"return",
"collect_result",
"(",
"command_line",
",",
"pid",
",",
"out",
",",
"err",
")",
"end"
] |
Run the command in the background. The command can survive the caller.
Works, for instance, to kick off some long running processes that we
don't care about. Note that this isn't quite full daemonization - we
don't close the streams of the other process, or scrub its environment or
anything.
@macro normalized
|
[
"Run",
"the",
"command",
"in",
"the",
"background",
".",
"The",
"command",
"can",
"survive",
"the",
"caller",
".",
"Works",
"for",
"instance",
"to",
"kick",
"off",
"some",
"long",
"running",
"processes",
"that",
"we",
"don",
"t",
"care",
"about",
".",
"Note",
"that",
"this",
"isn",
"t",
"quite",
"full",
"daemonization",
"-",
"we",
"don",
"t",
"close",
"the",
"streams",
"of",
"the",
"other",
"process",
"or",
"scrub",
"its",
"environment",
"or",
"anything",
"."
] |
9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99
|
https://github.com/LRDesign/Caliph/blob/9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99/lib/caliph/shell.rb#L149-L155
|
8,944
|
neiljohari/scram
|
lib/scram/concerns/holder.rb
|
Scram.Holder.can?
|
def can? action, target
target = target.to_s if target.is_a? Symbol
action = action.to_s
# Checks policies in priority order for explicit allow or deny.
policies.sort_by(&:priority).reverse.each do |policy|
opinion = policy.can?(self, action, target)
return opinion.to_bool if %i[allow deny].include? opinion
end
return false
end
|
ruby
|
def can? action, target
target = target.to_s if target.is_a? Symbol
action = action.to_s
# Checks policies in priority order for explicit allow or deny.
policies.sort_by(&:priority).reverse.each do |policy|
opinion = policy.can?(self, action, target)
return opinion.to_bool if %i[allow deny].include? opinion
end
return false
end
|
[
"def",
"can?",
"action",
",",
"target",
"target",
"=",
"target",
".",
"to_s",
"if",
"target",
".",
"is_a?",
"Symbol",
"action",
"=",
"action",
".",
"to_s",
"# Checks policies in priority order for explicit allow or deny.",
"policies",
".",
"sort_by",
"(",
":priority",
")",
".",
"reverse",
".",
"each",
"do",
"|",
"policy",
"|",
"opinion",
"=",
"policy",
".",
"can?",
"(",
"self",
",",
"action",
",",
"target",
")",
"return",
"opinion",
".",
"to_bool",
"if",
"%i[",
"allow",
"deny",
"]",
".",
"include?",
"opinion",
"end",
"return",
"false",
"end"
] |
Checks if this holder can perform some action on an object by checking the Holder's policies
@param action [String] What the user is trying to do to obj
@param obj [Object] The receiver of the action
@return [Boolean] Whether or not holder can action to object. We define a full abstainment as a failure to perform the action.
|
[
"Checks",
"if",
"this",
"holder",
"can",
"perform",
"some",
"action",
"on",
"an",
"object",
"by",
"checking",
"the",
"Holder",
"s",
"policies"
] |
df3e48e9e9cab4b363b1370df5991319d21c256d
|
https://github.com/neiljohari/scram/blob/df3e48e9e9cab4b363b1370df5991319d21c256d/lib/scram/concerns/holder.rb#L23-L34
|
8,945
|
kevgo/sections_rails
|
lib/sections_rails/section.rb
|
SectionsRails.Section.referenced_sections
|
def referenced_sections recursive = true
result = PartialParser.find_sections partial_content
# Find all sections within the already known sections.
if recursive
i = -1
while (i += 1) < result.size
Section.new(result[i]).referenced_sections(false).each do |referenced_section|
result << referenced_section unless result.include? referenced_section
end
end
end
result.sort!
end
|
ruby
|
def referenced_sections recursive = true
result = PartialParser.find_sections partial_content
# Find all sections within the already known sections.
if recursive
i = -1
while (i += 1) < result.size
Section.new(result[i]).referenced_sections(false).each do |referenced_section|
result << referenced_section unless result.include? referenced_section
end
end
end
result.sort!
end
|
[
"def",
"referenced_sections",
"recursive",
"=",
"true",
"result",
"=",
"PartialParser",
".",
"find_sections",
"partial_content",
"# Find all sections within the already known sections.",
"if",
"recursive",
"i",
"=",
"-",
"1",
"while",
"(",
"i",
"+=",
"1",
")",
"<",
"result",
".",
"size",
"Section",
".",
"new",
"(",
"result",
"[",
"i",
"]",
")",
".",
"referenced_sections",
"(",
"false",
")",
".",
"each",
"do",
"|",
"referenced_section",
"|",
"result",
"<<",
"referenced_section",
"unless",
"result",
".",
"include?",
"referenced_section",
"end",
"end",
"end",
"result",
".",
"sort!",
"end"
] |
Returns the sections that this section references.
If 'recursive = true' is given, searches recursively for sections referenced by the referenced sections.
Otherwise, simply returns the sections that are referenced by this section.
|
[
"Returns",
"the",
"sections",
"that",
"this",
"section",
"references",
".",
"If",
"recursive",
"=",
"true",
"is",
"given",
"searches",
"recursively",
"for",
"sections",
"referenced",
"by",
"the",
"referenced",
"sections",
".",
"Otherwise",
"simply",
"returns",
"the",
"sections",
"that",
"are",
"referenced",
"by",
"this",
"section",
"."
] |
e6e451e0888e16cc50978fe5b69797f47fdbe481
|
https://github.com/kevgo/sections_rails/blob/e6e451e0888e16cc50978fe5b69797f47fdbe481/lib/sections_rails/section.rb#L42-L55
|
8,946
|
kevgo/sections_rails
|
lib/sections_rails/section.rb
|
SectionsRails.Section.render
|
def render &block
raise "Section #{folder_filepath} doesn't exist." unless Dir.exists? folder_filepath
result = []
render_assets result if Rails.application.config.assets.compile
render_partial result, &block
result.join("\n").html_safe
end
|
ruby
|
def render &block
raise "Section #{folder_filepath} doesn't exist." unless Dir.exists? folder_filepath
result = []
render_assets result if Rails.application.config.assets.compile
render_partial result, &block
result.join("\n").html_safe
end
|
[
"def",
"render",
"&",
"block",
"raise",
"\"Section #{folder_filepath} doesn't exist.\"",
"unless",
"Dir",
".",
"exists?",
"folder_filepath",
"result",
"=",
"[",
"]",
"render_assets",
"result",
"if",
"Rails",
".",
"application",
".",
"config",
".",
"assets",
".",
"compile",
"render_partial",
"result",
",",
"block",
"result",
".",
"join",
"(",
"\"\\n\"",
")",
".",
"html_safe",
"end"
] |
Renders this section, i.e. returns the HTML for this section.
|
[
"Renders",
"this",
"section",
"i",
".",
"e",
".",
"returns",
"the",
"HTML",
"for",
"this",
"section",
"."
] |
e6e451e0888e16cc50978fe5b69797f47fdbe481
|
https://github.com/kevgo/sections_rails/blob/e6e451e0888e16cc50978fe5b69797f47fdbe481/lib/sections_rails/section.rb#L59-L66
|
8,947
|
lokalportal/chain_options
|
lib/chain_options/option.rb
|
ChainOptions.Option.new_value
|
def new_value(*args, &block)
value = value_from_args(args, &block)
value = if incremental
incremental_value(value)
else
filter_value(transformed_value(value))
end
if value_valid?(value)
self.custom_value = value
elsif invalid.to_s == 'default' && !incremental
default_value
else
fail ArgumentError, "The value #{value.inspect} is not valid."
end
end
|
ruby
|
def new_value(*args, &block)
value = value_from_args(args, &block)
value = if incremental
incremental_value(value)
else
filter_value(transformed_value(value))
end
if value_valid?(value)
self.custom_value = value
elsif invalid.to_s == 'default' && !incremental
default_value
else
fail ArgumentError, "The value #{value.inspect} is not valid."
end
end
|
[
"def",
"new_value",
"(",
"*",
"args",
",",
"&",
"block",
")",
"value",
"=",
"value_from_args",
"(",
"args",
",",
"block",
")",
"value",
"=",
"if",
"incremental",
"incremental_value",
"(",
"value",
")",
"else",
"filter_value",
"(",
"transformed_value",
"(",
"value",
")",
")",
"end",
"if",
"value_valid?",
"(",
"value",
")",
"self",
".",
"custom_value",
"=",
"value",
"elsif",
"invalid",
".",
"to_s",
"==",
"'default'",
"&&",
"!",
"incremental",
"default_value",
"else",
"fail",
"ArgumentError",
",",
"\"The value #{value.inspect} is not valid.\"",
"end",
"end"
] |
Extracts options and sets all the parameters.
Builds a new value for the option.
It automatically applies transformations and filters and validates the
resulting value, raising an exception if the value is not valid.
|
[
"Extracts",
"options",
"and",
"sets",
"all",
"the",
"parameters",
"."
] |
b42cd6c03aeca8938b274225ebaa38fe3803866a
|
https://github.com/lokalportal/chain_options/blob/b42cd6c03aeca8938b274225ebaa38fe3803866a/lib/chain_options/option.rb#L35-L51
|
8,948
|
lokalportal/chain_options
|
lib/chain_options/option.rb
|
ChainOptions.Option.to_h
|
def to_h
PARAMETERS.each_with_object({}) do |param, hash|
next if send(param).nil?
hash[param] = send(param)
end
end
|
ruby
|
def to_h
PARAMETERS.each_with_object({}) do |param, hash|
next if send(param).nil?
hash[param] = send(param)
end
end
|
[
"def",
"to_h",
"PARAMETERS",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"param",
",",
"hash",
"|",
"next",
"if",
"send",
"(",
"param",
")",
".",
"nil?",
"hash",
"[",
"param",
"]",
"=",
"send",
"(",
"param",
")",
"end",
"end"
] |
Looks through the parameters and returns the non-nil values as a hash
|
[
"Looks",
"through",
"the",
"parameters",
"and",
"returns",
"the",
"non",
"-",
"nil",
"values",
"as",
"a",
"hash"
] |
b42cd6c03aeca8938b274225ebaa38fe3803866a
|
https://github.com/lokalportal/chain_options/blob/b42cd6c03aeca8938b274225ebaa38fe3803866a/lib/chain_options/option.rb#L75-L81
|
8,949
|
lokalportal/chain_options
|
lib/chain_options/option.rb
|
ChainOptions.Option.value_from_args
|
def value_from_args(args, &block)
return block if ChainOptions::Util.blank?(args) && block && allow_block
flat_value(args)
end
|
ruby
|
def value_from_args(args, &block)
return block if ChainOptions::Util.blank?(args) && block && allow_block
flat_value(args)
end
|
[
"def",
"value_from_args",
"(",
"args",
",",
"&",
"block",
")",
"return",
"block",
"if",
"ChainOptions",
"::",
"Util",
".",
"blank?",
"(",
"args",
")",
"&&",
"block",
"&&",
"allow_block",
"flat_value",
"(",
"args",
")",
"end"
] |
Returns the block if nothing else if given and blocks are allowed to be
values.
|
[
"Returns",
"the",
"block",
"if",
"nothing",
"else",
"if",
"given",
"and",
"blocks",
"are",
"allowed",
"to",
"be",
"values",
"."
] |
b42cd6c03aeca8938b274225ebaa38fe3803866a
|
https://github.com/lokalportal/chain_options/blob/b42cd6c03aeca8938b274225ebaa38fe3803866a/lib/chain_options/option.rb#L102-L106
|
8,950
|
lokalportal/chain_options
|
lib/chain_options/option.rb
|
ChainOptions.Option.flat_value
|
def flat_value(args)
return args.first if args.is_a?(Enumerable) && args.count == 1
args
end
|
ruby
|
def flat_value(args)
return args.first if args.is_a?(Enumerable) && args.count == 1
args
end
|
[
"def",
"flat_value",
"(",
"args",
")",
"return",
"args",
".",
"first",
"if",
"args",
".",
"is_a?",
"(",
"Enumerable",
")",
"&&",
"args",
".",
"count",
"==",
"1",
"args",
"end"
] |
Reverses the auto-cast to Array that is applied at `new_value`.
|
[
"Reverses",
"the",
"auto",
"-",
"cast",
"to",
"Array",
"that",
"is",
"applied",
"at",
"new_value",
"."
] |
b42cd6c03aeca8938b274225ebaa38fe3803866a
|
https://github.com/lokalportal/chain_options/blob/b42cd6c03aeca8938b274225ebaa38fe3803866a/lib/chain_options/option.rb#L111-L115
|
8,951
|
lokalportal/chain_options
|
lib/chain_options/option.rb
|
ChainOptions.Option.transformed_value
|
def transformed_value(value)
return value unless transform
transformed = Array(value).map(&transform)
value.is_a?(Enumerable) ? transformed : transformed.first
end
|
ruby
|
def transformed_value(value)
return value unless transform
transformed = Array(value).map(&transform)
value.is_a?(Enumerable) ? transformed : transformed.first
end
|
[
"def",
"transformed_value",
"(",
"value",
")",
"return",
"value",
"unless",
"transform",
"transformed",
"=",
"Array",
"(",
"value",
")",
".",
"map",
"(",
"transform",
")",
"value",
".",
"is_a?",
"(",
"Enumerable",
")",
"?",
"transformed",
":",
"transformed",
".",
"first",
"end"
] |
Applies a transformation to the given value.
@param [Object] value
The new value to be transformed
If a `transform` was set up for the given option, it is used
as `to_proc` target when iterating over the value.
The value is always treated as a collection during this phase.
|
[
"Applies",
"a",
"transformation",
"to",
"the",
"given",
"value",
"."
] |
b42cd6c03aeca8938b274225ebaa38fe3803866a
|
https://github.com/lokalportal/chain_options/blob/b42cd6c03aeca8938b274225ebaa38fe3803866a/lib/chain_options/option.rb#L160-L165
|
8,952
|
ChrisSandison/missing_text
|
lib/missing_text/writer.rb
|
MissingText.Writer.get_entry_for
|
def get_entry_for(entry, language)
if entry.length > 1
entry_string = get_entry_for_rec(entry[1..-1], language, hashes[language][entry[0]])
else
entry_string = hashes[language][entry[0]]
end
if entry_string.kind_of?(Array)
entry_string = entry_string.map(&:inspect).join(', ')
end
entry_string
end
|
ruby
|
def get_entry_for(entry, language)
if entry.length > 1
entry_string = get_entry_for_rec(entry[1..-1], language, hashes[language][entry[0]])
else
entry_string = hashes[language][entry[0]]
end
if entry_string.kind_of?(Array)
entry_string = entry_string.map(&:inspect).join(', ')
end
entry_string
end
|
[
"def",
"get_entry_for",
"(",
"entry",
",",
"language",
")",
"if",
"entry",
".",
"length",
">",
"1",
"entry_string",
"=",
"get_entry_for_rec",
"(",
"entry",
"[",
"1",
"..",
"-",
"1",
"]",
",",
"language",
",",
"hashes",
"[",
"language",
"]",
"[",
"entry",
"[",
"0",
"]",
"]",
")",
"else",
"entry_string",
"=",
"hashes",
"[",
"language",
"]",
"[",
"entry",
"[",
"0",
"]",
"]",
"end",
"if",
"entry_string",
".",
"kind_of?",
"(",
"Array",
")",
"entry_string",
"=",
"entry_string",
".",
"map",
"(",
":inspect",
")",
".",
"join",
"(",
"', '",
")",
"end",
"entry_string",
"end"
] |
Takes in a locale code and returns the string for that language
|
[
"Takes",
"in",
"a",
"locale",
"code",
"and",
"returns",
"the",
"string",
"for",
"that",
"language"
] |
dd33f0118f0a69798537e0280a6c62dc387f3e81
|
https://github.com/ChrisSandison/missing_text/blob/dd33f0118f0a69798537e0280a6c62dc387f3e81/lib/missing_text/writer.rb#L63-L74
|
8,953
|
cordawyn/redlander
|
lib/redlander/parsing.rb
|
Redlander.Parsing.from
|
def from(content, options = {})
format = options[:format].to_s
mime_type = options[:mime_type] && options[:mime_type].to_s
type_uri = options[:type_uri] && options[:type_uri].to_s
base_uri = options[:base_uri] && options[:base_uri].to_s
content = Uri.new(content) if content.is_a?(URI)
# FIXME: to be fixed in librdf:
# ntriples parser absolutely needs "\n" at the end of the input
if format == "ntriples" && !content.is_a?(Uri) && !content.end_with?("\n")
content << "\n"
end
rdf_parser = Redland.librdf_new_parser(Redlander.rdf_world, format, mime_type, type_uri)
raise RedlandError, "Failed to create a new '#{format}' parser" if rdf_parser.null?
begin
if block_given?
rdf_stream =
if content.is_a?(Uri)
Redland.librdf_parser_parse_as_stream(rdf_parser, content.rdf_uri, base_uri)
else
Redland.librdf_parser_parse_string_as_stream(rdf_parser, content, base_uri)
end
raise RedlandError, "Failed to create a new stream" if rdf_stream.null?
begin
while Redland.librdf_stream_end(rdf_stream).zero?
statement = Statement.new(Redland.librdf_stream_get_object(rdf_stream))
statements.add(statement) if yield statement
Redland.librdf_stream_next(rdf_stream)
end
ensure
Redland.librdf_free_stream(rdf_stream)
end
else
if content.is_a?(Uri)
Redland.librdf_parser_parse_into_model(rdf_parser, content.rdf_uri, base_uri, @rdf_model).zero?
else
Redland.librdf_parser_parse_string_into_model(rdf_parser, content, base_uri, @rdf_model).zero?
end
end
ensure
Redland.librdf_free_parser(rdf_parser)
end
self
end
|
ruby
|
def from(content, options = {})
format = options[:format].to_s
mime_type = options[:mime_type] && options[:mime_type].to_s
type_uri = options[:type_uri] && options[:type_uri].to_s
base_uri = options[:base_uri] && options[:base_uri].to_s
content = Uri.new(content) if content.is_a?(URI)
# FIXME: to be fixed in librdf:
# ntriples parser absolutely needs "\n" at the end of the input
if format == "ntriples" && !content.is_a?(Uri) && !content.end_with?("\n")
content << "\n"
end
rdf_parser = Redland.librdf_new_parser(Redlander.rdf_world, format, mime_type, type_uri)
raise RedlandError, "Failed to create a new '#{format}' parser" if rdf_parser.null?
begin
if block_given?
rdf_stream =
if content.is_a?(Uri)
Redland.librdf_parser_parse_as_stream(rdf_parser, content.rdf_uri, base_uri)
else
Redland.librdf_parser_parse_string_as_stream(rdf_parser, content, base_uri)
end
raise RedlandError, "Failed to create a new stream" if rdf_stream.null?
begin
while Redland.librdf_stream_end(rdf_stream).zero?
statement = Statement.new(Redland.librdf_stream_get_object(rdf_stream))
statements.add(statement) if yield statement
Redland.librdf_stream_next(rdf_stream)
end
ensure
Redland.librdf_free_stream(rdf_stream)
end
else
if content.is_a?(Uri)
Redland.librdf_parser_parse_into_model(rdf_parser, content.rdf_uri, base_uri, @rdf_model).zero?
else
Redland.librdf_parser_parse_string_into_model(rdf_parser, content, base_uri, @rdf_model).zero?
end
end
ensure
Redland.librdf_free_parser(rdf_parser)
end
self
end
|
[
"def",
"from",
"(",
"content",
",",
"options",
"=",
"{",
"}",
")",
"format",
"=",
"options",
"[",
":format",
"]",
".",
"to_s",
"mime_type",
"=",
"options",
"[",
":mime_type",
"]",
"&&",
"options",
"[",
":mime_type",
"]",
".",
"to_s",
"type_uri",
"=",
"options",
"[",
":type_uri",
"]",
"&&",
"options",
"[",
":type_uri",
"]",
".",
"to_s",
"base_uri",
"=",
"options",
"[",
":base_uri",
"]",
"&&",
"options",
"[",
":base_uri",
"]",
".",
"to_s",
"content",
"=",
"Uri",
".",
"new",
"(",
"content",
")",
"if",
"content",
".",
"is_a?",
"(",
"URI",
")",
"# FIXME: to be fixed in librdf:",
"# ntriples parser absolutely needs \"\\n\" at the end of the input",
"if",
"format",
"==",
"\"ntriples\"",
"&&",
"!",
"content",
".",
"is_a?",
"(",
"Uri",
")",
"&&",
"!",
"content",
".",
"end_with?",
"(",
"\"\\n\"",
")",
"content",
"<<",
"\"\\n\"",
"end",
"rdf_parser",
"=",
"Redland",
".",
"librdf_new_parser",
"(",
"Redlander",
".",
"rdf_world",
",",
"format",
",",
"mime_type",
",",
"type_uri",
")",
"raise",
"RedlandError",
",",
"\"Failed to create a new '#{format}' parser\"",
"if",
"rdf_parser",
".",
"null?",
"begin",
"if",
"block_given?",
"rdf_stream",
"=",
"if",
"content",
".",
"is_a?",
"(",
"Uri",
")",
"Redland",
".",
"librdf_parser_parse_as_stream",
"(",
"rdf_parser",
",",
"content",
".",
"rdf_uri",
",",
"base_uri",
")",
"else",
"Redland",
".",
"librdf_parser_parse_string_as_stream",
"(",
"rdf_parser",
",",
"content",
",",
"base_uri",
")",
"end",
"raise",
"RedlandError",
",",
"\"Failed to create a new stream\"",
"if",
"rdf_stream",
".",
"null?",
"begin",
"while",
"Redland",
".",
"librdf_stream_end",
"(",
"rdf_stream",
")",
".",
"zero?",
"statement",
"=",
"Statement",
".",
"new",
"(",
"Redland",
".",
"librdf_stream_get_object",
"(",
"rdf_stream",
")",
")",
"statements",
".",
"add",
"(",
"statement",
")",
"if",
"yield",
"statement",
"Redland",
".",
"librdf_stream_next",
"(",
"rdf_stream",
")",
"end",
"ensure",
"Redland",
".",
"librdf_free_stream",
"(",
"rdf_stream",
")",
"end",
"else",
"if",
"content",
".",
"is_a?",
"(",
"Uri",
")",
"Redland",
".",
"librdf_parser_parse_into_model",
"(",
"rdf_parser",
",",
"content",
".",
"rdf_uri",
",",
"base_uri",
",",
"@rdf_model",
")",
".",
"zero?",
"else",
"Redland",
".",
"librdf_parser_parse_string_into_model",
"(",
"rdf_parser",
",",
"content",
",",
"base_uri",
",",
"@rdf_model",
")",
".",
"zero?",
"end",
"end",
"ensure",
"Redland",
".",
"librdf_free_parser",
"(",
"rdf_parser",
")",
"end",
"self",
"end"
] |
Core parsing method for non-streams
@note
If a block is given, the extracted statements will be yielded into
the block and inserted into the model depending on the output
of the block (if true, the statement will be added,
if false, the statement will not be added).
@param [String, URI] content
- Can be a String,
causing the statements to be extracted
directly from it, or
- URI
causing the content to be first pulled
from the specified URI (or a local file,
if URI schema == "file:")
@param [Hash] options
@option options [String] :format name of the parser to use,
@option options [String] :mime_type MIME type of the syntax, if applicable,
@option options [String, URI] :type_uri URI of syntax, if applicable,
@option options [String, URI] :base_uri base URI,
to be applied to the nodes with relative URIs.
@yieldparam [Statement]
@raise [RedlandError] if it fails to create a parser or stream
@return [Model]
|
[
"Core",
"parsing",
"method",
"for",
"non",
"-",
"streams"
] |
a5c84e15a7602c674606e531bda6a616b1237c44
|
https://github.com/cordawyn/redlander/blob/a5c84e15a7602c674606e531bda6a616b1237c44/lib/redlander/parsing.rb#L30-L76
|
8,954
|
mobyinc/Cathode
|
lib/cathode/index_request.rb
|
Cathode.IndexRequest.model
|
def model
if @resource_tree.size > 1
parent_model_id = params["#{@resource_tree.first.name.to_s.singularize}_id"]
model = @resource_tree.first.model.find(parent_model_id)
@resource_tree.drop(1).each do |resource|
model = model.send resource.name
end
model
else
super.all
end
end
|
ruby
|
def model
if @resource_tree.size > 1
parent_model_id = params["#{@resource_tree.first.name.to_s.singularize}_id"]
model = @resource_tree.first.model.find(parent_model_id)
@resource_tree.drop(1).each do |resource|
model = model.send resource.name
end
model
else
super.all
end
end
|
[
"def",
"model",
"if",
"@resource_tree",
".",
"size",
">",
"1",
"parent_model_id",
"=",
"params",
"[",
"\"#{@resource_tree.first.name.to_s.singularize}_id\"",
"]",
"model",
"=",
"@resource_tree",
".",
"first",
".",
"model",
".",
"find",
"(",
"parent_model_id",
")",
"@resource_tree",
".",
"drop",
"(",
"1",
")",
".",
"each",
"do",
"|",
"resource",
"|",
"model",
"=",
"model",
".",
"send",
"resource",
".",
"name",
"end",
"model",
"else",
"super",
".",
"all",
"end",
"end"
] |
Determine the model to use depending on the request. If a sub-resource
was requested, use the parent model to get the association. Otherwise, use
all the resource's model's records.
|
[
"Determine",
"the",
"model",
"to",
"use",
"depending",
"on",
"the",
"request",
".",
"If",
"a",
"sub",
"-",
"resource",
"was",
"requested",
"use",
"the",
"parent",
"model",
"to",
"get",
"the",
"association",
".",
"Otherwise",
"use",
"all",
"the",
"resource",
"s",
"model",
"s",
"records",
"."
] |
e17be4fb62ad61417e2a3a0a77406459015468a1
|
https://github.com/mobyinc/Cathode/blob/e17be4fb62ad61417e2a3a0a77406459015468a1/lib/cathode/index_request.rb#L7-L18
|
8,955
|
mobyinc/Cathode
|
lib/cathode/index_request.rb
|
Cathode.IndexRequest.default_action_block
|
def default_action_block
proc do
all_records = model
if allowed?(:paging) && params[:page]
page = params[:page]
per_page = params[:per_page] || 10
lower_bound = (per_page - 1) * page
upper_bound = lower_bound + per_page - 1
body all_records[lower_bound..upper_bound]
else
body all_records
end
end
end
|
ruby
|
def default_action_block
proc do
all_records = model
if allowed?(:paging) && params[:page]
page = params[:page]
per_page = params[:per_page] || 10
lower_bound = (per_page - 1) * page
upper_bound = lower_bound + per_page - 1
body all_records[lower_bound..upper_bound]
else
body all_records
end
end
end
|
[
"def",
"default_action_block",
"proc",
"do",
"all_records",
"=",
"model",
"if",
"allowed?",
"(",
":paging",
")",
"&&",
"params",
"[",
":page",
"]",
"page",
"=",
"params",
"[",
":page",
"]",
"per_page",
"=",
"params",
"[",
":per_page",
"]",
"||",
"10",
"lower_bound",
"=",
"(",
"per_page",
"-",
"1",
")",
"*",
"page",
"upper_bound",
"=",
"lower_bound",
"+",
"per_page",
"-",
"1",
"body",
"all_records",
"[",
"lower_bound",
"..",
"upper_bound",
"]",
"else",
"body",
"all_records",
"end",
"end",
"end"
] |
Determine the default action to use depending on the request. If the
`page` param was passed and the action allows paging, page the results.
Otherwise, set the request body to all records.
|
[
"Determine",
"the",
"default",
"action",
"to",
"use",
"depending",
"on",
"the",
"request",
".",
"If",
"the",
"page",
"param",
"was",
"passed",
"and",
"the",
"action",
"allows",
"paging",
"page",
"the",
"results",
".",
"Otherwise",
"set",
"the",
"request",
"body",
"to",
"all",
"records",
"."
] |
e17be4fb62ad61417e2a3a0a77406459015468a1
|
https://github.com/mobyinc/Cathode/blob/e17be4fb62ad61417e2a3a0a77406459015468a1/lib/cathode/index_request.rb#L23-L38
|
8,956
|
jamiely/simulator
|
lib/simulator/equation.rb
|
Simulator.Equation.evaluate_in
|
def evaluate_in(context, periods = [])
sandbox = Sandbox.new context, periods
sandbox.instance_eval &@equation_block
end
|
ruby
|
def evaluate_in(context, periods = [])
sandbox = Sandbox.new context, periods
sandbox.instance_eval &@equation_block
end
|
[
"def",
"evaluate_in",
"(",
"context",
",",
"periods",
"=",
"[",
"]",
")",
"sandbox",
"=",
"Sandbox",
".",
"new",
"context",
",",
"periods",
"sandbox",
".",
"instance_eval",
"@equation_block",
"end"
] |
evaluate the equation in the passed context
|
[
"evaluate",
"the",
"equation",
"in",
"the",
"passed",
"context"
] |
21395b72241d8f3ca93f90eecb5e1ad2870e9f69
|
https://github.com/jamiely/simulator/blob/21395b72241d8f3ca93f90eecb5e1ad2870e9f69/lib/simulator/equation.rb#L11-L14
|
8,957
|
jmettraux/rufus-jig
|
lib/rufus/jig/couch.rb
|
Rufus::Jig.Couch.all
|
def all(opts={})
opts = opts.dup
# don't touch the original
path = adjust('_all_docs')
opts[:include_docs] = true if opts[:include_docs].nil?
adjust_params(opts)
keys = opts.delete(:keys)
return [] if keys && keys.empty?
res = if keys
opts[:cache] = :with_body if opts[:cache].nil?
@http.post(path, { 'keys' => keys }, opts)
else
@http.get(path, opts)
end
rows = res['rows']
docs = if opts[:params][:include_docs]
rows.map { |row| row['doc'] }
else
rows.map { |row| { '_id' => row['id'], '_rev' => row['value']['rev'] } }
end
if opts[:include_design_docs] == false
docs = docs.reject { |doc| DESIGN_PATH_REGEX.match(doc['_id']) }
end
docs
end
|
ruby
|
def all(opts={})
opts = opts.dup
# don't touch the original
path = adjust('_all_docs')
opts[:include_docs] = true if opts[:include_docs].nil?
adjust_params(opts)
keys = opts.delete(:keys)
return [] if keys && keys.empty?
res = if keys
opts[:cache] = :with_body if opts[:cache].nil?
@http.post(path, { 'keys' => keys }, opts)
else
@http.get(path, opts)
end
rows = res['rows']
docs = if opts[:params][:include_docs]
rows.map { |row| row['doc'] }
else
rows.map { |row| { '_id' => row['id'], '_rev' => row['value']['rev'] } }
end
if opts[:include_design_docs] == false
docs = docs.reject { |doc| DESIGN_PATH_REGEX.match(doc['_id']) }
end
docs
end
|
[
"def",
"all",
"(",
"opts",
"=",
"{",
"}",
")",
"opts",
"=",
"opts",
".",
"dup",
"# don't touch the original",
"path",
"=",
"adjust",
"(",
"'_all_docs'",
")",
"opts",
"[",
":include_docs",
"]",
"=",
"true",
"if",
"opts",
"[",
":include_docs",
"]",
".",
"nil?",
"adjust_params",
"(",
"opts",
")",
"keys",
"=",
"opts",
".",
"delete",
"(",
":keys",
")",
"return",
"[",
"]",
"if",
"keys",
"&&",
"keys",
".",
"empty?",
"res",
"=",
"if",
"keys",
"opts",
"[",
":cache",
"]",
"=",
":with_body",
"if",
"opts",
"[",
":cache",
"]",
".",
"nil?",
"@http",
".",
"post",
"(",
"path",
",",
"{",
"'keys'",
"=>",
"keys",
"}",
",",
"opts",
")",
"else",
"@http",
".",
"get",
"(",
"path",
",",
"opts",
")",
"end",
"rows",
"=",
"res",
"[",
"'rows'",
"]",
"docs",
"=",
"if",
"opts",
"[",
":params",
"]",
"[",
":include_docs",
"]",
"rows",
".",
"map",
"{",
"|",
"row",
"|",
"row",
"[",
"'doc'",
"]",
"}",
"else",
"rows",
".",
"map",
"{",
"|",
"row",
"|",
"{",
"'_id'",
"=>",
"row",
"[",
"'id'",
"]",
",",
"'_rev'",
"=>",
"row",
"[",
"'value'",
"]",
"[",
"'rev'",
"]",
"}",
"}",
"end",
"if",
"opts",
"[",
":include_design_docs",
"]",
"==",
"false",
"docs",
"=",
"docs",
".",
"reject",
"{",
"|",
"doc",
"|",
"DESIGN_PATH_REGEX",
".",
"match",
"(",
"doc",
"[",
"'_id'",
"]",
")",
"}",
"end",
"docs",
"end"
] |
Returns all the docs in the current database.
c = Rufus::Jig::Couch.new('http://127.0.0.1:5984, 'my_db')
docs = c.all
docs = c.all(:include_docs => false)
docs = c.all(:include_design_docs => false)
docs = c.all(:skip => 10, :limit => 10)
It understands (passes) all the options for CouchDB view API :
http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options
|
[
"Returns",
"all",
"the",
"docs",
"in",
"the",
"current",
"database",
"."
] |
3df3661a71823b2f0f08ec605abeaa33e3a0ad38
|
https://github.com/jmettraux/rufus-jig/blob/3df3661a71823b2f0f08ec605abeaa33e3a0ad38/lib/rufus/jig/couch.rb#L113-L148
|
8,958
|
jmettraux/rufus-jig
|
lib/rufus/jig/couch.rb
|
Rufus::Jig.Couch.attach
|
def attach(doc_id, doc_rev, attachment_name, data, opts=nil)
if opts.nil?
opts = data
data = attachment_name
attachment_name = doc_rev
doc_rev = doc_id['_rev']
doc_id = doc_id['_id']
end
attachment_name = attachment_name.gsub(/\//, '%2F')
ct = opts[:content_type]
raise(ArgumentError.new(
":content_type option must be specified"
)) unless ct
opts[:cache] = false
path = adjust("#{doc_id}/#{attachment_name}?rev=#{doc_rev}")
if @http.variant == :patron
# patron, as of 0.4.5 (~> 0.4.10), has difficulties when PUTting
# attachements
# this is a fallback to net/http
require 'net/http'
http = Net::HTTP.new(@http.host, @http.port)
req = Net::HTTP::Put.new(path)
req['User-Agent'] =
"rufus-jig #{Rufus::Jig::VERSION} (patron 0.4.x fallback to net/http)"
req['Content-Type'] =
opts[:content_type]
req['Accept'] =
'application/json'
req.body = data
res = Rufus::Jig::HttpResponse.new(http.start { |h| h.request(req) })
return @http.send(:respond, :put, path, nil, opts, nil, res)
end
@http.put(path, data, opts)
end
|
ruby
|
def attach(doc_id, doc_rev, attachment_name, data, opts=nil)
if opts.nil?
opts = data
data = attachment_name
attachment_name = doc_rev
doc_rev = doc_id['_rev']
doc_id = doc_id['_id']
end
attachment_name = attachment_name.gsub(/\//, '%2F')
ct = opts[:content_type]
raise(ArgumentError.new(
":content_type option must be specified"
)) unless ct
opts[:cache] = false
path = adjust("#{doc_id}/#{attachment_name}?rev=#{doc_rev}")
if @http.variant == :patron
# patron, as of 0.4.5 (~> 0.4.10), has difficulties when PUTting
# attachements
# this is a fallback to net/http
require 'net/http'
http = Net::HTTP.new(@http.host, @http.port)
req = Net::HTTP::Put.new(path)
req['User-Agent'] =
"rufus-jig #{Rufus::Jig::VERSION} (patron 0.4.x fallback to net/http)"
req['Content-Type'] =
opts[:content_type]
req['Accept'] =
'application/json'
req.body = data
res = Rufus::Jig::HttpResponse.new(http.start { |h| h.request(req) })
return @http.send(:respond, :put, path, nil, opts, nil, res)
end
@http.put(path, data, opts)
end
|
[
"def",
"attach",
"(",
"doc_id",
",",
"doc_rev",
",",
"attachment_name",
",",
"data",
",",
"opts",
"=",
"nil",
")",
"if",
"opts",
".",
"nil?",
"opts",
"=",
"data",
"data",
"=",
"attachment_name",
"attachment_name",
"=",
"doc_rev",
"doc_rev",
"=",
"doc_id",
"[",
"'_rev'",
"]",
"doc_id",
"=",
"doc_id",
"[",
"'_id'",
"]",
"end",
"attachment_name",
"=",
"attachment_name",
".",
"gsub",
"(",
"/",
"\\/",
"/",
",",
"'%2F'",
")",
"ct",
"=",
"opts",
"[",
":content_type",
"]",
"raise",
"(",
"ArgumentError",
".",
"new",
"(",
"\":content_type option must be specified\"",
")",
")",
"unless",
"ct",
"opts",
"[",
":cache",
"]",
"=",
"false",
"path",
"=",
"adjust",
"(",
"\"#{doc_id}/#{attachment_name}?rev=#{doc_rev}\"",
")",
"if",
"@http",
".",
"variant",
"==",
":patron",
"# patron, as of 0.4.5 (~> 0.4.10), has difficulties when PUTting",
"# attachements",
"# this is a fallback to net/http",
"require",
"'net/http'",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"@http",
".",
"host",
",",
"@http",
".",
"port",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Put",
".",
"new",
"(",
"path",
")",
"req",
"[",
"'User-Agent'",
"]",
"=",
"\"rufus-jig #{Rufus::Jig::VERSION} (patron 0.4.x fallback to net/http)\"",
"req",
"[",
"'Content-Type'",
"]",
"=",
"opts",
"[",
":content_type",
"]",
"req",
"[",
"'Accept'",
"]",
"=",
"'application/json'",
"req",
".",
"body",
"=",
"data",
"res",
"=",
"Rufus",
"::",
"Jig",
"::",
"HttpResponse",
".",
"new",
"(",
"http",
".",
"start",
"{",
"|",
"h",
"|",
"h",
".",
"request",
"(",
"req",
")",
"}",
")",
"return",
"@http",
".",
"send",
"(",
":respond",
",",
":put",
",",
"path",
",",
"nil",
",",
"opts",
",",
"nil",
",",
"res",
")",
"end",
"@http",
".",
"put",
"(",
"path",
",",
"data",
",",
"opts",
")",
"end"
] |
Attaches a file to a couch document.
couch.attach(
doc['_id'], doc['_rev'], 'my_picture', data,
:content_type => 'image/jpeg')
or
couch.attach(
doc, 'my_picture', data,
:content_type => 'image/jpeg')
|
[
"Attaches",
"a",
"file",
"to",
"a",
"couch",
"document",
"."
] |
3df3661a71823b2f0f08ec605abeaa33e3a0ad38
|
https://github.com/jmettraux/rufus-jig/blob/3df3661a71823b2f0f08ec605abeaa33e3a0ad38/lib/rufus/jig/couch.rb#L215-L262
|
8,959
|
jmettraux/rufus-jig
|
lib/rufus/jig/couch.rb
|
Rufus::Jig.Couch.detach
|
def detach(doc_id, doc_rev, attachment_name=nil)
if attachment_name.nil?
attachment_name = doc_rev
doc_rev = doc_id['_rev']
doc_id = doc_id['_id']
end
attachment_name = attachment_name.gsub(/\//, '%2F')
path = adjust("#{doc_id}/#{attachment_name}?rev=#{doc_rev}")
@http.delete(path)
end
|
ruby
|
def detach(doc_id, doc_rev, attachment_name=nil)
if attachment_name.nil?
attachment_name = doc_rev
doc_rev = doc_id['_rev']
doc_id = doc_id['_id']
end
attachment_name = attachment_name.gsub(/\//, '%2F')
path = adjust("#{doc_id}/#{attachment_name}?rev=#{doc_rev}")
@http.delete(path)
end
|
[
"def",
"detach",
"(",
"doc_id",
",",
"doc_rev",
",",
"attachment_name",
"=",
"nil",
")",
"if",
"attachment_name",
".",
"nil?",
"attachment_name",
"=",
"doc_rev",
"doc_rev",
"=",
"doc_id",
"[",
"'_rev'",
"]",
"doc_id",
"=",
"doc_id",
"[",
"'_id'",
"]",
"end",
"attachment_name",
"=",
"attachment_name",
".",
"gsub",
"(",
"/",
"\\/",
"/",
",",
"'%2F'",
")",
"path",
"=",
"adjust",
"(",
"\"#{doc_id}/#{attachment_name}?rev=#{doc_rev}\"",
")",
"@http",
".",
"delete",
"(",
"path",
")",
"end"
] |
Detaches a file from a couch document.
couch.detach(doc['_id'], doc['_rev'], 'my_picture')
or
couch.detach(doc, 'my_picture')
|
[
"Detaches",
"a",
"file",
"from",
"a",
"couch",
"document",
"."
] |
3df3661a71823b2f0f08ec605abeaa33e3a0ad38
|
https://github.com/jmettraux/rufus-jig/blob/3df3661a71823b2f0f08ec605abeaa33e3a0ad38/lib/rufus/jig/couch.rb#L272-L285
|
8,960
|
jmettraux/rufus-jig
|
lib/rufus/jig/couch.rb
|
Rufus::Jig.Couch.on_change
|
def on_change(opts={}, &block)
query = {
'feed' => 'continuous',
'heartbeat' => opts[:heartbeat] || 20_000 }
#'since' => 0 } # that's already the default
query['include_docs'] = true if block.arity > 2
query = query.map { |k, v| "#{k}=#{v}" }.join('&')
socket = TCPSocket.open(@http.host, @http.port)
auth = @http.options[:basic_auth]
if auth
auth = Base64.encode64(auth.join(':')).strip
auth = "Authorization: Basic #{auth}\r\n"
else
auth = ''
end
socket.print("GET /#{path}/_changes?#{query} HTTP/1.1\r\n")
socket.print("User-Agent: rufus-jig #{Rufus::Jig::VERSION}\r\n")
#socket.print("Accept: application/json;charset=UTF-8\r\n")
socket.print(auth)
socket.print("\r\n")
# consider reply
answer = socket.gets.strip
status = answer.match(/^HTTP\/.+ (\d{3}) /)[1].to_i
raise Rufus::Jig::HttpError.new(status, answer) if status != 200
# discard headers
loop do
data = socket.gets
break if data.nil? || data == "\r\n"
end
# the on_change loop
loop do
data = socket.gets
break if data.nil?
data = (Rufus::Json.decode(data) rescue nil)
next unless data.is_a?(Hash)
args = [ data['id'], (data['deleted'] == true) ]
args << data['doc'] if block.arity > 2
block.call(*args)
end
on_change(opts, &block) if opts[:reconnect]
end
|
ruby
|
def on_change(opts={}, &block)
query = {
'feed' => 'continuous',
'heartbeat' => opts[:heartbeat] || 20_000 }
#'since' => 0 } # that's already the default
query['include_docs'] = true if block.arity > 2
query = query.map { |k, v| "#{k}=#{v}" }.join('&')
socket = TCPSocket.open(@http.host, @http.port)
auth = @http.options[:basic_auth]
if auth
auth = Base64.encode64(auth.join(':')).strip
auth = "Authorization: Basic #{auth}\r\n"
else
auth = ''
end
socket.print("GET /#{path}/_changes?#{query} HTTP/1.1\r\n")
socket.print("User-Agent: rufus-jig #{Rufus::Jig::VERSION}\r\n")
#socket.print("Accept: application/json;charset=UTF-8\r\n")
socket.print(auth)
socket.print("\r\n")
# consider reply
answer = socket.gets.strip
status = answer.match(/^HTTP\/.+ (\d{3}) /)[1].to_i
raise Rufus::Jig::HttpError.new(status, answer) if status != 200
# discard headers
loop do
data = socket.gets
break if data.nil? || data == "\r\n"
end
# the on_change loop
loop do
data = socket.gets
break if data.nil?
data = (Rufus::Json.decode(data) rescue nil)
next unless data.is_a?(Hash)
args = [ data['id'], (data['deleted'] == true) ]
args << data['doc'] if block.arity > 2
block.call(*args)
end
on_change(opts, &block) if opts[:reconnect]
end
|
[
"def",
"on_change",
"(",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"query",
"=",
"{",
"'feed'",
"=>",
"'continuous'",
",",
"'heartbeat'",
"=>",
"opts",
"[",
":heartbeat",
"]",
"||",
"20_000",
"}",
"#'since' => 0 } # that's already the default",
"query",
"[",
"'include_docs'",
"]",
"=",
"true",
"if",
"block",
".",
"arity",
">",
"2",
"query",
"=",
"query",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"\"#{k}=#{v}\"",
"}",
".",
"join",
"(",
"'&'",
")",
"socket",
"=",
"TCPSocket",
".",
"open",
"(",
"@http",
".",
"host",
",",
"@http",
".",
"port",
")",
"auth",
"=",
"@http",
".",
"options",
"[",
":basic_auth",
"]",
"if",
"auth",
"auth",
"=",
"Base64",
".",
"encode64",
"(",
"auth",
".",
"join",
"(",
"':'",
")",
")",
".",
"strip",
"auth",
"=",
"\"Authorization: Basic #{auth}\\r\\n\"",
"else",
"auth",
"=",
"''",
"end",
"socket",
".",
"print",
"(",
"\"GET /#{path}/_changes?#{query} HTTP/1.1\\r\\n\"",
")",
"socket",
".",
"print",
"(",
"\"User-Agent: rufus-jig #{Rufus::Jig::VERSION}\\r\\n\"",
")",
"#socket.print(\"Accept: application/json;charset=UTF-8\\r\\n\")",
"socket",
".",
"print",
"(",
"auth",
")",
"socket",
".",
"print",
"(",
"\"\\r\\n\"",
")",
"# consider reply",
"answer",
"=",
"socket",
".",
"gets",
".",
"strip",
"status",
"=",
"answer",
".",
"match",
"(",
"/",
"\\/",
"\\d",
"/",
")",
"[",
"1",
"]",
".",
"to_i",
"raise",
"Rufus",
"::",
"Jig",
"::",
"HttpError",
".",
"new",
"(",
"status",
",",
"answer",
")",
"if",
"status",
"!=",
"200",
"# discard headers",
"loop",
"do",
"data",
"=",
"socket",
".",
"gets",
"break",
"if",
"data",
".",
"nil?",
"||",
"data",
"==",
"\"\\r\\n\"",
"end",
"# the on_change loop",
"loop",
"do",
"data",
"=",
"socket",
".",
"gets",
"break",
"if",
"data",
".",
"nil?",
"data",
"=",
"(",
"Rufus",
"::",
"Json",
".",
"decode",
"(",
"data",
")",
"rescue",
"nil",
")",
"next",
"unless",
"data",
".",
"is_a?",
"(",
"Hash",
")",
"args",
"=",
"[",
"data",
"[",
"'id'",
"]",
",",
"(",
"data",
"[",
"'deleted'",
"]",
"==",
"true",
")",
"]",
"args",
"<<",
"data",
"[",
"'doc'",
"]",
"if",
"block",
".",
"arity",
">",
"2",
"block",
".",
"call",
"(",
"args",
")",
"end",
"on_change",
"(",
"opts",
",",
"block",
")",
"if",
"opts",
"[",
":reconnect",
"]",
"end"
] |
Watches the database for changes.
db.on_change do |doc_id, deleted|
puts "doc #{doc_id} has been #{deleted ? 'deleted' : 'changed'}"
end
db.on_change do |doc_id, deleted, doc|
puts "doc #{doc_id} has been #{deleted ? 'deleted' : 'changed'}"
p doc
end
This is a blocking method. One might want to wrap it inside of a Thread.
Note : doc inclusion (third parameter to the block) only works with
CouchDB >= 0.11.
|
[
"Watches",
"the",
"database",
"for",
"changes",
"."
] |
3df3661a71823b2f0f08ec605abeaa33e3a0ad38
|
https://github.com/jmettraux/rufus-jig/blob/3df3661a71823b2f0f08ec605abeaa33e3a0ad38/lib/rufus/jig/couch.rb#L303-L356
|
8,961
|
jmettraux/rufus-jig
|
lib/rufus/jig/couch.rb
|
Rufus::Jig.Couch.nuke_design_documents
|
def nuke_design_documents
docs = get('_all_docs')['rows']
views = docs.select { |d| d['id'] && DESIGN_PATH_REGEX.match(d['id']) }
views.each { |v| delete(v['id'], v['value']['rev']) }
end
|
ruby
|
def nuke_design_documents
docs = get('_all_docs')['rows']
views = docs.select { |d| d['id'] && DESIGN_PATH_REGEX.match(d['id']) }
views.each { |v| delete(v['id'], v['value']['rev']) }
end
|
[
"def",
"nuke_design_documents",
"docs",
"=",
"get",
"(",
"'_all_docs'",
")",
"[",
"'rows'",
"]",
"views",
"=",
"docs",
".",
"select",
"{",
"|",
"d",
"|",
"d",
"[",
"'id'",
"]",
"&&",
"DESIGN_PATH_REGEX",
".",
"match",
"(",
"d",
"[",
"'id'",
"]",
")",
"}",
"views",
".",
"each",
"{",
"|",
"v",
"|",
"delete",
"(",
"v",
"[",
"'id'",
"]",
",",
"v",
"[",
"'value'",
"]",
"[",
"'rev'",
"]",
")",
"}",
"end"
] |
A development method. Removes all the design documents in this couch
database.
Used in tests setup or teardown, when views are subject to frequent
changes (rufus-doric and co).
|
[
"A",
"development",
"method",
".",
"Removes",
"all",
"the",
"design",
"documents",
"in",
"this",
"couch",
"database",
"."
] |
3df3661a71823b2f0f08ec605abeaa33e3a0ad38
|
https://github.com/jmettraux/rufus-jig/blob/3df3661a71823b2f0f08ec605abeaa33e3a0ad38/lib/rufus/jig/couch.rb#L366-L373
|
8,962
|
jmettraux/rufus-jig
|
lib/rufus/jig/couch.rb
|
Rufus::Jig.Couch.query
|
def query(path, opts={})
opts = opts.dup
# don't touch the original
raw = opts.delete(:raw)
path = if DESIGN_PATH_REGEX.match(path)
path
else
doc_id, view = path.split(':')
path = "_design/#{doc_id}/_view/#{view}"
end
path = adjust(path)
adjust_params(opts)
keys = opts.delete(:keys)
res = if keys
opts[:cache] = :with_body if opts[:cache].nil?
@http.post(path, { 'keys' => keys }, opts)
else
@http.get(path, opts)
end
return nil if res == true
# POST and the view doesn't exist
return res if raw
res.nil? ? res : res['rows']
end
|
ruby
|
def query(path, opts={})
opts = opts.dup
# don't touch the original
raw = opts.delete(:raw)
path = if DESIGN_PATH_REGEX.match(path)
path
else
doc_id, view = path.split(':')
path = "_design/#{doc_id}/_view/#{view}"
end
path = adjust(path)
adjust_params(opts)
keys = opts.delete(:keys)
res = if keys
opts[:cache] = :with_body if opts[:cache].nil?
@http.post(path, { 'keys' => keys }, opts)
else
@http.get(path, opts)
end
return nil if res == true
# POST and the view doesn't exist
return res if raw
res.nil? ? res : res['rows']
end
|
[
"def",
"query",
"(",
"path",
",",
"opts",
"=",
"{",
"}",
")",
"opts",
"=",
"opts",
".",
"dup",
"# don't touch the original",
"raw",
"=",
"opts",
".",
"delete",
"(",
":raw",
")",
"path",
"=",
"if",
"DESIGN_PATH_REGEX",
".",
"match",
"(",
"path",
")",
"path",
"else",
"doc_id",
",",
"view",
"=",
"path",
".",
"split",
"(",
"':'",
")",
"path",
"=",
"\"_design/#{doc_id}/_view/#{view}\"",
"end",
"path",
"=",
"adjust",
"(",
"path",
")",
"adjust_params",
"(",
"opts",
")",
"keys",
"=",
"opts",
".",
"delete",
"(",
":keys",
")",
"res",
"=",
"if",
"keys",
"opts",
"[",
":cache",
"]",
"=",
":with_body",
"if",
"opts",
"[",
":cache",
"]",
".",
"nil?",
"@http",
".",
"post",
"(",
"path",
",",
"{",
"'keys'",
"=>",
"keys",
"}",
",",
"opts",
")",
"else",
"@http",
".",
"get",
"(",
"path",
",",
"opts",
")",
"end",
"return",
"nil",
"if",
"res",
"==",
"true",
"# POST and the view doesn't exist",
"return",
"res",
"if",
"raw",
"res",
".",
"nil?",
"?",
"res",
":",
"res",
"[",
"'rows'",
"]",
"end"
] |
Queries a view.
res = couch.query('_design/my_test/_view/my_view')
# [ {"id"=>"c3", "key"=>"capuccino", "value"=>nil},
# {"id"=>"c0", "key"=>"espresso", "value"=>nil},
# {"id"=>"c2", "key"=>"macchiato", "value"=>nil},
# {"id"=>"c4", "key"=>"macchiato", "value"=>nil},
# {"id"=>"c1", "key"=>"ristretto", "value"=>nil} ]
# or simply :
res = couch.query('my_test:my_view')
Accepts the usual couch parameters : limit, skip, descending, keys,
startkey, endkey, ...
|
[
"Queries",
"a",
"view",
"."
] |
3df3661a71823b2f0f08ec605abeaa33e3a0ad38
|
https://github.com/jmettraux/rufus-jig/blob/3df3661a71823b2f0f08ec605abeaa33e3a0ad38/lib/rufus/jig/couch.rb#L392-L425
|
8,963
|
jmettraux/rufus-jig
|
lib/rufus/jig/couch.rb
|
Rufus::Jig.Couch.query_for_docs
|
def query_for_docs(path, opts={})
res = query(path, opts.merge(:include_docs => true))
if res.nil?
nil
elsif opts[:raw]
res
else
res.collect { |row| row['doc'] }.uniq
end
end
|
ruby
|
def query_for_docs(path, opts={})
res = query(path, opts.merge(:include_docs => true))
if res.nil?
nil
elsif opts[:raw]
res
else
res.collect { |row| row['doc'] }.uniq
end
end
|
[
"def",
"query_for_docs",
"(",
"path",
",",
"opts",
"=",
"{",
"}",
")",
"res",
"=",
"query",
"(",
"path",
",",
"opts",
".",
"merge",
"(",
":include_docs",
"=>",
"true",
")",
")",
"if",
"res",
".",
"nil?",
"nil",
"elsif",
"opts",
"[",
":raw",
"]",
"res",
"else",
"res",
".",
"collect",
"{",
"|",
"row",
"|",
"row",
"[",
"'doc'",
"]",
"}",
".",
"uniq",
"end",
"end"
] |
A shortcut for
query(path, :include_docs => true).collect { |row| row['doc'] }
|
[
"A",
"shortcut",
"for"
] |
3df3661a71823b2f0f08ec605abeaa33e3a0ad38
|
https://github.com/jmettraux/rufus-jig/blob/3df3661a71823b2f0f08ec605abeaa33e3a0ad38/lib/rufus/jig/couch.rb#L431-L442
|
8,964
|
jstanley0/mvclient
|
lib/mvclient/client.rb
|
Motivosity.Client.send_appreciation!
|
def send_appreciation!(user_id, opts = {})
params = { "toUserID" => user_id }
params["companyValueID"] = opts[:company_value_id] if opts[:company_value_id]
params["amount"] = opts[:amount] if opts[:amount]
params["note"] = opts[:note] if opts[:note]
params["privateAppreciation"] = opts[:private] || false
put "/api/v1/user/#{user_id}/appreciation", {}, params
end
|
ruby
|
def send_appreciation!(user_id, opts = {})
params = { "toUserID" => user_id }
params["companyValueID"] = opts[:company_value_id] if opts[:company_value_id]
params["amount"] = opts[:amount] if opts[:amount]
params["note"] = opts[:note] if opts[:note]
params["privateAppreciation"] = opts[:private] || false
put "/api/v1/user/#{user_id}/appreciation", {}, params
end
|
[
"def",
"send_appreciation!",
"(",
"user_id",
",",
"opts",
"=",
"{",
"}",
")",
"params",
"=",
"{",
"\"toUserID\"",
"=>",
"user_id",
"}",
"params",
"[",
"\"companyValueID\"",
"]",
"=",
"opts",
"[",
":company_value_id",
"]",
"if",
"opts",
"[",
":company_value_id",
"]",
"params",
"[",
"\"amount\"",
"]",
"=",
"opts",
"[",
":amount",
"]",
"if",
"opts",
"[",
":amount",
"]",
"params",
"[",
"\"note\"",
"]",
"=",
"opts",
"[",
":note",
"]",
"if",
"opts",
"[",
":note",
"]",
"params",
"[",
"\"privateAppreciation\"",
"]",
"=",
"opts",
"[",
":private",
"]",
"||",
"false",
"put",
"\"/api/v1/user/#{user_id}/appreciation\"",
",",
"{",
"}",
",",
"params",
"end"
] |
sends appreciation to another User
raises BalanceError if insufficient funds exist
|
[
"sends",
"appreciation",
"to",
"another",
"User",
"raises",
"BalanceError",
"if",
"insufficient",
"funds",
"exist"
] |
22de66a942515f7ea8ac4dd8de71412ad2b1ad29
|
https://github.com/jstanley0/mvclient/blob/22de66a942515f7ea8ac4dd8de71412ad2b1ad29/lib/mvclient/client.rb#L51-L58
|
8,965
|
redding/ns-options
|
lib/ns-options/namespace_data.rb
|
NsOptions.NamespaceData.define
|
def define(&block)
if block && block.arity > 0
block.call @ns
elsif block
@ns.instance_eval(&block)
end
@ns
end
|
ruby
|
def define(&block)
if block && block.arity > 0
block.call @ns
elsif block
@ns.instance_eval(&block)
end
@ns
end
|
[
"def",
"define",
"(",
"&",
"block",
")",
"if",
"block",
"&&",
"block",
".",
"arity",
">",
"0",
"block",
".",
"call",
"@ns",
"elsif",
"block",
"@ns",
".",
"instance_eval",
"(",
"block",
")",
"end",
"@ns",
"end"
] |
define the parent ns using the given block
|
[
"define",
"the",
"parent",
"ns",
"using",
"the",
"given",
"block"
] |
63618a18e7a1d270dffc5a3cfea70ef45569e061
|
https://github.com/redding/ns-options/blob/63618a18e7a1d270dffc5a3cfea70ef45569e061/lib/ns-options/namespace_data.rb#L82-L89
|
8,966
|
rixth/tay
|
lib/tay/packager.rb
|
Tay.Packager.extension_id
|
def extension_id
raise Tay::PrivateKeyNotFound.new unless private_key_exists?
public_key = OpenSSL::PKey::RSA.new(File.read(full_key_path)).public_key.to_der
hash = Digest::SHA256.hexdigest(public_key)[0...32]
hash.unpack('C*').map{ |c| c < 97 ? c + 49 : c + 10 }.pack('C*')
end
|
ruby
|
def extension_id
raise Tay::PrivateKeyNotFound.new unless private_key_exists?
public_key = OpenSSL::PKey::RSA.new(File.read(full_key_path)).public_key.to_der
hash = Digest::SHA256.hexdigest(public_key)[0...32]
hash.unpack('C*').map{ |c| c < 97 ? c + 49 : c + 10 }.pack('C*')
end
|
[
"def",
"extension_id",
"raise",
"Tay",
"::",
"PrivateKeyNotFound",
".",
"new",
"unless",
"private_key_exists?",
"public_key",
"=",
"OpenSSL",
"::",
"PKey",
"::",
"RSA",
".",
"new",
"(",
"File",
".",
"read",
"(",
"full_key_path",
")",
")",
".",
"public_key",
".",
"to_der",
"hash",
"=",
"Digest",
"::",
"SHA256",
".",
"hexdigest",
"(",
"public_key",
")",
"[",
"0",
"...",
"32",
"]",
"hash",
".",
"unpack",
"(",
"'C*'",
")",
".",
"map",
"{",
"|",
"c",
"|",
"c",
"<",
"97",
"?",
"c",
"+",
"49",
":",
"c",
"+",
"10",
"}",
".",
"pack",
"(",
"'C*'",
")",
"end"
] |
Calculate the extension's ID from the key
Core concepts from supercollider.dk
|
[
"Calculate",
"the",
"extension",
"s",
"ID",
"from",
"the",
"key",
"Core",
"concepts",
"from",
"supercollider",
".",
"dk"
] |
60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5
|
https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/packager.rb#L47-L53
|
8,967
|
rixth/tay
|
lib/tay/packager.rb
|
Tay.Packager.write_new_key
|
def write_new_key
File.open(full_key_path, 'w') do |f|
f.write OpenSSL::PKey::RSA.generate(1024).export()
end
end
|
ruby
|
def write_new_key
File.open(full_key_path, 'w') do |f|
f.write OpenSSL::PKey::RSA.generate(1024).export()
end
end
|
[
"def",
"write_new_key",
"File",
".",
"open",
"(",
"full_key_path",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"OpenSSL",
"::",
"PKey",
"::",
"RSA",
".",
"generate",
"(",
"1024",
")",
".",
"export",
"(",
")",
"end",
"end"
] |
Generate a key with OpenSSL and write it to the key path
|
[
"Generate",
"a",
"key",
"with",
"OpenSSL",
"and",
"write",
"it",
"to",
"the",
"key",
"path"
] |
60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5
|
https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/packager.rb#L69-L73
|
8,968
|
mccraigmccraig/rsxml
|
lib/rsxml/xml.rb
|
Rsxml.Xml.traverse
|
def traverse(element, visitor, context = Visitor::Context.new)
ns_bindings = namespace_bindings_from_defs(element.namespace_definitions)
context.ns_stack.push(ns_bindings)
eelement, eattrs = explode_element(element)
begin
visitor.element(context, eelement, eattrs, ns_bindings) do
element.children.each do |child|
if child.element?
traverse(child, visitor, context)
elsif child.text?
visitor.text(context, child.content)
else
Rsxml.log{|logger| logger.warn("unknown Nokogiri Node type: #{child.inspect}")}
end
end
end
ensure
context.ns_stack.pop
end
visitor
end
|
ruby
|
def traverse(element, visitor, context = Visitor::Context.new)
ns_bindings = namespace_bindings_from_defs(element.namespace_definitions)
context.ns_stack.push(ns_bindings)
eelement, eattrs = explode_element(element)
begin
visitor.element(context, eelement, eattrs, ns_bindings) do
element.children.each do |child|
if child.element?
traverse(child, visitor, context)
elsif child.text?
visitor.text(context, child.content)
else
Rsxml.log{|logger| logger.warn("unknown Nokogiri Node type: #{child.inspect}")}
end
end
end
ensure
context.ns_stack.pop
end
visitor
end
|
[
"def",
"traverse",
"(",
"element",
",",
"visitor",
",",
"context",
"=",
"Visitor",
"::",
"Context",
".",
"new",
")",
"ns_bindings",
"=",
"namespace_bindings_from_defs",
"(",
"element",
".",
"namespace_definitions",
")",
"context",
".",
"ns_stack",
".",
"push",
"(",
"ns_bindings",
")",
"eelement",
",",
"eattrs",
"=",
"explode_element",
"(",
"element",
")",
"begin",
"visitor",
".",
"element",
"(",
"context",
",",
"eelement",
",",
"eattrs",
",",
"ns_bindings",
")",
"do",
"element",
".",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"if",
"child",
".",
"element?",
"traverse",
"(",
"child",
",",
"visitor",
",",
"context",
")",
"elsif",
"child",
".",
"text?",
"visitor",
".",
"text",
"(",
"context",
",",
"child",
".",
"content",
")",
"else",
"Rsxml",
".",
"log",
"{",
"|",
"logger",
"|",
"logger",
".",
"warn",
"(",
"\"unknown Nokogiri Node type: #{child.inspect}\"",
")",
"}",
"end",
"end",
"end",
"ensure",
"context",
".",
"ns_stack",
".",
"pop",
"end",
"visitor",
"end"
] |
pre-order traversal of the Nokogiri Nodes, calling methods on
the visitor with each Node
|
[
"pre",
"-",
"order",
"traversal",
"of",
"the",
"Nokogiri",
"Nodes",
"calling",
"methods",
"on",
"the",
"visitor",
"with",
"each",
"Node"
] |
3699c186f01be476a5942d64cd5c39f4d6bbe175
|
https://github.com/mccraigmccraig/rsxml/blob/3699c186f01be476a5942d64cd5c39f4d6bbe175/lib/rsxml/xml.rb#L63-L86
|
8,969
|
fenton-project/fenton_shell
|
lib/fenton_shell/config_file.rb
|
FentonShell.ConfigFile.config_file_create
|
def config_file_create(global_options, options)
config_directory_create(global_options)
file = "#{global_options[:directory]}/config"
options.store(:fenton_server_url, global_options[:fenton_server_url])
content = config_generation(options)
File.write(file, content)
[true, 'ConfigFile': ['created!']]
end
|
ruby
|
def config_file_create(global_options, options)
config_directory_create(global_options)
file = "#{global_options[:directory]}/config"
options.store(:fenton_server_url, global_options[:fenton_server_url])
content = config_generation(options)
File.write(file, content)
[true, 'ConfigFile': ['created!']]
end
|
[
"def",
"config_file_create",
"(",
"global_options",
",",
"options",
")",
"config_directory_create",
"(",
"global_options",
")",
"file",
"=",
"\"#{global_options[:directory]}/config\"",
"options",
".",
"store",
"(",
":fenton_server_url",
",",
"global_options",
"[",
":fenton_server_url",
"]",
")",
"content",
"=",
"config_generation",
"(",
"options",
")",
"File",
".",
"write",
"(",
"file",
",",
"content",
")",
"[",
"true",
",",
"'ConfigFile'",
":",
"[",
"'created!'",
"]",
"]",
"end"
] |
Creates the configuration file
@param options [Hash] fields from fenton command line
@return [Object] true or false
@return [String] message on success or failure
|
[
"Creates",
"the",
"configuration",
"file"
] |
6e1d76186fa7ee7a3be141afad9361e3a3e0ec91
|
https://github.com/fenton-project/fenton_shell/blob/6e1d76186fa7ee7a3be141afad9361e3a3e0ec91/lib/fenton_shell/config_file.rb#L69-L78
|
8,970
|
fenton-project/fenton_shell
|
lib/fenton_shell/config_file.rb
|
FentonShell.ConfigFile.config_generation
|
def config_generation(options)
config_contents = {}
config_options = options.keys.map(&:to_sym).sort.uniq
config_options.delete(:password)
config_options.each do |config_option|
config_contents.store(config_option.to_sym, options[config_option])
end
config_contents.store(:default_organization, options[:username])
config_contents.to_yaml
end
|
ruby
|
def config_generation(options)
config_contents = {}
config_options = options.keys.map(&:to_sym).sort.uniq
config_options.delete(:password)
config_options.each do |config_option|
config_contents.store(config_option.to_sym, options[config_option])
end
config_contents.store(:default_organization, options[:username])
config_contents.to_yaml
end
|
[
"def",
"config_generation",
"(",
"options",
")",
"config_contents",
"=",
"{",
"}",
"config_options",
"=",
"options",
".",
"keys",
".",
"map",
"(",
":to_sym",
")",
".",
"sort",
".",
"uniq",
"config_options",
".",
"delete",
"(",
":password",
")",
"config_options",
".",
"each",
"do",
"|",
"config_option",
"|",
"config_contents",
".",
"store",
"(",
"config_option",
".",
"to_sym",
",",
"options",
"[",
"config_option",
"]",
")",
"end",
"config_contents",
".",
"store",
"(",
":default_organization",
",",
"options",
"[",
":username",
"]",
")",
"config_contents",
".",
"to_yaml",
"end"
] |
Generates the configuration file content
@param options [Hash] fields from fenton command line
@return [String] true or false
|
[
"Generates",
"the",
"configuration",
"file",
"content"
] |
6e1d76186fa7ee7a3be141afad9361e3a3e0ec91
|
https://github.com/fenton-project/fenton_shell/blob/6e1d76186fa7ee7a3be141afad9361e3a3e0ec91/lib/fenton_shell/config_file.rb#L84-L96
|
8,971
|
GoConflux/conify
|
lib/conify/helpers.rb
|
Conify.Helpers.format_with_bang
|
def format_with_bang(message)
return message if !message.is_a?(String)
return '' if message.to_s.strip == ''
" ! " + message.encode('utf-8', 'binary', invalid: :replace, undef: :replace).split("\n").join("\n ! ")
end
|
ruby
|
def format_with_bang(message)
return message if !message.is_a?(String)
return '' if message.to_s.strip == ''
" ! " + message.encode('utf-8', 'binary', invalid: :replace, undef: :replace).split("\n").join("\n ! ")
end
|
[
"def",
"format_with_bang",
"(",
"message",
")",
"return",
"message",
"if",
"!",
"message",
".",
"is_a?",
"(",
"String",
")",
"return",
"''",
"if",
"message",
".",
"to_s",
".",
"strip",
"==",
"''",
"\" ! \"",
"+",
"message",
".",
"encode",
"(",
"'utf-8'",
",",
"'binary'",
",",
"invalid",
":",
":replace",
",",
"undef",
":",
":replace",
")",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"join",
"(",
"\"\\n ! \"",
")",
"end"
] |
Add a bang to an error message
|
[
"Add",
"a",
"bang",
"to",
"an",
"error",
"message"
] |
2232fa8a3b144566f4558ab888988559d4dff6bd
|
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/helpers.rb#L11-L15
|
8,972
|
GoConflux/conify
|
lib/conify/helpers.rb
|
Conify.Helpers.to_table
|
def to_table(data, headers)
column_lengths = []
gutter = 2
table = ''
# Figure out column widths based on longest string in each column (including the header string)
headers.each { |header|
width = data.map { |_| _[header] }.max_by(&:length).length
width = header.length if width < header.length
column_lengths << width
}
# format the length of a table cell string to make it as wide as the column (by adding extra spaces)
format_row_entry = lambda { |entry, i|
entry + (' ' * (column_lengths[i] - entry.length + gutter))
}
# Add headers
headers.each_with_index { |header, i|
table += format_row_entry.call(header, i)
}
table += "\n"
# Add line breaks under headers
column_lengths.each { |length|
table += (('-' * length) + (' ' * gutter))
}
table += "\n"
# Add rows
data.each { |row|
headers.each_with_index { |header, i|
table += format_row_entry.call(row[header], i)
}
table += "\n"
}
table
end
|
ruby
|
def to_table(data, headers)
column_lengths = []
gutter = 2
table = ''
# Figure out column widths based on longest string in each column (including the header string)
headers.each { |header|
width = data.map { |_| _[header] }.max_by(&:length).length
width = header.length if width < header.length
column_lengths << width
}
# format the length of a table cell string to make it as wide as the column (by adding extra spaces)
format_row_entry = lambda { |entry, i|
entry + (' ' * (column_lengths[i] - entry.length + gutter))
}
# Add headers
headers.each_with_index { |header, i|
table += format_row_entry.call(header, i)
}
table += "\n"
# Add line breaks under headers
column_lengths.each { |length|
table += (('-' * length) + (' ' * gutter))
}
table += "\n"
# Add rows
data.each { |row|
headers.each_with_index { |header, i|
table += format_row_entry.call(row[header], i)
}
table += "\n"
}
table
end
|
[
"def",
"to_table",
"(",
"data",
",",
"headers",
")",
"column_lengths",
"=",
"[",
"]",
"gutter",
"=",
"2",
"table",
"=",
"''",
"# Figure out column widths based on longest string in each column (including the header string)",
"headers",
".",
"each",
"{",
"|",
"header",
"|",
"width",
"=",
"data",
".",
"map",
"{",
"|",
"_",
"|",
"_",
"[",
"header",
"]",
"}",
".",
"max_by",
"(",
":length",
")",
".",
"length",
"width",
"=",
"header",
".",
"length",
"if",
"width",
"<",
"header",
".",
"length",
"column_lengths",
"<<",
"width",
"}",
"# format the length of a table cell string to make it as wide as the column (by adding extra spaces)",
"format_row_entry",
"=",
"lambda",
"{",
"|",
"entry",
",",
"i",
"|",
"entry",
"+",
"(",
"' '",
"*",
"(",
"column_lengths",
"[",
"i",
"]",
"-",
"entry",
".",
"length",
"+",
"gutter",
")",
")",
"}",
"# Add headers",
"headers",
".",
"each_with_index",
"{",
"|",
"header",
",",
"i",
"|",
"table",
"+=",
"format_row_entry",
".",
"call",
"(",
"header",
",",
"i",
")",
"}",
"table",
"+=",
"\"\\n\"",
"# Add line breaks under headers",
"column_lengths",
".",
"each",
"{",
"|",
"length",
"|",
"table",
"+=",
"(",
"(",
"'-'",
"*",
"length",
")",
"+",
"(",
"' '",
"*",
"gutter",
")",
")",
"}",
"table",
"+=",
"\"\\n\"",
"# Add rows",
"data",
".",
"each",
"{",
"|",
"row",
"|",
"headers",
".",
"each_with_index",
"{",
"|",
"header",
",",
"i",
"|",
"table",
"+=",
"format_row_entry",
".",
"call",
"(",
"row",
"[",
"header",
"]",
",",
"i",
")",
"}",
"table",
"+=",
"\"\\n\"",
"}",
"table",
"end"
] |
format some data into a table to then be displayed to the user
|
[
"format",
"some",
"data",
"into",
"a",
"table",
"to",
"then",
"be",
"displayed",
"to",
"the",
"user"
] |
2232fa8a3b144566f4558ab888988559d4dff6bd
|
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/helpers.rb#L28-L71
|
8,973
|
xiuxian123/loyals
|
projects/loyal_warden/lib/warden/proxy.rb
|
Warden.Proxy.clear_strategies_cache!
|
def clear_strategies_cache!(*args)
scope, opts = _retrieve_scope_and_opts(args)
@winning_strategies.delete(scope)
@strategies[scope].each do |k, v|
v.clear! if args.empty? || args.include?(k)
end
end
|
ruby
|
def clear_strategies_cache!(*args)
scope, opts = _retrieve_scope_and_opts(args)
@winning_strategies.delete(scope)
@strategies[scope].each do |k, v|
v.clear! if args.empty? || args.include?(k)
end
end
|
[
"def",
"clear_strategies_cache!",
"(",
"*",
"args",
")",
"scope",
",",
"opts",
"=",
"_retrieve_scope_and_opts",
"(",
"args",
")",
"@winning_strategies",
".",
"delete",
"(",
"scope",
")",
"@strategies",
"[",
"scope",
"]",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"v",
".",
"clear!",
"if",
"args",
".",
"empty?",
"||",
"args",
".",
"include?",
"(",
"k",
")",
"end",
"end"
] |
Clear the cache of performed strategies so far. Warden runs each
strategy just once during the request lifecycle. You can clear the
strategies cache if you want to allow a strategy to be run more than
once.
This method has the same API as authenticate, allowing you to clear
specific strategies for given scope:
Parameters:
args - a list of symbols (labels) that name the strategies to attempt
opts - an options hash that contains the :scope of the user to check
Example:
# Clear all strategies for the configured default_scope
env['warden'].clear_strategies_cache!
# Clear all strategies for the :admin scope
env['warden'].clear_strategies_cache!(:scope => :admin)
# Clear password strategy for the :admin scope
env['warden'].clear_strategies_cache!(:password, :scope => :admin)
:api: public
|
[
"Clear",
"the",
"cache",
"of",
"performed",
"strategies",
"so",
"far",
".",
"Warden",
"runs",
"each",
"strategy",
"just",
"once",
"during",
"the",
"request",
"lifecycle",
".",
"You",
"can",
"clear",
"the",
"strategies",
"cache",
"if",
"you",
"want",
"to",
"allow",
"a",
"strategy",
"to",
"be",
"run",
"more",
"than",
"once",
"."
] |
41f586ca1551f64e5375ad32a406d5fca0afae43
|
https://github.com/xiuxian123/loyals/blob/41f586ca1551f64e5375ad32a406d5fca0afae43/projects/loyal_warden/lib/warden/proxy.rb#L71-L78
|
8,974
|
xiuxian123/loyals
|
projects/loyal_warden/lib/warden/proxy.rb
|
Warden.Proxy.set_user
|
def set_user(user, opts = {})
scope = (opts[:scope] ||= @config.default_scope)
# Get the default options from the master configuration for the given scope
opts = (@config[:scope_defaults][scope] || {}).merge(opts)
opts[:event] ||= :set_user
@users[scope] = user
if opts[:store] != false && opts[:event] != :fetch
options = env[ENV_SESSION_OPTIONS]
options[:renew] = true if options
session_serializer.store(user, scope)
end
run_callbacks = opts.fetch(:run_callbacks, true)
manager._run_callbacks(:after_set_user, user, self, opts) if run_callbacks
@users[scope]
end
|
ruby
|
def set_user(user, opts = {})
scope = (opts[:scope] ||= @config.default_scope)
# Get the default options from the master configuration for the given scope
opts = (@config[:scope_defaults][scope] || {}).merge(opts)
opts[:event] ||= :set_user
@users[scope] = user
if opts[:store] != false && opts[:event] != :fetch
options = env[ENV_SESSION_OPTIONS]
options[:renew] = true if options
session_serializer.store(user, scope)
end
run_callbacks = opts.fetch(:run_callbacks, true)
manager._run_callbacks(:after_set_user, user, self, opts) if run_callbacks
@users[scope]
end
|
[
"def",
"set_user",
"(",
"user",
",",
"opts",
"=",
"{",
"}",
")",
"scope",
"=",
"(",
"opts",
"[",
":scope",
"]",
"||=",
"@config",
".",
"default_scope",
")",
"# Get the default options from the master configuration for the given scope",
"opts",
"=",
"(",
"@config",
"[",
":scope_defaults",
"]",
"[",
"scope",
"]",
"||",
"{",
"}",
")",
".",
"merge",
"(",
"opts",
")",
"opts",
"[",
":event",
"]",
"||=",
":set_user",
"@users",
"[",
"scope",
"]",
"=",
"user",
"if",
"opts",
"[",
":store",
"]",
"!=",
"false",
"&&",
"opts",
"[",
":event",
"]",
"!=",
":fetch",
"options",
"=",
"env",
"[",
"ENV_SESSION_OPTIONS",
"]",
"options",
"[",
":renew",
"]",
"=",
"true",
"if",
"options",
"session_serializer",
".",
"store",
"(",
"user",
",",
"scope",
")",
"end",
"run_callbacks",
"=",
"opts",
".",
"fetch",
"(",
":run_callbacks",
",",
"true",
")",
"manager",
".",
"_run_callbacks",
"(",
":after_set_user",
",",
"user",
",",
"self",
",",
"opts",
")",
"if",
"run_callbacks",
"@users",
"[",
"scope",
"]",
"end"
] |
Manually set the user into the session and auth proxy
Parameters:
user - An object that has been setup to serialize into and out of the session.
opts - An options hash. Use the :scope option to set the scope of the user, set the :store option to false to skip serializing into the session, set the :run_callbacks to false to skip running the callbacks (the default is true).
:api: public
|
[
"Manually",
"set",
"the",
"user",
"into",
"the",
"session",
"and",
"auth",
"proxy"
] |
41f586ca1551f64e5375ad32a406d5fca0afae43
|
https://github.com/xiuxian123/loyals/blob/41f586ca1551f64e5375ad32a406d5fca0afae43/projects/loyal_warden/lib/warden/proxy.rb#L164-L182
|
8,975
|
tongueroo/lono
|
lib/lono/core.rb
|
Lono.Core.env_from_profile
|
def env_from_profile(aws_profile)
data = YAML.load_file("#{Lono.root}/config/settings.yml")
env = data.find do |_env, setting|
setting ||= {}
profiles = setting['aws_profiles']
profiles && profiles.include?(aws_profile)
end
env.first if env
end
|
ruby
|
def env_from_profile(aws_profile)
data = YAML.load_file("#{Lono.root}/config/settings.yml")
env = data.find do |_env, setting|
setting ||= {}
profiles = setting['aws_profiles']
profiles && profiles.include?(aws_profile)
end
env.first if env
end
|
[
"def",
"env_from_profile",
"(",
"aws_profile",
")",
"data",
"=",
"YAML",
".",
"load_file",
"(",
"\"#{Lono.root}/config/settings.yml\"",
")",
"env",
"=",
"data",
".",
"find",
"do",
"|",
"_env",
",",
"setting",
"|",
"setting",
"||=",
"{",
"}",
"profiles",
"=",
"setting",
"[",
"'aws_profiles'",
"]",
"profiles",
"&&",
"profiles",
".",
"include?",
"(",
"aws_profile",
")",
"end",
"env",
".",
"first",
"if",
"env",
"end"
] |
Do not use the Setting class to load the profile because it can cause an
infinite loop then if we decide to use Lono.env from within settings class.
|
[
"Do",
"not",
"use",
"the",
"Setting",
"class",
"to",
"load",
"the",
"profile",
"because",
"it",
"can",
"cause",
"an",
"infinite",
"loop",
"then",
"if",
"we",
"decide",
"to",
"use",
"Lono",
".",
"env",
"from",
"within",
"settings",
"class",
"."
] |
0135ec4cdb641970cd0bf7a5947b09d3153f739a
|
https://github.com/tongueroo/lono/blob/0135ec4cdb641970cd0bf7a5947b09d3153f739a/lib/lono/core.rb#L46-L54
|
8,976
|
szhu/hashcontrol
|
lib/hash_control/validator.rb
|
HashControl.Validator.require
|
def require(*keys)
permitted_keys.merge keys
required_keys = keys.to_set
unless (missing_keys = required_keys - hash_keys).empty?
error "required #{terms} #{missing_keys.to_a} missing" + postscript
end
self
end
|
ruby
|
def require(*keys)
permitted_keys.merge keys
required_keys = keys.to_set
unless (missing_keys = required_keys - hash_keys).empty?
error "required #{terms} #{missing_keys.to_a} missing" + postscript
end
self
end
|
[
"def",
"require",
"(",
"*",
"keys",
")",
"permitted_keys",
".",
"merge",
"keys",
"required_keys",
"=",
"keys",
".",
"to_set",
"unless",
"(",
"missing_keys",
"=",
"required_keys",
"-",
"hash_keys",
")",
".",
"empty?",
"error",
"\"required #{terms} #{missing_keys.to_a} missing\"",
"+",
"postscript",
"end",
"self",
"end"
] |
Specifies keys that must exist
|
[
"Specifies",
"keys",
"that",
"must",
"exist"
] |
e416c0af53f1ce582ef2d3cd074b9aeefc1fab4f
|
https://github.com/szhu/hashcontrol/blob/e416c0af53f1ce582ef2d3cd074b9aeefc1fab4f/lib/hash_control/validator.rb#L20-L27
|
8,977
|
cordawyn/redlander
|
lib/redlander/node.rb
|
Redlander.Node.datatype
|
def datatype
if instance_variable_defined?(:@datatype)
@datatype
else
@datatype = if literal?
rdf_uri = Redland.librdf_node_get_literal_value_datatype_uri(rdf_node)
rdf_uri.null? ? XmlSchema.datatype_of("") : URI.parse(Redland.librdf_uri_to_string(rdf_uri))
else
nil
end
end
end
|
ruby
|
def datatype
if instance_variable_defined?(:@datatype)
@datatype
else
@datatype = if literal?
rdf_uri = Redland.librdf_node_get_literal_value_datatype_uri(rdf_node)
rdf_uri.null? ? XmlSchema.datatype_of("") : URI.parse(Redland.librdf_uri_to_string(rdf_uri))
else
nil
end
end
end
|
[
"def",
"datatype",
"if",
"instance_variable_defined?",
"(",
":@datatype",
")",
"@datatype",
"else",
"@datatype",
"=",
"if",
"literal?",
"rdf_uri",
"=",
"Redland",
".",
"librdf_node_get_literal_value_datatype_uri",
"(",
"rdf_node",
")",
"rdf_uri",
".",
"null?",
"?",
"XmlSchema",
".",
"datatype_of",
"(",
"\"\"",
")",
":",
"URI",
".",
"parse",
"(",
"Redland",
".",
"librdf_uri_to_string",
"(",
"rdf_uri",
")",
")",
"else",
"nil",
"end",
"end",
"end"
] |
Datatype URI for the literal node, or nil
|
[
"Datatype",
"URI",
"for",
"the",
"literal",
"node",
"or",
"nil"
] |
a5c84e15a7602c674606e531bda6a616b1237c44
|
https://github.com/cordawyn/redlander/blob/a5c84e15a7602c674606e531bda6a616b1237c44/lib/redlander/node.rb#L40-L51
|
8,978
|
cordawyn/redlander
|
lib/redlander/node.rb
|
Redlander.Node.value
|
def value
if resource?
uri
elsif blank?
Redland.librdf_node_get_blank_identifier(rdf_node).force_encoding("UTF-8")
else
v = Redland.librdf_node_get_literal_value(rdf_node).force_encoding("UTF-8")
v << "@#{lang}" if lang
XmlSchema.instantiate(v, datatype)
end
end
|
ruby
|
def value
if resource?
uri
elsif blank?
Redland.librdf_node_get_blank_identifier(rdf_node).force_encoding("UTF-8")
else
v = Redland.librdf_node_get_literal_value(rdf_node).force_encoding("UTF-8")
v << "@#{lang}" if lang
XmlSchema.instantiate(v, datatype)
end
end
|
[
"def",
"value",
"if",
"resource?",
"uri",
"elsif",
"blank?",
"Redland",
".",
"librdf_node_get_blank_identifier",
"(",
"rdf_node",
")",
".",
"force_encoding",
"(",
"\"UTF-8\"",
")",
"else",
"v",
"=",
"Redland",
".",
"librdf_node_get_literal_value",
"(",
"rdf_node",
")",
".",
"force_encoding",
"(",
"\"UTF-8\"",
")",
"v",
"<<",
"\"@#{lang}\"",
"if",
"lang",
"XmlSchema",
".",
"instantiate",
"(",
"v",
",",
"datatype",
")",
"end",
"end"
] |
Value of the literal node as a Ruby object instance.
Returns an instance of URI for resource nodes,
"blank identifier" for blank nodes.
@return [URI, Any]
|
[
"Value",
"of",
"the",
"literal",
"node",
"as",
"a",
"Ruby",
"object",
"instance",
"."
] |
a5c84e15a7602c674606e531bda6a616b1237c44
|
https://github.com/cordawyn/redlander/blob/a5c84e15a7602c674606e531bda6a616b1237c44/lib/redlander/node.rb#L134-L144
|
8,979
|
jdickey/repository-base
|
lib/repository/base.rb
|
Repository.Base.delete
|
def delete(identifier)
RecordDeleter.new(identifier: identifier, dao: dao, factory: factory)
.delete
end
|
ruby
|
def delete(identifier)
RecordDeleter.new(identifier: identifier, dao: dao, factory: factory)
.delete
end
|
[
"def",
"delete",
"(",
"identifier",
")",
"RecordDeleter",
".",
"new",
"(",
"identifier",
":",
"identifier",
",",
"dao",
":",
"dao",
",",
"factory",
":",
"factory",
")",
".",
"delete",
"end"
] |
Remove a record from the underlying DAO whose slug matches the passed-in
identifier.
@param identifier [String] [Slug](http://en.wikipedia.org/wiki/Semantic_URL#Slug)
for record to be deleted.
@return [Repository::Support::StoreResult] An object containing
information about the success or failure of an action.
@since 0.0.5
|
[
"Remove",
"a",
"record",
"from",
"the",
"underlying",
"DAO",
"whose",
"slug",
"matches",
"the",
"passed",
"-",
"in",
"identifier",
"."
] |
b0f14156c1345d9ae878868cb6500f721653b4dc
|
https://github.com/jdickey/repository-base/blob/b0f14156c1345d9ae878868cb6500f721653b4dc/lib/repository/base.rb#L64-L67
|
8,980
|
rspeicher/will_paginate_renderers
|
lib/will_paginate_renderers/gmail.rb
|
WillPaginateRenderers.Gmail.window
|
def window
base = @collection.offset
high = base + @collection.per_page
high = @collection.total_entries if high > @collection.total_entries
# TODO: What's the best way to allow customization of this text, particularly "of"?
tag(:span, " #{base + 1} - #{high} of #{@collection.total_entries} ",
:class => WillPaginateRenderers.pagination_options[:gmail_window_class])
end
|
ruby
|
def window
base = @collection.offset
high = base + @collection.per_page
high = @collection.total_entries if high > @collection.total_entries
# TODO: What's the best way to allow customization of this text, particularly "of"?
tag(:span, " #{base + 1} - #{high} of #{@collection.total_entries} ",
:class => WillPaginateRenderers.pagination_options[:gmail_window_class])
end
|
[
"def",
"window",
"base",
"=",
"@collection",
".",
"offset",
"high",
"=",
"base",
"+",
"@collection",
".",
"per_page",
"high",
"=",
"@collection",
".",
"total_entries",
"if",
"high",
">",
"@collection",
".",
"total_entries",
"# TODO: What's the best way to allow customization of this text, particularly \"of\"?",
"tag",
"(",
":span",
",",
"\" #{base + 1} - #{high} of #{@collection.total_entries} \"",
",",
":class",
"=>",
"WillPaginateRenderers",
".",
"pagination_options",
"[",
":gmail_window_class",
"]",
")",
"end"
] |
Renders the "x - y of z" text
|
[
"Renders",
"the",
"x",
"-",
"y",
"of",
"z",
"text"
] |
30f1b1b8aaab70237858b93d9aa74464e4e42fb3
|
https://github.com/rspeicher/will_paginate_renderers/blob/30f1b1b8aaab70237858b93d9aa74464e4e42fb3/lib/will_paginate_renderers/gmail.rb#L74-L82
|
8,981
|
maxehmookau/echonest-ruby-api
|
lib/echonest-ruby-api/artist.rb
|
Echonest.Artist.news
|
def news(options = { results: 1 })
response = get_response(results: options[:results], name: @name)
response[:news].collect do |b|
Blog.new(name: b[:name], site: b[:site], url: b[:url])
end
end
|
ruby
|
def news(options = { results: 1 })
response = get_response(results: options[:results], name: @name)
response[:news].collect do |b|
Blog.new(name: b[:name], site: b[:site], url: b[:url])
end
end
|
[
"def",
"news",
"(",
"options",
"=",
"{",
"results",
":",
"1",
"}",
")",
"response",
"=",
"get_response",
"(",
"results",
":",
"options",
"[",
":results",
"]",
",",
"name",
":",
"@name",
")",
"response",
"[",
":news",
"]",
".",
"collect",
"do",
"|",
"b",
"|",
"Blog",
".",
"new",
"(",
"name",
":",
"b",
"[",
":name",
"]",
",",
"site",
":",
"b",
"[",
":site",
"]",
",",
"url",
":",
"b",
"[",
":url",
"]",
")",
"end",
"end"
] |
This appears to be from more "reputable" sources?
|
[
"This",
"appears",
"to",
"be",
"from",
"more",
"reputable",
"sources?"
] |
5d90cb6adec03d139f264665206ad507b6cc0a00
|
https://github.com/maxehmookau/echonest-ruby-api/blob/5d90cb6adec03d139f264665206ad507b6cc0a00/lib/echonest-ruby-api/artist.rb#L40-L46
|
8,982
|
sugaryourcoffee/syclink
|
lib/syclink/website.rb
|
SycLink.Website.list_links
|
def list_links(args = {})
if args.empty?
links
else
links.select { |link| link.match? args }
end
end
|
ruby
|
def list_links(args = {})
if args.empty?
links
else
links.select { |link| link.match? args }
end
end
|
[
"def",
"list_links",
"(",
"args",
"=",
"{",
"}",
")",
"if",
"args",
".",
"empty?",
"links",
"else",
"links",
".",
"select",
"{",
"|",
"link",
"|",
"link",
".",
"match?",
"args",
"}",
"end",
"end"
] |
List links that match the attributes
|
[
"List",
"links",
"that",
"match",
"the",
"attributes"
] |
941ee2045c946daa1e0db394eb643aa82c1254cc
|
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/website.rb#L38-L44
|
8,983
|
sugaryourcoffee/syclink
|
lib/syclink/website.rb
|
SycLink.Website.merge_links_on
|
def merge_links_on(attribute, concat_string = ',')
links_group_by(attribute)
.select { |key, link_list| links.size > 1 }
.map do |key, link_list|
merge_attributes = Link::ATTRS - [attribute]
link_list.first
.update(Hash[extract_columns(link_list, merge_attributes)
.map { |c| c.uniq.join(concat_string) }
.collect { |v| [merge_attributes.shift, v] }])
link_list.shift
link_list.each { |link| links.delete(link) }
end
end
|
ruby
|
def merge_links_on(attribute, concat_string = ',')
links_group_by(attribute)
.select { |key, link_list| links.size > 1 }
.map do |key, link_list|
merge_attributes = Link::ATTRS - [attribute]
link_list.first
.update(Hash[extract_columns(link_list, merge_attributes)
.map { |c| c.uniq.join(concat_string) }
.collect { |v| [merge_attributes.shift, v] }])
link_list.shift
link_list.each { |link| links.delete(link) }
end
end
|
[
"def",
"merge_links_on",
"(",
"attribute",
",",
"concat_string",
"=",
"','",
")",
"links_group_by",
"(",
"attribute",
")",
".",
"select",
"{",
"|",
"key",
",",
"link_list",
"|",
"links",
".",
"size",
">",
"1",
"}",
".",
"map",
"do",
"|",
"key",
",",
"link_list",
"|",
"merge_attributes",
"=",
"Link",
"::",
"ATTRS",
"-",
"[",
"attribute",
"]",
"link_list",
".",
"first",
".",
"update",
"(",
"Hash",
"[",
"extract_columns",
"(",
"link_list",
",",
"merge_attributes",
")",
".",
"map",
"{",
"|",
"c",
"|",
"c",
".",
"uniq",
".",
"join",
"(",
"concat_string",
")",
"}",
".",
"collect",
"{",
"|",
"v",
"|",
"[",
"merge_attributes",
".",
"shift",
",",
"v",
"]",
"}",
"]",
")",
"link_list",
".",
"shift",
"link_list",
".",
"each",
"{",
"|",
"link",
"|",
"links",
".",
"delete",
"(",
"link",
")",
"}",
"end",
"end"
] |
Merge links based on the provided attribue to one link by combining the
values. The first link will be updated and the obsolete links are deleted
and will be returned
|
[
"Merge",
"links",
"based",
"on",
"the",
"provided",
"attribue",
"to",
"one",
"link",
"by",
"combining",
"the",
"values",
".",
"The",
"first",
"link",
"will",
"be",
"updated",
"and",
"the",
"obsolete",
"links",
"are",
"deleted",
"and",
"will",
"be",
"returned"
] |
941ee2045c946daa1e0db394eb643aa82c1254cc
|
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/website.rb#L60-L72
|
8,984
|
sugaryourcoffee/syclink
|
lib/syclink/website.rb
|
SycLink.Website.links_group_by
|
def links_group_by(attribute, linkz = links)
linkz.map { |link| { key: link.send(attribute), link: link } }
.group_by { |entry| entry[:key] }
.each { |key, link| link.map! { |l| l[:link] }}
end
|
ruby
|
def links_group_by(attribute, linkz = links)
linkz.map { |link| { key: link.send(attribute), link: link } }
.group_by { |entry| entry[:key] }
.each { |key, link| link.map! { |l| l[:link] }}
end
|
[
"def",
"links_group_by",
"(",
"attribute",
",",
"linkz",
"=",
"links",
")",
"linkz",
".",
"map",
"{",
"|",
"link",
"|",
"{",
"key",
":",
"link",
".",
"send",
"(",
"attribute",
")",
",",
"link",
":",
"link",
"}",
"}",
".",
"group_by",
"{",
"|",
"entry",
"|",
"entry",
"[",
":key",
"]",
"}",
".",
"each",
"{",
"|",
"key",
",",
"link",
"|",
"link",
".",
"map!",
"{",
"|",
"l",
"|",
"l",
"[",
":link",
"]",
"}",
"}",
"end"
] |
Groups the links on the provided attribute. If no links array is provided
the links from self are used
|
[
"Groups",
"the",
"links",
"on",
"the",
"provided",
"attribute",
".",
"If",
"no",
"links",
"array",
"is",
"provided",
"the",
"links",
"from",
"self",
"are",
"used"
] |
941ee2045c946daa1e0db394eb643aa82c1254cc
|
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/website.rb#L76-L80
|
8,985
|
sugaryourcoffee/syclink
|
lib/syclink/website.rb
|
SycLink.Website.links_duplicate_on
|
def links_duplicate_on(attribute, separator)
links.map do |link|
link.send(attribute).split(separator).collect do |value|
link.dup.update(Hash[attribute, value])
end
end.flatten
end
|
ruby
|
def links_duplicate_on(attribute, separator)
links.map do |link|
link.send(attribute).split(separator).collect do |value|
link.dup.update(Hash[attribute, value])
end
end.flatten
end
|
[
"def",
"links_duplicate_on",
"(",
"attribute",
",",
"separator",
")",
"links",
".",
"map",
"do",
"|",
"link",
"|",
"link",
".",
"send",
"(",
"attribute",
")",
".",
"split",
"(",
"separator",
")",
".",
"collect",
"do",
"|",
"value",
"|",
"link",
".",
"dup",
".",
"update",
"(",
"Hash",
"[",
"attribute",
",",
"value",
"]",
")",
"end",
"end",
".",
"flatten",
"end"
] |
Create multiple Links based on the attribute provided. The specified
spearator will splitt the attribute value in distinct values and for each
different value a Link will be created
|
[
"Create",
"multiple",
"Links",
"based",
"on",
"the",
"attribute",
"provided",
".",
"The",
"specified",
"spearator",
"will",
"splitt",
"the",
"attribute",
"value",
"in",
"distinct",
"values",
"and",
"for",
"each",
"different",
"value",
"a",
"Link",
"will",
"be",
"created"
] |
941ee2045c946daa1e0db394eb643aa82c1254cc
|
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/website.rb#L92-L98
|
8,986
|
sugaryourcoffee/syclink
|
lib/syclink/website.rb
|
SycLink.Website.link_attribute_list
|
def link_attribute_list(attribute, separator = nil)
links.map {|link| link.send(attribute).split(separator)}.flatten.uniq.sort
end
|
ruby
|
def link_attribute_list(attribute, separator = nil)
links.map {|link| link.send(attribute).split(separator)}.flatten.uniq.sort
end
|
[
"def",
"link_attribute_list",
"(",
"attribute",
",",
"separator",
"=",
"nil",
")",
"links",
".",
"map",
"{",
"|",
"link",
"|",
"link",
".",
"send",
"(",
"attribute",
")",
".",
"split",
"(",
"separator",
")",
"}",
".",
"flatten",
".",
"uniq",
".",
"sort",
"end"
] |
List all attributes of the links
|
[
"List",
"all",
"attributes",
"of",
"the",
"links"
] |
941ee2045c946daa1e0db394eb643aa82c1254cc
|
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/website.rb#L106-L108
|
8,987
|
Deradon/Rdcpu16
|
lib/dcpu16/cpu.rb
|
DCPU16.CPU.run
|
def run
@started_at = Time.now
max_cycles = 1
while true do
if @cycle < max_cycles
step
else
diff = Time.now - @started_at
max_cycles = (diff * @clock_cycle)
end
end
end
|
ruby
|
def run
@started_at = Time.now
max_cycles = 1
while true do
if @cycle < max_cycles
step
else
diff = Time.now - @started_at
max_cycles = (diff * @clock_cycle)
end
end
end
|
[
"def",
"run",
"@started_at",
"=",
"Time",
".",
"now",
"max_cycles",
"=",
"1",
"while",
"true",
"do",
"if",
"@cycle",
"<",
"max_cycles",
"step",
"else",
"diff",
"=",
"Time",
".",
"now",
"-",
"@started_at",
"max_cycles",
"=",
"(",
"diff",
"*",
"@clock_cycle",
")",
"end",
"end",
"end"
] |
Run in endless loop
|
[
"Run",
"in",
"endless",
"loop"
] |
a4460927aa64c2a514c57993e8ea13f5b48377e9
|
https://github.com/Deradon/Rdcpu16/blob/a4460927aa64c2a514c57993e8ea13f5b48377e9/lib/dcpu16/cpu.rb#L51-L63
|
8,988
|
dannyxu2015/imwukong
|
lib/imwukong/api.rb
|
Imwukong.Base.wk_api_info
|
def wk_api_info(api_method='')
api_method ||= ''
fail 'Invalid wukong api' unless api_method == '' || api_method =~ WK_API_FORMAT
if api_method.size > 0
m = api_method.to_s.match(/^wk_([a-zA-Z0-9]+)_(.+)/)
method_group = m[1].singularize
method_name = m[2]
end
apis = api_method.size > 0 ? API_LIST.select { |a| a[:method_group]==method_group && method_name==a[:method_name] } : API_LIST
fail 'api not found' unless apis.present?
apis.map do |api|
method_group = api[:method_pluralize] ? api[:method_group].pluralize : api[:method_group]
method_name = "wk_#{method_group}_#{api[:method_name]}"
"#{method_name}, #{api_url(api)}, #{api[:args].inspect} "
end
end
|
ruby
|
def wk_api_info(api_method='')
api_method ||= ''
fail 'Invalid wukong api' unless api_method == '' || api_method =~ WK_API_FORMAT
if api_method.size > 0
m = api_method.to_s.match(/^wk_([a-zA-Z0-9]+)_(.+)/)
method_group = m[1].singularize
method_name = m[2]
end
apis = api_method.size > 0 ? API_LIST.select { |a| a[:method_group]==method_group && method_name==a[:method_name] } : API_LIST
fail 'api not found' unless apis.present?
apis.map do |api|
method_group = api[:method_pluralize] ? api[:method_group].pluralize : api[:method_group]
method_name = "wk_#{method_group}_#{api[:method_name]}"
"#{method_name}, #{api_url(api)}, #{api[:args].inspect} "
end
end
|
[
"def",
"wk_api_info",
"(",
"api_method",
"=",
"''",
")",
"api_method",
"||=",
"''",
"fail",
"'Invalid wukong api'",
"unless",
"api_method",
"==",
"''",
"||",
"api_method",
"=~",
"WK_API_FORMAT",
"if",
"api_method",
".",
"size",
">",
"0",
"m",
"=",
"api_method",
".",
"to_s",
".",
"match",
"(",
"/",
"/",
")",
"method_group",
"=",
"m",
"[",
"1",
"]",
".",
"singularize",
"method_name",
"=",
"m",
"[",
"2",
"]",
"end",
"apis",
"=",
"api_method",
".",
"size",
">",
"0",
"?",
"API_LIST",
".",
"select",
"{",
"|",
"a",
"|",
"a",
"[",
":method_group",
"]",
"==",
"method_group",
"&&",
"method_name",
"==",
"a",
"[",
":method_name",
"]",
"}",
":",
"API_LIST",
"fail",
"'api not found'",
"unless",
"apis",
".",
"present?",
"apis",
".",
"map",
"do",
"|",
"api",
"|",
"method_group",
"=",
"api",
"[",
":method_pluralize",
"]",
"?",
"api",
"[",
":method_group",
"]",
".",
"pluralize",
":",
"api",
"[",
":method_group",
"]",
"method_name",
"=",
"\"wk_#{method_group}_#{api[:method_name]}\"",
"\"#{method_name}, #{api_url(api)}, #{api[:args].inspect} \"",
"end",
"end"
] |
api detail info, include request url & arguments
@param api_method, string, default output information of all api
@return an array of match api info string, format: api_name, REQUEST url, arguments symbol array
|
[
"api",
"detail",
"info",
"include",
"request",
"url",
"&",
"arguments"
] |
80c7712cef13e7ee6bd84e604371d47acda89927
|
https://github.com/dannyxu2015/imwukong/blob/80c7712cef13e7ee6bd84e604371d47acda89927/lib/imwukong/api.rb#L484-L499
|
8,989
|
astjohn/cornerstone
|
app/models/cornerstone/post.rb
|
Cornerstone.Post.update_counter_cache
|
def update_counter_cache
self.discussion.reply_count = Post.where(:discussion_id => self.discussion.id)
.count - 1
self.discussion.save
end
|
ruby
|
def update_counter_cache
self.discussion.reply_count = Post.where(:discussion_id => self.discussion.id)
.count - 1
self.discussion.save
end
|
[
"def",
"update_counter_cache",
"self",
".",
"discussion",
".",
"reply_count",
"=",
"Post",
".",
"where",
"(",
":discussion_id",
"=>",
"self",
".",
"discussion",
".",
"id",
")",
".",
"count",
"-",
"1",
"self",
".",
"discussion",
".",
"save",
"end"
] |
Custom counter cache. Does not include the first post of a discussion.
|
[
"Custom",
"counter",
"cache",
".",
"Does",
"not",
"include",
"the",
"first",
"post",
"of",
"a",
"discussion",
"."
] |
d7af7c06288477c961f3e328b8640df4be337301
|
https://github.com/astjohn/cornerstone/blob/d7af7c06288477c961f3e328b8640df4be337301/app/models/cornerstone/post.rb#L74-L78
|
8,990
|
astjohn/cornerstone
|
app/models/cornerstone/post.rb
|
Cornerstone.Post.anonymous_or_user_attr
|
def anonymous_or_user_attr(attr)
unless self.user_id.nil?
mthd = "user_#{attr.to_s}"
# TODO: rails caching is messing this relationship up.
# will .user work even if model name is something else. e.g. AdminUser ??
self.user.send(attr)
else
case attr
when :cornerstone_name
self.send(:name)
when :cornerstone_email
self.send(:email)
end
end
end
|
ruby
|
def anonymous_or_user_attr(attr)
unless self.user_id.nil?
mthd = "user_#{attr.to_s}"
# TODO: rails caching is messing this relationship up.
# will .user work even if model name is something else. e.g. AdminUser ??
self.user.send(attr)
else
case attr
when :cornerstone_name
self.send(:name)
when :cornerstone_email
self.send(:email)
end
end
end
|
[
"def",
"anonymous_or_user_attr",
"(",
"attr",
")",
"unless",
"self",
".",
"user_id",
".",
"nil?",
"mthd",
"=",
"\"user_#{attr.to_s}\"",
"# TODO: rails caching is messing this relationship up.",
"# will .user work even if model name is something else. e.g. AdminUser ??",
"self",
".",
"user",
".",
"send",
"(",
"attr",
")",
"else",
"case",
"attr",
"when",
":cornerstone_name",
"self",
".",
"send",
"(",
":name",
")",
"when",
":cornerstone_email",
"self",
".",
"send",
"(",
":email",
")",
"end",
"end",
"end"
] |
Returns the requested attribute of the user if it exists, or post's attribute
|
[
"Returns",
"the",
"requested",
"attribute",
"of",
"the",
"user",
"if",
"it",
"exists",
"or",
"post",
"s",
"attribute"
] |
d7af7c06288477c961f3e328b8640df4be337301
|
https://github.com/astjohn/cornerstone/blob/d7af7c06288477c961f3e328b8640df4be337301/app/models/cornerstone/post.rb#L81-L95
|
8,991
|
SpeciesFileGroup/taxonifi
|
lib/taxonifi/export/format/obo_nomenclature.rb
|
Taxonifi::Export.OboNomenclature.export
|
def export()
super
f = new_output_file('obo_nomenclature.obo')
# header
f.puts 'format-version: 1.2'
f.puts "date: #{@time}"
f.puts 'saved-by: someone'
f.puts 'auto-generated-by: Taxonifi'
f.puts 'synonymtypedef: COMMONNAME "common name"'
f.puts 'synonymtypedef: MISSPELLING "misspelling" EXACT'
f.puts 'synonymtypedef: TAXONNAMEUSAGE "name with (author year)" NARROW'
f.puts "default-namespace: #{@namespace}"
f.puts "ontology: FIX-ME-taxonifi-ontology\n\n"
# terms
@name_collection.collection.each do |n|
f.puts '[Term]'
f.puts "id: #{id_string(n)}"
f.puts "name: #{n.name}"
f.puts "is_a: #{id_string(n.parent)} ! #{n.parent.name}" if n.parent
f.puts "property_value: has_rank #{rank_string(n)}"
f.puts
end
# typedefs
f.puts "[Typedef]"
f.puts "id: has_rank"
f.puts "name: has taxonomic rank"
f.puts "is_metadata_tag: true"
true
end
|
ruby
|
def export()
super
f = new_output_file('obo_nomenclature.obo')
# header
f.puts 'format-version: 1.2'
f.puts "date: #{@time}"
f.puts 'saved-by: someone'
f.puts 'auto-generated-by: Taxonifi'
f.puts 'synonymtypedef: COMMONNAME "common name"'
f.puts 'synonymtypedef: MISSPELLING "misspelling" EXACT'
f.puts 'synonymtypedef: TAXONNAMEUSAGE "name with (author year)" NARROW'
f.puts "default-namespace: #{@namespace}"
f.puts "ontology: FIX-ME-taxonifi-ontology\n\n"
# terms
@name_collection.collection.each do |n|
f.puts '[Term]'
f.puts "id: #{id_string(n)}"
f.puts "name: #{n.name}"
f.puts "is_a: #{id_string(n.parent)} ! #{n.parent.name}" if n.parent
f.puts "property_value: has_rank #{rank_string(n)}"
f.puts
end
# typedefs
f.puts "[Typedef]"
f.puts "id: has_rank"
f.puts "name: has taxonomic rank"
f.puts "is_metadata_tag: true"
true
end
|
[
"def",
"export",
"(",
")",
"super",
"f",
"=",
"new_output_file",
"(",
"'obo_nomenclature.obo'",
")",
"# header ",
"f",
".",
"puts",
"'format-version: 1.2'",
"f",
".",
"puts",
"\"date: #{@time}\"",
"f",
".",
"puts",
"'saved-by: someone'",
"f",
".",
"puts",
"'auto-generated-by: Taxonifi'",
"f",
".",
"puts",
"'synonymtypedef: COMMONNAME \"common name\"'",
"f",
".",
"puts",
"'synonymtypedef: MISSPELLING \"misspelling\" EXACT'",
"f",
".",
"puts",
"'synonymtypedef: TAXONNAMEUSAGE \"name with (author year)\" NARROW'",
"f",
".",
"puts",
"\"default-namespace: #{@namespace}\"",
"f",
".",
"puts",
"\"ontology: FIX-ME-taxonifi-ontology\\n\\n\"",
"# terms",
"@name_collection",
".",
"collection",
".",
"each",
"do",
"|",
"n",
"|",
"f",
".",
"puts",
"'[Term]'",
"f",
".",
"puts",
"\"id: #{id_string(n)}\"",
"f",
".",
"puts",
"\"name: #{n.name}\"",
"f",
".",
"puts",
"\"is_a: #{id_string(n.parent)} ! #{n.parent.name}\"",
"if",
"n",
".",
"parent",
"f",
".",
"puts",
"\"property_value: has_rank #{rank_string(n)}\"",
"f",
".",
"puts",
"end",
"# typedefs",
"f",
".",
"puts",
"\"[Typedef]\"",
"f",
".",
"puts",
"\"id: has_rank\"",
"f",
".",
"puts",
"\"name: has taxonomic rank\"",
"f",
".",
"puts",
"\"is_metadata_tag: true\"",
"true",
"end"
] |
Writes the file.
|
[
"Writes",
"the",
"file",
"."
] |
100dc94e7ffd378f6a81381c13768e35b2b65bf2
|
https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/export/format/obo_nomenclature.rb#L28-L60
|
8,992
|
culturecode/templatr
|
app/models/templatr/field.rb
|
Templatr.Field.has_unique_name
|
def has_unique_name
invalid = false
if template
invalid ||= template.common_fields.any? {|field| field.name.downcase == self.name.downcase && field != self }
invalid ||= template.default_fields.any? {|field| field.name.downcase == self.name.downcase && field != self }
else
scope = self.class.common.where("LOWER(name) = LOWER(?)", self.name)
scope = scope.where("id != ?", self.id) if persisted?
invalid ||= scope.exists?
end
errors.add(:name, "has already been taken") if invalid
end
|
ruby
|
def has_unique_name
invalid = false
if template
invalid ||= template.common_fields.any? {|field| field.name.downcase == self.name.downcase && field != self }
invalid ||= template.default_fields.any? {|field| field.name.downcase == self.name.downcase && field != self }
else
scope = self.class.common.where("LOWER(name) = LOWER(?)", self.name)
scope = scope.where("id != ?", self.id) if persisted?
invalid ||= scope.exists?
end
errors.add(:name, "has already been taken") if invalid
end
|
[
"def",
"has_unique_name",
"invalid",
"=",
"false",
"if",
"template",
"invalid",
"||=",
"template",
".",
"common_fields",
".",
"any?",
"{",
"|",
"field",
"|",
"field",
".",
"name",
".",
"downcase",
"==",
"self",
".",
"name",
".",
"downcase",
"&&",
"field",
"!=",
"self",
"}",
"invalid",
"||=",
"template",
".",
"default_fields",
".",
"any?",
"{",
"|",
"field",
"|",
"field",
".",
"name",
".",
"downcase",
"==",
"self",
".",
"name",
".",
"downcase",
"&&",
"field",
"!=",
"self",
"}",
"else",
"scope",
"=",
"self",
".",
"class",
".",
"common",
".",
"where",
"(",
"\"LOWER(name) = LOWER(?)\"",
",",
"self",
".",
"name",
")",
"scope",
"=",
"scope",
".",
"where",
"(",
"\"id != ?\"",
",",
"self",
".",
"id",
")",
"if",
"persisted?",
"invalid",
"||=",
"scope",
".",
"exists?",
"end",
"errors",
".",
"add",
"(",
":name",
",",
"\"has already been taken\"",
")",
"if",
"invalid",
"end"
] |
Checks the current template and the common fields for any field with the same name
|
[
"Checks",
"the",
"current",
"template",
"and",
"the",
"common",
"fields",
"for",
"any",
"field",
"with",
"the",
"same",
"name"
] |
0bffb930736b4339fb8a9e8adc080404dc6860d8
|
https://github.com/culturecode/templatr/blob/0bffb930736b4339fb8a9e8adc080404dc6860d8/app/models/templatr/field.rb#L157-L169
|
8,993
|
culturecode/templatr
|
app/models/templatr/field.rb
|
Templatr.Field.disambiguate_fields
|
def disambiguate_fields
if name_changed? # New, Updated
fields = self.class.specific.where("LOWER(name) = LOWER(?)", self.name)
fields.update_all(:disambiguate => fields.many?)
end
if name_was # Updated, Destroyed
fields = self.class.specific.where("LOWER(name) = LOWER(?)", self.name_was)
fields.update_all(:disambiguate => fields.many?)
end
end
|
ruby
|
def disambiguate_fields
if name_changed? # New, Updated
fields = self.class.specific.where("LOWER(name) = LOWER(?)", self.name)
fields.update_all(:disambiguate => fields.many?)
end
if name_was # Updated, Destroyed
fields = self.class.specific.where("LOWER(name) = LOWER(?)", self.name_was)
fields.update_all(:disambiguate => fields.many?)
end
end
|
[
"def",
"disambiguate_fields",
"if",
"name_changed?",
"# New, Updated",
"fields",
"=",
"self",
".",
"class",
".",
"specific",
".",
"where",
"(",
"\"LOWER(name) = LOWER(?)\"",
",",
"self",
".",
"name",
")",
"fields",
".",
"update_all",
"(",
":disambiguate",
"=>",
"fields",
".",
"many?",
")",
"end",
"if",
"name_was",
"# Updated, Destroyed",
"fields",
"=",
"self",
".",
"class",
".",
"specific",
".",
"where",
"(",
"\"LOWER(name) = LOWER(?)\"",
",",
"self",
".",
"name_was",
")",
"fields",
".",
"update_all",
"(",
":disambiguate",
"=>",
"fields",
".",
"many?",
")",
"end",
"end"
] |
Finds all fields with the same name and ensures they know there is another field with the same name
thus allowing us to have them a prefix that lets us identify them in a query string
|
[
"Finds",
"all",
"fields",
"with",
"the",
"same",
"name",
"and",
"ensures",
"they",
"know",
"there",
"is",
"another",
"field",
"with",
"the",
"same",
"name",
"thus",
"allowing",
"us",
"to",
"have",
"them",
"a",
"prefix",
"that",
"lets",
"us",
"identify",
"them",
"in",
"a",
"query",
"string"
] |
0bffb930736b4339fb8a9e8adc080404dc6860d8
|
https://github.com/culturecode/templatr/blob/0bffb930736b4339fb8a9e8adc080404dc6860d8/app/models/templatr/field.rb#L192-L202
|
8,994
|
mochnatiy/flexible_accessibility
|
lib/flexible_accessibility/route_provider.rb
|
FlexibleAccessibility.RouteProvider.app_routes_as_hash
|
def app_routes_as_hash
Rails.application.routes.routes.each do |route|
controller = route.defaults[:controller]
next if controller.nil?
key = controller.split('/').map(&:camelize).join('::')
routes[key] ||= []
routes[key] << route.defaults[:action]
end
end
|
ruby
|
def app_routes_as_hash
Rails.application.routes.routes.each do |route|
controller = route.defaults[:controller]
next if controller.nil?
key = controller.split('/').map(&:camelize).join('::')
routes[key] ||= []
routes[key] << route.defaults[:action]
end
end
|
[
"def",
"app_routes_as_hash",
"Rails",
".",
"application",
".",
"routes",
".",
"routes",
".",
"each",
"do",
"|",
"route",
"|",
"controller",
"=",
"route",
".",
"defaults",
"[",
":controller",
"]",
"next",
"if",
"controller",
".",
"nil?",
"key",
"=",
"controller",
".",
"split",
"(",
"'/'",
")",
".",
"map",
"(",
":camelize",
")",
".",
"join",
"(",
"'::'",
")",
"routes",
"[",
"key",
"]",
"||=",
"[",
"]",
"routes",
"[",
"key",
"]",
"<<",
"route",
".",
"defaults",
"[",
":action",
"]",
"end",
"end"
] |
Routes from routes.rb
|
[
"Routes",
"from",
"routes",
".",
"rb"
] |
ffd7f76e0765aa28909625b3bfa282264b8a5195
|
https://github.com/mochnatiy/flexible_accessibility/blob/ffd7f76e0765aa28909625b3bfa282264b8a5195/lib/flexible_accessibility/route_provider.rb#L96-L106
|
8,995
|
andymarthin/bca_statement
|
lib/bca_statement/client.rb
|
BcaStatement.Client.get_statement
|
def get_statement(start_date = '2016-08-29', end_date = '2016-09-01')
return nil unless @access_token
@timestamp = Time.now.iso8601(3)
@start_date = start_date.to_s
@end_date = end_date.to_s
@path = "/banking/v3/corporates/"
@relative_url = "#{@path}#{@corporate_id}/accounts/#{@account_number}/statements?EndDate=#{@end_date}&StartDate=#{@start_date}"
begin
response = RestClient.get("#{@base_url}#{@relative_url}",
"Content-Type": 'application/json',
"Authorization": "Bearer #{@access_token}",
"Origin": @domain,
"X-BCA-Key": @api_key,
"X-BCA-Timestamp": @timestamp,
"X-BCA-Signature": signature)
elements = JSON.parse response.body
statements = []
elements['Data'].each do |element|
year = Date.parse(@start_date).strftime('%m').to_i.eql?(12) ? Date.parse(@start_date).strftime('%Y') : Date.parse(@end_date).strftime('%Y')
date = element['TransactionDate'].eql?("PEND") ? element['TransactionDate'] : "#{element['TransactionDate']}/#{year}"
attribute = {
date: date,
brance_code: element['BranchCode'],
type: element['TransactionType'],
amount: element['TransactionAmount'].to_f,
name: element['TransactionName'],
trailer: element['Trailer']
}
statements << BcaStatement::Entities::Statement.new(attribute)
end
statements
rescue RestClient::ExceptionWithResponse => err
return nil
end
end
|
ruby
|
def get_statement(start_date = '2016-08-29', end_date = '2016-09-01')
return nil unless @access_token
@timestamp = Time.now.iso8601(3)
@start_date = start_date.to_s
@end_date = end_date.to_s
@path = "/banking/v3/corporates/"
@relative_url = "#{@path}#{@corporate_id}/accounts/#{@account_number}/statements?EndDate=#{@end_date}&StartDate=#{@start_date}"
begin
response = RestClient.get("#{@base_url}#{@relative_url}",
"Content-Type": 'application/json',
"Authorization": "Bearer #{@access_token}",
"Origin": @domain,
"X-BCA-Key": @api_key,
"X-BCA-Timestamp": @timestamp,
"X-BCA-Signature": signature)
elements = JSON.parse response.body
statements = []
elements['Data'].each do |element|
year = Date.parse(@start_date).strftime('%m').to_i.eql?(12) ? Date.parse(@start_date).strftime('%Y') : Date.parse(@end_date).strftime('%Y')
date = element['TransactionDate'].eql?("PEND") ? element['TransactionDate'] : "#{element['TransactionDate']}/#{year}"
attribute = {
date: date,
brance_code: element['BranchCode'],
type: element['TransactionType'],
amount: element['TransactionAmount'].to_f,
name: element['TransactionName'],
trailer: element['Trailer']
}
statements << BcaStatement::Entities::Statement.new(attribute)
end
statements
rescue RestClient::ExceptionWithResponse => err
return nil
end
end
|
[
"def",
"get_statement",
"(",
"start_date",
"=",
"'2016-08-29'",
",",
"end_date",
"=",
"'2016-09-01'",
")",
"return",
"nil",
"unless",
"@access_token",
"@timestamp",
"=",
"Time",
".",
"now",
".",
"iso8601",
"(",
"3",
")",
"@start_date",
"=",
"start_date",
".",
"to_s",
"@end_date",
"=",
"end_date",
".",
"to_s",
"@path",
"=",
"\"/banking/v3/corporates/\"",
"@relative_url",
"=",
"\"#{@path}#{@corporate_id}/accounts/#{@account_number}/statements?EndDate=#{@end_date}&StartDate=#{@start_date}\"",
"begin",
"response",
"=",
"RestClient",
".",
"get",
"(",
"\"#{@base_url}#{@relative_url}\"",
",",
"\"Content-Type\"",
":",
"'application/json'",
",",
"\"Authorization\"",
":",
"\"Bearer #{@access_token}\"",
",",
"\"Origin\"",
":",
"@domain",
",",
"\"X-BCA-Key\"",
":",
"@api_key",
",",
"\"X-BCA-Timestamp\"",
":",
"@timestamp",
",",
"\"X-BCA-Signature\"",
":",
"signature",
")",
"elements",
"=",
"JSON",
".",
"parse",
"response",
".",
"body",
"statements",
"=",
"[",
"]",
"elements",
"[",
"'Data'",
"]",
".",
"each",
"do",
"|",
"element",
"|",
"year",
"=",
"Date",
".",
"parse",
"(",
"@start_date",
")",
".",
"strftime",
"(",
"'%m'",
")",
".",
"to_i",
".",
"eql?",
"(",
"12",
")",
"?",
"Date",
".",
"parse",
"(",
"@start_date",
")",
".",
"strftime",
"(",
"'%Y'",
")",
":",
"Date",
".",
"parse",
"(",
"@end_date",
")",
".",
"strftime",
"(",
"'%Y'",
")",
"date",
"=",
"element",
"[",
"'TransactionDate'",
"]",
".",
"eql?",
"(",
"\"PEND\"",
")",
"?",
"element",
"[",
"'TransactionDate'",
"]",
":",
"\"#{element['TransactionDate']}/#{year}\"",
"attribute",
"=",
"{",
"date",
":",
"date",
",",
"brance_code",
":",
"element",
"[",
"'BranchCode'",
"]",
",",
"type",
":",
"element",
"[",
"'TransactionType'",
"]",
",",
"amount",
":",
"element",
"[",
"'TransactionAmount'",
"]",
".",
"to_f",
",",
"name",
":",
"element",
"[",
"'TransactionName'",
"]",
",",
"trailer",
":",
"element",
"[",
"'Trailer'",
"]",
"}",
"statements",
"<<",
"BcaStatement",
"::",
"Entities",
"::",
"Statement",
".",
"new",
"(",
"attribute",
")",
"end",
"statements",
"rescue",
"RestClient",
"::",
"ExceptionWithResponse",
"=>",
"err",
"return",
"nil",
"end",
"end"
] |
Get your BCA Bisnis account statement for a period up to 31 days.
|
[
"Get",
"your",
"BCA",
"Bisnis",
"account",
"statement",
"for",
"a",
"period",
"up",
"to",
"31",
"days",
"."
] |
d095a1623077d89202296271904bc68e5bfb960c
|
https://github.com/andymarthin/bca_statement/blob/d095a1623077d89202296271904bc68e5bfb960c/lib/bca_statement/client.rb#L24-L60
|
8,996
|
andymarthin/bca_statement
|
lib/bca_statement/client.rb
|
BcaStatement.Client.balance
|
def balance
return nil unless @access_token
begin
@timestamp = Time.now.iso8601(3)
@relative_url = "/banking/v3/corporates/#{@corporate_id}/accounts/#{@account_number}"
response = RestClient.get("#{@base_url}#{@relative_url}",
"Content-Type": 'application/json',
"Authorization": "Bearer #{@access_token}",
"Origin": @domain,
"X-BCA-Key": @api_key,
"X-BCA-Timestamp": @timestamp,
"X-BCA-Signature": signature)
data = JSON.parse response.body
if account_detail_success = data['AccountDetailDataSuccess']
detail = account_detail_success.first
attribute = {
account_number: detail['AccountNumber'],
currency: detail['Currency'],
balance: detail['Balance'].to_f,
available_balance: detail['AvailableBalance'].to_f,
float_amount: detail['FloatAmount'].to_f,
hold_amount: detail['HoldAmount'].to_f,
plafon: detail['Plafon'].to_f
}
BcaStatement::Entities::Balance.new(attribute)
else
return nil
end
rescue RestClient::ExceptionWithResponse => err
return nil
end
end
|
ruby
|
def balance
return nil unless @access_token
begin
@timestamp = Time.now.iso8601(3)
@relative_url = "/banking/v3/corporates/#{@corporate_id}/accounts/#{@account_number}"
response = RestClient.get("#{@base_url}#{@relative_url}",
"Content-Type": 'application/json',
"Authorization": "Bearer #{@access_token}",
"Origin": @domain,
"X-BCA-Key": @api_key,
"X-BCA-Timestamp": @timestamp,
"X-BCA-Signature": signature)
data = JSON.parse response.body
if account_detail_success = data['AccountDetailDataSuccess']
detail = account_detail_success.first
attribute = {
account_number: detail['AccountNumber'],
currency: detail['Currency'],
balance: detail['Balance'].to_f,
available_balance: detail['AvailableBalance'].to_f,
float_amount: detail['FloatAmount'].to_f,
hold_amount: detail['HoldAmount'].to_f,
plafon: detail['Plafon'].to_f
}
BcaStatement::Entities::Balance.new(attribute)
else
return nil
end
rescue RestClient::ExceptionWithResponse => err
return nil
end
end
|
[
"def",
"balance",
"return",
"nil",
"unless",
"@access_token",
"begin",
"@timestamp",
"=",
"Time",
".",
"now",
".",
"iso8601",
"(",
"3",
")",
"@relative_url",
"=",
"\"/banking/v3/corporates/#{@corporate_id}/accounts/#{@account_number}\"",
"response",
"=",
"RestClient",
".",
"get",
"(",
"\"#{@base_url}#{@relative_url}\"",
",",
"\"Content-Type\"",
":",
"'application/json'",
",",
"\"Authorization\"",
":",
"\"Bearer #{@access_token}\"",
",",
"\"Origin\"",
":",
"@domain",
",",
"\"X-BCA-Key\"",
":",
"@api_key",
",",
"\"X-BCA-Timestamp\"",
":",
"@timestamp",
",",
"\"X-BCA-Signature\"",
":",
"signature",
")",
"data",
"=",
"JSON",
".",
"parse",
"response",
".",
"body",
"if",
"account_detail_success",
"=",
"data",
"[",
"'AccountDetailDataSuccess'",
"]",
"detail",
"=",
"account_detail_success",
".",
"first",
"attribute",
"=",
"{",
"account_number",
":",
"detail",
"[",
"'AccountNumber'",
"]",
",",
"currency",
":",
"detail",
"[",
"'Currency'",
"]",
",",
"balance",
":",
"detail",
"[",
"'Balance'",
"]",
".",
"to_f",
",",
"available_balance",
":",
"detail",
"[",
"'AvailableBalance'",
"]",
".",
"to_f",
",",
"float_amount",
":",
"detail",
"[",
"'FloatAmount'",
"]",
".",
"to_f",
",",
"hold_amount",
":",
"detail",
"[",
"'HoldAmount'",
"]",
".",
"to_f",
",",
"plafon",
":",
"detail",
"[",
"'Plafon'",
"]",
".",
"to_f",
"}",
"BcaStatement",
"::",
"Entities",
"::",
"Balance",
".",
"new",
"(",
"attribute",
")",
"else",
"return",
"nil",
"end",
"rescue",
"RestClient",
"::",
"ExceptionWithResponse",
"=>",
"err",
"return",
"nil",
"end",
"end"
] |
Get your BCA Bisnis account balance information
|
[
"Get",
"your",
"BCA",
"Bisnis",
"account",
"balance",
"information"
] |
d095a1623077d89202296271904bc68e5bfb960c
|
https://github.com/andymarthin/bca_statement/blob/d095a1623077d89202296271904bc68e5bfb960c/lib/bca_statement/client.rb#L63-L97
|
8,997
|
tsenying/simple_geocoder
|
lib/simple_geocoder/geocoder.rb
|
SimpleGeocoder.Geocoder.geocode!
|
def geocode!(address, options = {})
response = call_geocoder_service(address, options)
if response.is_a?(Net::HTTPOK)
return JSON.parse response.body
else
raise ResponseError.new response
end
end
|
ruby
|
def geocode!(address, options = {})
response = call_geocoder_service(address, options)
if response.is_a?(Net::HTTPOK)
return JSON.parse response.body
else
raise ResponseError.new response
end
end
|
[
"def",
"geocode!",
"(",
"address",
",",
"options",
"=",
"{",
"}",
")",
"response",
"=",
"call_geocoder_service",
"(",
"address",
",",
"options",
")",
"if",
"response",
".",
"is_a?",
"(",
"Net",
"::",
"HTTPOK",
")",
"return",
"JSON",
".",
"parse",
"response",
".",
"body",
"else",
"raise",
"ResponseError",
".",
"new",
"response",
"end",
"end"
] |
raise ResponseError exception on error
|
[
"raise",
"ResponseError",
"exception",
"on",
"error"
] |
8958504584dc02c048f56295f1c4f19e52a2be6a
|
https://github.com/tsenying/simple_geocoder/blob/8958504584dc02c048f56295f1c4f19e52a2be6a/lib/simple_geocoder/geocoder.rb#L26-L33
|
8,998
|
tsenying/simple_geocoder
|
lib/simple_geocoder/geocoder.rb
|
SimpleGeocoder.Geocoder.find_location
|
def find_location(address)
result = geocode(address)
if result['status'] == 'OK'
return result['results'][0]['geometry']['location']
else
latlon_regexp = /(-?([1-8]?[0-9]\.{1}\d{1,6}|90\.{1}0{1,6})),(-?((([1]?[0-7][0-9]|[1-9]?[0-9])\.{1}\d{1,6})|[1]?[1-8][0]\.{1}0{1,6}))/
if address =~ latlon_regexp
location = $&.split(',').map {|e| e.to_f}
return { "lat" => location[0], "lng" => location[1] }
else
return nil
end
end
end
|
ruby
|
def find_location(address)
result = geocode(address)
if result['status'] == 'OK'
return result['results'][0]['geometry']['location']
else
latlon_regexp = /(-?([1-8]?[0-9]\.{1}\d{1,6}|90\.{1}0{1,6})),(-?((([1]?[0-7][0-9]|[1-9]?[0-9])\.{1}\d{1,6})|[1]?[1-8][0]\.{1}0{1,6}))/
if address =~ latlon_regexp
location = $&.split(',').map {|e| e.to_f}
return { "lat" => location[0], "lng" => location[1] }
else
return nil
end
end
end
|
[
"def",
"find_location",
"(",
"address",
")",
"result",
"=",
"geocode",
"(",
"address",
")",
"if",
"result",
"[",
"'status'",
"]",
"==",
"'OK'",
"return",
"result",
"[",
"'results'",
"]",
"[",
"0",
"]",
"[",
"'geometry'",
"]",
"[",
"'location'",
"]",
"else",
"latlon_regexp",
"=",
"/",
"\\.",
"\\d",
"\\.",
"\\.",
"\\d",
"\\.",
"/",
"if",
"address",
"=~",
"latlon_regexp",
"location",
"=",
"$&",
".",
"split",
"(",
"','",
")",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"to_f",
"}",
"return",
"{",
"\"lat\"",
"=>",
"location",
"[",
"0",
"]",
",",
"\"lng\"",
"=>",
"location",
"[",
"1",
"]",
"}",
"else",
"return",
"nil",
"end",
"end",
"end"
] |
if geocoding fails, then look for lat,lng string in address
|
[
"if",
"geocoding",
"fails",
"then",
"look",
"for",
"lat",
"lng",
"string",
"in",
"address"
] |
8958504584dc02c048f56295f1c4f19e52a2be6a
|
https://github.com/tsenying/simple_geocoder/blob/8958504584dc02c048f56295f1c4f19e52a2be6a/lib/simple_geocoder/geocoder.rb#L36-L49
|
8,999
|
jeremyruppel/psql
|
lib/psql/database.rb
|
PSQL.Database.object
|
def object( object_name )
object = objects.find do |obj|
obj[ 'name' ] == object_name
end
if !object
raise "Database #{name} does not have an object named '#{object_name}'."
end
klass = PSQL.const_get object[ 'type' ].capitalize
klass.new object[ 'name' ], name
end
|
ruby
|
def object( object_name )
object = objects.find do |obj|
obj[ 'name' ] == object_name
end
if !object
raise "Database #{name} does not have an object named '#{object_name}'."
end
klass = PSQL.const_get object[ 'type' ].capitalize
klass.new object[ 'name' ], name
end
|
[
"def",
"object",
"(",
"object_name",
")",
"object",
"=",
"objects",
".",
"find",
"do",
"|",
"obj",
"|",
"obj",
"[",
"'name'",
"]",
"==",
"object_name",
"end",
"if",
"!",
"object",
"raise",
"\"Database #{name} does not have an object named '#{object_name}'.\"",
"end",
"klass",
"=",
"PSQL",
".",
"const_get",
"object",
"[",
"'type'",
"]",
".",
"capitalize",
"klass",
".",
"new",
"object",
"[",
"'name'",
"]",
",",
"name",
"end"
] |
Finds a database object by name. Objects are tables, views, or
sequences.
|
[
"Finds",
"a",
"database",
"object",
"by",
"name",
".",
"Objects",
"are",
"tables",
"views",
"or",
"sequences",
"."
] |
feb0a6cc5ca8b18c60412bc6b2a1ff4239fc42b9
|
https://github.com/jeremyruppel/psql/blob/feb0a6cc5ca8b18c60412bc6b2a1ff4239fc42b9/lib/psql/database.rb#L19-L30
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.