id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
|
---|---|---|---|---|---|---|---|---|---|---|---|
5,400 | cantino/guess_html_encoding | lib/guess_html_encoding.rb | GuessHtmlEncoding.HTMLScanner.charset_from_meta_content | def charset_from_meta_content(string)
charset_match = string.match(/charset\s*\=\s*(.+)/i)
if charset_match
charset_value = charset_match[1]
charset_value[/\A\"(.*)\"/, 1] ||
charset_value[/\A\'(.*)\'/, 1] ||
charset_value[/(.*)[\s;]/, 1] ||
charset_value[/(.*)/, 1]
else
nil
end
end | ruby | def charset_from_meta_content(string)
charset_match = string.match(/charset\s*\=\s*(.+)/i)
if charset_match
charset_value = charset_match[1]
charset_value[/\A\"(.*)\"/, 1] ||
charset_value[/\A\'(.*)\'/, 1] ||
charset_value[/(.*)[\s;]/, 1] ||
charset_value[/(.*)/, 1]
else
nil
end
end | [
"def",
"charset_from_meta_content",
"(",
"string",
")",
"charset_match",
"=",
"string",
".",
"match",
"(",
"/",
"\\s",
"\\=",
"\\s",
"/i",
")",
"if",
"charset_match",
"charset_value",
"=",
"charset_match",
"[",
"1",
"]",
"charset_value",
"[",
"/",
"\\A",
"\\\"",
"\\\"",
"/",
",",
"1",
"]",
"||",
"charset_value",
"[",
"/",
"\\A",
"\\'",
"\\'",
"/",
",",
"1",
"]",
"||",
"charset_value",
"[",
"/",
"\\s",
"/",
",",
"1",
"]",
"||",
"charset_value",
"[",
"/",
"/",
",",
"1",
"]",
"else",
"nil",
"end",
"end"
] | Given a string representing the 'content' attribute value of a meta tag
with an `http-equiv` attribute, returns the charset specified within that
value, or nil. | [
"Given",
"a",
"string",
"representing",
"the",
"content",
"attribute",
"value",
"of",
"a",
"meta",
"tag",
"with",
"an",
"http",
"-",
"equiv",
"attribute",
"returns",
"the",
"charset",
"specified",
"within",
"that",
"value",
"or",
"nil",
"."
] | a908233b20b7f3c602cb5b2a7fb57fd3b905f264 | https://github.com/cantino/guess_html_encoding/blob/a908233b20b7f3c602cb5b2a7fb57fd3b905f264/lib/guess_html_encoding.rb#L180-L196 |
5,401 | cantino/guess_html_encoding | lib/guess_html_encoding.rb | GuessHtmlEncoding.HTMLScanner.attribute_value | def attribute_value(string)
attribute_value = ''
position = 0
length = string.length
while position < length
# x09 (ASCII TAB), 0x0A (ASCII LF), 0x0C (ASCII FF), 0x0D (ASCII CR), or 0x20 (ASCII space) then advance position to the next byte, then, repeat this step.
if string[position] =~ /[\u{09}\u{0A}\u{0C}\u{0D}\u{20}]/
position += 1
elsif string[position] =~ /['"]/
attribute_value, position = quoted_value(string[position, length])
break
elsif string[position] == '>'
position += 1
break
else
attribute_value, position = unquoted_value(string[position, length])
break
end
end
[attribute_value, position]
end | ruby | def attribute_value(string)
attribute_value = ''
position = 0
length = string.length
while position < length
# x09 (ASCII TAB), 0x0A (ASCII LF), 0x0C (ASCII FF), 0x0D (ASCII CR), or 0x20 (ASCII space) then advance position to the next byte, then, repeat this step.
if string[position] =~ /[\u{09}\u{0A}\u{0C}\u{0D}\u{20}]/
position += 1
elsif string[position] =~ /['"]/
attribute_value, position = quoted_value(string[position, length])
break
elsif string[position] == '>'
position += 1
break
else
attribute_value, position = unquoted_value(string[position, length])
break
end
end
[attribute_value, position]
end | [
"def",
"attribute_value",
"(",
"string",
")",
"attribute_value",
"=",
"''",
"position",
"=",
"0",
"length",
"=",
"string",
".",
"length",
"while",
"position",
"<",
"length",
"# x09 (ASCII TAB), 0x0A (ASCII LF), 0x0C (ASCII FF), 0x0D (ASCII CR), or 0x20 (ASCII space) then advance position to the next byte, then, repeat this step.",
"if",
"string",
"[",
"position",
"]",
"=~",
"/",
"\\u{09}",
"\\u{0A}",
"\\u{0C}",
"\\u{0D}",
"\\u{20}",
"/",
"position",
"+=",
"1",
"elsif",
"string",
"[",
"position",
"]",
"=~",
"/",
"/",
"attribute_value",
",",
"position",
"=",
"quoted_value",
"(",
"string",
"[",
"position",
",",
"length",
"]",
")",
"break",
"elsif",
"string",
"[",
"position",
"]",
"==",
"'>'",
"position",
"+=",
"1",
"break",
"else",
"attribute_value",
",",
"position",
"=",
"unquoted_value",
"(",
"string",
"[",
"position",
",",
"length",
"]",
")",
"break",
"end",
"end",
"[",
"attribute_value",
",",
"position",
"]",
"end"
] | Given a string, this returns the attribute value from the start of the string,
and the position of the following character in the string | [
"Given",
"a",
"string",
"this",
"returns",
"the",
"attribute",
"value",
"from",
"the",
"start",
"of",
"the",
"string",
"and",
"the",
"position",
"of",
"the",
"following",
"character",
"in",
"the",
"string"
] | a908233b20b7f3c602cb5b2a7fb57fd3b905f264 | https://github.com/cantino/guess_html_encoding/blob/a908233b20b7f3c602cb5b2a7fb57fd3b905f264/lib/guess_html_encoding.rb#L266-L295 |
5,402 | stuart/oqgraph_rails | lib/oqgraph/node.rb | OQGraph.Node.create_edge_to_and_from | def create_edge_to_and_from(other, weight = 1.0)
self.class.edge_class.create!(:from_id => id, :to_id => other.id, :weight => weight)
self.class.edge_class.create!(:from_id => other.id, :to_id => id, :weight => weight)
end | ruby | def create_edge_to_and_from(other, weight = 1.0)
self.class.edge_class.create!(:from_id => id, :to_id => other.id, :weight => weight)
self.class.edge_class.create!(:from_id => other.id, :to_id => id, :weight => weight)
end | [
"def",
"create_edge_to_and_from",
"(",
"other",
",",
"weight",
"=",
"1.0",
")",
"self",
".",
"class",
".",
"edge_class",
".",
"create!",
"(",
":from_id",
"=>",
"id",
",",
":to_id",
"=>",
"other",
".",
"id",
",",
":weight",
"=>",
"weight",
")",
"self",
".",
"class",
".",
"edge_class",
".",
"create!",
"(",
":from_id",
"=>",
"other",
".",
"id",
",",
":to_id",
"=>",
"id",
",",
":weight",
"=>",
"weight",
")",
"end"
] | +other+ graph node to edge to
+weight+ positive float denoting edge weight
Creates a two way edge between this node and another. | [
"+",
"other",
"+",
"graph",
"node",
"to",
"edge",
"to",
"+",
"weight",
"+",
"positive",
"float",
"denoting",
"edge",
"weight",
"Creates",
"a",
"two",
"way",
"edge",
"between",
"this",
"node",
"and",
"another",
"."
] | 836ccbe770d357f30d71ec30b1dfd5f267624883 | https://github.com/stuart/oqgraph_rails/blob/836ccbe770d357f30d71ec30b1dfd5f267624883/lib/oqgraph/node.rb#L56-L59 |
5,403 | stuart/oqgraph_rails | lib/oqgraph/node.rb | OQGraph.Node.path_weight_to | def path_weight_to(other)
shortest_path_to(other,:method => :djikstra).map{|edge| edge.weight.to_f}.sum
end | ruby | def path_weight_to(other)
shortest_path_to(other,:method => :djikstra).map{|edge| edge.weight.to_f}.sum
end | [
"def",
"path_weight_to",
"(",
"other",
")",
"shortest_path_to",
"(",
"other",
",",
":method",
"=>",
":djikstra",
")",
".",
"map",
"{",
"|",
"edge",
"|",
"edge",
".",
"weight",
".",
"to_f",
"}",
".",
"sum",
"end"
] | +other+ The target node to find a route to
Gives the path weight as a float of the shortest path to the other | [
"+",
"other",
"+",
"The",
"target",
"node",
"to",
"find",
"a",
"route",
"to",
"Gives",
"the",
"path",
"weight",
"as",
"a",
"float",
"of",
"the",
"shortest",
"path",
"to",
"the",
"other"
] | 836ccbe770d357f30d71ec30b1dfd5f267624883 | https://github.com/stuart/oqgraph_rails/blob/836ccbe770d357f30d71ec30b1dfd5f267624883/lib/oqgraph/node.rb#L74-L76 |
5,404 | shanebdavis/gui_geometry | lib/gui_geometry/rectangle.rb | GuiGeo.Rectangle.bound | def bound(val)
case val
when Rectangle then
r = val.clone
r.size = r.size.min(size)
r.loc = r.loc.bound(loc, loc + size - val.size)
r
when Point then (val-loc).bound(point, size) + loc
else raise ArgumentError.new("wrong type: (#{val.class}) - Rectangle or Point expected")
end
end | ruby | def bound(val)
case val
when Rectangle then
r = val.clone
r.size = r.size.min(size)
r.loc = r.loc.bound(loc, loc + size - val.size)
r
when Point then (val-loc).bound(point, size) + loc
else raise ArgumentError.new("wrong type: (#{val.class}) - Rectangle or Point expected")
end
end | [
"def",
"bound",
"(",
"val",
")",
"case",
"val",
"when",
"Rectangle",
"then",
"r",
"=",
"val",
".",
"clone",
"r",
".",
"size",
"=",
"r",
".",
"size",
".",
"min",
"(",
"size",
")",
"r",
".",
"loc",
"=",
"r",
".",
"loc",
".",
"bound",
"(",
"loc",
",",
"loc",
"+",
"size",
"-",
"val",
".",
"size",
")",
"r",
"when",
"Point",
"then",
"(",
"val",
"-",
"loc",
")",
".",
"bound",
"(",
"point",
",",
"size",
")",
"+",
"loc",
"else",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"wrong type: (#{val.class}) - Rectangle or Point expected\"",
")",
"end",
"end"
] | val can be a Rectangle or Point
returns a Rectangle or Point that is within this Rectangle
For Rectangles, the size is only changed if it has to be | [
"val",
"can",
"be",
"a",
"Rectangle",
"or",
"Point",
"returns",
"a",
"Rectangle",
"or",
"Point",
"that",
"is",
"within",
"this",
"Rectangle",
"For",
"Rectangles",
"the",
"size",
"is",
"only",
"changed",
"if",
"it",
"has",
"to",
"be"
] | ed0688f7484a31435063c0fa1895ddaf3900d959 | https://github.com/shanebdavis/gui_geometry/blob/ed0688f7484a31435063c0fa1895ddaf3900d959/lib/gui_geometry/rectangle.rb#L33-L43 |
5,405 | shanebdavis/gui_geometry | lib/gui_geometry/rectangle.rb | GuiGeo.Rectangle.disjoint | def disjoint(b)
return self if !b || contains(b)
return b if b.contains(self)
return self,b unless overlaps?(b)
tl_contained = contains?(b.tl) ? 1 : 0
tr_contained = contains?(b.tr) ? 1 : 0
bl_contained = contains?(b.bl) ? 1 : 0
br_contained = contains?(b.br) ? 1 : 0
sum = tl_contained + tr_contained + bl_contained + br_contained
case sum
when 0 # rectangles form a plus "+"
if b.y < self.y
r1,r2 = b,self
else
r1,r2 = self,b
end
tl1 = r1.tl
br1 = point(r1.right, r2.top)
tl2 = point(r1.left, r2.bottom)
br2 = r1.br
[
r2,
rect(tl1,br1-tl1),
rect(tl2,br2-tl2),
]
when 1
when 2
else raise "internal error in disjoint - cases 3 and 4 should be taken care of by the return-tests at the top of the method"
end
end | ruby | def disjoint(b)
return self if !b || contains(b)
return b if b.contains(self)
return self,b unless overlaps?(b)
tl_contained = contains?(b.tl) ? 1 : 0
tr_contained = contains?(b.tr) ? 1 : 0
bl_contained = contains?(b.bl) ? 1 : 0
br_contained = contains?(b.br) ? 1 : 0
sum = tl_contained + tr_contained + bl_contained + br_contained
case sum
when 0 # rectangles form a plus "+"
if b.y < self.y
r1,r2 = b,self
else
r1,r2 = self,b
end
tl1 = r1.tl
br1 = point(r1.right, r2.top)
tl2 = point(r1.left, r2.bottom)
br2 = r1.br
[
r2,
rect(tl1,br1-tl1),
rect(tl2,br2-tl2),
]
when 1
when 2
else raise "internal error in disjoint - cases 3 and 4 should be taken care of by the return-tests at the top of the method"
end
end | [
"def",
"disjoint",
"(",
"b",
")",
"return",
"self",
"if",
"!",
"b",
"||",
"contains",
"(",
"b",
")",
"return",
"b",
"if",
"b",
".",
"contains",
"(",
"self",
")",
"return",
"self",
",",
"b",
"unless",
"overlaps?",
"(",
"b",
")",
"tl_contained",
"=",
"contains?",
"(",
"b",
".",
"tl",
")",
"?",
"1",
":",
"0",
"tr_contained",
"=",
"contains?",
"(",
"b",
".",
"tr",
")",
"?",
"1",
":",
"0",
"bl_contained",
"=",
"contains?",
"(",
"b",
".",
"bl",
")",
"?",
"1",
":",
"0",
"br_contained",
"=",
"contains?",
"(",
"b",
".",
"br",
")",
"?",
"1",
":",
"0",
"sum",
"=",
"tl_contained",
"+",
"tr_contained",
"+",
"bl_contained",
"+",
"br_contained",
"case",
"sum",
"when",
"0",
"# rectangles form a plus \"+\"",
"if",
"b",
".",
"y",
"<",
"self",
".",
"y",
"r1",
",",
"r2",
"=",
"b",
",",
"self",
"else",
"r1",
",",
"r2",
"=",
"self",
",",
"b",
"end",
"tl1",
"=",
"r1",
".",
"tl",
"br1",
"=",
"point",
"(",
"r1",
".",
"right",
",",
"r2",
".",
"top",
")",
"tl2",
"=",
"point",
"(",
"r1",
".",
"left",
",",
"r2",
".",
"bottom",
")",
"br2",
"=",
"r1",
".",
"br",
"[",
"r2",
",",
"rect",
"(",
"tl1",
",",
"br1",
"-",
"tl1",
")",
",",
"rect",
"(",
"tl2",
",",
"br2",
"-",
"tl2",
")",
",",
"]",
"when",
"1",
"when",
"2",
"else",
"raise",
"\"internal error in disjoint - cases 3 and 4 should be taken care of by the return-tests at the top of the method\"",
"end",
"end"
] | return 1-3 rectangles which, together, cover exactly the same area as self and b, but do not overlapp | [
"return",
"1",
"-",
"3",
"rectangles",
"which",
"together",
"cover",
"exactly",
"the",
"same",
"area",
"as",
"self",
"and",
"b",
"but",
"do",
"not",
"overlapp"
] | ed0688f7484a31435063c0fa1895ddaf3900d959 | https://github.com/shanebdavis/gui_geometry/blob/ed0688f7484a31435063c0fa1895ddaf3900d959/lib/gui_geometry/rectangle.rb#L117-L150 |
5,406 | trumant/pogoplug | lib/pogoplug/client.rb | PogoPlug.Client.version | def version
response = get('/getVersion', {}, false)
ApiVersion.new(response.body['version'], response.body['builddate'])
end | ruby | def version
response = get('/getVersion', {}, false)
ApiVersion.new(response.body['version'], response.body['builddate'])
end | [
"def",
"version",
"response",
"=",
"get",
"(",
"'/getVersion'",
",",
"{",
"}",
",",
"false",
")",
"ApiVersion",
".",
"new",
"(",
"response",
".",
"body",
"[",
"'version'",
"]",
",",
"response",
".",
"body",
"[",
"'builddate'",
"]",
")",
"end"
] | Retrieve the current version information of the service | [
"Retrieve",
"the",
"current",
"version",
"information",
"of",
"the",
"service"
] | 4b071385945c713fe0f202b366d2a948215329e4 | https://github.com/trumant/pogoplug/blob/4b071385945c713fe0f202b366d2a948215329e4/lib/pogoplug/client.rb#L19-L22 |
5,407 | trumant/pogoplug | lib/pogoplug/client.rb | PogoPlug.Client.devices | def devices
response = get('/listDevices')
devices = []
response.body['devices'].each do |d|
devices << Device.from_json(d, @token, @logger)
end
devices
end | ruby | def devices
response = get('/listDevices')
devices = []
response.body['devices'].each do |d|
devices << Device.from_json(d, @token, @logger)
end
devices
end | [
"def",
"devices",
"response",
"=",
"get",
"(",
"'/listDevices'",
")",
"devices",
"=",
"[",
"]",
"response",
".",
"body",
"[",
"'devices'",
"]",
".",
"each",
"do",
"|",
"d",
"|",
"devices",
"<<",
"Device",
".",
"from_json",
"(",
"d",
",",
"@token",
",",
"@logger",
")",
"end",
"devices",
"end"
] | Retrieve a list of devices that are registered with the PogoPlug account | [
"Retrieve",
"a",
"list",
"of",
"devices",
"that",
"are",
"registered",
"with",
"the",
"PogoPlug",
"account"
] | 4b071385945c713fe0f202b366d2a948215329e4 | https://github.com/trumant/pogoplug/blob/4b071385945c713fe0f202b366d2a948215329e4/lib/pogoplug/client.rb#L33-L40 |
5,408 | trumant/pogoplug | lib/pogoplug/client.rb | PogoPlug.Client.services | def services(device_id=nil, shared=false)
params = { shared: shared }
params[:deviceid] = device_id unless device_id.nil?
response = get('/listServices', params)
services = []
response.body['services'].each do |s|
services << Service.from_json(s, @token, @logger)
end
services
end | ruby | def services(device_id=nil, shared=false)
params = { shared: shared }
params[:deviceid] = device_id unless device_id.nil?
response = get('/listServices', params)
services = []
response.body['services'].each do |s|
services << Service.from_json(s, @token, @logger)
end
services
end | [
"def",
"services",
"(",
"device_id",
"=",
"nil",
",",
"shared",
"=",
"false",
")",
"params",
"=",
"{",
"shared",
":",
"shared",
"}",
"params",
"[",
":deviceid",
"]",
"=",
"device_id",
"unless",
"device_id",
".",
"nil?",
"response",
"=",
"get",
"(",
"'/listServices'",
",",
"params",
")",
"services",
"=",
"[",
"]",
"response",
".",
"body",
"[",
"'services'",
"]",
".",
"each",
"do",
"|",
"s",
"|",
"services",
"<<",
"Service",
".",
"from_json",
"(",
"s",
",",
"@token",
",",
"@logger",
")",
"end",
"services",
"end"
] | Retrieve a list of services | [
"Retrieve",
"a",
"list",
"of",
"services"
] | 4b071385945c713fe0f202b366d2a948215329e4 | https://github.com/trumant/pogoplug/blob/4b071385945c713fe0f202b366d2a948215329e4/lib/pogoplug/client.rb#L49-L59 |
5,409 | aprescott/serif | lib/serif/filters.rb | Serif.FileDigest.render | def render(context)
return "" unless ENV["ENV"] == "production"
full_path = File.join(context["site"]["__directory"], @path.strip)
return @prefix + DIGEST_CACHE[full_path] if DIGEST_CACHE[full_path]
digest = Digest::MD5.hexdigest(File.read(full_path))
DIGEST_CACHE[full_path] = digest
@prefix + digest
end | ruby | def render(context)
return "" unless ENV["ENV"] == "production"
full_path = File.join(context["site"]["__directory"], @path.strip)
return @prefix + DIGEST_CACHE[full_path] if DIGEST_CACHE[full_path]
digest = Digest::MD5.hexdigest(File.read(full_path))
DIGEST_CACHE[full_path] = digest
@prefix + digest
end | [
"def",
"render",
"(",
"context",
")",
"return",
"\"\"",
"unless",
"ENV",
"[",
"\"ENV\"",
"]",
"==",
"\"production\"",
"full_path",
"=",
"File",
".",
"join",
"(",
"context",
"[",
"\"site\"",
"]",
"[",
"\"__directory\"",
"]",
",",
"@path",
".",
"strip",
")",
"return",
"@prefix",
"+",
"DIGEST_CACHE",
"[",
"full_path",
"]",
"if",
"DIGEST_CACHE",
"[",
"full_path",
"]",
"digest",
"=",
"Digest",
"::",
"MD5",
".",
"hexdigest",
"(",
"File",
".",
"read",
"(",
"full_path",
")",
")",
"DIGEST_CACHE",
"[",
"full_path",
"]",
"=",
"digest",
"@prefix",
"+",
"digest",
"end"
] | Takes the given path and returns the MD5
hex digest of the file's contents.
The path argument is first stripped, and any leading
"/" has no effect. | [
"Takes",
"the",
"given",
"path",
"and",
"returns",
"the",
"MD5",
"hex",
"digest",
"of",
"the",
"file",
"s",
"contents",
"."
] | 4798021fe7419b3fc5f458619dd64149e8c5967e | https://github.com/aprescott/serif/blob/4798021fe7419b3fc5f458619dd64149e8c5967e/lib/serif/filters.rb#L59-L70 |
5,410 | snusnu/substation | lib/substation/dispatcher.rb | Substation.Dispatcher.call | def call(name, input)
fetch(name).call(Request.new(name, env, input))
end | ruby | def call(name, input)
fetch(name).call(Request.new(name, env, input))
end | [
"def",
"call",
"(",
"name",
",",
"input",
")",
"fetch",
"(",
"name",
")",
".",
"call",
"(",
"Request",
".",
"new",
"(",
"name",
",",
"env",
",",
"input",
")",
")",
"end"
] | Invoke the action identified by +name+
@example
module App
class Environment
def initialize(storage, logger)
@storage, @logger = storage, logger
end
end
class SomeUseCase
def self.call(request)
data = perform_work
request.success(data)
end
end
end
storage = SomeStorageAbstraction.new
env = App::Environment.new(storage, Logger.new($stdout))
config = { :some_use_case => { :action => App::SomeUseCase } }
dispatcher = Substation::Dispatcher.coerce(config, env)
response = dispatcher.call(:some_use_case, :some_input)
response.success? # => true
@param [Symbol] name
a registered action name
@param [Object] input
the input model instance to pass to the action
@return [Response]
the response returned when calling the action
@raise [UnknownActionError]
if no action is registered for +name+
@api public | [
"Invoke",
"the",
"action",
"identified",
"by",
"+",
"name",
"+"
] | fabf062a3640f5e82dae68597f0709b63f6b9027 | https://github.com/snusnu/substation/blob/fabf062a3640f5e82dae68597f0709b63f6b9027/lib/substation/dispatcher.rb#L66-L68 |
5,411 | Birdie0/qna_maker | lib/qna_maker/endpoints/create_kb.rb | QnAMaker.Client.create_kb | def create_kb(name, qna_pairs = [], urls = [])
response = @http.post(
"#{BASE_URL}/create",
json: {
name: name,
qnaPairs: qna_pairs.map { |pair| { question: pair[0], answer: pair[1] } },
urls: urls
}
)
case response.code
when 201
QnAMaker::Client.new(
response.parse['kbId'],
@subscription_key,
response.parse['dataExtractionResults']
)
when 400
raise BadArgumentError, response.parse['error']['message'].join(' ')
when 401
raise UnauthorizedError, response.parse['error']['message']
else
raise UnknownError, "Oh no! (#{response.code})"
end
end | ruby | def create_kb(name, qna_pairs = [], urls = [])
response = @http.post(
"#{BASE_URL}/create",
json: {
name: name,
qnaPairs: qna_pairs.map { |pair| { question: pair[0], answer: pair[1] } },
urls: urls
}
)
case response.code
when 201
QnAMaker::Client.new(
response.parse['kbId'],
@subscription_key,
response.parse['dataExtractionResults']
)
when 400
raise BadArgumentError, response.parse['error']['message'].join(' ')
when 401
raise UnauthorizedError, response.parse['error']['message']
else
raise UnknownError, "Oh no! (#{response.code})"
end
end | [
"def",
"create_kb",
"(",
"name",
",",
"qna_pairs",
"=",
"[",
"]",
",",
"urls",
"=",
"[",
"]",
")",
"response",
"=",
"@http",
".",
"post",
"(",
"\"#{BASE_URL}/create\"",
",",
"json",
":",
"{",
"name",
":",
"name",
",",
"qnaPairs",
":",
"qna_pairs",
".",
"map",
"{",
"|",
"pair",
"|",
"{",
"question",
":",
"pair",
"[",
"0",
"]",
",",
"answer",
":",
"pair",
"[",
"1",
"]",
"}",
"}",
",",
"urls",
":",
"urls",
"}",
")",
"case",
"response",
".",
"code",
"when",
"201",
"QnAMaker",
"::",
"Client",
".",
"new",
"(",
"response",
".",
"parse",
"[",
"'kbId'",
"]",
",",
"@subscription_key",
",",
"response",
".",
"parse",
"[",
"'dataExtractionResults'",
"]",
")",
"when",
"400",
"raise",
"BadArgumentError",
",",
"response",
".",
"parse",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
".",
"join",
"(",
"' '",
")",
"when",
"401",
"raise",
"UnauthorizedError",
",",
"response",
".",
"parse",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"else",
"raise",
"UnknownError",
",",
"\"Oh no! (#{response.code})\"",
"end",
"end"
] | Creates a new knowledge base.
@param [String] name friendly name for the knowledge base (Required)
@param [Array<Array(String, String)>] qna_pairs list of question and answer pairs to be added to the knowledge base.
Max 1000 Q-A pairs per request.
@param [Array<String>] urls list of URLs to be processed and indexed in the knowledge base.
In case of existing URL, it will be fetched again and KB will be updated with new data. Max 5 urls per request.
@return [Client] client object | [
"Creates",
"a",
"new",
"knowledge",
"base",
"."
] | 5ac204ede100355352438b8ff4fe30ad84d9257b | https://github.com/Birdie0/qna_maker/blob/5ac204ede100355352438b8ff4fe30ad84d9257b/lib/qna_maker/endpoints/create_kb.rb#L14-L38 |
5,412 | leshill/mongodoc | lib/mongo_doc/index.rb | MongoDoc.Index.index | def index(*args)
options_and_fields = args.extract_options!
if args.any?
collection.create_index(args.first, options_and_fields)
else
fields = options_and_fields.except(*OPTIONS)
options = options_and_fields.slice(*OPTIONS)
collection.create_index(to_mongo_direction(fields), options)
end
end | ruby | def index(*args)
options_and_fields = args.extract_options!
if args.any?
collection.create_index(args.first, options_and_fields)
else
fields = options_and_fields.except(*OPTIONS)
options = options_and_fields.slice(*OPTIONS)
collection.create_index(to_mongo_direction(fields), options)
end
end | [
"def",
"index",
"(",
"*",
"args",
")",
"options_and_fields",
"=",
"args",
".",
"extract_options!",
"if",
"args",
".",
"any?",
"collection",
".",
"create_index",
"(",
"args",
".",
"first",
",",
"options_and_fields",
")",
"else",
"fields",
"=",
"options_and_fields",
".",
"except",
"(",
"OPTIONS",
")",
"options",
"=",
"options_and_fields",
".",
"slice",
"(",
"OPTIONS",
")",
"collection",
".",
"create_index",
"(",
"to_mongo_direction",
"(",
"fields",
")",
",",
"options",
")",
"end",
"end"
] | Create an index on a collection.
For compound indexes, pass pairs of fields and
directions (+:asc+, +:desc+) as a hash.
For a unique index, pass the option +:unique => true+.
To create the index in the background, pass the options +:background => true+.
If you want to remove duplicates from existing records when creating the
unique index, pass the option +:dropDups => true+
For GeoIndexing, specify the minimum and maximum longitude and latitude
values with the +:min+ and +:max+ options.
<tt>Person.index(:last_name)</tt>
<tt>Person.index(:ssn, :unique => true)</tt>
<tt>Person.index(:first_name => :asc, :last_name => :asc)</tt>
<tt>Person.index(:first_name => :asc, :last_name => :asc, :unique => true)</tt> | [
"Create",
"an",
"index",
"on",
"a",
"collection",
"."
] | fb2a4ec456d4c4ae1eb92e117dc73f55951fc3b4 | https://github.com/leshill/mongodoc/blob/fb2a4ec456d4c4ae1eb92e117dc73f55951fc3b4/lib/mongo_doc/index.rb#L26-L35 |
5,413 | koraktor/rubikon | lib/rubikon/progress_bar.rb | Rubikon.ProgressBar.+ | def +(value = 1)
return if (value <= 0) || (@value == @maximum)
@value += value
old_progress = @progress
add_progress = ((@value - @progress / @factor) * @factor).round
@progress += add_progress
if @progress > @size
@progress = @size
add_progress = @size - old_progress
end
if add_progress > 0
@ostream << @progress_char * add_progress
@ostream.flush
@ostream.putc 10 if @progress == @size
end
self
end | ruby | def +(value = 1)
return if (value <= 0) || (@value == @maximum)
@value += value
old_progress = @progress
add_progress = ((@value - @progress / @factor) * @factor).round
@progress += add_progress
if @progress > @size
@progress = @size
add_progress = @size - old_progress
end
if add_progress > 0
@ostream << @progress_char * add_progress
@ostream.flush
@ostream.putc 10 if @progress == @size
end
self
end | [
"def",
"+",
"(",
"value",
"=",
"1",
")",
"return",
"if",
"(",
"value",
"<=",
"0",
")",
"||",
"(",
"@value",
"==",
"@maximum",
")",
"@value",
"+=",
"value",
"old_progress",
"=",
"@progress",
"add_progress",
"=",
"(",
"(",
"@value",
"-",
"@progress",
"/",
"@factor",
")",
"*",
"@factor",
")",
".",
"round",
"@progress",
"+=",
"add_progress",
"if",
"@progress",
">",
"@size",
"@progress",
"=",
"@size",
"add_progress",
"=",
"@size",
"-",
"old_progress",
"end",
"if",
"add_progress",
">",
"0",
"@ostream",
"<<",
"@progress_char",
"*",
"add_progress",
"@ostream",
".",
"flush",
"@ostream",
".",
"putc",
"10",
"if",
"@progress",
"==",
"@size",
"end",
"self",
"end"
] | Create a new ProgressBar using the given options.
@param [Hash, Numeric] options A Hash of options to customize the
progress bar or the maximum value of the progress bar
@see Application::InstanceMethods#progress_bar
@option options [String] :char ('#') The character used for progress bar
display
@option options [Numeric] :maximum (100) The maximum value of this
progress bar
@option options [IO] :ostream ($stdout) The output stream where the
progress bar should be displayed
@option options [Numeric] :size (20) The actual size of the progress bar
@option options [Numeric] :start (0) The start value of the progress bar
Add an amount to the current value of the progress bar
This triggers a refresh of the progress bar, if the added value actually
changes the displayed bar.
@param [Numeric] value The amount to add to the progress bar
@return [ProgressBar] The progress bar itself
@example Different alternatives to increase the progress
progress_bar + 1 # (will add 1)
progress_bar + 5 # (will add 5)
progress_bar.+ # (will add 1) | [
"Create",
"a",
"new",
"ProgressBar",
"using",
"the",
"given",
"options",
"."
] | c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b | https://github.com/koraktor/rubikon/blob/c5a09d2a6a0878bb4ae5bcf71fcb111646ed0b2b/lib/rubikon/progress_bar.rb#L67-L86 |
5,414 | stevenosloan/borrower | lib/borrower/public_api.rb | Borrower.PublicAPI.put | def put content, destination, on_conflict=:overwrite
if on_conflict != :overwrite && Content::Item.new( destination ).exists?
case on_conflict
when :skip then return
when :prompt then
input = Util.get_input "a file already exists at #{destination}\noverwrite? (y|n): "
return unless input.downcase == "y"
when :raise_error then
raise "File already exists at #{destination}"
end
end
Content.put content, destination
end | ruby | def put content, destination, on_conflict=:overwrite
if on_conflict != :overwrite && Content::Item.new( destination ).exists?
case on_conflict
when :skip then return
when :prompt then
input = Util.get_input "a file already exists at #{destination}\noverwrite? (y|n): "
return unless input.downcase == "y"
when :raise_error then
raise "File already exists at #{destination}"
end
end
Content.put content, destination
end | [
"def",
"put",
"content",
",",
"destination",
",",
"on_conflict",
"=",
":overwrite",
"if",
"on_conflict",
"!=",
":overwrite",
"&&",
"Content",
"::",
"Item",
".",
"new",
"(",
"destination",
")",
".",
"exists?",
"case",
"on_conflict",
"when",
":skip",
"then",
"return",
"when",
":prompt",
"then",
"input",
"=",
"Util",
".",
"get_input",
"\"a file already exists at #{destination}\\noverwrite? (y|n): \"",
"return",
"unless",
"input",
".",
"downcase",
"==",
"\"y\"",
"when",
":raise_error",
"then",
"raise",
"\"File already exists at #{destination}\"",
"end",
"end",
"Content",
".",
"put",
"content",
",",
"destination",
"end"
] | write the content to a destination file
@param [String] content content for the file
@param [String] destination path to write contents to
@param [Symbol] on_conflict what to do if the destination exists
@return [Void] | [
"write",
"the",
"content",
"to",
"a",
"destination",
"file"
] | cbb71876fe62ee48724cf60307b5b7b5c1e00944 | https://github.com/stevenosloan/borrower/blob/cbb71876fe62ee48724cf60307b5b7b5c1e00944/lib/borrower/public_api.rb#L20-L34 |
5,415 | scepticulous/crypto-toolbox | lib/crypto-toolbox/ciphers/caesar.rb | Ciphers.Caesar.encipher | def encipher(message,shift)
assert_valid_shift!(shift)
real_shift = convert_shift(shift)
message.split("").map do|char|
mod = (char =~ /[a-z]/) ? 123 : 91
offset = (char =~ /[a-z]/) ? 97 : 65
(char =~ /[^a-zA-Z]/) ? char : CryptBuffer(char).add(real_shift, mod: mod, offset: offset).str
end.join
end | ruby | def encipher(message,shift)
assert_valid_shift!(shift)
real_shift = convert_shift(shift)
message.split("").map do|char|
mod = (char =~ /[a-z]/) ? 123 : 91
offset = (char =~ /[a-z]/) ? 97 : 65
(char =~ /[^a-zA-Z]/) ? char : CryptBuffer(char).add(real_shift, mod: mod, offset: offset).str
end.join
end | [
"def",
"encipher",
"(",
"message",
",",
"shift",
")",
"assert_valid_shift!",
"(",
"shift",
")",
"real_shift",
"=",
"convert_shift",
"(",
"shift",
")",
"message",
".",
"split",
"(",
"\"\"",
")",
".",
"map",
"do",
"|",
"char",
"|",
"mod",
"=",
"(",
"char",
"=~",
"/",
"/",
")",
"?",
"123",
":",
"91",
"offset",
"=",
"(",
"char",
"=~",
"/",
"/",
")",
"?",
"97",
":",
"65",
"(",
"char",
"=~",
"/",
"/",
")",
"?",
"char",
":",
"CryptBuffer",
"(",
"char",
")",
".",
"add",
"(",
"real_shift",
",",
"mod",
":",
"mod",
",",
"offset",
":",
"offset",
")",
".",
"str",
"end",
".",
"join",
"end"
] | =begin
Within encipher and decipher we use a regexp comparision.
Array lookups are must slower and byte comparision is a little faster,
but much more complicated
Alphabet letter lookup algorithm comparision:
Comparison: (see benchmarks/string_comparision.rb)
string.bytes.first == A : 3289762.7 i/s
string =~ [A-Za-Z] : 2010285.8 i/s - 1.64x slower
Letter Array include?(A): 76997.0 i/s - 42.73x slower
=end | [
"=",
"begin",
"Within",
"encipher",
"and",
"decipher",
"we",
"use",
"a",
"regexp",
"comparision",
".",
"Array",
"lookups",
"are",
"must",
"slower",
"and",
"byte",
"comparision",
"is",
"a",
"little",
"faster",
"but",
"much",
"more",
"complicated"
] | cdbe371109e497db2c2af5c1fe0f359612f44816 | https://github.com/scepticulous/crypto-toolbox/blob/cdbe371109e497db2c2af5c1fe0f359612f44816/lib/crypto-toolbox/ciphers/caesar.rb#L27-L37 |
5,416 | trumant/pogoplug | lib/pogoplug/service_client.rb | PogoPlug.ServiceClient.create_entity | def create_entity(file, io = nil, properties = {})
params = { deviceid: @device_id, serviceid: @service_id, filename: file.name, type: file.type }.merge(properties)
params[:parentid] = file.parent_id unless file.parent_id.nil?
if params[:properties]
params[:properties] = params[:properties].to_json
end
file_handle = unless file.id
response = get('/createFile', params)
File.from_json(response.body['file'])
else
file
end
if io
HttpHelper.send_file(files_url, @token, @device_id, @service_id, file_handle, io, @logger)
file_handle.size = io.size
end
file_handle
end | ruby | def create_entity(file, io = nil, properties = {})
params = { deviceid: @device_id, serviceid: @service_id, filename: file.name, type: file.type }.merge(properties)
params[:parentid] = file.parent_id unless file.parent_id.nil?
if params[:properties]
params[:properties] = params[:properties].to_json
end
file_handle = unless file.id
response = get('/createFile', params)
File.from_json(response.body['file'])
else
file
end
if io
HttpHelper.send_file(files_url, @token, @device_id, @service_id, file_handle, io, @logger)
file_handle.size = io.size
end
file_handle
end | [
"def",
"create_entity",
"(",
"file",
",",
"io",
"=",
"nil",
",",
"properties",
"=",
"{",
"}",
")",
"params",
"=",
"{",
"deviceid",
":",
"@device_id",
",",
"serviceid",
":",
"@service_id",
",",
"filename",
":",
"file",
".",
"name",
",",
"type",
":",
"file",
".",
"type",
"}",
".",
"merge",
"(",
"properties",
")",
"params",
"[",
":parentid",
"]",
"=",
"file",
".",
"parent_id",
"unless",
"file",
".",
"parent_id",
".",
"nil?",
"if",
"params",
"[",
":properties",
"]",
"params",
"[",
":properties",
"]",
"=",
"params",
"[",
":properties",
"]",
".",
"to_json",
"end",
"file_handle",
"=",
"unless",
"file",
".",
"id",
"response",
"=",
"get",
"(",
"'/createFile'",
",",
"params",
")",
"File",
".",
"from_json",
"(",
"response",
".",
"body",
"[",
"'file'",
"]",
")",
"else",
"file",
"end",
"if",
"io",
"HttpHelper",
".",
"send_file",
"(",
"files_url",
",",
"@token",
",",
"@device_id",
",",
"@service_id",
",",
"file_handle",
",",
"io",
",",
"@logger",
")",
"file_handle",
".",
"size",
"=",
"io",
".",
"size",
"end",
"file_handle",
"end"
] | Creates a file handle and optionally attach an io.
The provided file argument is expected to contain at minimum
a name, type and parent_id. If it has a mimetype that will be assumed to
match the mimetype of the io. | [
"Creates",
"a",
"file",
"handle",
"and",
"optionally",
"attach",
"an",
"io",
".",
"The",
"provided",
"file",
"argument",
"is",
"expected",
"to",
"contain",
"at",
"minimum",
"a",
"name",
"type",
"and",
"parent_id",
".",
"If",
"it",
"has",
"a",
"mimetype",
"that",
"will",
"be",
"assumed",
"to",
"match",
"the",
"mimetype",
"of",
"the",
"io",
"."
] | 4b071385945c713fe0f202b366d2a948215329e4 | https://github.com/trumant/pogoplug/blob/4b071385945c713fe0f202b366d2a948215329e4/lib/pogoplug/service_client.rb#L25-L46 |
5,417 | blahah/assemblotron | lib/assemblotron/assemblermanager.rb | Assemblotron.AssemblerManager.load_assemblers | def load_assemblers
Biopsy::Settings.instance.target_dir.each do |dir|
Dir.chdir dir do
Dir['*.yml'].each do |file|
name = File.basename(file, '.yml')
target = Assembler.new
target.load_by_name name
unless System.match? target.bindeps[:url]
logger.info "Assembler #{target.name} is not available" +
" for this operating system"
next
end
bin_paths = target.bindeps[:binaries].map do |bin|
Which.which bin
end
missing_bin = bin_paths.any? { |path| path.empty? }
if missing_bin
logger.debug "Assembler #{target.name} was not installed"
missing = bin_paths
.select{ |path| path.empty? }
.map.with_index{ |path, i| target.bindeps[:binaries][i] }
logger.debug "(missing binaries: #{missing.join(', ')})"
@assemblers_uninst << target
else
@assemblers << target
end
end
end
end
end | ruby | def load_assemblers
Biopsy::Settings.instance.target_dir.each do |dir|
Dir.chdir dir do
Dir['*.yml'].each do |file|
name = File.basename(file, '.yml')
target = Assembler.new
target.load_by_name name
unless System.match? target.bindeps[:url]
logger.info "Assembler #{target.name} is not available" +
" for this operating system"
next
end
bin_paths = target.bindeps[:binaries].map do |bin|
Which.which bin
end
missing_bin = bin_paths.any? { |path| path.empty? }
if missing_bin
logger.debug "Assembler #{target.name} was not installed"
missing = bin_paths
.select{ |path| path.empty? }
.map.with_index{ |path, i| target.bindeps[:binaries][i] }
logger.debug "(missing binaries: #{missing.join(', ')})"
@assemblers_uninst << target
else
@assemblers << target
end
end
end
end
end | [
"def",
"load_assemblers",
"Biopsy",
"::",
"Settings",
".",
"instance",
".",
"target_dir",
".",
"each",
"do",
"|",
"dir",
"|",
"Dir",
".",
"chdir",
"dir",
"do",
"Dir",
"[",
"'*.yml'",
"]",
".",
"each",
"do",
"|",
"file",
"|",
"name",
"=",
"File",
".",
"basename",
"(",
"file",
",",
"'.yml'",
")",
"target",
"=",
"Assembler",
".",
"new",
"target",
".",
"load_by_name",
"name",
"unless",
"System",
".",
"match?",
"target",
".",
"bindeps",
"[",
":url",
"]",
"logger",
".",
"info",
"\"Assembler #{target.name} is not available\"",
"+",
"\" for this operating system\"",
"next",
"end",
"bin_paths",
"=",
"target",
".",
"bindeps",
"[",
":binaries",
"]",
".",
"map",
"do",
"|",
"bin",
"|",
"Which",
".",
"which",
"bin",
"end",
"missing_bin",
"=",
"bin_paths",
".",
"any?",
"{",
"|",
"path",
"|",
"path",
".",
"empty?",
"}",
"if",
"missing_bin",
"logger",
".",
"debug",
"\"Assembler #{target.name} was not installed\"",
"missing",
"=",
"bin_paths",
".",
"select",
"{",
"|",
"path",
"|",
"path",
".",
"empty?",
"}",
".",
"map",
".",
"with_index",
"{",
"|",
"path",
",",
"i",
"|",
"target",
".",
"bindeps",
"[",
":binaries",
"]",
"[",
"i",
"]",
"}",
"logger",
".",
"debug",
"\"(missing binaries: #{missing.join(', ')})\"",
"@assemblers_uninst",
"<<",
"target",
"else",
"@assemblers",
"<<",
"target",
"end",
"end",
"end",
"end",
"end"
] | Discover and load available assemblers. | [
"Discover",
"and",
"load",
"available",
"assemblers",
"."
] | 475d59c72ba36ebb2799076a0009758d12fa1508 | https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/assemblermanager.rb#L15-L44 |
5,418 | blahah/assemblotron | lib/assemblotron/assemblermanager.rb | Assemblotron.AssemblerManager.assembler_names | def assembler_names
a = []
@assemblers.each do |t|
a << t.name
a << t.shortname if t.shortname
end
a
end | ruby | def assembler_names
a = []
@assemblers.each do |t|
a << t.name
a << t.shortname if t.shortname
end
a
end | [
"def",
"assembler_names",
"a",
"=",
"[",
"]",
"@assemblers",
".",
"each",
"do",
"|",
"t",
"|",
"a",
"<<",
"t",
".",
"name",
"a",
"<<",
"t",
".",
"shortname",
"if",
"t",
".",
"shortname",
"end",
"a",
"end"
] | load_assemblers
Collect all valid names for available assemblers
@return [Array<String>] names and shortnames (if
applicable) for available assemblers. | [
"load_assemblers",
"Collect",
"all",
"valid",
"names",
"for",
"available",
"assemblers"
] | 475d59c72ba36ebb2799076a0009758d12fa1508 | https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/assemblermanager.rb#L50-L57 |
5,419 | blahah/assemblotron | lib/assemblotron/assemblermanager.rb | Assemblotron.AssemblerManager.list_assemblers | def list_assemblers
str = ""
if @assemblers.empty?
str << "\nNo assemblers are currently installed! Please install some.\n"
else
str << <<-EOS
Installed assemblers are listed below.
Shortnames are shown in brackets if available.
Assemblers installed:
EOS
@assemblers.each do |a|
p = " - #{a.name}"
p += " (#{a.shortname})" if a.respond_to? :shortname
str << p + "\n"
end
end
if @assemblers_uninst.empty?
str << "\nAll available assemblers are already installed!\n"
else
str << <<-EOS
Assemblers that are available to be installed are listed below.
To install one, use:
atron --install-assemblers <name OR shortname>
Assemblers installable:
EOS
@assemblers_uninst.each do |a|
p = " - #{a.name}"
p += " (#{a.shortname})" if a.respond_to? :shortname
str << p + "\n"
end
end
str + "\n"
end | ruby | def list_assemblers
str = ""
if @assemblers.empty?
str << "\nNo assemblers are currently installed! Please install some.\n"
else
str << <<-EOS
Installed assemblers are listed below.
Shortnames are shown in brackets if available.
Assemblers installed:
EOS
@assemblers.each do |a|
p = " - #{a.name}"
p += " (#{a.shortname})" if a.respond_to? :shortname
str << p + "\n"
end
end
if @assemblers_uninst.empty?
str << "\nAll available assemblers are already installed!\n"
else
str << <<-EOS
Assemblers that are available to be installed are listed below.
To install one, use:
atron --install-assemblers <name OR shortname>
Assemblers installable:
EOS
@assemblers_uninst.each do |a|
p = " - #{a.name}"
p += " (#{a.shortname})" if a.respond_to? :shortname
str << p + "\n"
end
end
str + "\n"
end | [
"def",
"list_assemblers",
"str",
"=",
"\"\"",
"if",
"@assemblers",
".",
"empty?",
"str",
"<<",
"\"\\nNo assemblers are currently installed! Please install some.\\n\"",
"else",
"str",
"<<",
"<<-EOS",
"EOS",
"@assemblers",
".",
"each",
"do",
"|",
"a",
"|",
"p",
"=",
"\" - #{a.name}\"",
"p",
"+=",
"\" (#{a.shortname})\"",
"if",
"a",
".",
"respond_to?",
":shortname",
"str",
"<<",
"p",
"+",
"\"\\n\"",
"end",
"end",
"if",
"@assemblers_uninst",
".",
"empty?",
"str",
"<<",
"\"\\nAll available assemblers are already installed!\\n\"",
"else",
"str",
"<<",
"<<-EOS",
"EOS",
"@assemblers_uninst",
".",
"each",
"do",
"|",
"a",
"|",
"p",
"=",
"\" - #{a.name}\"",
"p",
"+=",
"\" (#{a.shortname})\"",
"if",
"a",
".",
"respond_to?",
":shortname",
"str",
"<<",
"p",
"+",
"\"\\n\"",
"end",
"end",
"str",
"+",
"\"\\n\"",
"end"
] | assemblers
Return a help message listing installed assemblers. | [
"assemblers",
"Return",
"a",
"help",
"message",
"listing",
"installed",
"assemblers",
"."
] | 475d59c72ba36ebb2799076a0009758d12fa1508 | https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/assemblermanager.rb#L60-L103 |
5,420 | blahah/assemblotron | lib/assemblotron/assemblermanager.rb | Assemblotron.AssemblerManager.get_assembler | def get_assembler assembler
ret = @assemblers.find do |a|
a.name == assembler ||
a.shortname == assembler
end
raise "couldn't find assembler #{assembler}" if ret.nil?
ret
end | ruby | def get_assembler assembler
ret = @assemblers.find do |a|
a.name == assembler ||
a.shortname == assembler
end
raise "couldn't find assembler #{assembler}" if ret.nil?
ret
end | [
"def",
"get_assembler",
"assembler",
"ret",
"=",
"@assemblers",
".",
"find",
"do",
"|",
"a",
"|",
"a",
".",
"name",
"==",
"assembler",
"||",
"a",
".",
"shortname",
"==",
"assembler",
"end",
"raise",
"\"couldn't find assembler #{assembler}\"",
"if",
"ret",
".",
"nil?",
"ret",
"end"
] | Given the name of an assembler, get the loaded assembler
ready for optimisation.
@param assembler [String] assembler name or shortname
@return [Biopsy::Target] the loaded assembler | [
"Given",
"the",
"name",
"of",
"an",
"assembler",
"get",
"the",
"loaded",
"assembler",
"ready",
"for",
"optimisation",
"."
] | 475d59c72ba36ebb2799076a0009758d12fa1508 | https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/assemblermanager.rb#L157-L164 |
5,421 | blahah/assemblotron | lib/assemblotron/assemblermanager.rb | Assemblotron.AssemblerManager.run_all_assemblers | def run_all_assemblers options
res = {}
subset = false
unless options[:assemblers] == 'all'
subset = options[:assemblers].split(',')
missing = []
subset.each do |choice|
missing < choice unless @assemblers.any do |a|
a.name == choice || a.shortname == choice
end
end
unless missing.empty?
log.error "The specified assemblers (#{missing.join(', ')}) were not valid choices"
log.error "Please choose from the options in --list-assembler"
exit(1)
end
end
unless options[:skip_final]
if (File.exist? 'final_assemblies')
logger.warn("Directory final_assemblies already exists. Some results may be overwritten.")
end
FileUtils.mkdir_p('final_assemblies')
final_dir = File.expand_path 'final_assemblies'
end
results_filepath = Time.now.to_s.gsub(/ /, '_') + '.json'
@assemblers.each do |assembler|
logger.info "Starting optimisation for #{assembler.name}"
this_res = run_assembler assembler
logger.info "Optimisation of #{assembler.name} finished"
# run the final assembly
unless options[:skip_final]
this_final_dir = File.join(final_dir, assembler.name.downcase)
Dir.chdir this_final_dir do
logger.info "Running full assembly for #{assembler.name}" +
" with optimal parameters"
# use the full read set
this_res[:left] = options[:left]
this_res[:right] = options[:right]
this_res[:threads] = options[:threads]
final = final_assembly assembler, res
this_res[:final] = final
end
res[assembler.name] = this_res
end
File.open(results_filepath, 'w') do |out|
out.write JSON.pretty_generate(res)
end
logger.info "Result file updated: #{results_filepath}"
end
logger.info "All assemblers optimised"
res
end | ruby | def run_all_assemblers options
res = {}
subset = false
unless options[:assemblers] == 'all'
subset = options[:assemblers].split(',')
missing = []
subset.each do |choice|
missing < choice unless @assemblers.any do |a|
a.name == choice || a.shortname == choice
end
end
unless missing.empty?
log.error "The specified assemblers (#{missing.join(', ')}) were not valid choices"
log.error "Please choose from the options in --list-assembler"
exit(1)
end
end
unless options[:skip_final]
if (File.exist? 'final_assemblies')
logger.warn("Directory final_assemblies already exists. Some results may be overwritten.")
end
FileUtils.mkdir_p('final_assemblies')
final_dir = File.expand_path 'final_assemblies'
end
results_filepath = Time.now.to_s.gsub(/ /, '_') + '.json'
@assemblers.each do |assembler|
logger.info "Starting optimisation for #{assembler.name}"
this_res = run_assembler assembler
logger.info "Optimisation of #{assembler.name} finished"
# run the final assembly
unless options[:skip_final]
this_final_dir = File.join(final_dir, assembler.name.downcase)
Dir.chdir this_final_dir do
logger.info "Running full assembly for #{assembler.name}" +
" with optimal parameters"
# use the full read set
this_res[:left] = options[:left]
this_res[:right] = options[:right]
this_res[:threads] = options[:threads]
final = final_assembly assembler, res
this_res[:final] = final
end
res[assembler.name] = this_res
end
File.open(results_filepath, 'w') do |out|
out.write JSON.pretty_generate(res)
end
logger.info "Result file updated: #{results_filepath}"
end
logger.info "All assemblers optimised"
res
end | [
"def",
"run_all_assemblers",
"options",
"res",
"=",
"{",
"}",
"subset",
"=",
"false",
"unless",
"options",
"[",
":assemblers",
"]",
"==",
"'all'",
"subset",
"=",
"options",
"[",
":assemblers",
"]",
".",
"split",
"(",
"','",
")",
"missing",
"=",
"[",
"]",
"subset",
".",
"each",
"do",
"|",
"choice",
"|",
"missing",
"<",
"choice",
"unless",
"@assemblers",
".",
"any",
"do",
"|",
"a",
"|",
"a",
".",
"name",
"==",
"choice",
"||",
"a",
".",
"shortname",
"==",
"choice",
"end",
"end",
"unless",
"missing",
".",
"empty?",
"log",
".",
"error",
"\"The specified assemblers (#{missing.join(', ')}) were not valid choices\"",
"log",
".",
"error",
"\"Please choose from the options in --list-assembler\"",
"exit",
"(",
"1",
")",
"end",
"end",
"unless",
"options",
"[",
":skip_final",
"]",
"if",
"(",
"File",
".",
"exist?",
"'final_assemblies'",
")",
"logger",
".",
"warn",
"(",
"\"Directory final_assemblies already exists. Some results may be overwritten.\"",
")",
"end",
"FileUtils",
".",
"mkdir_p",
"(",
"'final_assemblies'",
")",
"final_dir",
"=",
"File",
".",
"expand_path",
"'final_assemblies'",
"end",
"results_filepath",
"=",
"Time",
".",
"now",
".",
"to_s",
".",
"gsub",
"(",
"/",
"/",
",",
"'_'",
")",
"+",
"'.json'",
"@assemblers",
".",
"each",
"do",
"|",
"assembler",
"|",
"logger",
".",
"info",
"\"Starting optimisation for #{assembler.name}\"",
"this_res",
"=",
"run_assembler",
"assembler",
"logger",
".",
"info",
"\"Optimisation of #{assembler.name} finished\"",
"# run the final assembly",
"unless",
"options",
"[",
":skip_final",
"]",
"this_final_dir",
"=",
"File",
".",
"join",
"(",
"final_dir",
",",
"assembler",
".",
"name",
".",
"downcase",
")",
"Dir",
".",
"chdir",
"this_final_dir",
"do",
"logger",
".",
"info",
"\"Running full assembly for #{assembler.name}\"",
"+",
"\" with optimal parameters\"",
"# use the full read set",
"this_res",
"[",
":left",
"]",
"=",
"options",
"[",
":left",
"]",
"this_res",
"[",
":right",
"]",
"=",
"options",
"[",
":right",
"]",
"this_res",
"[",
":threads",
"]",
"=",
"options",
"[",
":threads",
"]",
"final",
"=",
"final_assembly",
"assembler",
",",
"res",
"this_res",
"[",
":final",
"]",
"=",
"final",
"end",
"res",
"[",
"assembler",
".",
"name",
"]",
"=",
"this_res",
"end",
"File",
".",
"open",
"(",
"results_filepath",
",",
"'w'",
")",
"do",
"|",
"out",
"|",
"out",
".",
"write",
"JSON",
".",
"pretty_generate",
"(",
"res",
")",
"end",
"logger",
".",
"info",
"\"Result file updated: #{results_filepath}\"",
"end",
"logger",
".",
"info",
"\"All assemblers optimised\"",
"res",
"end"
] | Run optimisation and final assembly for each assembler | [
"Run",
"optimisation",
"and",
"final",
"assembly",
"for",
"each",
"assembler"
] | 475d59c72ba36ebb2799076a0009758d12fa1508 | https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/assemblermanager.rb#L167-L230 |
5,422 | blahah/assemblotron | lib/assemblotron/assemblermanager.rb | Assemblotron.AssemblerManager.run_assembler | def run_assembler assembler
# run the optimisation
opts = @options.clone
opts[:left] = opts[:left_subset]
opts[:right] = opts[:right_subset]
if @options[:optimiser] == 'sweep'
logger.info("Using full parameter sweep optimiser")
algorithm = Biopsy::ParameterSweeper.new(assembler.parameters)
elsif @options[:optimiser] == 'tabu'
logger.info("Using tabu search optimiser")
algorithm = Biopsy::TabuSearch.new(assembler.parameters)
else
logger.error("Optimiser '#{@options[:optimiser]}' is not a valid optiion")
logger.error("Please check the options using --help")
exit(1)
end
exp = Biopsy::Experiment.new(assembler,
options: opts,
threads: @options[:threads],
timelimit: @options[:timelimit],
algorithm: algorithm,
verbosity: :loud)
exp.run
end | ruby | def run_assembler assembler
# run the optimisation
opts = @options.clone
opts[:left] = opts[:left_subset]
opts[:right] = opts[:right_subset]
if @options[:optimiser] == 'sweep'
logger.info("Using full parameter sweep optimiser")
algorithm = Biopsy::ParameterSweeper.new(assembler.parameters)
elsif @options[:optimiser] == 'tabu'
logger.info("Using tabu search optimiser")
algorithm = Biopsy::TabuSearch.new(assembler.parameters)
else
logger.error("Optimiser '#{@options[:optimiser]}' is not a valid optiion")
logger.error("Please check the options using --help")
exit(1)
end
exp = Biopsy::Experiment.new(assembler,
options: opts,
threads: @options[:threads],
timelimit: @options[:timelimit],
algorithm: algorithm,
verbosity: :loud)
exp.run
end | [
"def",
"run_assembler",
"assembler",
"# run the optimisation",
"opts",
"=",
"@options",
".",
"clone",
"opts",
"[",
":left",
"]",
"=",
"opts",
"[",
":left_subset",
"]",
"opts",
"[",
":right",
"]",
"=",
"opts",
"[",
":right_subset",
"]",
"if",
"@options",
"[",
":optimiser",
"]",
"==",
"'sweep'",
"logger",
".",
"info",
"(",
"\"Using full parameter sweep optimiser\"",
")",
"algorithm",
"=",
"Biopsy",
"::",
"ParameterSweeper",
".",
"new",
"(",
"assembler",
".",
"parameters",
")",
"elsif",
"@options",
"[",
":optimiser",
"]",
"==",
"'tabu'",
"logger",
".",
"info",
"(",
"\"Using tabu search optimiser\"",
")",
"algorithm",
"=",
"Biopsy",
"::",
"TabuSearch",
".",
"new",
"(",
"assembler",
".",
"parameters",
")",
"else",
"logger",
".",
"error",
"(",
"\"Optimiser '#{@options[:optimiser]}' is not a valid optiion\"",
")",
"logger",
".",
"error",
"(",
"\"Please check the options using --help\"",
")",
"exit",
"(",
"1",
")",
"end",
"exp",
"=",
"Biopsy",
"::",
"Experiment",
".",
"new",
"(",
"assembler",
",",
"options",
":",
"opts",
",",
"threads",
":",
"@options",
"[",
":threads",
"]",
",",
"timelimit",
":",
"@options",
"[",
":timelimit",
"]",
",",
"algorithm",
":",
"algorithm",
",",
"verbosity",
":",
":loud",
")",
"exp",
".",
"run",
"end"
] | Run optimisation for the named assembler
@param [String] assembler name or shortname | [
"Run",
"optimisation",
"for",
"the",
"named",
"assembler"
] | 475d59c72ba36ebb2799076a0009758d12fa1508 | https://github.com/blahah/assemblotron/blob/475d59c72ba36ebb2799076a0009758d12fa1508/lib/assemblotron/assemblermanager.rb#L235-L258 |
5,423 | Sharparam/chatrix | lib/chatrix/rooms.rb | Chatrix.Rooms.[] | def [](id)
return @rooms[id] if id.start_with? '!'
if id.start_with? '#'
res = @rooms.find { |_, r| r.canonical_alias == id }
return res.last if res.respond_to? :last
end
res = @rooms.find { |_, r| r.name == id }
res.last if res.respond_to? :last
end | ruby | def [](id)
return @rooms[id] if id.start_with? '!'
if id.start_with? '#'
res = @rooms.find { |_, r| r.canonical_alias == id }
return res.last if res.respond_to? :last
end
res = @rooms.find { |_, r| r.name == id }
res.last if res.respond_to? :last
end | [
"def",
"[]",
"(",
"id",
")",
"return",
"@rooms",
"[",
"id",
"]",
"if",
"id",
".",
"start_with?",
"'!'",
"if",
"id",
".",
"start_with?",
"'#'",
"res",
"=",
"@rooms",
".",
"find",
"{",
"|",
"_",
",",
"r",
"|",
"r",
".",
"canonical_alias",
"==",
"id",
"}",
"return",
"res",
".",
"last",
"if",
"res",
".",
"respond_to?",
":last",
"end",
"res",
"=",
"@rooms",
".",
"find",
"{",
"|",
"_",
",",
"r",
"|",
"r",
".",
"name",
"==",
"id",
"}",
"res",
".",
"last",
"if",
"res",
".",
"respond_to?",
":last",
"end"
] | Initializes a new Rooms instance.
@param users [Users] The User manager.
@param matrix [Matrix] The Matrix API instance.
Gets a room by its ID, alias, or name.
@return [Room,nil] Returns the room instance if the room was found,
otherwise `nil`. | [
"Initializes",
"a",
"new",
"Rooms",
"instance",
"."
] | 6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34 | https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/rooms.rb#L30-L40 |
5,424 | Sharparam/chatrix | lib/chatrix/rooms.rb | Chatrix.Rooms.process_events | def process_events(events)
process_join events['join'] if events.key? 'join'
process_invite events['invite'] if events.key? 'invite'
process_leave events['leave'] if events.key? 'leave'
end | ruby | def process_events(events)
process_join events['join'] if events.key? 'join'
process_invite events['invite'] if events.key? 'invite'
process_leave events['leave'] if events.key? 'leave'
end | [
"def",
"process_events",
"(",
"events",
")",
"process_join",
"events",
"[",
"'join'",
"]",
"if",
"events",
".",
"key?",
"'join'",
"process_invite",
"events",
"[",
"'invite'",
"]",
"if",
"events",
".",
"key?",
"'invite'",
"process_leave",
"events",
"[",
"'leave'",
"]",
"if",
"events",
".",
"key?",
"'leave'",
"end"
] | Processes a list of room events from syncs.
@param events [Hash] A hash of room events as returned from the server. | [
"Processes",
"a",
"list",
"of",
"room",
"events",
"from",
"syncs",
"."
] | 6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34 | https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/rooms.rb#L54-L58 |
5,425 | Sharparam/chatrix | lib/chatrix/rooms.rb | Chatrix.Rooms.get_room | def get_room(id)
return @rooms[id] if @rooms.key? id
room = Room.new id, @users, @matrix
@rooms[id] = room
broadcast(:added, room)
room
end | ruby | def get_room(id)
return @rooms[id] if @rooms.key? id
room = Room.new id, @users, @matrix
@rooms[id] = room
broadcast(:added, room)
room
end | [
"def",
"get_room",
"(",
"id",
")",
"return",
"@rooms",
"[",
"id",
"]",
"if",
"@rooms",
".",
"key?",
"id",
"room",
"=",
"Room",
".",
"new",
"id",
",",
"@users",
",",
"@matrix",
"@rooms",
"[",
"id",
"]",
"=",
"room",
"broadcast",
"(",
":added",
",",
"room",
")",
"room",
"end"
] | Gets the Room instance associated with a room ID.
If there is no Room instance for the ID, one is created and returned.
@param id [String] The room ID to get an instance for.
@return [Room] An instance of the Room class for the specified ID. | [
"Gets",
"the",
"Room",
"instance",
"associated",
"with",
"a",
"room",
"ID",
".",
"If",
"there",
"is",
"no",
"Room",
"instance",
"for",
"the",
"ID",
"one",
"is",
"created",
"and",
"returned",
"."
] | 6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34 | https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/rooms.rb#L67-L73 |
5,426 | Sharparam/chatrix | lib/chatrix/rooms.rb | Chatrix.Rooms.process_join | def process_join(events)
events.each do |room, data|
get_room(room).process_join data
end
end | ruby | def process_join(events)
events.each do |room, data|
get_room(room).process_join data
end
end | [
"def",
"process_join",
"(",
"events",
")",
"events",
".",
"each",
"do",
"|",
"room",
",",
"data",
"|",
"get_room",
"(",
"room",
")",
".",
"process_join",
"data",
"end",
"end"
] | Process `join` room events.
@param events [Hash{String=>Hash}] Events to process. | [
"Process",
"join",
"room",
"events",
"."
] | 6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34 | https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/rooms.rb#L78-L82 |
5,427 | Sharparam/chatrix | lib/chatrix/rooms.rb | Chatrix.Rooms.process_invite | def process_invite(events)
events.each do |room, data|
get_room(room).process_invite data
end
end | ruby | def process_invite(events)
events.each do |room, data|
get_room(room).process_invite data
end
end | [
"def",
"process_invite",
"(",
"events",
")",
"events",
".",
"each",
"do",
"|",
"room",
",",
"data",
"|",
"get_room",
"(",
"room",
")",
".",
"process_invite",
"data",
"end",
"end"
] | Process `invite` room events.
@param events [Hash{String=>Hash}] Events to process. | [
"Process",
"invite",
"room",
"events",
"."
] | 6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34 | https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/rooms.rb#L87-L91 |
5,428 | Sharparam/chatrix | lib/chatrix/rooms.rb | Chatrix.Rooms.process_leave | def process_leave(events)
events.each do |room, data|
get_room(room).process_leave data
end
end | ruby | def process_leave(events)
events.each do |room, data|
get_room(room).process_leave data
end
end | [
"def",
"process_leave",
"(",
"events",
")",
"events",
".",
"each",
"do",
"|",
"room",
",",
"data",
"|",
"get_room",
"(",
"room",
")",
".",
"process_leave",
"data",
"end",
"end"
] | Process `leave` room events.
@param events [Hash{String=>Hash}] Events to process. | [
"Process",
"leave",
"room",
"events",
"."
] | 6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34 | https://github.com/Sharparam/chatrix/blob/6f2e9cf3a614ba7e8a9960f7d9b97092c0ce1e34/lib/chatrix/rooms.rb#L96-L100 |
5,429 | ianwhite/resources_controller | lib/resources_controller/helper.rb | ResourcesController.Helper.method_missing | def method_missing(method, *args, &block)
if controller.resource_named_route_helper_method?(method)
self.class.send(:delegate, method, :to => :controller)
controller.send(method, *args)
else
super(method, *args, &block)
end
end | ruby | def method_missing(method, *args, &block)
if controller.resource_named_route_helper_method?(method)
self.class.send(:delegate, method, :to => :controller)
controller.send(method, *args)
else
super(method, *args, &block)
end
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"controller",
".",
"resource_named_route_helper_method?",
"(",
"method",
")",
"self",
".",
"class",
".",
"send",
"(",
":delegate",
",",
"method",
",",
":to",
"=>",
":controller",
")",
"controller",
".",
"send",
"(",
"method",
",",
"args",
")",
"else",
"super",
"(",
"method",
",",
"args",
",",
"block",
")",
"end",
"end"
] | Delegate named_route helper method to the controller. Create the delegation
to short circuit the method_missing call for future invocations. | [
"Delegate",
"named_route",
"helper",
"method",
"to",
"the",
"controller",
".",
"Create",
"the",
"delegation",
"to",
"short",
"circuit",
"the",
"method_missing",
"call",
"for",
"future",
"invocations",
"."
] | 14e76843ccf7d22a6da5da6db81681397c4838c5 | https://github.com/ianwhite/resources_controller/blob/14e76843ccf7d22a6da5da6db81681397c4838c5/lib/resources_controller/helper.rb#L81-L88 |
5,430 | ideonetwork/lato-core | app/cells/lato_core/widgets/index/cell.rb | LatoCore.Widgets::Index::Cell.generate_table_head | def generate_table_head
labels = []
if @args[:head] && @args[:head].length > 0
# manage case with custom head
labels = []
if @args[:actions_on_start] && @show_row_actions
labels.push(LANGUAGES[:lato_core][:mixed][:actions])
end
@args[:head].each do |head|
if head.is_a?(Hash)
sort_value = @args[:records].is_a?(Hash) ? @args[:records][:sort] : ''
sort_dir_value = @args[:records].is_a?(Hash) ? @args[:records][:sort_dir] : 'ASC'
active_class = sort_value == head[:sort] ? "attr-active attr-sort-#{sort_dir_value}" : ''
active_sort = sort_value == head[:sort] ? (sort_dir_value == 'ASC' ? 'DESC' : 'ASC') : sort_dir_value
search_value = @args[:records].is_a?(Hash) ? @args[:records][:search] : ''
url = core__add_param_to_url(@args[:index_url], 'widget_index[search]', search_value)
url = core__add_param_to_url(url, 'widget_index[sort]', head[:sort])
url = core__add_param_to_url(url, 'widget_index[sort_dir]', active_sort)
string = "<a href='#{url}' class='#{active_class}'>#{head[:label]}</a>"
labels.push(string)
else
labels.push(head)
end
end
if !@args[:actions_on_start] && @show_row_actions
labels.push(LANGUAGES[:lato_core][:mixed][:actions])
end
elsif @records&.length > 0
# manage case without custom head
labels = []
if @args[:actions_on_start] && @show_row_actions
labels.push(LANGUAGES[:lato_core][:mixed][:actions])
end
labels = labels + @records.first.attributes.keys.map {|s| s.gsub('_', ' ')}
labels = labels.map(&:capitalize)
if !@args[:actions_on_start] && @show_row_actions
labels.push(LANGUAGES[:lato_core][:mixed][:actions])
end
end
return LatoCore::Elements::Table::Head::Cell.new(labels: labels)
end | ruby | def generate_table_head
labels = []
if @args[:head] && @args[:head].length > 0
# manage case with custom head
labels = []
if @args[:actions_on_start] && @show_row_actions
labels.push(LANGUAGES[:lato_core][:mixed][:actions])
end
@args[:head].each do |head|
if head.is_a?(Hash)
sort_value = @args[:records].is_a?(Hash) ? @args[:records][:sort] : ''
sort_dir_value = @args[:records].is_a?(Hash) ? @args[:records][:sort_dir] : 'ASC'
active_class = sort_value == head[:sort] ? "attr-active attr-sort-#{sort_dir_value}" : ''
active_sort = sort_value == head[:sort] ? (sort_dir_value == 'ASC' ? 'DESC' : 'ASC') : sort_dir_value
search_value = @args[:records].is_a?(Hash) ? @args[:records][:search] : ''
url = core__add_param_to_url(@args[:index_url], 'widget_index[search]', search_value)
url = core__add_param_to_url(url, 'widget_index[sort]', head[:sort])
url = core__add_param_to_url(url, 'widget_index[sort_dir]', active_sort)
string = "<a href='#{url}' class='#{active_class}'>#{head[:label]}</a>"
labels.push(string)
else
labels.push(head)
end
end
if !@args[:actions_on_start] && @show_row_actions
labels.push(LANGUAGES[:lato_core][:mixed][:actions])
end
elsif @records&.length > 0
# manage case without custom head
labels = []
if @args[:actions_on_start] && @show_row_actions
labels.push(LANGUAGES[:lato_core][:mixed][:actions])
end
labels = labels + @records.first.attributes.keys.map {|s| s.gsub('_', ' ')}
labels = labels.map(&:capitalize)
if !@args[:actions_on_start] && @show_row_actions
labels.push(LANGUAGES[:lato_core][:mixed][:actions])
end
end
return LatoCore::Elements::Table::Head::Cell.new(labels: labels)
end | [
"def",
"generate_table_head",
"labels",
"=",
"[",
"]",
"if",
"@args",
"[",
":head",
"]",
"&&",
"@args",
"[",
":head",
"]",
".",
"length",
">",
"0",
"# manage case with custom head",
"labels",
"=",
"[",
"]",
"if",
"@args",
"[",
":actions_on_start",
"]",
"&&",
"@show_row_actions",
"labels",
".",
"push",
"(",
"LANGUAGES",
"[",
":lato_core",
"]",
"[",
":mixed",
"]",
"[",
":actions",
"]",
")",
"end",
"@args",
"[",
":head",
"]",
".",
"each",
"do",
"|",
"head",
"|",
"if",
"head",
".",
"is_a?",
"(",
"Hash",
")",
"sort_value",
"=",
"@args",
"[",
":records",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"@args",
"[",
":records",
"]",
"[",
":sort",
"]",
":",
"''",
"sort_dir_value",
"=",
"@args",
"[",
":records",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"@args",
"[",
":records",
"]",
"[",
":sort_dir",
"]",
":",
"'ASC'",
"active_class",
"=",
"sort_value",
"==",
"head",
"[",
":sort",
"]",
"?",
"\"attr-active attr-sort-#{sort_dir_value}\"",
":",
"''",
"active_sort",
"=",
"sort_value",
"==",
"head",
"[",
":sort",
"]",
"?",
"(",
"sort_dir_value",
"==",
"'ASC'",
"?",
"'DESC'",
":",
"'ASC'",
")",
":",
"sort_dir_value",
"search_value",
"=",
"@args",
"[",
":records",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"@args",
"[",
":records",
"]",
"[",
":search",
"]",
":",
"''",
"url",
"=",
"core__add_param_to_url",
"(",
"@args",
"[",
":index_url",
"]",
",",
"'widget_index[search]'",
",",
"search_value",
")",
"url",
"=",
"core__add_param_to_url",
"(",
"url",
",",
"'widget_index[sort]'",
",",
"head",
"[",
":sort",
"]",
")",
"url",
"=",
"core__add_param_to_url",
"(",
"url",
",",
"'widget_index[sort_dir]'",
",",
"active_sort",
")",
"string",
"=",
"\"<a href='#{url}' class='#{active_class}'>#{head[:label]}</a>\"",
"labels",
".",
"push",
"(",
"string",
")",
"else",
"labels",
".",
"push",
"(",
"head",
")",
"end",
"end",
"if",
"!",
"@args",
"[",
":actions_on_start",
"]",
"&&",
"@show_row_actions",
"labels",
".",
"push",
"(",
"LANGUAGES",
"[",
":lato_core",
"]",
"[",
":mixed",
"]",
"[",
":actions",
"]",
")",
"end",
"elsif",
"@records",
"&.",
"length",
">",
"0",
"# manage case without custom head",
"labels",
"=",
"[",
"]",
"if",
"@args",
"[",
":actions_on_start",
"]",
"&&",
"@show_row_actions",
"labels",
".",
"push",
"(",
"LANGUAGES",
"[",
":lato_core",
"]",
"[",
":mixed",
"]",
"[",
":actions",
"]",
")",
"end",
"labels",
"=",
"labels",
"+",
"@records",
".",
"first",
".",
"attributes",
".",
"keys",
".",
"map",
"{",
"|",
"s",
"|",
"s",
".",
"gsub",
"(",
"'_'",
",",
"' '",
")",
"}",
"labels",
"=",
"labels",
".",
"map",
"(",
":capitalize",
")",
"if",
"!",
"@args",
"[",
":actions_on_start",
"]",
"&&",
"@show_row_actions",
"labels",
".",
"push",
"(",
"LANGUAGES",
"[",
":lato_core",
"]",
"[",
":mixed",
"]",
"[",
":actions",
"]",
")",
"end",
"end",
"return",
"LatoCore",
"::",
"Elements",
"::",
"Table",
"::",
"Head",
"::",
"Cell",
".",
"new",
"(",
"labels",
":",
"labels",
")",
"end"
] | This function generate the head for the table. | [
"This",
"function",
"generate",
"the",
"head",
"for",
"the",
"table",
"."
] | c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c | https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/cells/lato_core/widgets/index/cell.rb#L84-L127 |
5,431 | ideonetwork/lato-core | app/cells/lato_core/widgets/index/cell.rb | LatoCore.Widgets::Index::Cell.generate_table_rows | def generate_table_rows
table_rows = []
if @args[:columns] && @args[:columns].length > 0
# manage case with custom columns
table_rows = generate_table_rows_from_columns_functions(@args[:columns])
elsif @records && @records.length > 0
# manage case without custom columns
table_rows = generate_table_rows_from_columns_functions(@records.first.attributes.keys)
end
return table_rows
end | ruby | def generate_table_rows
table_rows = []
if @args[:columns] && @args[:columns].length > 0
# manage case with custom columns
table_rows = generate_table_rows_from_columns_functions(@args[:columns])
elsif @records && @records.length > 0
# manage case without custom columns
table_rows = generate_table_rows_from_columns_functions(@records.first.attributes.keys)
end
return table_rows
end | [
"def",
"generate_table_rows",
"table_rows",
"=",
"[",
"]",
"if",
"@args",
"[",
":columns",
"]",
"&&",
"@args",
"[",
":columns",
"]",
".",
"length",
">",
"0",
"# manage case with custom columns",
"table_rows",
"=",
"generate_table_rows_from_columns_functions",
"(",
"@args",
"[",
":columns",
"]",
")",
"elsif",
"@records",
"&&",
"@records",
".",
"length",
">",
"0",
"# manage case without custom columns",
"table_rows",
"=",
"generate_table_rows_from_columns_functions",
"(",
"@records",
".",
"first",
".",
"attributes",
".",
"keys",
")",
"end",
"return",
"table_rows",
"end"
] | This function generate the rows fr the table. | [
"This",
"function",
"generate",
"the",
"rows",
"fr",
"the",
"table",
"."
] | c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c | https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/cells/lato_core/widgets/index/cell.rb#L137-L149 |
5,432 | ideonetwork/lato-core | app/cells/lato_core/widgets/index/cell.rb | LatoCore.Widgets::Index::Cell.generate_table_rows_from_columns_functions | def generate_table_rows_from_columns_functions columns_functions
table_rows = []
@records.each do |record|
labels = []
# add actions to row columns
if @args[:actions_on_start] && @show_row_actions
labels.push(generate_actions_bottongroup_for_record(record))
end
# add function result to row columns
columns_functions.each do |column_function|
labels.push(record.send(column_function))
end
# add actions to row columns
if !@args[:actions_on_start] && @show_row_actions
labels.push(generate_actions_bottongroup_for_record(record))
end
# puts rows on table rows
table_rows.push(LatoCore::Elements::Table::Row::Cell.new(labels: labels))
end
return table_rows
end | ruby | def generate_table_rows_from_columns_functions columns_functions
table_rows = []
@records.each do |record|
labels = []
# add actions to row columns
if @args[:actions_on_start] && @show_row_actions
labels.push(generate_actions_bottongroup_for_record(record))
end
# add function result to row columns
columns_functions.each do |column_function|
labels.push(record.send(column_function))
end
# add actions to row columns
if !@args[:actions_on_start] && @show_row_actions
labels.push(generate_actions_bottongroup_for_record(record))
end
# puts rows on table rows
table_rows.push(LatoCore::Elements::Table::Row::Cell.new(labels: labels))
end
return table_rows
end | [
"def",
"generate_table_rows_from_columns_functions",
"columns_functions",
"table_rows",
"=",
"[",
"]",
"@records",
".",
"each",
"do",
"|",
"record",
"|",
"labels",
"=",
"[",
"]",
"# add actions to row columns",
"if",
"@args",
"[",
":actions_on_start",
"]",
"&&",
"@show_row_actions",
"labels",
".",
"push",
"(",
"generate_actions_bottongroup_for_record",
"(",
"record",
")",
")",
"end",
"# add function result to row columns",
"columns_functions",
".",
"each",
"do",
"|",
"column_function",
"|",
"labels",
".",
"push",
"(",
"record",
".",
"send",
"(",
"column_function",
")",
")",
"end",
"# add actions to row columns",
"if",
"!",
"@args",
"[",
":actions_on_start",
"]",
"&&",
"@show_row_actions",
"labels",
".",
"push",
"(",
"generate_actions_bottongroup_for_record",
"(",
"record",
")",
")",
"end",
"# puts rows on table rows",
"table_rows",
".",
"push",
"(",
"LatoCore",
"::",
"Elements",
"::",
"Table",
"::",
"Row",
"::",
"Cell",
".",
"new",
"(",
"labels",
":",
"labels",
")",
")",
"end",
"return",
"table_rows",
"end"
] | This function generate the rows for a list of columns. | [
"This",
"function",
"generate",
"the",
"rows",
"for",
"a",
"list",
"of",
"columns",
"."
] | c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c | https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/cells/lato_core/widgets/index/cell.rb#L152-L174 |
5,433 | ideonetwork/lato-core | app/cells/lato_core/widgets/index/cell.rb | LatoCore.Widgets::Index::Cell.generate_actions_bottongroup_for_record | def generate_actions_bottongroup_for_record record
action_buttons = []
action_buttons.push(generate_show_button(record.id)) if @args[:actions][:show]
action_buttons.push(generate_edit_button(record.id)) if @args[:actions][:edit]
action_buttons.push(generate_delete_button(record.id)) if @args[:actions][:delete]
return LatoCore::Elements::Buttongroup::Cell.new(buttons: action_buttons)
end | ruby | def generate_actions_bottongroup_for_record record
action_buttons = []
action_buttons.push(generate_show_button(record.id)) if @args[:actions][:show]
action_buttons.push(generate_edit_button(record.id)) if @args[:actions][:edit]
action_buttons.push(generate_delete_button(record.id)) if @args[:actions][:delete]
return LatoCore::Elements::Buttongroup::Cell.new(buttons: action_buttons)
end | [
"def",
"generate_actions_bottongroup_for_record",
"record",
"action_buttons",
"=",
"[",
"]",
"action_buttons",
".",
"push",
"(",
"generate_show_button",
"(",
"record",
".",
"id",
")",
")",
"if",
"@args",
"[",
":actions",
"]",
"[",
":show",
"]",
"action_buttons",
".",
"push",
"(",
"generate_edit_button",
"(",
"record",
".",
"id",
")",
")",
"if",
"@args",
"[",
":actions",
"]",
"[",
":edit",
"]",
"action_buttons",
".",
"push",
"(",
"generate_delete_button",
"(",
"record",
".",
"id",
")",
")",
"if",
"@args",
"[",
":actions",
"]",
"[",
":delete",
"]",
"return",
"LatoCore",
"::",
"Elements",
"::",
"Buttongroup",
"::",
"Cell",
".",
"new",
"(",
"buttons",
":",
"action_buttons",
")",
"end"
] | This function generate row actions for a table row. | [
"This",
"function",
"generate",
"row",
"actions",
"for",
"a",
"table",
"row",
"."
] | c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c | https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/cells/lato_core/widgets/index/cell.rb#L177-L183 |
5,434 | ideonetwork/lato-core | app/cells/lato_core/widgets/index/cell.rb | LatoCore.Widgets::Index::Cell.generate_delete_button | def generate_delete_button record_id
return unless @args[:index_url]
url = @args[:index_url].end_with?('/') ? "#{@args[:index_url].gsub(/\?.*/, '')}#{record_id}" : "#{@args[:index_url].gsub(/\?.*/, '')}/#{record_id}"
return LatoCore::Elements::Button::Cell.new(label: LANGUAGES[:lato_core][:mixed][:delete], url: url, method: 'delete',
icon: 'trash', style: 'danger', confirmation: {
message: LANGUAGES[:lato_core][:mixed][:default_delete_message],
positive_response: LANGUAGES[:lato_core][:mixed][:default_delete_positive_response],
negative_response: LANGUAGES[:lato_core][:mixed][:default_delete_negative_response]
})
end | ruby | def generate_delete_button record_id
return unless @args[:index_url]
url = @args[:index_url].end_with?('/') ? "#{@args[:index_url].gsub(/\?.*/, '')}#{record_id}" : "#{@args[:index_url].gsub(/\?.*/, '')}/#{record_id}"
return LatoCore::Elements::Button::Cell.new(label: LANGUAGES[:lato_core][:mixed][:delete], url: url, method: 'delete',
icon: 'trash', style: 'danger', confirmation: {
message: LANGUAGES[:lato_core][:mixed][:default_delete_message],
positive_response: LANGUAGES[:lato_core][:mixed][:default_delete_positive_response],
negative_response: LANGUAGES[:lato_core][:mixed][:default_delete_negative_response]
})
end | [
"def",
"generate_delete_button",
"record_id",
"return",
"unless",
"@args",
"[",
":index_url",
"]",
"url",
"=",
"@args",
"[",
":index_url",
"]",
".",
"end_with?",
"(",
"'/'",
")",
"?",
"\"#{@args[:index_url].gsub(/\\?.*/, '')}#{record_id}\"",
":",
"\"#{@args[:index_url].gsub(/\\?.*/, '')}/#{record_id}\"",
"return",
"LatoCore",
"::",
"Elements",
"::",
"Button",
"::",
"Cell",
".",
"new",
"(",
"label",
":",
"LANGUAGES",
"[",
":lato_core",
"]",
"[",
":mixed",
"]",
"[",
":delete",
"]",
",",
"url",
":",
"url",
",",
"method",
":",
"'delete'",
",",
"icon",
":",
"'trash'",
",",
"style",
":",
"'danger'",
",",
"confirmation",
":",
"{",
"message",
":",
"LANGUAGES",
"[",
":lato_core",
"]",
"[",
":mixed",
"]",
"[",
":default_delete_message",
"]",
",",
"positive_response",
":",
"LANGUAGES",
"[",
":lato_core",
"]",
"[",
":mixed",
"]",
"[",
":default_delete_positive_response",
"]",
",",
"negative_response",
":",
"LANGUAGES",
"[",
":lato_core",
"]",
"[",
":mixed",
"]",
"[",
":default_delete_negative_response",
"]",
"}",
")",
"end"
] | This function generate the delete button for a record. | [
"This",
"function",
"generate",
"the",
"delete",
"button",
"for",
"a",
"record",
"."
] | c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c | https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/cells/lato_core/widgets/index/cell.rb#L202-L211 |
5,435 | ideonetwork/lato-core | app/cells/lato_core/widgets/index/cell.rb | LatoCore.Widgets::Index::Cell.generate_new_button | def generate_new_button
return unless @args[:index_url]
url = "#{@args[:index_url].gsub(/\?.*/, '')}/new"
return LatoCore::Elements::Button::Cell.new(label: LANGUAGES[:lato_core][:mixed][:new],
url: url, icon: 'plus')
end | ruby | def generate_new_button
return unless @args[:index_url]
url = "#{@args[:index_url].gsub(/\?.*/, '')}/new"
return LatoCore::Elements::Button::Cell.new(label: LANGUAGES[:lato_core][:mixed][:new],
url: url, icon: 'plus')
end | [
"def",
"generate_new_button",
"return",
"unless",
"@args",
"[",
":index_url",
"]",
"url",
"=",
"\"#{@args[:index_url].gsub(/\\?.*/, '')}/new\"",
"return",
"LatoCore",
"::",
"Elements",
"::",
"Button",
"::",
"Cell",
".",
"new",
"(",
"label",
":",
"LANGUAGES",
"[",
":lato_core",
"]",
"[",
":mixed",
"]",
"[",
":new",
"]",
",",
"url",
":",
"url",
",",
"icon",
":",
"'plus'",
")",
"end"
] | This function generate new button. | [
"This",
"function",
"generate",
"new",
"button",
"."
] | c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c | https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/cells/lato_core/widgets/index/cell.rb#L214-L219 |
5,436 | ideonetwork/lato-core | app/cells/lato_core/widgets/index/cell.rb | LatoCore.Widgets::Index::Cell.generate_search_input | def generate_search_input
search_placeholder = ''
if @args[:records].is_a?(Hash)
search_placeholder = @args[:records][:search_key].is_a?(Array) ? @args[:records][:search_key].to_sentence : @args[:records][:search_key].humanize
end
search_value = @args[:records].is_a?(Hash) ? @args[:records][:search] : ''
return LatoCore::Inputs::Text::Cell.new(name: 'widget_index[search]', value: search_value, placeholder: search_placeholder)
end | ruby | def generate_search_input
search_placeholder = ''
if @args[:records].is_a?(Hash)
search_placeholder = @args[:records][:search_key].is_a?(Array) ? @args[:records][:search_key].to_sentence : @args[:records][:search_key].humanize
end
search_value = @args[:records].is_a?(Hash) ? @args[:records][:search] : ''
return LatoCore::Inputs::Text::Cell.new(name: 'widget_index[search]', value: search_value, placeholder: search_placeholder)
end | [
"def",
"generate_search_input",
"search_placeholder",
"=",
"''",
"if",
"@args",
"[",
":records",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"search_placeholder",
"=",
"@args",
"[",
":records",
"]",
"[",
":search_key",
"]",
".",
"is_a?",
"(",
"Array",
")",
"?",
"@args",
"[",
":records",
"]",
"[",
":search_key",
"]",
".",
"to_sentence",
":",
"@args",
"[",
":records",
"]",
"[",
":search_key",
"]",
".",
"humanize",
"end",
"search_value",
"=",
"@args",
"[",
":records",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"@args",
"[",
":records",
"]",
"[",
":search",
"]",
":",
"''",
"return",
"LatoCore",
"::",
"Inputs",
"::",
"Text",
"::",
"Cell",
".",
"new",
"(",
"name",
":",
"'widget_index[search]'",
",",
"value",
":",
"search_value",
",",
"placeholder",
":",
"search_placeholder",
")",
"end"
] | This function generate and return the search input. | [
"This",
"function",
"generate",
"and",
"return",
"the",
"search",
"input",
"."
] | c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c | https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/cells/lato_core/widgets/index/cell.rb#L230-L237 |
5,437 | ideonetwork/lato-core | app/cells/lato_core/widgets/index/cell.rb | LatoCore.Widgets::Index::Cell.generate_search_submit | def generate_search_submit
return LatoCore::Elements::Button::Cell.new(label: ' ', icon: 'search', type: 'submit', icon_align: 'right')
end | ruby | def generate_search_submit
return LatoCore::Elements::Button::Cell.new(label: ' ', icon: 'search', type: 'submit', icon_align: 'right')
end | [
"def",
"generate_search_submit",
"return",
"LatoCore",
"::",
"Elements",
"::",
"Button",
"::",
"Cell",
".",
"new",
"(",
"label",
":",
"' '",
",",
"icon",
":",
"'search'",
",",
"type",
":",
"'submit'",
",",
"icon_align",
":",
"'right'",
")",
"end"
] | This function generate the search submit button. | [
"This",
"function",
"generate",
"the",
"search",
"submit",
"button",
"."
] | c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c | https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/app/cells/lato_core/widgets/index/cell.rb#L240-L242 |
5,438 | razor-x/config_curator | lib/config_curator/units/config_file.rb | ConfigCurator.ConfigFile.install_file | def install_file
FileUtils.mkdir_p File.dirname(destination_path)
FileUtils.copy source_path, destination_path, preserve: true
end | ruby | def install_file
FileUtils.mkdir_p File.dirname(destination_path)
FileUtils.copy source_path, destination_path, preserve: true
end | [
"def",
"install_file",
"FileUtils",
".",
"mkdir_p",
"File",
".",
"dirname",
"(",
"destination_path",
")",
"FileUtils",
".",
"copy",
"source_path",
",",
"destination_path",
",",
"preserve",
":",
"true",
"end"
] | Recursively creates the necessary directories and install the file. | [
"Recursively",
"creates",
"the",
"necessary",
"directories",
"and",
"install",
"the",
"file",
"."
] | b0c0742ba0c36acf66de3eafd23a7d17b210036b | https://github.com/razor-x/config_curator/blob/b0c0742ba0c36acf66de3eafd23a7d17b210036b/lib/config_curator/units/config_file.rb#L61-L64 |
5,439 | kunishi/algebra-ruby2 | lib/algebra/polynomial.rb | Algebra.Polynomial.need_paren_in_coeff? | def need_paren_in_coeff?
if constant?
c = @coeff[0]
if c.respond_to?(:need_paren_in_coeff?)
c.need_paren_in_coeff?
elsif c.is_a?(Numeric)
false
else
true
end
elsif !monomial?
true
else
false
end
end | ruby | def need_paren_in_coeff?
if constant?
c = @coeff[0]
if c.respond_to?(:need_paren_in_coeff?)
c.need_paren_in_coeff?
elsif c.is_a?(Numeric)
false
else
true
end
elsif !monomial?
true
else
false
end
end | [
"def",
"need_paren_in_coeff?",
"if",
"constant?",
"c",
"=",
"@coeff",
"[",
"0",
"]",
"if",
"c",
".",
"respond_to?",
"(",
":need_paren_in_coeff?",
")",
"c",
".",
"need_paren_in_coeff?",
"elsif",
"c",
".",
"is_a?",
"(",
"Numeric",
")",
"false",
"else",
"true",
"end",
"elsif",
"!",
"monomial?",
"true",
"else",
"false",
"end",
"end"
] | def cont; @coeff.first.gcd_all(* @coeff[1..-1]); end
def pp; self / cont; end | [
"def",
"cont",
";"
] | 8976fbaac14933d3206324c845b879bf67fa0cf7 | https://github.com/kunishi/algebra-ruby2/blob/8976fbaac14933d3206324c845b879bf67fa0cf7/lib/algebra/polynomial.rb#L372-L387 |
5,440 | expresspigeon/expresspigeon-ruby | lib/expresspigeon-ruby/messages.rb | ExpressPigeon.Messages.reports | def reports(from_id, start_date = nil, end_date = nil)
params = []
if from_id
params << "from_id=#{from_id}"
end
if start_date and not end_date
raise 'must include both start_date and end_date'
end
if end_date and not start_date
raise 'must include both start_date and end_date'
end
if start_date and end_date
params << "start_date=#{start_date.strftime('%FT%T.%L%z')}"
params << "end_date=#{end_date.strftime('%FT%T.%L%z')}"
end
query = "#{@endpoint}?"
if params.size > 0
query << params.join('&')
end
get query
end | ruby | def reports(from_id, start_date = nil, end_date = nil)
params = []
if from_id
params << "from_id=#{from_id}"
end
if start_date and not end_date
raise 'must include both start_date and end_date'
end
if end_date and not start_date
raise 'must include both start_date and end_date'
end
if start_date and end_date
params << "start_date=#{start_date.strftime('%FT%T.%L%z')}"
params << "end_date=#{end_date.strftime('%FT%T.%L%z')}"
end
query = "#{@endpoint}?"
if params.size > 0
query << params.join('&')
end
get query
end | [
"def",
"reports",
"(",
"from_id",
",",
"start_date",
"=",
"nil",
",",
"end_date",
"=",
"nil",
")",
"params",
"=",
"[",
"]",
"if",
"from_id",
"params",
"<<",
"\"from_id=#{from_id}\"",
"end",
"if",
"start_date",
"and",
"not",
"end_date",
"raise",
"'must include both start_date and end_date'",
"end",
"if",
"end_date",
"and",
"not",
"start_date",
"raise",
"'must include both start_date and end_date'",
"end",
"if",
"start_date",
"and",
"end_date",
"params",
"<<",
"\"start_date=#{start_date.strftime('%FT%T.%L%z')}\"",
"params",
"<<",
"\"end_date=#{end_date.strftime('%FT%T.%L%z')}\"",
"end",
"query",
"=",
"\"#{@endpoint}?\"",
"if",
"params",
".",
"size",
">",
"0",
"query",
"<<",
"params",
".",
"join",
"(",
"'&'",
")",
"end",
"get",
"query",
"end"
] | Report for a group of messages in a given time period.
* +start_date+ is instance of Time
* +end_date+ is instance of Time | [
"Report",
"for",
"a",
"group",
"of",
"messages",
"in",
"a",
"given",
"time",
"period",
"."
] | 1cdbd0184c112512724fa827297e7c3880964802 | https://github.com/expresspigeon/expresspigeon-ruby/blob/1cdbd0184c112512724fa827297e7c3880964802/lib/expresspigeon-ruby/messages.rb#L61-L87 |
5,441 | Birdie0/qna_maker | lib/qna_maker/endpoints/train_kb.rb | QnAMaker.Client.train_kb | def train_kb(feedback_records = [])
feedback_records = feedback_records.map do |record|
{ userId: record[0],
userQuestion: record[1],
kbQuestion: record[2],
kbAnswer: record[3] }
end
response = @http.patch(
"#{BASE_URL}/#{@knowledgebase_id}/train",
json: { feedbackRecords: feedback_records }
)
case response.code
when 204
nil
when 400
raise BadArgumentError, response.parse['error']['message'].join(' ')
when 401
raise UnauthorizedError, response.parse['error']['message']
when 403
raise ForbiddenError, response.parse['error']['message']
when 404
raise NotFoundError, response.parse['error']['message']
when 408
raise OperationTimeOutError, response.parse['error']['message']
when 429
raise RateLimitExceededError, response.parse['error']['message']
else
raise UnknownError, "Oh no! (#{response.code})"
end
end | ruby | def train_kb(feedback_records = [])
feedback_records = feedback_records.map do |record|
{ userId: record[0],
userQuestion: record[1],
kbQuestion: record[2],
kbAnswer: record[3] }
end
response = @http.patch(
"#{BASE_URL}/#{@knowledgebase_id}/train",
json: { feedbackRecords: feedback_records }
)
case response.code
when 204
nil
when 400
raise BadArgumentError, response.parse['error']['message'].join(' ')
when 401
raise UnauthorizedError, response.parse['error']['message']
when 403
raise ForbiddenError, response.parse['error']['message']
when 404
raise NotFoundError, response.parse['error']['message']
when 408
raise OperationTimeOutError, response.parse['error']['message']
when 429
raise RateLimitExceededError, response.parse['error']['message']
else
raise UnknownError, "Oh no! (#{response.code})"
end
end | [
"def",
"train_kb",
"(",
"feedback_records",
"=",
"[",
"]",
")",
"feedback_records",
"=",
"feedback_records",
".",
"map",
"do",
"|",
"record",
"|",
"{",
"userId",
":",
"record",
"[",
"0",
"]",
",",
"userQuestion",
":",
"record",
"[",
"1",
"]",
",",
"kbQuestion",
":",
"record",
"[",
"2",
"]",
",",
"kbAnswer",
":",
"record",
"[",
"3",
"]",
"}",
"end",
"response",
"=",
"@http",
".",
"patch",
"(",
"\"#{BASE_URL}/#{@knowledgebase_id}/train\"",
",",
"json",
":",
"{",
"feedbackRecords",
":",
"feedback_records",
"}",
")",
"case",
"response",
".",
"code",
"when",
"204",
"nil",
"when",
"400",
"raise",
"BadArgumentError",
",",
"response",
".",
"parse",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
".",
"join",
"(",
"' '",
")",
"when",
"401",
"raise",
"UnauthorizedError",
",",
"response",
".",
"parse",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"when",
"403",
"raise",
"ForbiddenError",
",",
"response",
".",
"parse",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"when",
"404",
"raise",
"NotFoundError",
",",
"response",
".",
"parse",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"when",
"408",
"raise",
"OperationTimeOutError",
",",
"response",
".",
"parse",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"when",
"429",
"raise",
"RateLimitExceededError",
",",
"response",
".",
"parse",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"else",
"raise",
"UnknownError",
",",
"\"Oh no! (#{response.code})\"",
"end",
"end"
] | The developer of the knowledge base service can use this API to submit
user feedback for tuning question-answer matching. QnA Maker uses active
learning to learn from the user utterances that come on a published
Knowledge base service.
@param [Array<Array(String, String, String, String)>] feedback_records
\[user_id, user_question, kb_question, kb_answer]
@return [nil] on success | [
"The",
"developer",
"of",
"the",
"knowledge",
"base",
"service",
"can",
"use",
"this",
"API",
"to",
"submit",
"user",
"feedback",
"for",
"tuning",
"question",
"-",
"answer",
"matching",
".",
"QnA",
"Maker",
"uses",
"active",
"learning",
"to",
"learn",
"from",
"the",
"user",
"utterances",
"that",
"come",
"on",
"a",
"published",
"Knowledge",
"base",
"service",
"."
] | 5ac204ede100355352438b8ff4fe30ad84d9257b | https://github.com/Birdie0/qna_maker/blob/5ac204ede100355352438b8ff4fe30ad84d9257b/lib/qna_maker/endpoints/train_kb.rb#L14-L44 |
5,442 | sawaken/tsparser | lib/definition/arib_time.rb | TSparser.AribTime.convert_mjd_to_date | def convert_mjd_to_date(mjd)
y_ = ((mjd - 15078.2) / 365.25).to_i
m_ = ((mjd - 14956.1 - (y_ * 365.25).to_i) / 30.6001).to_i
d = mjd - 14956 - (y_ * 365.25).to_i - (m_ * 30.6001).to_i
k = (m_ == 14 || m_ == 15) ? 1 : 0
y = y_ + k
m = m_ - 1 - k * 12
return Date.new(1900 + y, m, d)
end | ruby | def convert_mjd_to_date(mjd)
y_ = ((mjd - 15078.2) / 365.25).to_i
m_ = ((mjd - 14956.1 - (y_ * 365.25).to_i) / 30.6001).to_i
d = mjd - 14956 - (y_ * 365.25).to_i - (m_ * 30.6001).to_i
k = (m_ == 14 || m_ == 15) ? 1 : 0
y = y_ + k
m = m_ - 1 - k * 12
return Date.new(1900 + y, m, d)
end | [
"def",
"convert_mjd_to_date",
"(",
"mjd",
")",
"y_",
"=",
"(",
"(",
"mjd",
"-",
"15078.2",
")",
"/",
"365.25",
")",
".",
"to_i",
"m_",
"=",
"(",
"(",
"mjd",
"-",
"14956.1",
"-",
"(",
"y_",
"*",
"365.25",
")",
".",
"to_i",
")",
"/",
"30.6001",
")",
".",
"to_i",
"d",
"=",
"mjd",
"-",
"14956",
"-",
"(",
"y_",
"*",
"365.25",
")",
".",
"to_i",
"-",
"(",
"m_",
"*",
"30.6001",
")",
".",
"to_i",
"k",
"=",
"(",
"m_",
"==",
"14",
"||",
"m_",
"==",
"15",
")",
"?",
"1",
":",
"0",
"y",
"=",
"y_",
"+",
"k",
"m",
"=",
"m_",
"-",
"1",
"-",
"k",
"*",
"12",
"return",
"Date",
".",
"new",
"(",
"1900",
"+",
"y",
",",
"m",
",",
"d",
")",
"end"
] | ARIB STD-B10 2, appendix-C | [
"ARIB",
"STD",
"-",
"B10",
"2",
"appendix",
"-",
"C"
] | 069500619eb12528782761356c75e444c328c4e1 | https://github.com/sawaken/tsparser/blob/069500619eb12528782761356c75e444c328c4e1/lib/definition/arib_time.rb#L19-L27 |
5,443 | snusnu/substation | lib/substation/chain.rb | Substation.Chain.call | def call(request)
reduce(request) { |result, processor|
begin
response = processor.call(result)
return response unless processor.success?(response)
processor.result(response)
rescue => exception
return on_exception(request, result.data, exception)
end
}
end | ruby | def call(request)
reduce(request) { |result, processor|
begin
response = processor.call(result)
return response unless processor.success?(response)
processor.result(response)
rescue => exception
return on_exception(request, result.data, exception)
end
}
end | [
"def",
"call",
"(",
"request",
")",
"reduce",
"(",
"request",
")",
"{",
"|",
"result",
",",
"processor",
"|",
"begin",
"response",
"=",
"processor",
".",
"call",
"(",
"result",
")",
"return",
"response",
"unless",
"processor",
".",
"success?",
"(",
"response",
")",
"processor",
".",
"result",
"(",
"response",
")",
"rescue",
"=>",
"exception",
"return",
"on_exception",
"(",
"request",
",",
"result",
".",
"data",
",",
"exception",
")",
"end",
"}",
"end"
] | Call the chain
Invokes all processors and returns either the first
{Response::Failure} that it encounters, or if all
goes well, the {Response::Success} returned from
the last processor.
@example
module App
SOME_ACTION = Substation::Chain.new [
Validator.new(MY_VALIDATOR),
Pivot.new(Actions::SOME_ACTION),
Presenter.new(Presenters::SomePresenter)
]
env = Object.new # your env would obviously differ
input = { 'name' => 'John' }
request = Substation::Request.new(env, input)
response = SOME_ACTION.call(request)
if response.success?
response.output # => the output wrapped in a presenter
else
response.output # => if validation, pivot or presenter failed
end
end
@param [Request] request
the request to handle
@return [Response::Success]
the response returned from the last processor
@return [Response::Failure]
the response returned from the failing processor's failure chain
@return [Response::Exception]
the response returned from invoking the {#exception_chain}
@api public | [
"Call",
"the",
"chain"
] | fabf062a3640f5e82dae68597f0709b63f6b9027 | https://github.com/snusnu/substation/blob/fabf062a3640f5e82dae68597f0709b63f6b9027/lib/substation/chain.rb#L137-L147 |
5,444 | snusnu/substation | lib/substation/chain.rb | Substation.Chain.on_exception | def on_exception(state, data, exception)
response = self.class.exception_response(state, data, exception)
exception_chain.call(response)
end | ruby | def on_exception(state, data, exception)
response = self.class.exception_response(state, data, exception)
exception_chain.call(response)
end | [
"def",
"on_exception",
"(",
"state",
",",
"data",
",",
"exception",
")",
"response",
"=",
"self",
".",
"class",
".",
"exception_response",
"(",
"state",
",",
"data",
",",
"exception",
")",
"exception_chain",
".",
"call",
"(",
"response",
")",
"end"
] | Call the failure chain in case of an uncaught exception
@param [Request] request
the initial request passed into the chain
@param [Object] data
the processed data available when the exception was raised
@param [Class<StandardError>] exception
the exception instance that was raised
@return [Response::Exception]
@api private | [
"Call",
"the",
"failure",
"chain",
"in",
"case",
"of",
"an",
"uncaught",
"exception"
] | fabf062a3640f5e82dae68597f0709b63f6b9027 | https://github.com/snusnu/substation/blob/fabf062a3640f5e82dae68597f0709b63f6b9027/lib/substation/chain.rb#L165-L168 |
5,445 | mikerodrigues/onkyo_eiscp_ruby | lib/eiscp/receiver.rb | EISCP.Receiver.update_state | def update_state
Thread.new do
Dictionary.commands.each do |zone, commands|
Dictionary.commands[zone].each do |command, info|
info[:values].each do |value, _|
if value == 'QSTN'
send(Parser.parse(command + "QSTN"))
# If we send any faster we risk making the stereo drop replies.
# A dropped reply is not necessarily indicative of the
# receiver's failure to receive the command and change state
# accordingly. In this case, we're only making queries, so we do
# want to capture every reply.
sleep DEFAULT_TIMEOUT
end
end
end
end
end
end | ruby | def update_state
Thread.new do
Dictionary.commands.each do |zone, commands|
Dictionary.commands[zone].each do |command, info|
info[:values].each do |value, _|
if value == 'QSTN'
send(Parser.parse(command + "QSTN"))
# If we send any faster we risk making the stereo drop replies.
# A dropped reply is not necessarily indicative of the
# receiver's failure to receive the command and change state
# accordingly. In this case, we're only making queries, so we do
# want to capture every reply.
sleep DEFAULT_TIMEOUT
end
end
end
end
end
end | [
"def",
"update_state",
"Thread",
".",
"new",
"do",
"Dictionary",
".",
"commands",
".",
"each",
"do",
"|",
"zone",
",",
"commands",
"|",
"Dictionary",
".",
"commands",
"[",
"zone",
"]",
".",
"each",
"do",
"|",
"command",
",",
"info",
"|",
"info",
"[",
":values",
"]",
".",
"each",
"do",
"|",
"value",
",",
"_",
"|",
"if",
"value",
"==",
"'QSTN'",
"send",
"(",
"Parser",
".",
"parse",
"(",
"command",
"+",
"\"QSTN\"",
")",
")",
"# If we send any faster we risk making the stereo drop replies. ",
"# A dropped reply is not necessarily indicative of the",
"# receiver's failure to receive the command and change state",
"# accordingly. In this case, we're only making queries, so we do",
"# want to capture every reply.",
"sleep",
"DEFAULT_TIMEOUT",
"end",
"end",
"end",
"end",
"end",
"end"
] | Runs every command that supports the 'QSTN' value. This is a good way to
get the sate of the receiver after connecting. | [
"Runs",
"every",
"command",
"that",
"supports",
"the",
"QSTN",
"value",
".",
"This",
"is",
"a",
"good",
"way",
"to",
"get",
"the",
"sate",
"of",
"the",
"receiver",
"after",
"connecting",
"."
] | c51f8b22c74decd88b1d1a91e170885c4ec2a0b0 | https://github.com/mikerodrigues/onkyo_eiscp_ruby/blob/c51f8b22c74decd88b1d1a91e170885c4ec2a0b0/lib/eiscp/receiver.rb#L190-L208 |
5,446 | lautis/sweet_notifications | lib/sweet_notifications/controller_runtime.rb | SweetNotifications.ControllerRuntime.controller_runtime | def controller_runtime(name, log_subscriber)
runtime_attr = "#{name.to_s.underscore}_runtime".to_sym
Module.new do
extend ActiveSupport::Concern
attr_internal runtime_attr
protected
define_method :process_action do |action, *args|
log_subscriber.reset_runtime
super(action, *args)
end
define_method :cleanup_view_runtime do |&block|
runtime_before_render = log_subscriber.reset_runtime
send("#{runtime_attr}=",
(send(runtime_attr) || 0) + runtime_before_render)
runtime = super(&block)
runtime_after_render = log_subscriber.reset_runtime
send("#{runtime_attr}=", send(runtime_attr) + runtime_after_render)
runtime - runtime_after_render
end
define_method :append_info_to_payload do |payload|
super(payload)
runtime = (send(runtime_attr) || 0) + log_subscriber.reset_runtime
payload[runtime_attr] = runtime
end
const_set(:ClassMethods, Module.new do
define_method :log_process_action do |payload|
messages = super(payload)
runtime = payload[runtime_attr]
if runtime && runtime != 0
messages << format("#{name}: %.1fms", runtime.to_f)
end
messages
end
end)
end
end | ruby | def controller_runtime(name, log_subscriber)
runtime_attr = "#{name.to_s.underscore}_runtime".to_sym
Module.new do
extend ActiveSupport::Concern
attr_internal runtime_attr
protected
define_method :process_action do |action, *args|
log_subscriber.reset_runtime
super(action, *args)
end
define_method :cleanup_view_runtime do |&block|
runtime_before_render = log_subscriber.reset_runtime
send("#{runtime_attr}=",
(send(runtime_attr) || 0) + runtime_before_render)
runtime = super(&block)
runtime_after_render = log_subscriber.reset_runtime
send("#{runtime_attr}=", send(runtime_attr) + runtime_after_render)
runtime - runtime_after_render
end
define_method :append_info_to_payload do |payload|
super(payload)
runtime = (send(runtime_attr) || 0) + log_subscriber.reset_runtime
payload[runtime_attr] = runtime
end
const_set(:ClassMethods, Module.new do
define_method :log_process_action do |payload|
messages = super(payload)
runtime = payload[runtime_attr]
if runtime && runtime != 0
messages << format("#{name}: %.1fms", runtime.to_f)
end
messages
end
end)
end
end | [
"def",
"controller_runtime",
"(",
"name",
",",
"log_subscriber",
")",
"runtime_attr",
"=",
"\"#{name.to_s.underscore}_runtime\"",
".",
"to_sym",
"Module",
".",
"new",
"do",
"extend",
"ActiveSupport",
"::",
"Concern",
"attr_internal",
"runtime_attr",
"protected",
"define_method",
":process_action",
"do",
"|",
"action",
",",
"*",
"args",
"|",
"log_subscriber",
".",
"reset_runtime",
"super",
"(",
"action",
",",
"args",
")",
"end",
"define_method",
":cleanup_view_runtime",
"do",
"|",
"&",
"block",
"|",
"runtime_before_render",
"=",
"log_subscriber",
".",
"reset_runtime",
"send",
"(",
"\"#{runtime_attr}=\"",
",",
"(",
"send",
"(",
"runtime_attr",
")",
"||",
"0",
")",
"+",
"runtime_before_render",
")",
"runtime",
"=",
"super",
"(",
"block",
")",
"runtime_after_render",
"=",
"log_subscriber",
".",
"reset_runtime",
"send",
"(",
"\"#{runtime_attr}=\"",
",",
"send",
"(",
"runtime_attr",
")",
"+",
"runtime_after_render",
")",
"runtime",
"-",
"runtime_after_render",
"end",
"define_method",
":append_info_to_payload",
"do",
"|",
"payload",
"|",
"super",
"(",
"payload",
")",
"runtime",
"=",
"(",
"send",
"(",
"runtime_attr",
")",
"||",
"0",
")",
"+",
"log_subscriber",
".",
"reset_runtime",
"payload",
"[",
"runtime_attr",
"]",
"=",
"runtime",
"end",
"const_set",
"(",
":ClassMethods",
",",
"Module",
".",
"new",
"do",
"define_method",
":log_process_action",
"do",
"|",
"payload",
"|",
"messages",
"=",
"super",
"(",
"payload",
")",
"runtime",
"=",
"payload",
"[",
"runtime_attr",
"]",
"if",
"runtime",
"&&",
"runtime",
"!=",
"0",
"messages",
"<<",
"format",
"(",
"\"#{name}: %.1fms\"",
",",
"runtime",
".",
"to_f",
")",
"end",
"messages",
"end",
"end",
")",
"end",
"end"
] | Define a controller runtime logger for a LogSusbcriber
@param name [String] title for logging
@return [Module] controller runtime tracking mixin | [
"Define",
"a",
"controller",
"runtime",
"logger",
"for",
"a",
"LogSusbcriber"
] | fcd137a1b474d24e1bc86619d116fc32caba8c19 | https://github.com/lautis/sweet_notifications/blob/fcd137a1b474d24e1bc86619d116fc32caba8c19/lib/sweet_notifications/controller_runtime.rb#L11-L51 |
5,447 | ideonetwork/lato-core | lib/lato_core/interfaces/apihelpers.rb | LatoCore.Interface::Apihelpers.core__send_request_success | def core__send_request_success(payload)
response = { result: true, error_message: nil }
response[:payload] = payload if payload
render json: response
end | ruby | def core__send_request_success(payload)
response = { result: true, error_message: nil }
response[:payload] = payload if payload
render json: response
end | [
"def",
"core__send_request_success",
"(",
"payload",
")",
"response",
"=",
"{",
"result",
":",
"true",
",",
"error_message",
":",
"nil",
"}",
"response",
"[",
":payload",
"]",
"=",
"payload",
"if",
"payload",
"render",
"json",
":",
"response",
"end"
] | This function render a normal success response with a custom payload. | [
"This",
"function",
"render",
"a",
"normal",
"success",
"response",
"with",
"a",
"custom",
"payload",
"."
] | c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c | https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/apihelpers.rb#L8-L12 |
5,448 | ideonetwork/lato-core | lib/lato_core/interfaces/apihelpers.rb | LatoCore.Interface::Apihelpers.core__send_request_fail | def core__send_request_fail(error, payload: nil)
response = { result: false, error_message: error }
response[:payload] = payload if payload
render json: response
end | ruby | def core__send_request_fail(error, payload: nil)
response = { result: false, error_message: error }
response[:payload] = payload if payload
render json: response
end | [
"def",
"core__send_request_fail",
"(",
"error",
",",
"payload",
":",
"nil",
")",
"response",
"=",
"{",
"result",
":",
"false",
",",
"error_message",
":",
"error",
"}",
"response",
"[",
":payload",
"]",
"=",
"payload",
"if",
"payload",
"render",
"json",
":",
"response",
"end"
] | This function render an error message with a possible custom payload. | [
"This",
"function",
"render",
"an",
"error",
"message",
"with",
"a",
"possible",
"custom",
"payload",
"."
] | c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c | https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/apihelpers.rb#L15-L19 |
5,449 | evgenyneu/siba | lib/siba/siba_file.rb | Siba.SibaFile.shell_ok? | def shell_ok?(command)
# Using Open3 instead of `` or system("cmd") in order to hide stderr output
sout, status = Open3.capture2e command
return status.to_i == 0
rescue
return false
end | ruby | def shell_ok?(command)
# Using Open3 instead of `` or system("cmd") in order to hide stderr output
sout, status = Open3.capture2e command
return status.to_i == 0
rescue
return false
end | [
"def",
"shell_ok?",
"(",
"command",
")",
"# Using Open3 instead of `` or system(\"cmd\") in order to hide stderr output",
"sout",
",",
"status",
"=",
"Open3",
".",
"capture2e",
"command",
"return",
"status",
".",
"to_i",
"==",
"0",
"rescue",
"return",
"false",
"end"
] | Runs the shell command.
Works the same way as Kernel.system method but without showing the output.
Returns true if it was successfull. | [
"Runs",
"the",
"shell",
"command",
".",
"Works",
"the",
"same",
"way",
"as",
"Kernel",
".",
"system",
"method",
"but",
"without",
"showing",
"the",
"output",
".",
"Returns",
"true",
"if",
"it",
"was",
"successfull",
"."
] | 04cd0eca8222092c14ce4a662b48f5f113ffe6df | https://github.com/evgenyneu/siba/blob/04cd0eca8222092c14ce4a662b48f5f113ffe6df/lib/siba/siba_file.rb#L65-L71 |
5,450 | reggieb/Disclaimer | app/models/disclaimer/document.rb | Disclaimer.Document.modify_via_segment_holder_acts_as_list_method | def modify_via_segment_holder_acts_as_list_method(method, segment)
segment_holder = segment_holder_for(segment)
raise segment_not_associated_message(method, segment) unless segment_holder
segment_holder.send(method)
end | ruby | def modify_via_segment_holder_acts_as_list_method(method, segment)
segment_holder = segment_holder_for(segment)
raise segment_not_associated_message(method, segment) unless segment_holder
segment_holder.send(method)
end | [
"def",
"modify_via_segment_holder_acts_as_list_method",
"(",
"method",
",",
"segment",
")",
"segment_holder",
"=",
"segment_holder_for",
"(",
"segment",
")",
"raise",
"segment_not_associated_message",
"(",
"method",
",",
"segment",
")",
"unless",
"segment_holder",
"segment_holder",
".",
"send",
"(",
"method",
")",
"end"
] | This method, together with method missing, is used to allow segments
to be ordered within a document. It allows an acts_as_list method to be
passed to the segment_holder holding a segment, so as to alter its position.
For example:
document.move_to_top document.segments.last
will move the last segment so that it becomes the first within
document.segments.
The syntax is:
document.<acts_as_list_method> <the_segment_to_be_moved>
The segment must already belong to the document | [
"This",
"method",
"together",
"with",
"method",
"missing",
"is",
"used",
"to",
"allow",
"segments",
"to",
"be",
"ordered",
"within",
"a",
"document",
".",
"It",
"allows",
"an",
"acts_as_list",
"method",
"to",
"be",
"passed",
"to",
"the",
"segment_holder",
"holding",
"a",
"segment",
"so",
"as",
"to",
"alter",
"its",
"position",
"."
] | 591511cfb41c355b22ce13898298688e069cf2ce | https://github.com/reggieb/Disclaimer/blob/591511cfb41c355b22ce13898298688e069cf2ce/app/models/disclaimer/document.rb#L55-L59 |
5,451 | leshill/mongodoc | lib/mongo_doc/document.rb | MongoDoc.Document.update | def update(attrs, safe = false)
self.attributes = attrs
if new_record?
_root.send(:_save, safe) if _root
_save(safe)
else
_update_attributes(converted_attributes(attrs), safe)
end
end | ruby | def update(attrs, safe = false)
self.attributes = attrs
if new_record?
_root.send(:_save, safe) if _root
_save(safe)
else
_update_attributes(converted_attributes(attrs), safe)
end
end | [
"def",
"update",
"(",
"attrs",
",",
"safe",
"=",
"false",
")",
"self",
".",
"attributes",
"=",
"attrs",
"if",
"new_record?",
"_root",
".",
"send",
"(",
":_save",
",",
"safe",
")",
"if",
"_root",
"_save",
"(",
"safe",
")",
"else",
"_update_attributes",
"(",
"converted_attributes",
"(",
"attrs",
")",
",",
"safe",
")",
"end",
"end"
] | Update without checking validations. The +Document+ will be saved without validations if it is a new record. | [
"Update",
"without",
"checking",
"validations",
".",
"The",
"+",
"Document",
"+",
"will",
"be",
"saved",
"without",
"validations",
"if",
"it",
"is",
"a",
"new",
"record",
"."
] | fb2a4ec456d4c4ae1eb92e117dc73f55951fc3b4 | https://github.com/leshill/mongodoc/blob/fb2a4ec456d4c4ae1eb92e117dc73f55951fc3b4/lib/mongo_doc/document.rb#L120-L128 |
5,452 | Birdie0/qna_maker | lib/qna_maker/endpoints/download_kb.rb | QnAMaker.Client.download_kb | def download_kb
response = @http.get(
"#{BASE_URL}/#{@knowledgebase_id}"
)
case response.code
when 200
response.parse
when 400
raise BadArgumentError, response.parse['error']['message'].join(' ')
when 401
raise UnauthorizedError, response.parse['error']['message']
when 403
raise ForbiddenError, response.parse['error']['message'].join(' ')
when 404
raise NotFoundError, response.parse['error']['message'].join(' ')
else
raise UnknownError, "Oh no! (#{response.code})"
end
end | ruby | def download_kb
response = @http.get(
"#{BASE_URL}/#{@knowledgebase_id}"
)
case response.code
when 200
response.parse
when 400
raise BadArgumentError, response.parse['error']['message'].join(' ')
when 401
raise UnauthorizedError, response.parse['error']['message']
when 403
raise ForbiddenError, response.parse['error']['message'].join(' ')
when 404
raise NotFoundError, response.parse['error']['message'].join(' ')
else
raise UnknownError, "Oh no! (#{response.code})"
end
end | [
"def",
"download_kb",
"response",
"=",
"@http",
".",
"get",
"(",
"\"#{BASE_URL}/#{@knowledgebase_id}\"",
")",
"case",
"response",
".",
"code",
"when",
"200",
"response",
".",
"parse",
"when",
"400",
"raise",
"BadArgumentError",
",",
"response",
".",
"parse",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
".",
"join",
"(",
"' '",
")",
"when",
"401",
"raise",
"UnauthorizedError",
",",
"response",
".",
"parse",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"when",
"403",
"raise",
"ForbiddenError",
",",
"response",
".",
"parse",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
".",
"join",
"(",
"' '",
")",
"when",
"404",
"raise",
"NotFoundError",
",",
"response",
".",
"parse",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
".",
"join",
"(",
"' '",
")",
"else",
"raise",
"UnknownError",
",",
"\"Oh no! (#{response.code})\"",
"end",
"end"
] | Downloads all the data associated with the specified knowledge base
@return [String] SAS url (valid for 30 mins) to tsv file in blob storage | [
"Downloads",
"all",
"the",
"data",
"associated",
"with",
"the",
"specified",
"knowledge",
"base"
] | 5ac204ede100355352438b8ff4fe30ad84d9257b | https://github.com/Birdie0/qna_maker/blob/5ac204ede100355352438b8ff4fe30ad84d9257b/lib/qna_maker/endpoints/download_kb.rb#L8-L27 |
5,453 | webzakimbo/bcome-kontrol | lib/objects/orchestration/interactive_terraform.rb | Bcome::Orchestration.InteractiveTerraform.form_var_string | def form_var_string
terraform_vars = terraform_metadata
ec2_credentials = @node.network_driver.raw_fog_credentials
cleaned_data = terraform_vars.select{|k,v|
!v.is_a?(Hash) && !v.is_a?(Array)
} # we can't yet handle nested terraform metadata on the command line so no arrays or hashes
all_vars = cleaned_data.merge({
:access_key => ec2_credentials["aws_access_key_id"],
:secret_key => ec2_credentials["aws_secret_access_key"]
})
all_vars.collect{|key, value| "-var #{key}=\"#{value}\""}.join("\s")
end | ruby | def form_var_string
terraform_vars = terraform_metadata
ec2_credentials = @node.network_driver.raw_fog_credentials
cleaned_data = terraform_vars.select{|k,v|
!v.is_a?(Hash) && !v.is_a?(Array)
} # we can't yet handle nested terraform metadata on the command line so no arrays or hashes
all_vars = cleaned_data.merge({
:access_key => ec2_credentials["aws_access_key_id"],
:secret_key => ec2_credentials["aws_secret_access_key"]
})
all_vars.collect{|key, value| "-var #{key}=\"#{value}\""}.join("\s")
end | [
"def",
"form_var_string",
"terraform_vars",
"=",
"terraform_metadata",
"ec2_credentials",
"=",
"@node",
".",
"network_driver",
".",
"raw_fog_credentials",
"cleaned_data",
"=",
"terraform_vars",
".",
"select",
"{",
"|",
"k",
",",
"v",
"|",
"!",
"v",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"!",
"v",
".",
"is_a?",
"(",
"Array",
")",
"}",
"# we can't yet handle nested terraform metadata on the command line so no arrays or hashes",
"all_vars",
"=",
"cleaned_data",
".",
"merge",
"(",
"{",
":access_key",
"=>",
"ec2_credentials",
"[",
"\"aws_access_key_id\"",
"]",
",",
":secret_key",
"=>",
"ec2_credentials",
"[",
"\"aws_secret_access_key\"",
"]",
"}",
")",
"all_vars",
".",
"collect",
"{",
"|",
"key",
",",
"value",
"|",
"\"-var #{key}=\\\"#{value}\\\"\"",
"}",
".",
"join",
"(",
"\"\\s\"",
")",
"end"
] | Get the terraform variables for this stack, and merge in with our EC2 access keys | [
"Get",
"the",
"terraform",
"variables",
"for",
"this",
"stack",
"and",
"merge",
"in",
"with",
"our",
"EC2",
"access",
"keys"
] | 59129cc7c8bb6c39e457abed783aa23c1d60cd05 | https://github.com/webzakimbo/bcome-kontrol/blob/59129cc7c8bb6c39e457abed783aa23c1d60cd05/lib/objects/orchestration/interactive_terraform.rb#L49-L63 |
5,454 | ManageIQ/polisher | lib/polisher/gem/files.rb | Polisher.GemFiles.has_file_satisfied_by? | def has_file_satisfied_by?(spec_file)
file_paths.any? { |gem_file| RPM::Spec.file_satisfies?(spec_file, gem_file) }
end | ruby | def has_file_satisfied_by?(spec_file)
file_paths.any? { |gem_file| RPM::Spec.file_satisfies?(spec_file, gem_file) }
end | [
"def",
"has_file_satisfied_by?",
"(",
"spec_file",
")",
"file_paths",
".",
"any?",
"{",
"|",
"gem_file",
"|",
"RPM",
"::",
"Spec",
".",
"file_satisfies?",
"(",
"spec_file",
",",
"gem_file",
")",
"}",
"end"
] | module ClassMethods
Return bool indicating if spec file satisfies any file in gem | [
"module",
"ClassMethods",
"Return",
"bool",
"indicating",
"if",
"spec",
"file",
"satisfies",
"any",
"file",
"in",
"gem"
] | 8c19023c72573999c9dc53ec2e2a3eef11a9531e | https://github.com/ManageIQ/polisher/blob/8c19023c72573999c9dc53ec2e2a3eef11a9531e/lib/polisher/gem/files.rb#L63-L65 |
5,455 | ManageIQ/polisher | lib/polisher/gem/files.rb | Polisher.GemFiles.unpack | def unpack(&bl)
dir = nil
pkg = ::Gem::Installer.new gem_path, :unpack => true
if bl
Dir.mktmpdir do |tmpdir|
pkg.unpack tmpdir
bl.call tmpdir
end
else
dir = Dir.mktmpdir
pkg.unpack dir
end
dir
end | ruby | def unpack(&bl)
dir = nil
pkg = ::Gem::Installer.new gem_path, :unpack => true
if bl
Dir.mktmpdir do |tmpdir|
pkg.unpack tmpdir
bl.call tmpdir
end
else
dir = Dir.mktmpdir
pkg.unpack dir
end
dir
end | [
"def",
"unpack",
"(",
"&",
"bl",
")",
"dir",
"=",
"nil",
"pkg",
"=",
"::",
"Gem",
"::",
"Installer",
".",
"new",
"gem_path",
",",
":unpack",
"=>",
"true",
"if",
"bl",
"Dir",
".",
"mktmpdir",
"do",
"|",
"tmpdir",
"|",
"pkg",
".",
"unpack",
"tmpdir",
"bl",
".",
"call",
"tmpdir",
"end",
"else",
"dir",
"=",
"Dir",
".",
"mktmpdir",
"pkg",
".",
"unpack",
"dir",
"end",
"dir",
"end"
] | Unpack files & return unpacked directory
If block is specified, it will be invoked
with directory after which directory will be removed | [
"Unpack",
"files",
"&",
"return",
"unpacked",
"directory"
] | 8c19023c72573999c9dc53ec2e2a3eef11a9531e | https://github.com/ManageIQ/polisher/blob/8c19023c72573999c9dc53ec2e2a3eef11a9531e/lib/polisher/gem/files.rb#L71-L86 |
5,456 | ManageIQ/polisher | lib/polisher/gem/files.rb | Polisher.GemFiles.each_file | def each_file(&bl)
unpack do |dir|
Pathname.new(dir).find do |path|
next if path.to_s == dir.to_s
pathstr = path.to_s.gsub("#{dir}/", '')
bl.call pathstr unless pathstr.blank?
end
end
end | ruby | def each_file(&bl)
unpack do |dir|
Pathname.new(dir).find do |path|
next if path.to_s == dir.to_s
pathstr = path.to_s.gsub("#{dir}/", '')
bl.call pathstr unless pathstr.blank?
end
end
end | [
"def",
"each_file",
"(",
"&",
"bl",
")",
"unpack",
"do",
"|",
"dir",
"|",
"Pathname",
".",
"new",
"(",
"dir",
")",
".",
"find",
"do",
"|",
"path",
"|",
"next",
"if",
"path",
".",
"to_s",
"==",
"dir",
".",
"to_s",
"pathstr",
"=",
"path",
".",
"to_s",
".",
"gsub",
"(",
"\"#{dir}/\"",
",",
"''",
")",
"bl",
".",
"call",
"pathstr",
"unless",
"pathstr",
".",
"blank?",
"end",
"end",
"end"
] | Iterate over each file in gem invoking block with path | [
"Iterate",
"over",
"each",
"file",
"in",
"gem",
"invoking",
"block",
"with",
"path"
] | 8c19023c72573999c9dc53ec2e2a3eef11a9531e | https://github.com/ManageIQ/polisher/blob/8c19023c72573999c9dc53ec2e2a3eef11a9531e/lib/polisher/gem/files.rb#L89-L97 |
5,457 | razor-x/config_curator | lib/config_curator/units/component.rb | ConfigCurator.Component.install_component | def install_component
if (backend != :stdlib && command?('rsync')) || backend == :rsync
FileUtils.mkdir_p destination_path
cmd = [command?('rsync'), '-rtc', '--del', '--links', "#{source_path}/", destination_path]
logger.debug { "Running command: #{cmd.join ' '}" }
system(*cmd)
else
FileUtils.remove_entry_secure destination_path if Dir.exist? destination_path
FileUtils.mkdir_p destination_path
FileUtils.cp_r "#{source_path}/.", destination_path, preserve: true
end
end | ruby | def install_component
if (backend != :stdlib && command?('rsync')) || backend == :rsync
FileUtils.mkdir_p destination_path
cmd = [command?('rsync'), '-rtc', '--del', '--links', "#{source_path}/", destination_path]
logger.debug { "Running command: #{cmd.join ' '}" }
system(*cmd)
else
FileUtils.remove_entry_secure destination_path if Dir.exist? destination_path
FileUtils.mkdir_p destination_path
FileUtils.cp_r "#{source_path}/.", destination_path, preserve: true
end
end | [
"def",
"install_component",
"if",
"(",
"backend",
"!=",
":stdlib",
"&&",
"command?",
"(",
"'rsync'",
")",
")",
"||",
"backend",
"==",
":rsync",
"FileUtils",
".",
"mkdir_p",
"destination_path",
"cmd",
"=",
"[",
"command?",
"(",
"'rsync'",
")",
",",
"'-rtc'",
",",
"'--del'",
",",
"'--links'",
",",
"\"#{source_path}/\"",
",",
"destination_path",
"]",
"logger",
".",
"debug",
"{",
"\"Running command: #{cmd.join ' '}\"",
"}",
"system",
"(",
"cmd",
")",
"else",
"FileUtils",
".",
"remove_entry_secure",
"destination_path",
"if",
"Dir",
".",
"exist?",
"destination_path",
"FileUtils",
".",
"mkdir_p",
"destination_path",
"FileUtils",
".",
"cp_r",
"\"#{source_path}/.\"",
",",
"destination_path",
",",
"preserve",
":",
"true",
"end",
"end"
] | Recursively creates the necessary directories and installs the component.
Any files in the install directory not in the source directory are removed.
Use rsync if available. | [
"Recursively",
"creates",
"the",
"necessary",
"directories",
"and",
"installs",
"the",
"component",
".",
"Any",
"files",
"in",
"the",
"install",
"directory",
"not",
"in",
"the",
"source",
"directory",
"are",
"removed",
".",
"Use",
"rsync",
"if",
"available",
"."
] | b0c0742ba0c36acf66de3eafd23a7d17b210036b | https://github.com/razor-x/config_curator/blob/b0c0742ba0c36acf66de3eafd23a7d17b210036b/lib/config_curator/units/component.rb#L49-L60 |
5,458 | razor-x/config_curator | lib/config_curator/units/component.rb | ConfigCurator.Component.set_mode | def set_mode
chmod = command? 'chmod'
find = command? 'find'
return unless chmod && find
{fmode: 'f', dmode: 'd'}.each do |k, v|
next if send(k).nil?
cmd = [find, destination_path, '-type', v, '-exec']
cmd.concat [chmod, send(k).to_s(8), '{}', '+']
logger.debug { "Running command: #{cmd.join ' '}" }
system(*cmd)
end
end | ruby | def set_mode
chmod = command? 'chmod'
find = command? 'find'
return unless chmod && find
{fmode: 'f', dmode: 'd'}.each do |k, v|
next if send(k).nil?
cmd = [find, destination_path, '-type', v, '-exec']
cmd.concat [chmod, send(k).to_s(8), '{}', '+']
logger.debug { "Running command: #{cmd.join ' '}" }
system(*cmd)
end
end | [
"def",
"set_mode",
"chmod",
"=",
"command?",
"'chmod'",
"find",
"=",
"command?",
"'find'",
"return",
"unless",
"chmod",
"&&",
"find",
"{",
"fmode",
":",
"'f'",
",",
"dmode",
":",
"'d'",
"}",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"next",
"if",
"send",
"(",
"k",
")",
".",
"nil?",
"cmd",
"=",
"[",
"find",
",",
"destination_path",
",",
"'-type'",
",",
"v",
",",
"'-exec'",
"]",
"cmd",
".",
"concat",
"[",
"chmod",
",",
"send",
"(",
"k",
")",
".",
"to_s",
"(",
"8",
")",
",",
"'{}'",
",",
"'+'",
"]",
"logger",
".",
"debug",
"{",
"\"Running command: #{cmd.join ' '}\"",
"}",
"system",
"(",
"cmd",
")",
"end",
"end"
] | Recursively sets file mode.
@todo Make this more platform independent. | [
"Recursively",
"sets",
"file",
"mode",
"."
] | b0c0742ba0c36acf66de3eafd23a7d17b210036b | https://github.com/razor-x/config_curator/blob/b0c0742ba0c36acf66de3eafd23a7d17b210036b/lib/config_curator/units/component.rb#L64-L77 |
5,459 | razor-x/config_curator | lib/config_curator/units/component.rb | ConfigCurator.Component.set_owner | def set_owner
return unless owner || group
chown = command? 'chown'
return unless chown
cmd = [chown, '-R', "#{owner}:#{group}", destination_path]
logger.debug { "Running command: #{cmd.join ' '}" }
system(*cmd)
end | ruby | def set_owner
return unless owner || group
chown = command? 'chown'
return unless chown
cmd = [chown, '-R', "#{owner}:#{group}", destination_path]
logger.debug { "Running command: #{cmd.join ' '}" }
system(*cmd)
end | [
"def",
"set_owner",
"return",
"unless",
"owner",
"||",
"group",
"chown",
"=",
"command?",
"'chown'",
"return",
"unless",
"chown",
"cmd",
"=",
"[",
"chown",
",",
"'-R'",
",",
"\"#{owner}:#{group}\"",
",",
"destination_path",
"]",
"logger",
".",
"debug",
"{",
"\"Running command: #{cmd.join ' '}\"",
"}",
"system",
"(",
"cmd",
")",
"end"
] | Recursively sets file owner and group.
@todo Make this more platform independent. | [
"Recursively",
"sets",
"file",
"owner",
"and",
"group",
"."
] | b0c0742ba0c36acf66de3eafd23a7d17b210036b | https://github.com/razor-x/config_curator/blob/b0c0742ba0c36acf66de3eafd23a7d17b210036b/lib/config_curator/units/component.rb#L81-L90 |
5,460 | wizardwerdna/pokerstats | lib/pokerstats/hand_statistics.rb | Pokerstats.HandStatistics.calculate_player_position | def calculate_player_position screen_name
@cached_player_position = {}
@player_hashes.sort!{|a,b| button_relative_seat(a) <=> button_relative_seat(b)}
@player_hashes = [@player_hashes.pop] + @player_hashes unless @player_hashes.first[:seat] == @button_player_index
@player_hashes.each_with_index{|player, index| player[:position] = index, @cached_player_position[player[:screen_name]] = index}
@cached_player_position[screen_name]
end | ruby | def calculate_player_position screen_name
@cached_player_position = {}
@player_hashes.sort!{|a,b| button_relative_seat(a) <=> button_relative_seat(b)}
@player_hashes = [@player_hashes.pop] + @player_hashes unless @player_hashes.first[:seat] == @button_player_index
@player_hashes.each_with_index{|player, index| player[:position] = index, @cached_player_position[player[:screen_name]] = index}
@cached_player_position[screen_name]
end | [
"def",
"calculate_player_position",
"screen_name",
"@cached_player_position",
"=",
"{",
"}",
"@player_hashes",
".",
"sort!",
"{",
"|",
"a",
",",
"b",
"|",
"button_relative_seat",
"(",
"a",
")",
"<=>",
"button_relative_seat",
"(",
"b",
")",
"}",
"@player_hashes",
"=",
"[",
"@player_hashes",
".",
"pop",
"]",
"+",
"@player_hashes",
"unless",
"@player_hashes",
".",
"first",
"[",
":seat",
"]",
"==",
"@button_player_index",
"@player_hashes",
".",
"each_with_index",
"{",
"|",
"player",
",",
"index",
"|",
"player",
"[",
":position",
"]",
"=",
"index",
",",
"@cached_player_position",
"[",
"player",
"[",
":screen_name",
"]",
"]",
"=",
"index",
"}",
"@cached_player_position",
"[",
"screen_name",
"]",
"end"
] | long computation is cached, which cache is cleared every time a new player is registered | [
"long",
"computation",
"is",
"cached",
"which",
"cache",
"is",
"cleared",
"every",
"time",
"a",
"new",
"player",
"is",
"registered"
] | 315a4db29630c586fb080d084fa17dcad9494a84 | https://github.com/wizardwerdna/pokerstats/blob/315a4db29630c586fb080d084fa17dcad9494a84/lib/pokerstats/hand_statistics.rb#L119-L125 |
5,461 | wizardwerdna/pokerstats | lib/pokerstats/hand_statistics.rb | Pokerstats.HandStatistics.betting_order? | def betting_order?(screen_name_first, screen_name_second)
if button?(screen_name_first)
false
elsif button?(screen_name_second)
true
else
position(screen_name_first) < position(screen_name_second)
end
end | ruby | def betting_order?(screen_name_first, screen_name_second)
if button?(screen_name_first)
false
elsif button?(screen_name_second)
true
else
position(screen_name_first) < position(screen_name_second)
end
end | [
"def",
"betting_order?",
"(",
"screen_name_first",
",",
"screen_name_second",
")",
"if",
"button?",
"(",
"screen_name_first",
")",
"false",
"elsif",
"button?",
"(",
"screen_name_second",
")",
"true",
"else",
"position",
"(",
"screen_name_first",
")",
"<",
"position",
"(",
"screen_name_second",
")",
"end",
"end"
] | player screen_name_first goes before player screen_name_second | [
"player",
"screen_name_first",
"goes",
"before",
"player",
"screen_name_second"
] | 315a4db29630c586fb080d084fa17dcad9494a84 | https://github.com/wizardwerdna/pokerstats/blob/315a4db29630c586fb080d084fa17dcad9494a84/lib/pokerstats/hand_statistics.rb#L132-L140 |
5,462 | bruce/paginator | lib/paginator/pager.rb | Paginator.Pager.page | def page(number)
number = (n = number.to_i) > 0 ? n : 1
Page.new(self, number, lambda {
offset = (number - 1) * @per_page
args = [offset]
args << @per_page if @select.arity == 2
@select.call(*args)
})
end | ruby | def page(number)
number = (n = number.to_i) > 0 ? n : 1
Page.new(self, number, lambda {
offset = (number - 1) * @per_page
args = [offset]
args << @per_page if @select.arity == 2
@select.call(*args)
})
end | [
"def",
"page",
"(",
"number",
")",
"number",
"=",
"(",
"n",
"=",
"number",
".",
"to_i",
")",
">",
"0",
"?",
"n",
":",
"1",
"Page",
".",
"new",
"(",
"self",
",",
"number",
",",
"lambda",
"{",
"offset",
"=",
"(",
"number",
"-",
"1",
")",
"*",
"@per_page",
"args",
"=",
"[",
"offset",
"]",
"args",
"<<",
"@per_page",
"if",
"@select",
".",
"arity",
"==",
"2",
"@select",
".",
"call",
"(",
"args",
")",
"}",
")",
"end"
] | Retrieve page object by number | [
"Retrieve",
"page",
"object",
"by",
"number"
] | 31f6f618674b4bb4d9e052e4b2f49865125ef413 | https://github.com/bruce/paginator/blob/31f6f618674b4bb4d9e052e4b2f49865125ef413/lib/paginator/pager.rb#L48-L56 |
5,463 | wordjelly/Auth | lib/auth/mailgun.rb | Auth.Mailgun.add_webhook_identifier_to_email | def add_webhook_identifier_to_email(email)
email.message.mailgun_variables = {}
email.message.mailgun_variables["webhook_identifier"] = BSON::ObjectId.new.to_s
email
end | ruby | def add_webhook_identifier_to_email(email)
email.message.mailgun_variables = {}
email.message.mailgun_variables["webhook_identifier"] = BSON::ObjectId.new.to_s
email
end | [
"def",
"add_webhook_identifier_to_email",
"(",
"email",
")",
"email",
".",
"message",
".",
"mailgun_variables",
"=",
"{",
"}",
"email",
".",
"message",
".",
"mailgun_variables",
"[",
"\"webhook_identifier\"",
"]",
"=",
"BSON",
"::",
"ObjectId",
".",
"new",
".",
"to_s",
"email",
"end"
] | returns the email after adding a webhook identifier variable. | [
"returns",
"the",
"email",
"after",
"adding",
"a",
"webhook",
"identifier",
"variable",
"."
] | e1b6697a13c845f57b3cc83bfb79059a09541f47 | https://github.com/wordjelly/Auth/blob/e1b6697a13c845f57b3cc83bfb79059a09541f47/lib/auth/mailgun.rb#L4-L8 |
5,464 | postmodern/deployml | lib/deployml/shell.rb | DeploYML.Shell.ruby | def ruby(program,*arguments)
command = [program, *arguments]
# assume that `.rb` scripts do not have a `#!/usr/bin/env ruby`
command.unshift('ruby') if program[-3,3] == '.rb'
# if the environment uses bundler, run all ruby commands via `bundle exec`
if (@environment && @environment.bundler)
command.unshift('bundle','exec')
end
run(*command)
end | ruby | def ruby(program,*arguments)
command = [program, *arguments]
# assume that `.rb` scripts do not have a `#!/usr/bin/env ruby`
command.unshift('ruby') if program[-3,3] == '.rb'
# if the environment uses bundler, run all ruby commands via `bundle exec`
if (@environment && @environment.bundler)
command.unshift('bundle','exec')
end
run(*command)
end | [
"def",
"ruby",
"(",
"program",
",",
"*",
"arguments",
")",
"command",
"=",
"[",
"program",
",",
"arguments",
"]",
"# assume that `.rb` scripts do not have a `#!/usr/bin/env ruby`",
"command",
".",
"unshift",
"(",
"'ruby'",
")",
"if",
"program",
"[",
"-",
"3",
",",
"3",
"]",
"==",
"'.rb'",
"# if the environment uses bundler, run all ruby commands via `bundle exec`",
"if",
"(",
"@environment",
"&&",
"@environment",
".",
"bundler",
")",
"command",
".",
"unshift",
"(",
"'bundle'",
",",
"'exec'",
")",
"end",
"run",
"(",
"command",
")",
"end"
] | Executes a Ruby program.
@param [Symbol, String] program
Name of the Ruby program to run.
@param [Array<String>] arguments
Additional arguments for the Ruby program.
@since 0.5.2 | [
"Executes",
"a",
"Ruby",
"program",
"."
] | 4369d4ea719e41f0dc3aa6496e6422ad476b0dda | https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/shell.rb#L80-L92 |
5,465 | postmodern/deployml | lib/deployml/shell.rb | DeploYML.Shell.shellescape | def shellescape(str)
# An empty argument will be skipped, so return empty quotes.
return "''" if str.empty?
str = str.dup
# Process as a single byte sequence because not all shell
# implementations are multibyte aware.
str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/n, "\\\\\\1")
# A LF cannot be escaped with a backslash because a backslash + LF
# combo is regarded as line continuation and simply ignored.
str.gsub!(/\n/, "'\n'")
return str
end | ruby | def shellescape(str)
# An empty argument will be skipped, so return empty quotes.
return "''" if str.empty?
str = str.dup
# Process as a single byte sequence because not all shell
# implementations are multibyte aware.
str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/n, "\\\\\\1")
# A LF cannot be escaped with a backslash because a backslash + LF
# combo is regarded as line continuation and simply ignored.
str.gsub!(/\n/, "'\n'")
return str
end | [
"def",
"shellescape",
"(",
"str",
")",
"# An empty argument will be skipped, so return empty quotes.",
"return",
"\"''\"",
"if",
"str",
".",
"empty?",
"str",
"=",
"str",
".",
"dup",
"# Process as a single byte sequence because not all shell",
"# implementations are multibyte aware.",
"str",
".",
"gsub!",
"(",
"/",
"\\-",
"\\/",
"\\n",
"/n",
",",
"\"\\\\\\\\\\\\1\"",
")",
"# A LF cannot be escaped with a backslash because a backslash + LF",
"# combo is regarded as line continuation and simply ignored.",
"str",
".",
"gsub!",
"(",
"/",
"\\n",
"/",
",",
"\"'\\n'\"",
")",
"return",
"str",
"end"
] | Escapes a string so that it can be safely used in a Bourne shell
command line.
Note that a resulted string should be used unquoted and is not
intended for use in double quotes nor in single quotes.
@param [String] str
The string to escape.
@return [String]
The shell-escaped string.
@example
open("| grep #{Shellwords.escape(pattern)} file") { |pipe|
# ...
}
@note Vendored from `shellwords.rb` line 72 from Ruby 1.9.2. | [
"Escapes",
"a",
"string",
"so",
"that",
"it",
"can",
"be",
"safely",
"used",
"in",
"a",
"Bourne",
"shell",
"command",
"line",
"."
] | 4369d4ea719e41f0dc3aa6496e6422ad476b0dda | https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/shell.rb#L141-L156 |
5,466 | postmodern/deployml | lib/deployml/shell.rb | DeploYML.Shell.rake_task | def rake_task(name,*arguments)
name = name.to_s
unless arguments.empty?
name += ('[' + arguments.join(',') + ']')
end
return name
end | ruby | def rake_task(name,*arguments)
name = name.to_s
unless arguments.empty?
name += ('[' + arguments.join(',') + ']')
end
return name
end | [
"def",
"rake_task",
"(",
"name",
",",
"*",
"arguments",
")",
"name",
"=",
"name",
".",
"to_s",
"unless",
"arguments",
".",
"empty?",
"name",
"+=",
"(",
"'['",
"+",
"arguments",
".",
"join",
"(",
"','",
")",
"+",
"']'",
")",
"end",
"return",
"name",
"end"
] | Builds a `rake` task name.
@param [String, Symbol] name
The name of the `rake` task.
@param [Array] arguments
Additional arguments to pass to the `rake` task.
@return [String]
The `rake` task name to be called. | [
"Builds",
"a",
"rake",
"task",
"name",
"."
] | 4369d4ea719e41f0dc3aa6496e6422ad476b0dda | https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/shell.rb#L170-L178 |
5,467 | sawaken/tsparser | lib/binary.rb | TSparser.Binary.read_byte_as_integer | def read_byte_as_integer(bytelen)
unless bit_pointer % 8 == 0
raise BinaryException.new("Bit pointer must be pointing start of byte. " +
"But now pointing #{bit_pointer}.")
end
if self.length - bit_pointer/8 < bytelen
raise BinaryException.new("Rest of self length(#{self.length - bit_pointer/8}byte) " +
"is shorter than specified byte length(#{bytelen}byte).")
end
response = 0
bytelen.times do |i|
response = response << 8
response += to_i(bit_pointer/8 + i)
end
bit_pointer_inc(bytelen * 8)
return response
end | ruby | def read_byte_as_integer(bytelen)
unless bit_pointer % 8 == 0
raise BinaryException.new("Bit pointer must be pointing start of byte. " +
"But now pointing #{bit_pointer}.")
end
if self.length - bit_pointer/8 < bytelen
raise BinaryException.new("Rest of self length(#{self.length - bit_pointer/8}byte) " +
"is shorter than specified byte length(#{bytelen}byte).")
end
response = 0
bytelen.times do |i|
response = response << 8
response += to_i(bit_pointer/8 + i)
end
bit_pointer_inc(bytelen * 8)
return response
end | [
"def",
"read_byte_as_integer",
"(",
"bytelen",
")",
"unless",
"bit_pointer",
"%",
"8",
"==",
"0",
"raise",
"BinaryException",
".",
"new",
"(",
"\"Bit pointer must be pointing start of byte. \"",
"+",
"\"But now pointing #{bit_pointer}.\"",
")",
"end",
"if",
"self",
".",
"length",
"-",
"bit_pointer",
"/",
"8",
"<",
"bytelen",
"raise",
"BinaryException",
".",
"new",
"(",
"\"Rest of self length(#{self.length - bit_pointer/8}byte) \"",
"+",
"\"is shorter than specified byte length(#{bytelen}byte).\"",
")",
"end",
"response",
"=",
"0",
"bytelen",
".",
"times",
"do",
"|",
"i",
"|",
"response",
"=",
"response",
"<<",
"8",
"response",
"+=",
"to_i",
"(",
"bit_pointer",
"/",
"8",
"+",
"i",
")",
"end",
"bit_pointer_inc",
"(",
"bytelen",
"*",
"8",
")",
"return",
"response",
"end"
] | Read specified length of bytes and return as Integer instance.
Bit pointer proceed for that length. | [
"Read",
"specified",
"length",
"of",
"bytes",
"and",
"return",
"as",
"Integer",
"instance",
".",
"Bit",
"pointer",
"proceed",
"for",
"that",
"length",
"."
] | 069500619eb12528782761356c75e444c328c4e1 | https://github.com/sawaken/tsparser/blob/069500619eb12528782761356c75e444c328c4e1/lib/binary.rb#L119-L135 |
5,468 | sawaken/tsparser | lib/binary.rb | TSparser.Binary.read_one_bit | def read_one_bit
unless self.length * 8 - bit_pointer > 0
raise BinaryException.new("Readable buffer doesn't exist" +
"(#{self.length * 8 - bit_pointer}bit exists).")
end
response = to_i(bit_pointer/8)[7 - bit_pointer%8]
bit_pointer_inc(1)
return response
end | ruby | def read_one_bit
unless self.length * 8 - bit_pointer > 0
raise BinaryException.new("Readable buffer doesn't exist" +
"(#{self.length * 8 - bit_pointer}bit exists).")
end
response = to_i(bit_pointer/8)[7 - bit_pointer%8]
bit_pointer_inc(1)
return response
end | [
"def",
"read_one_bit",
"unless",
"self",
".",
"length",
"*",
"8",
"-",
"bit_pointer",
">",
"0",
"raise",
"BinaryException",
".",
"new",
"(",
"\"Readable buffer doesn't exist\"",
"+",
"\"(#{self.length * 8 - bit_pointer}bit exists).\"",
")",
"end",
"response",
"=",
"to_i",
"(",
"bit_pointer",
"/",
"8",
")",
"[",
"7",
"-",
"bit_pointer",
"%",
"8",
"]",
"bit_pointer_inc",
"(",
"1",
")",
"return",
"response",
"end"
] | Read one bit and return as 0 or 1.
Bit pointer proceed for one. | [
"Read",
"one",
"bit",
"and",
"return",
"as",
"0",
"or",
"1",
".",
"Bit",
"pointer",
"proceed",
"for",
"one",
"."
] | 069500619eb12528782761356c75e444c328c4e1 | https://github.com/sawaken/tsparser/blob/069500619eb12528782761356c75e444c328c4e1/lib/binary.rb#L139-L147 |
5,469 | sawaken/tsparser | lib/binary.rb | TSparser.Binary.read_bit_as_binary | def read_bit_as_binary(bitlen)
unless bit_pointer % 8 == 0
raise BinaryException.new("Bit pointer must be pointing start of byte. " +
"But now pointing #{bit_pointer}.")
end
unless bitlen % 8 == 0
raise BinaryException.new("Arg must be integer of multiple of 8. " +
"But you specified #{bitlen}.")
end
if self.length - bit_pointer/8 < bitlen/8
raise BinaryException.new("Rest of self length(#{self.length - bit_pointer/8}byte)" +
" is shorter than specified byte length(#{bitlen/8}byte).")
end
response = self[bit_pointer/8, bitlen/8]
bit_pointer_inc(bitlen)
return response
end | ruby | def read_bit_as_binary(bitlen)
unless bit_pointer % 8 == 0
raise BinaryException.new("Bit pointer must be pointing start of byte. " +
"But now pointing #{bit_pointer}.")
end
unless bitlen % 8 == 0
raise BinaryException.new("Arg must be integer of multiple of 8. " +
"But you specified #{bitlen}.")
end
if self.length - bit_pointer/8 < bitlen/8
raise BinaryException.new("Rest of self length(#{self.length - bit_pointer/8}byte)" +
" is shorter than specified byte length(#{bitlen/8}byte).")
end
response = self[bit_pointer/8, bitlen/8]
bit_pointer_inc(bitlen)
return response
end | [
"def",
"read_bit_as_binary",
"(",
"bitlen",
")",
"unless",
"bit_pointer",
"%",
"8",
"==",
"0",
"raise",
"BinaryException",
".",
"new",
"(",
"\"Bit pointer must be pointing start of byte. \"",
"+",
"\"But now pointing #{bit_pointer}.\"",
")",
"end",
"unless",
"bitlen",
"%",
"8",
"==",
"0",
"raise",
"BinaryException",
".",
"new",
"(",
"\"Arg must be integer of multiple of 8. \"",
"+",
"\"But you specified #{bitlen}.\"",
")",
"end",
"if",
"self",
".",
"length",
"-",
"bit_pointer",
"/",
"8",
"<",
"bitlen",
"/",
"8",
"raise",
"BinaryException",
".",
"new",
"(",
"\"Rest of self length(#{self.length - bit_pointer/8}byte)\"",
"+",
"\" is shorter than specified byte length(#{bitlen/8}byte).\"",
")",
"end",
"response",
"=",
"self",
"[",
"bit_pointer",
"/",
"8",
",",
"bitlen",
"/",
"8",
"]",
"bit_pointer_inc",
"(",
"bitlen",
")",
"return",
"response",
"end"
] | Read specified length of bits and return as Binary instance.
Bit pointer proceed for that length.
*Warning*: "bitlen" must be integer of multiple of 8, and bit pointer must be pointing
start of byte. | [
"Read",
"specified",
"length",
"of",
"bits",
"and",
"return",
"as",
"Binary",
"instance",
".",
"Bit",
"pointer",
"proceed",
"for",
"that",
"length",
"."
] | 069500619eb12528782761356c75e444c328c4e1 | https://github.com/sawaken/tsparser/blob/069500619eb12528782761356c75e444c328c4e1/lib/binary.rb#L154-L170 |
5,470 | webzakimbo/bcome-kontrol | lib/objects/registry/command/external.rb | Bcome::Registry::Command.External.execute | def execute(node, arguments)
full_command = construct_full_command(node, arguments)
begin
puts "\n(external) > #{full_command}".bc_blue + "\n\n"
system(full_command)
rescue Interrupt
puts "\nExiting gracefully from interrupt\n".warning
end
end | ruby | def execute(node, arguments)
full_command = construct_full_command(node, arguments)
begin
puts "\n(external) > #{full_command}".bc_blue + "\n\n"
system(full_command)
rescue Interrupt
puts "\nExiting gracefully from interrupt\n".warning
end
end | [
"def",
"execute",
"(",
"node",
",",
"arguments",
")",
"full_command",
"=",
"construct_full_command",
"(",
"node",
",",
"arguments",
")",
"begin",
"puts",
"\"\\n(external) > #{full_command}\"",
".",
"bc_blue",
"+",
"\"\\n\\n\"",
"system",
"(",
"full_command",
")",
"rescue",
"Interrupt",
"puts",
"\"\\nExiting gracefully from interrupt\\n\"",
".",
"warning",
"end",
"end"
] | In which the bcome context is passed to an external call | [
"In",
"which",
"the",
"bcome",
"context",
"is",
"passed",
"to",
"an",
"external",
"call"
] | 59129cc7c8bb6c39e457abed783aa23c1d60cd05 | https://github.com/webzakimbo/bcome-kontrol/blob/59129cc7c8bb6c39e457abed783aa23c1d60cd05/lib/objects/registry/command/external.rb#L5-L13 |
5,471 | kontena/opto | lib/opto/group.rb | Opto.Group.option | def option(option_name)
if option_name.to_s.include?('.')
parts = option_name.to_s.split('.')
var_name = parts.pop
group = parts.inject(self) do |base, part|
grp = base.option(part).value
if grp.nil?
raise NameError, "No such group: #{base.name}.#{part}"
elsif grp.kind_of?(Opto::Group)
grp
else
raise TypeError, "Is not a group: #{base.name}.#{part}"
end
end
else
group = self
var_name = option_name
end
group.options.find { |opt| opt.name == var_name }
end | ruby | def option(option_name)
if option_name.to_s.include?('.')
parts = option_name.to_s.split('.')
var_name = parts.pop
group = parts.inject(self) do |base, part|
grp = base.option(part).value
if grp.nil?
raise NameError, "No such group: #{base.name}.#{part}"
elsif grp.kind_of?(Opto::Group)
grp
else
raise TypeError, "Is not a group: #{base.name}.#{part}"
end
end
else
group = self
var_name = option_name
end
group.options.find { |opt| opt.name == var_name }
end | [
"def",
"option",
"(",
"option_name",
")",
"if",
"option_name",
".",
"to_s",
".",
"include?",
"(",
"'.'",
")",
"parts",
"=",
"option_name",
".",
"to_s",
".",
"split",
"(",
"'.'",
")",
"var_name",
"=",
"parts",
".",
"pop",
"group",
"=",
"parts",
".",
"inject",
"(",
"self",
")",
"do",
"|",
"base",
",",
"part",
"|",
"grp",
"=",
"base",
".",
"option",
"(",
"part",
")",
".",
"value",
"if",
"grp",
".",
"nil?",
"raise",
"NameError",
",",
"\"No such group: #{base.name}.#{part}\"",
"elsif",
"grp",
".",
"kind_of?",
"(",
"Opto",
"::",
"Group",
")",
"grp",
"else",
"raise",
"TypeError",
",",
"\"Is not a group: #{base.name}.#{part}\"",
"end",
"end",
"else",
"group",
"=",
"self",
"var_name",
"=",
"option_name",
"end",
"group",
".",
"options",
".",
"find",
"{",
"|",
"opt",
"|",
"opt",
".",
"name",
"==",
"var_name",
"}",
"end"
] | Find a member by name
@param [String] option_name
@return [Opto::Option] | [
"Find",
"a",
"member",
"by",
"name"
] | 7be243226fd2dc6beca61f49379894115396a424 | https://github.com/kontena/opto/blob/7be243226fd2dc6beca61f49379894115396a424/lib/opto/group.rb#L110-L130 |
5,472 | opengovernment/govkit | lib/gov_kit/acts_as_noteworthy.rb | GovKit::ActsAsNoteworthy.ActMethods.acts_as_noteworthy | def acts_as_noteworthy(options={})
class_inheritable_accessor :options
self.options = options
unless included_modules.include? InstanceMethods
instance_eval do
has_many :mentions, :as => :owner, :order => 'date desc'
with_options :as => :owner, :class_name => "Mention" do |c|
c.has_many :google_news_mentions, :conditions => {:search_source => "Google News"}, :order => 'date desc'
c.has_many :google_blog_mentions, :conditions => {:search_source => "Google Blogs"}, :order => 'date desc'
# c.has_many :technorati_mentions, :conditions => {:search_source => "Technorati"}, :order => 'date desc'
c.has_many :bing_mentions, :conditions => {:search_source => "Bing"}, :order => 'date desc'
end
end
extend ClassMethods
include InstanceMethods
end
end | ruby | def acts_as_noteworthy(options={})
class_inheritable_accessor :options
self.options = options
unless included_modules.include? InstanceMethods
instance_eval do
has_many :mentions, :as => :owner, :order => 'date desc'
with_options :as => :owner, :class_name => "Mention" do |c|
c.has_many :google_news_mentions, :conditions => {:search_source => "Google News"}, :order => 'date desc'
c.has_many :google_blog_mentions, :conditions => {:search_source => "Google Blogs"}, :order => 'date desc'
# c.has_many :technorati_mentions, :conditions => {:search_source => "Technorati"}, :order => 'date desc'
c.has_many :bing_mentions, :conditions => {:search_source => "Bing"}, :order => 'date desc'
end
end
extend ClassMethods
include InstanceMethods
end
end | [
"def",
"acts_as_noteworthy",
"(",
"options",
"=",
"{",
"}",
")",
"class_inheritable_accessor",
":options",
"self",
".",
"options",
"=",
"options",
"unless",
"included_modules",
".",
"include?",
"InstanceMethods",
"instance_eval",
"do",
"has_many",
":mentions",
",",
":as",
"=>",
":owner",
",",
":order",
"=>",
"'date desc'",
"with_options",
":as",
"=>",
":owner",
",",
":class_name",
"=>",
"\"Mention\"",
"do",
"|",
"c",
"|",
"c",
".",
"has_many",
":google_news_mentions",
",",
":conditions",
"=>",
"{",
":search_source",
"=>",
"\"Google News\"",
"}",
",",
":order",
"=>",
"'date desc'",
"c",
".",
"has_many",
":google_blog_mentions",
",",
":conditions",
"=>",
"{",
":search_source",
"=>",
"\"Google Blogs\"",
"}",
",",
":order",
"=>",
"'date desc'",
"# c.has_many :technorati_mentions, :conditions => {:search_source => \"Technorati\"}, :order => 'date desc'",
"c",
".",
"has_many",
":bing_mentions",
",",
":conditions",
"=>",
"{",
":search_source",
"=>",
"\"Bing\"",
"}",
",",
":order",
"=>",
"'date desc'",
"end",
"end",
"extend",
"ClassMethods",
"include",
"InstanceMethods",
"end",
"end"
] | Sets up the relationship between the model and the mention model
@param [Hash] opts a hash of options to be used by the relationship | [
"Sets",
"up",
"the",
"relationship",
"between",
"the",
"model",
"and",
"the",
"mention",
"model"
] | 6e1864ef173109dbb1cfadedb19e69849f8ed226 | https://github.com/opengovernment/govkit/blob/6e1864ef173109dbb1cfadedb19e69849f8ed226/lib/gov_kit/acts_as_noteworthy.rb#L12-L31 |
5,473 | opengovernment/govkit | lib/gov_kit/acts_as_noteworthy.rb | GovKit::ActsAsNoteworthy.InstanceMethods.raw_mentions | def raw_mentions
opts = self.options.clone
attributes = opts.delete(:with)
if opts[:geo]
opts[:geo] = self.instance_eval("#{opts[:geo]}")
end
query = []
attributes.each do |attr|
query << self.instance_eval("#{attr}")
end
{
:google_news => GovKit::SearchEngines::GoogleNews.search(query, opts),
:google_blogs => GovKit::SearchEngines::GoogleBlog.search(query, opts),
# :technorati => GovKit::SearchEngines::Technorati.search(query),
:bing => GovKit::SearchEngines::Bing.search(query, opts)
}
end | ruby | def raw_mentions
opts = self.options.clone
attributes = opts.delete(:with)
if opts[:geo]
opts[:geo] = self.instance_eval("#{opts[:geo]}")
end
query = []
attributes.each do |attr|
query << self.instance_eval("#{attr}")
end
{
:google_news => GovKit::SearchEngines::GoogleNews.search(query, opts),
:google_blogs => GovKit::SearchEngines::GoogleBlog.search(query, opts),
# :technorati => GovKit::SearchEngines::Technorati.search(query),
:bing => GovKit::SearchEngines::Bing.search(query, opts)
}
end | [
"def",
"raw_mentions",
"opts",
"=",
"self",
".",
"options",
".",
"clone",
"attributes",
"=",
"opts",
".",
"delete",
"(",
":with",
")",
"if",
"opts",
"[",
":geo",
"]",
"opts",
"[",
":geo",
"]",
"=",
"self",
".",
"instance_eval",
"(",
"\"#{opts[:geo]}\"",
")",
"end",
"query",
"=",
"[",
"]",
"attributes",
".",
"each",
"do",
"|",
"attr",
"|",
"query",
"<<",
"self",
".",
"instance_eval",
"(",
"\"#{attr}\"",
")",
"end",
"{",
":google_news",
"=>",
"GovKit",
"::",
"SearchEngines",
"::",
"GoogleNews",
".",
"search",
"(",
"query",
",",
"opts",
")",
",",
":google_blogs",
"=>",
"GovKit",
"::",
"SearchEngines",
"::",
"GoogleBlog",
".",
"search",
"(",
"query",
",",
"opts",
")",
",",
"# :technorati => GovKit::SearchEngines::Technorati.search(query),",
":bing",
"=>",
"GovKit",
"::",
"SearchEngines",
"::",
"Bing",
".",
"search",
"(",
"query",
",",
"opts",
")",
"}",
"end"
] | Generates the raw mentions to be loaded into the Mention objects
@return [Hash] a hash of all the mentions found of the object in question. | [
"Generates",
"the",
"raw",
"mentions",
"to",
"be",
"loaded",
"into",
"the",
"Mention",
"objects"
] | 6e1864ef173109dbb1cfadedb19e69849f8ed226 | https://github.com/opengovernment/govkit/blob/6e1864ef173109dbb1cfadedb19e69849f8ed226/lib/gov_kit/acts_as_noteworthy.rb#L42-L61 |
5,474 | Birdie0/qna_maker | lib/qna_maker/endpoints/publish_kb.rb | QnAMaker.Client.publish_kb | def publish_kb
response = @http.put(
"#{BASE_URL}/#{@knowledgebase_id}"
)
case response.code
when 204
nil
when 400
raise BadArgumentError, response.parse['error']['message'].join(' ')
when 401
raise UnauthorizedError, response.parse['error']['message']
when 403
raise ForbiddenError, response.parse['error']['message']
when 404
raise NotFoundError, response.parse['error']['message']
when 409
raise ConflictError, response.parse['error']['message']
else
raise UnknownError, "Oh no! (#{response.code})"
end
end | ruby | def publish_kb
response = @http.put(
"#{BASE_URL}/#{@knowledgebase_id}"
)
case response.code
when 204
nil
when 400
raise BadArgumentError, response.parse['error']['message'].join(' ')
when 401
raise UnauthorizedError, response.parse['error']['message']
when 403
raise ForbiddenError, response.parse['error']['message']
when 404
raise NotFoundError, response.parse['error']['message']
when 409
raise ConflictError, response.parse['error']['message']
else
raise UnknownError, "Oh no! (#{response.code})"
end
end | [
"def",
"publish_kb",
"response",
"=",
"@http",
".",
"put",
"(",
"\"#{BASE_URL}/#{@knowledgebase_id}\"",
")",
"case",
"response",
".",
"code",
"when",
"204",
"nil",
"when",
"400",
"raise",
"BadArgumentError",
",",
"response",
".",
"parse",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
".",
"join",
"(",
"' '",
")",
"when",
"401",
"raise",
"UnauthorizedError",
",",
"response",
".",
"parse",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"when",
"403",
"raise",
"ForbiddenError",
",",
"response",
".",
"parse",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"when",
"404",
"raise",
"NotFoundError",
",",
"response",
".",
"parse",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"when",
"409",
"raise",
"ConflictError",
",",
"response",
".",
"parse",
"[",
"'error'",
"]",
"[",
"'message'",
"]",
"else",
"raise",
"UnknownError",
",",
"\"Oh no! (#{response.code})\"",
"end",
"end"
] | Publish all unpublished in the knowledgebase to the prod endpoint
@return [nil] on success | [
"Publish",
"all",
"unpublished",
"in",
"the",
"knowledgebase",
"to",
"the",
"prod",
"endpoint"
] | 5ac204ede100355352438b8ff4fe30ad84d9257b | https://github.com/Birdie0/qna_maker/blob/5ac204ede100355352438b8ff4fe30ad84d9257b/lib/qna_maker/endpoints/publish_kb.rb#L8-L29 |
5,475 | cbot/push0r | lib/push0r/APNS/ApnsPushMessage.rb | Push0r.ApnsPushMessage.simple | def simple(alert_text = nil, sound = nil, badge = nil, category = nil)
new_payload = {aps: {}}
if alert_text
new_payload[:aps][:alert] = alert_text
end
if sound
new_payload[:aps][:sound] = sound
end
if badge
new_payload[:aps][:badge] = badge
end
if category
new_payload[:aps][:category] = category
end
@payload.merge!(new_payload)
return self
end | ruby | def simple(alert_text = nil, sound = nil, badge = nil, category = nil)
new_payload = {aps: {}}
if alert_text
new_payload[:aps][:alert] = alert_text
end
if sound
new_payload[:aps][:sound] = sound
end
if badge
new_payload[:aps][:badge] = badge
end
if category
new_payload[:aps][:category] = category
end
@payload.merge!(new_payload)
return self
end | [
"def",
"simple",
"(",
"alert_text",
"=",
"nil",
",",
"sound",
"=",
"nil",
",",
"badge",
"=",
"nil",
",",
"category",
"=",
"nil",
")",
"new_payload",
"=",
"{",
"aps",
":",
"{",
"}",
"}",
"if",
"alert_text",
"new_payload",
"[",
":aps",
"]",
"[",
":alert",
"]",
"=",
"alert_text",
"end",
"if",
"sound",
"new_payload",
"[",
":aps",
"]",
"[",
":sound",
"]",
"=",
"sound",
"end",
"if",
"badge",
"new_payload",
"[",
":aps",
"]",
"[",
":badge",
"]",
"=",
"badge",
"end",
"if",
"category",
"new_payload",
"[",
":aps",
"]",
"[",
":category",
"]",
"=",
"category",
"end",
"@payload",
".",
"merge!",
"(",
"new_payload",
")",
"return",
"self",
"end"
] | Returns a new ApnsPushMessage instance that encapsulates a single push notification to be sent to a single user.
@param receiver_token [String] the apns push token (aka device token) to push the notification to
@param environment [Fixnum] the environment to use when sending this push message. Defaults to ApnsEnvironment::PRODUCTION.
@param identifier [Fixnum] a unique identifier to identify this push message during error handling. If nil, a random identifier is automatically generated.
@param time_to_live [Fixnum] The time to live in seconds for this push messages. If nil, the time to live is set to zero seconds.
Convenience method to attach common data (that is an alert, a sound or a badge value) to this message's payload.
@param alert_text [String] the alert text to be displayed
@param sound [String] the sound to be played
@param badge [Fixnum] the badge value to be displayed
@param category [String] the category this message belongs to (see UIUserNotificationCategory in apple's documentation) | [
"Returns",
"a",
"new",
"ApnsPushMessage",
"instance",
"that",
"encapsulates",
"a",
"single",
"push",
"notification",
"to",
"be",
"sent",
"to",
"a",
"single",
"user",
"."
] | 07eb7bece1f251608529dea0d7a93af1444ffeb6 | https://github.com/cbot/push0r/blob/07eb7bece1f251608529dea0d7a93af1444ffeb6/lib/push0r/APNS/ApnsPushMessage.rb#L24-L42 |
5,476 | ideonetwork/lato-core | lib/lato_core/interfaces/cells.rb | LatoCore.Interface::Cells.core__widgets_index | def core__widgets_index(records, search: nil, pagination: 50)
response = {
records: records,
total: records.length,
per_page: pagination,
search: '',
search_key: search,
sort: '',
sort_dir: 'ASC',
pagination: 1,
}
# manage search
if search && params[:widget_index] && params[:widget_index][:search] && !params[:widget_index][:search].blank?
search_array = search.is_a?(Array) ? search : [search]
query1 = ''
query2 = []
search_array.each do |s|
query1 += "#{s} like ? OR "
query2.push("%#{params[:widget_index][:search]}%")
end
query1 = query1[0...-4]
query = [query1] + query2
response[:records] = response[:records].where(query)
response[:total] = response[:records].length
response[:search] = params[:widget_index][:search]
end
# manage sort
if params[:widget_index] && !params[:widget_index][:sort].blank? && !params[:widget_index][:sort_dir].blank?
response[:sort] = params[:widget_index][:sort]
response[:sort_dir] = params[:widget_index][:sort_dir]
response[:records] = response[:records].order("#{params[:widget_index][:sort]} #{params[:widget_index][:sort_dir]}")
end
# manage pagination
if pagination
if params[:widget_index] && params[:widget_index][:pagination]
response[:pagination] = params[:widget_index][:pagination].to_i
end
response[:records] = core__paginate_array(response[:records], pagination, response[:pagination])
end
# return response
response
end | ruby | def core__widgets_index(records, search: nil, pagination: 50)
response = {
records: records,
total: records.length,
per_page: pagination,
search: '',
search_key: search,
sort: '',
sort_dir: 'ASC',
pagination: 1,
}
# manage search
if search && params[:widget_index] && params[:widget_index][:search] && !params[:widget_index][:search].blank?
search_array = search.is_a?(Array) ? search : [search]
query1 = ''
query2 = []
search_array.each do |s|
query1 += "#{s} like ? OR "
query2.push("%#{params[:widget_index][:search]}%")
end
query1 = query1[0...-4]
query = [query1] + query2
response[:records] = response[:records].where(query)
response[:total] = response[:records].length
response[:search] = params[:widget_index][:search]
end
# manage sort
if params[:widget_index] && !params[:widget_index][:sort].blank? && !params[:widget_index][:sort_dir].blank?
response[:sort] = params[:widget_index][:sort]
response[:sort_dir] = params[:widget_index][:sort_dir]
response[:records] = response[:records].order("#{params[:widget_index][:sort]} #{params[:widget_index][:sort_dir]}")
end
# manage pagination
if pagination
if params[:widget_index] && params[:widget_index][:pagination]
response[:pagination] = params[:widget_index][:pagination].to_i
end
response[:records] = core__paginate_array(response[:records], pagination, response[:pagination])
end
# return response
response
end | [
"def",
"core__widgets_index",
"(",
"records",
",",
"search",
":",
"nil",
",",
"pagination",
":",
"50",
")",
"response",
"=",
"{",
"records",
":",
"records",
",",
"total",
":",
"records",
".",
"length",
",",
"per_page",
":",
"pagination",
",",
"search",
":",
"''",
",",
"search_key",
":",
"search",
",",
"sort",
":",
"''",
",",
"sort_dir",
":",
"'ASC'",
",",
"pagination",
":",
"1",
",",
"}",
"# manage search",
"if",
"search",
"&&",
"params",
"[",
":widget_index",
"]",
"&&",
"params",
"[",
":widget_index",
"]",
"[",
":search",
"]",
"&&",
"!",
"params",
"[",
":widget_index",
"]",
"[",
":search",
"]",
".",
"blank?",
"search_array",
"=",
"search",
".",
"is_a?",
"(",
"Array",
")",
"?",
"search",
":",
"[",
"search",
"]",
"query1",
"=",
"''",
"query2",
"=",
"[",
"]",
"search_array",
".",
"each",
"do",
"|",
"s",
"|",
"query1",
"+=",
"\"#{s} like ? OR \"",
"query2",
".",
"push",
"(",
"\"%#{params[:widget_index][:search]}%\"",
")",
"end",
"query1",
"=",
"query1",
"[",
"0",
"...",
"-",
"4",
"]",
"query",
"=",
"[",
"query1",
"]",
"+",
"query2",
"response",
"[",
":records",
"]",
"=",
"response",
"[",
":records",
"]",
".",
"where",
"(",
"query",
")",
"response",
"[",
":total",
"]",
"=",
"response",
"[",
":records",
"]",
".",
"length",
"response",
"[",
":search",
"]",
"=",
"params",
"[",
":widget_index",
"]",
"[",
":search",
"]",
"end",
"# manage sort",
"if",
"params",
"[",
":widget_index",
"]",
"&&",
"!",
"params",
"[",
":widget_index",
"]",
"[",
":sort",
"]",
".",
"blank?",
"&&",
"!",
"params",
"[",
":widget_index",
"]",
"[",
":sort_dir",
"]",
".",
"blank?",
"response",
"[",
":sort",
"]",
"=",
"params",
"[",
":widget_index",
"]",
"[",
":sort",
"]",
"response",
"[",
":sort_dir",
"]",
"=",
"params",
"[",
":widget_index",
"]",
"[",
":sort_dir",
"]",
"response",
"[",
":records",
"]",
"=",
"response",
"[",
":records",
"]",
".",
"order",
"(",
"\"#{params[:widget_index][:sort]} #{params[:widget_index][:sort_dir]}\"",
")",
"end",
"# manage pagination",
"if",
"pagination",
"if",
"params",
"[",
":widget_index",
"]",
"&&",
"params",
"[",
":widget_index",
"]",
"[",
":pagination",
"]",
"response",
"[",
":pagination",
"]",
"=",
"params",
"[",
":widget_index",
"]",
"[",
":pagination",
"]",
".",
"to_i",
"end",
"response",
"[",
":records",
"]",
"=",
"core__paginate_array",
"(",
"response",
"[",
":records",
"]",
",",
"pagination",
",",
"response",
"[",
":pagination",
"]",
")",
"end",
"# return response",
"response",
"end"
] | This function manage the widget index from front end. | [
"This",
"function",
"manage",
"the",
"widget",
"index",
"from",
"front",
"end",
"."
] | c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c | https://github.com/ideonetwork/lato-core/blob/c01fa585725c8e9992f25d8a7bd4ba2d0bfca08c/lib/lato_core/interfaces/cells.rb#L14-L56 |
5,477 | thinkerbot/configurable | lib/configurable/class_methods.rb | Configurable.ClassMethods.remove_config | def remove_config(key, options={})
unless config_registry.has_key?(key)
raise NameError.new("#{key.inspect} is not a config on #{self}")
end
options = {
:reader => true,
:writer => true
}.merge(options)
config = config_registry.delete(key)
reset_configs
remove_method(config.reader) if options[:reader]
remove_method(config.writer) if options[:writer]
config
end | ruby | def remove_config(key, options={})
unless config_registry.has_key?(key)
raise NameError.new("#{key.inspect} is not a config on #{self}")
end
options = {
:reader => true,
:writer => true
}.merge(options)
config = config_registry.delete(key)
reset_configs
remove_method(config.reader) if options[:reader]
remove_method(config.writer) if options[:writer]
config
end | [
"def",
"remove_config",
"(",
"key",
",",
"options",
"=",
"{",
"}",
")",
"unless",
"config_registry",
".",
"has_key?",
"(",
"key",
")",
"raise",
"NameError",
".",
"new",
"(",
"\"#{key.inspect} is not a config on #{self}\"",
")",
"end",
"options",
"=",
"{",
":reader",
"=>",
"true",
",",
":writer",
"=>",
"true",
"}",
".",
"merge",
"(",
"options",
")",
"config",
"=",
"config_registry",
".",
"delete",
"(",
"key",
")",
"reset_configs",
"remove_method",
"(",
"config",
".",
"reader",
")",
"if",
"options",
"[",
":reader",
"]",
"remove_method",
"(",
"config",
".",
"writer",
")",
"if",
"options",
"[",
":writer",
"]",
"config",
"end"
] | Removes a config much like remove_method removes a method. The reader
and writer for the config are likewise removed. Nested configs can be
removed using this method.
Setting :reader or :writer to false in the options prevents those
methods from being removed. | [
"Removes",
"a",
"config",
"much",
"like",
"remove_method",
"removes",
"a",
"method",
".",
"The",
"reader",
"and",
"writer",
"for",
"the",
"config",
"are",
"likewise",
"removed",
".",
"Nested",
"configs",
"can",
"be",
"removed",
"using",
"this",
"method",
"."
] | 43c611f767f14194827b1fe31bc72c8bdf54efdf | https://github.com/thinkerbot/configurable/blob/43c611f767f14194827b1fe31bc72c8bdf54efdf/lib/configurable/class_methods.rb#L200-L217 |
5,478 | thinkerbot/configurable | lib/configurable/class_methods.rb | Configurable.ClassMethods.undef_config | def undef_config(key, options={})
unless configs.has_key?(key)
raise NameError.new("#{key.inspect} is not a config on #{self}")
end
options = {
:reader => true,
:writer => true
}.merge(options)
config = configs[key]
config_registry[key] = nil
reset_configs
undef_method(config.reader) if options[:reader]
undef_method(config.writer) if options[:writer]
config
end | ruby | def undef_config(key, options={})
unless configs.has_key?(key)
raise NameError.new("#{key.inspect} is not a config on #{self}")
end
options = {
:reader => true,
:writer => true
}.merge(options)
config = configs[key]
config_registry[key] = nil
reset_configs
undef_method(config.reader) if options[:reader]
undef_method(config.writer) if options[:writer]
config
end | [
"def",
"undef_config",
"(",
"key",
",",
"options",
"=",
"{",
"}",
")",
"unless",
"configs",
".",
"has_key?",
"(",
"key",
")",
"raise",
"NameError",
".",
"new",
"(",
"\"#{key.inspect} is not a config on #{self}\"",
")",
"end",
"options",
"=",
"{",
":reader",
"=>",
"true",
",",
":writer",
"=>",
"true",
"}",
".",
"merge",
"(",
"options",
")",
"config",
"=",
"configs",
"[",
"key",
"]",
"config_registry",
"[",
"key",
"]",
"=",
"nil",
"reset_configs",
"undef_method",
"(",
"config",
".",
"reader",
")",
"if",
"options",
"[",
":reader",
"]",
"undef_method",
"(",
"config",
".",
"writer",
")",
"if",
"options",
"[",
":writer",
"]",
"config",
"end"
] | Undefines a config much like undef_method undefines a method. The
reader and writer for the config are likewise undefined. Nested configs
can be undefined using this method.
Setting :reader or :writer to false in the options prevents those
methods from being undefined.
==== Implementation Note
Configurations are undefined by setting the key to nil in the registry.
Deleting the config is not sufficient because the registry needs to
convey to self and subclasses to not inherit the config from ancestors.
This is unlike remove_config where the config is simply deleted from the
config_registry. | [
"Undefines",
"a",
"config",
"much",
"like",
"undef_method",
"undefines",
"a",
"method",
".",
"The",
"reader",
"and",
"writer",
"for",
"the",
"config",
"are",
"likewise",
"undefined",
".",
"Nested",
"configs",
"can",
"be",
"undefined",
"using",
"this",
"method",
"."
] | 43c611f767f14194827b1fe31bc72c8bdf54efdf | https://github.com/thinkerbot/configurable/blob/43c611f767f14194827b1fe31bc72c8bdf54efdf/lib/configurable/class_methods.rb#L234-L252 |
5,479 | thinkerbot/configurable | lib/configurable/class_methods.rb | Configurable.ClassMethods.remove_config_type | def remove_config_type(name)
unless config_type_registry.has_key?(name)
raise NameError.new("#{name.inspect} is not a config_type on #{self}")
end
config_type = config_type_registry.delete(name)
reset_config_types
config_type
end | ruby | def remove_config_type(name)
unless config_type_registry.has_key?(name)
raise NameError.new("#{name.inspect} is not a config_type on #{self}")
end
config_type = config_type_registry.delete(name)
reset_config_types
config_type
end | [
"def",
"remove_config_type",
"(",
"name",
")",
"unless",
"config_type_registry",
".",
"has_key?",
"(",
"name",
")",
"raise",
"NameError",
".",
"new",
"(",
"\"#{name.inspect} is not a config_type on #{self}\"",
")",
"end",
"config_type",
"=",
"config_type_registry",
".",
"delete",
"(",
"name",
")",
"reset_config_types",
"config_type",
"end"
] | Removes a config_type much like remove_method removes a method. | [
"Removes",
"a",
"config_type",
"much",
"like",
"remove_method",
"removes",
"a",
"method",
"."
] | 43c611f767f14194827b1fe31bc72c8bdf54efdf | https://github.com/thinkerbot/configurable/blob/43c611f767f14194827b1fe31bc72c8bdf54efdf/lib/configurable/class_methods.rb#L272-L280 |
5,480 | thinkerbot/configurable | lib/configurable/class_methods.rb | Configurable.ClassMethods.undef_config_type | def undef_config_type(name)
unless config_types.has_key?(name)
raise NameError.new("#{name.inspect} is not a config_type on #{self}")
end
config_type = config_type_registry[name]
config_type_registry[name] = nil
reset_config_types
config_type
end | ruby | def undef_config_type(name)
unless config_types.has_key?(name)
raise NameError.new("#{name.inspect} is not a config_type on #{self}")
end
config_type = config_type_registry[name]
config_type_registry[name] = nil
reset_config_types
config_type
end | [
"def",
"undef_config_type",
"(",
"name",
")",
"unless",
"config_types",
".",
"has_key?",
"(",
"name",
")",
"raise",
"NameError",
".",
"new",
"(",
"\"#{name.inspect} is not a config_type on #{self}\"",
")",
"end",
"config_type",
"=",
"config_type_registry",
"[",
"name",
"]",
"config_type_registry",
"[",
"name",
"]",
"=",
"nil",
"reset_config_types",
"config_type",
"end"
] | Undefines a config_type much like undef_method undefines a method.
==== Implementation Note
ConfigClasses are undefined by setting the key to nil in the registry.
Deleting the config_type is not sufficient because the registry needs to
convey to self and subclasses to not inherit the config_type from
ancestors.
This is unlike remove_config_type where the config_type is simply
deleted from the config_type_registry. | [
"Undefines",
"a",
"config_type",
"much",
"like",
"undef_method",
"undefines",
"a",
"method",
"."
] | 43c611f767f14194827b1fe31bc72c8bdf54efdf | https://github.com/thinkerbot/configurable/blob/43c611f767f14194827b1fe31bc72c8bdf54efdf/lib/configurable/class_methods.rb#L293-L302 |
5,481 | thinkerbot/configurable | lib/configurable/class_methods.rb | Configurable.ClassMethods.check_infinite_nest | def check_infinite_nest(klass) # :nodoc:
raise "infinite nest detected" if klass == self
klass.configs.each_value do |config|
if config.type.kind_of?(NestType)
check_infinite_nest(config.type.configurable.class)
end
end
end | ruby | def check_infinite_nest(klass) # :nodoc:
raise "infinite nest detected" if klass == self
klass.configs.each_value do |config|
if config.type.kind_of?(NestType)
check_infinite_nest(config.type.configurable.class)
end
end
end | [
"def",
"check_infinite_nest",
"(",
"klass",
")",
"# :nodoc:",
"raise",
"\"infinite nest detected\"",
"if",
"klass",
"==",
"self",
"klass",
".",
"configs",
".",
"each_value",
"do",
"|",
"config",
"|",
"if",
"config",
".",
"type",
".",
"kind_of?",
"(",
"NestType",
")",
"check_infinite_nest",
"(",
"config",
".",
"type",
".",
"configurable",
".",
"class",
")",
"end",
"end",
"end"
] | helper to recursively check for an infinite nest | [
"helper",
"to",
"recursively",
"check",
"for",
"an",
"infinite",
"nest"
] | 43c611f767f14194827b1fe31bc72c8bdf54efdf | https://github.com/thinkerbot/configurable/blob/43c611f767f14194827b1fe31bc72c8bdf54efdf/lib/configurable/class_methods.rb#L334-L342 |
5,482 | lautis/sweet_notifications | lib/sweet_notifications/log_subscriber.rb | SweetNotifications.LogSubscriber.message | def message(event, label, body)
@odd = !@odd
label_color = @odd ? odd_color : even_color
format(
' %s (%.2fms) %s',
color(label, label_color, true),
event.duration,
color(body, nil, !@odd)
)
end | ruby | def message(event, label, body)
@odd = !@odd
label_color = @odd ? odd_color : even_color
format(
' %s (%.2fms) %s',
color(label, label_color, true),
event.duration,
color(body, nil, !@odd)
)
end | [
"def",
"message",
"(",
"event",
",",
"label",
",",
"body",
")",
"@odd",
"=",
"!",
"@odd",
"label_color",
"=",
"@odd",
"?",
"odd_color",
":",
"even_color",
"format",
"(",
"' %s (%.2fms) %s'",
",",
"color",
"(",
"label",
",",
"label_color",
",",
"true",
")",
",",
"event",
".",
"duration",
",",
"color",
"(",
"body",
",",
"nil",
",",
"!",
"@odd",
")",
")",
"end"
] | Format a message for logging
@param event [ActiveSupport::Notifications::Event] subscribed event
@param label [String] label for log messages
@param body [String] the rest
@return [String] formatted message for logging
==== Examples
event :test do |event|
message(event, 'Test', 'message body')
end
# => " Test (0.00ms) message body" | [
"Format",
"a",
"message",
"for",
"logging"
] | fcd137a1b474d24e1bc86619d116fc32caba8c19 | https://github.com/lautis/sweet_notifications/blob/fcd137a1b474d24e1bc86619d116fc32caba8c19/lib/sweet_notifications/log_subscriber.rb#L28-L38 |
5,483 | postmodern/deployml | lib/deployml/remote_shell.rb | DeploYML.RemoteShell.join | def join
commands = []
@history.each do |command|
program = command[0]
arguments = command[1..-1].map { |word| shellescape(word.to_s) }
commands << [program, *arguments].join(' ')
end
return commands.join(' && ')
end | ruby | def join
commands = []
@history.each do |command|
program = command[0]
arguments = command[1..-1].map { |word| shellescape(word.to_s) }
commands << [program, *arguments].join(' ')
end
return commands.join(' && ')
end | [
"def",
"join",
"commands",
"=",
"[",
"]",
"@history",
".",
"each",
"do",
"|",
"command",
"|",
"program",
"=",
"command",
"[",
"0",
"]",
"arguments",
"=",
"command",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"map",
"{",
"|",
"word",
"|",
"shellescape",
"(",
"word",
".",
"to_s",
")",
"}",
"commands",
"<<",
"[",
"program",
",",
"arguments",
"]",
".",
"join",
"(",
"' '",
")",
"end",
"return",
"commands",
".",
"join",
"(",
"' && '",
")",
"end"
] | Joins the command history together with ` && `, to form a
single command.
@return [String]
A single command string. | [
"Joins",
"the",
"command",
"history",
"together",
"with",
"&&",
"to",
"form",
"a",
"single",
"command",
"."
] | 4369d4ea719e41f0dc3aa6496e6422ad476b0dda | https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/remote_shell.rb#L99-L110 |
5,484 | postmodern/deployml | lib/deployml/remote_shell.rb | DeploYML.RemoteShell.ssh_uri | def ssh_uri
unless @uri.host
raise(InvalidConfig,"URI does not have a host: #{@uri}",caller)
end
new_uri = @uri.host
new_uri = "#{@uri.user}@#{new_uri}" if @uri.user
return new_uri
end | ruby | def ssh_uri
unless @uri.host
raise(InvalidConfig,"URI does not have a host: #{@uri}",caller)
end
new_uri = @uri.host
new_uri = "#{@uri.user}@#{new_uri}" if @uri.user
return new_uri
end | [
"def",
"ssh_uri",
"unless",
"@uri",
".",
"host",
"raise",
"(",
"InvalidConfig",
",",
"\"URI does not have a host: #{@uri}\"",
",",
"caller",
")",
"end",
"new_uri",
"=",
"@uri",
".",
"host",
"new_uri",
"=",
"\"#{@uri.user}@#{new_uri}\"",
"if",
"@uri",
".",
"user",
"return",
"new_uri",
"end"
] | Converts the URI to one compatible with SSH.
@return [String]
The SSH compatible URI.
@raise [InvalidConfig]
The URI of the shell does not have a host component. | [
"Converts",
"the",
"URI",
"to",
"one",
"compatible",
"with",
"SSH",
"."
] | 4369d4ea719e41f0dc3aa6496e6422ad476b0dda | https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/remote_shell.rb#L121-L130 |
5,485 | postmodern/deployml | lib/deployml/remote_shell.rb | DeploYML.RemoteShell.ssh | def ssh(*arguments)
options = []
# Add the -p option if an alternate destination port is given
if @uri.port
options += ['-p', @uri.port.to_s]
end
# append the SSH URI
options << ssh_uri
# append the additional arguments
arguments.each { |arg| options << arg.to_s }
return system('ssh',*options)
end | ruby | def ssh(*arguments)
options = []
# Add the -p option if an alternate destination port is given
if @uri.port
options += ['-p', @uri.port.to_s]
end
# append the SSH URI
options << ssh_uri
# append the additional arguments
arguments.each { |arg| options << arg.to_s }
return system('ssh',*options)
end | [
"def",
"ssh",
"(",
"*",
"arguments",
")",
"options",
"=",
"[",
"]",
"# Add the -p option if an alternate destination port is given",
"if",
"@uri",
".",
"port",
"options",
"+=",
"[",
"'-p'",
",",
"@uri",
".",
"port",
".",
"to_s",
"]",
"end",
"# append the SSH URI",
"options",
"<<",
"ssh_uri",
"# append the additional arguments",
"arguments",
".",
"each",
"{",
"|",
"arg",
"|",
"options",
"<<",
"arg",
".",
"to_s",
"}",
"return",
"system",
"(",
"'ssh'",
",",
"options",
")",
"end"
] | Starts a SSH session with the destination server.
@param [Array] arguments
Additional arguments to pass to SSH. | [
"Starts",
"a",
"SSH",
"session",
"with",
"the",
"destination",
"server",
"."
] | 4369d4ea719e41f0dc3aa6496e6422ad476b0dda | https://github.com/postmodern/deployml/blob/4369d4ea719e41f0dc3aa6496e6422ad476b0dda/lib/deployml/remote_shell.rb#L138-L153 |
5,486 | ManageIQ/polisher | lib/polisher/util/conf_helpers.rb | ConfHelpers.ClassMethods.conf_attr | def conf_attr(name, opts = {})
@conf_attrs ||= []
@conf_attrs << name
default = opts[:default]
accumulate = opts[:accumulate]
send(:define_singleton_method, name) do |*args|
nvar = "@#{name}".intern
current = instance_variable_get(nvar)
envk = "POLISHER_#{name.to_s.upcase}"
if accumulate
instance_variable_set(nvar, []) unless current
current = instance_variable_get(nvar)
current << default
current << ENV[envk]
current += args
current.uniq!
current.compact!
current.flatten!
instance_variable_set(nvar, current)
else
instance_variable_set(nvar, default) unless current
instance_variable_set(nvar, ENV[envk]) if ENV.key?(envk)
instance_variable_set(nvar, args.first) unless args.empty?
end
instance_variable_get(nvar)
end
send(:define_method, name) do
self.class.send(name)
end
end | ruby | def conf_attr(name, opts = {})
@conf_attrs ||= []
@conf_attrs << name
default = opts[:default]
accumulate = opts[:accumulate]
send(:define_singleton_method, name) do |*args|
nvar = "@#{name}".intern
current = instance_variable_get(nvar)
envk = "POLISHER_#{name.to_s.upcase}"
if accumulate
instance_variable_set(nvar, []) unless current
current = instance_variable_get(nvar)
current << default
current << ENV[envk]
current += args
current.uniq!
current.compact!
current.flatten!
instance_variable_set(nvar, current)
else
instance_variable_set(nvar, default) unless current
instance_variable_set(nvar, ENV[envk]) if ENV.key?(envk)
instance_variable_set(nvar, args.first) unless args.empty?
end
instance_variable_get(nvar)
end
send(:define_method, name) do
self.class.send(name)
end
end | [
"def",
"conf_attr",
"(",
"name",
",",
"opts",
"=",
"{",
"}",
")",
"@conf_attrs",
"||=",
"[",
"]",
"@conf_attrs",
"<<",
"name",
"default",
"=",
"opts",
"[",
":default",
"]",
"accumulate",
"=",
"opts",
"[",
":accumulate",
"]",
"send",
"(",
":define_singleton_method",
",",
"name",
")",
"do",
"|",
"*",
"args",
"|",
"nvar",
"=",
"\"@#{name}\"",
".",
"intern",
"current",
"=",
"instance_variable_get",
"(",
"nvar",
")",
"envk",
"=",
"\"POLISHER_#{name.to_s.upcase}\"",
"if",
"accumulate",
"instance_variable_set",
"(",
"nvar",
",",
"[",
"]",
")",
"unless",
"current",
"current",
"=",
"instance_variable_get",
"(",
"nvar",
")",
"current",
"<<",
"default",
"current",
"<<",
"ENV",
"[",
"envk",
"]",
"current",
"+=",
"args",
"current",
".",
"uniq!",
"current",
".",
"compact!",
"current",
".",
"flatten!",
"instance_variable_set",
"(",
"nvar",
",",
"current",
")",
"else",
"instance_variable_set",
"(",
"nvar",
",",
"default",
")",
"unless",
"current",
"instance_variable_set",
"(",
"nvar",
",",
"ENV",
"[",
"envk",
"]",
")",
"if",
"ENV",
".",
"key?",
"(",
"envk",
")",
"instance_variable_set",
"(",
"nvar",
",",
"args",
".",
"first",
")",
"unless",
"args",
".",
"empty?",
"end",
"instance_variable_get",
"(",
"nvar",
")",
"end",
"send",
"(",
":define_method",
",",
"name",
")",
"do",
"self",
".",
"class",
".",
"send",
"(",
"name",
")",
"end",
"end"
] | Defines a 'config attribute' or attribute on the class
which this is defined in. Accessors to the single shared
attribute will be added to the class as well as instances
of the class. Specify the default value with the attr name
or via an env variable
@example
class Custom
extend ConfHelpers
conf_attr :data_dir, :default => '/etc/'
end
Custom.data_dir # => '/etc/'
ENV['POLISHER_DATA_DIR'] = '/usr/'
Custom.data_dir # => '/usr/'
Custom.data_dir == Custom.new.data_dir # => true | [
"Defines",
"a",
"config",
"attribute",
"or",
"attribute",
"on",
"the",
"class",
"which",
"this",
"is",
"defined",
"in",
".",
"Accessors",
"to",
"the",
"single",
"shared",
"attribute",
"will",
"be",
"added",
"to",
"the",
"class",
"as",
"well",
"as",
"instances",
"of",
"the",
"class",
".",
"Specify",
"the",
"default",
"value",
"with",
"the",
"attr",
"name",
"or",
"via",
"an",
"env",
"variable"
] | 8c19023c72573999c9dc53ec2e2a3eef11a9531e | https://github.com/ManageIQ/polisher/blob/8c19023c72573999c9dc53ec2e2a3eef11a9531e/lib/polisher/util/conf_helpers.rb#L30-L63 |
5,487 | kjvarga/arid_cache | lib/arid_cache/helpers.rb | AridCache.Helpers.lookup | def lookup(object, key, opts, &block)
if !block.nil?
define(object, key, opts, &block)
elsif key =~ /(.*)_count$/
if AridCache.store.has?(object, $1)
method_for_cached(object, $1, :fetch_count, key)
elsif object.respond_to?(key)
define(object, key, opts, :fetch_count)
elsif object.respond_to?($1)
define(object, $1, opts, :fetch_count, key)
else
raise ArgumentError.new("#{object} doesn't respond to #{key.inspect} or #{$1.inspect}. Cannot dynamically create query to get the count, please call with a block.")
end
elsif AridCache.store.has?(object, key)
method_for_cached(object, key, :fetch)
elsif object.respond_to?(key)
define(object, key, opts, &block)
else
raise ArgumentError.new("#{object} doesn't respond to #{key.inspect}! Cannot dynamically create query, please call with a block.")
end
object.send("cached_#{key}", opts)
end | ruby | def lookup(object, key, opts, &block)
if !block.nil?
define(object, key, opts, &block)
elsif key =~ /(.*)_count$/
if AridCache.store.has?(object, $1)
method_for_cached(object, $1, :fetch_count, key)
elsif object.respond_to?(key)
define(object, key, opts, :fetch_count)
elsif object.respond_to?($1)
define(object, $1, opts, :fetch_count, key)
else
raise ArgumentError.new("#{object} doesn't respond to #{key.inspect} or #{$1.inspect}. Cannot dynamically create query to get the count, please call with a block.")
end
elsif AridCache.store.has?(object, key)
method_for_cached(object, key, :fetch)
elsif object.respond_to?(key)
define(object, key, opts, &block)
else
raise ArgumentError.new("#{object} doesn't respond to #{key.inspect}! Cannot dynamically create query, please call with a block.")
end
object.send("cached_#{key}", opts)
end | [
"def",
"lookup",
"(",
"object",
",",
"key",
",",
"opts",
",",
"&",
"block",
")",
"if",
"!",
"block",
".",
"nil?",
"define",
"(",
"object",
",",
"key",
",",
"opts",
",",
"block",
")",
"elsif",
"key",
"=~",
"/",
"/",
"if",
"AridCache",
".",
"store",
".",
"has?",
"(",
"object",
",",
"$1",
")",
"method_for_cached",
"(",
"object",
",",
"$1",
",",
":fetch_count",
",",
"key",
")",
"elsif",
"object",
".",
"respond_to?",
"(",
"key",
")",
"define",
"(",
"object",
",",
"key",
",",
"opts",
",",
":fetch_count",
")",
"elsif",
"object",
".",
"respond_to?",
"(",
"$1",
")",
"define",
"(",
"object",
",",
"$1",
",",
"opts",
",",
":fetch_count",
",",
"key",
")",
"else",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"#{object} doesn't respond to #{key.inspect} or #{$1.inspect}. Cannot dynamically create query to get the count, please call with a block.\"",
")",
"end",
"elsif",
"AridCache",
".",
"store",
".",
"has?",
"(",
"object",
",",
"key",
")",
"method_for_cached",
"(",
"object",
",",
"key",
",",
":fetch",
")",
"elsif",
"object",
".",
"respond_to?",
"(",
"key",
")",
"define",
"(",
"object",
",",
"key",
",",
"opts",
",",
"block",
")",
"else",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"#{object} doesn't respond to #{key.inspect}! Cannot dynamically create query, please call with a block.\"",
")",
"end",
"object",
".",
"send",
"(",
"\"cached_#{key}\"",
",",
"opts",
")",
"end"
] | Lookup something from the cache.
If no block is provided, create one dynamically. If a block is
provided, it is only used the first time it is encountered.
This allows you to dynamically define your caches while still
returning the results of your query.
@return a WillPaginate::Collection if the options include :page,
a Fixnum count if the request is for a count or the results of
the ActiveRecord query otherwise. | [
"Lookup",
"something",
"from",
"the",
"cache",
"."
] | 8a1e21b970aae37a3206a4ee08efa6f1002fc9e0 | https://github.com/kjvarga/arid_cache/blob/8a1e21b970aae37a3206a4ee08efa6f1002fc9e0/lib/arid_cache/helpers.rb#L14-L35 |
5,488 | kjvarga/arid_cache | lib/arid_cache/helpers.rb | AridCache.Helpers.define | def define(object, key, opts, fetch_method=:fetch, method_name=nil, &block)
# FIXME: Pass default options to store.add
# Pass nil in for now until we get the cache_ calls working.
# This means that the first time you define a dynamic cache
# (by passing in a block), the options you used are not
# stored in the blueprint and applied to each subsequent call.
#
# Otherwise we have a situation where a :limit passed in to the
# first call persists when no options are passed in on subsequent calls,
# but if a different :limit is passed in that limit is applied.
#
# I think in this scenario one would expect no limit to be applied
# if no options are passed in.
#
# When the cache_ methods are supported, those options should be
# remembered and applied to the collection however.
blueprint = AridCache.store.add_object_cache_configuration(object, key, nil, block)
method_for_cached(object, key, fetch_method, method_name)
blueprint
end | ruby | def define(object, key, opts, fetch_method=:fetch, method_name=nil, &block)
# FIXME: Pass default options to store.add
# Pass nil in for now until we get the cache_ calls working.
# This means that the first time you define a dynamic cache
# (by passing in a block), the options you used are not
# stored in the blueprint and applied to each subsequent call.
#
# Otherwise we have a situation where a :limit passed in to the
# first call persists when no options are passed in on subsequent calls,
# but if a different :limit is passed in that limit is applied.
#
# I think in this scenario one would expect no limit to be applied
# if no options are passed in.
#
# When the cache_ methods are supported, those options should be
# remembered and applied to the collection however.
blueprint = AridCache.store.add_object_cache_configuration(object, key, nil, block)
method_for_cached(object, key, fetch_method, method_name)
blueprint
end | [
"def",
"define",
"(",
"object",
",",
"key",
",",
"opts",
",",
"fetch_method",
"=",
":fetch",
",",
"method_name",
"=",
"nil",
",",
"&",
"block",
")",
"# FIXME: Pass default options to store.add",
"# Pass nil in for now until we get the cache_ calls working.",
"# This means that the first time you define a dynamic cache",
"# (by passing in a block), the options you used are not",
"# stored in the blueprint and applied to each subsequent call.",
"#",
"# Otherwise we have a situation where a :limit passed in to the",
"# first call persists when no options are passed in on subsequent calls,",
"# but if a different :limit is passed in that limit is applied.",
"#",
"# I think in this scenario one would expect no limit to be applied",
"# if no options are passed in.",
"#",
"# When the cache_ methods are supported, those options should be",
"# remembered and applied to the collection however.",
"blueprint",
"=",
"AridCache",
".",
"store",
".",
"add_object_cache_configuration",
"(",
"object",
",",
"key",
",",
"nil",
",",
"block",
")",
"method_for_cached",
"(",
"object",
",",
"key",
",",
"fetch_method",
",",
"method_name",
")",
"blueprint",
"end"
] | Store the options and optional block for a call to the cache.
If no block is provided, create one dynamically.
@return an AridCache::Store::Blueprint. | [
"Store",
"the",
"options",
"and",
"optional",
"block",
"for",
"a",
"call",
"to",
"the",
"cache",
"."
] | 8a1e21b970aae37a3206a4ee08efa6f1002fc9e0 | https://github.com/kjvarga/arid_cache/blob/8a1e21b970aae37a3206a4ee08efa6f1002fc9e0/lib/arid_cache/helpers.rb#L42-L62 |
5,489 | kjvarga/arid_cache | lib/arid_cache/helpers.rb | AridCache.Helpers.class_name | def class_name(object, *modifiers)
name = object.is_a?(Class) ? object.name : object.class.name
name = 'AnonymousClass' if name.nil?
while modifier = modifiers.shift
case modifier
when :downcase
name = name.downcase
when :pluralize
name = AridCache::Inflector.pluralize(name)
else
raise ArgumentError.new("Unsupported modifier #{modifier.inspect}")
end
end
name
end | ruby | def class_name(object, *modifiers)
name = object.is_a?(Class) ? object.name : object.class.name
name = 'AnonymousClass' if name.nil?
while modifier = modifiers.shift
case modifier
when :downcase
name = name.downcase
when :pluralize
name = AridCache::Inflector.pluralize(name)
else
raise ArgumentError.new("Unsupported modifier #{modifier.inspect}")
end
end
name
end | [
"def",
"class_name",
"(",
"object",
",",
"*",
"modifiers",
")",
"name",
"=",
"object",
".",
"is_a?",
"(",
"Class",
")",
"?",
"object",
".",
"name",
":",
"object",
".",
"class",
".",
"name",
"name",
"=",
"'AnonymousClass'",
"if",
"name",
".",
"nil?",
"while",
"modifier",
"=",
"modifiers",
".",
"shift",
"case",
"modifier",
"when",
":downcase",
"name",
"=",
"name",
".",
"downcase",
"when",
":pluralize",
"name",
"=",
"AridCache",
"::",
"Inflector",
".",
"pluralize",
"(",
"name",
")",
"else",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Unsupported modifier #{modifier.inspect}\"",
")",
"end",
"end",
"name",
"end"
] | Return the object's class name.
== Arguments
* +object+ - an instance or class. If it's an anonymous class, the name is nil
so we return 'anonymous_class' and 'anonymous_instance'.
* +modifiers+ - one or more symbols indicating the order and type of modification
to perform on the result. Choose from: :downcase (return lowercase name),
:pluralize (pluralize the name) | [
"Return",
"the",
"object",
"s",
"class",
"name",
"."
] | 8a1e21b970aae37a3206a4ee08efa6f1002fc9e0 | https://github.com/kjvarga/arid_cache/blob/8a1e21b970aae37a3206a4ee08efa6f1002fc9e0/lib/arid_cache/helpers.rb#L78-L92 |
5,490 | teknobingo/trust | lib/trust/permissions.rb | Trust.Permissions.authorized? | def authorized?
trace 'authorized?', 0, "@user: #{@user.inspect}, @action: #{@action.inspect}, @klass: #{@klass.inspect}, @subject: #{@subject.inspect}, @parent: #{@parent.inspect}"
if params_handler = (user && (permission_by_role || permission_by_member_role))
params_handler = params_handler_default(params_handler)
end
params_handler
end | ruby | def authorized?
trace 'authorized?', 0, "@user: #{@user.inspect}, @action: #{@action.inspect}, @klass: #{@klass.inspect}, @subject: #{@subject.inspect}, @parent: #{@parent.inspect}"
if params_handler = (user && (permission_by_role || permission_by_member_role))
params_handler = params_handler_default(params_handler)
end
params_handler
end | [
"def",
"authorized?",
"trace",
"'authorized?'",
",",
"0",
",",
"\"@user: #{@user.inspect}, @action: #{@action.inspect}, @klass: #{@klass.inspect}, @subject: #{@subject.inspect}, @parent: #{@parent.inspect}\"",
"if",
"params_handler",
"=",
"(",
"user",
"&&",
"(",
"permission_by_role",
"||",
"permission_by_member_role",
")",
")",
"params_handler",
"=",
"params_handler_default",
"(",
"params_handler",
")",
"end",
"params_handler",
"end"
] | Initializes the permission object
calling the +authorized?+ method on the instance later will test for the authorization.
== Parameters:
+user+ - user object, must respond to role_symbols
+action+ - action, such as :create, :show, etc. Should not be an alias
+klass+ - the class of the subject.
+subject+ - the subject tested for authorization
+parent+ - the parent object, normally declared through belongs_to
See {Trust::Authorization} for more details
Returns params_handler if the user is authorized to perform the action
The handler contains information used by the resource on retrieing parametes later | [
"Initializes",
"the",
"permission",
"object"
] | 715c5395536c7b312bc166f09f64a1c0d48bee23 | https://github.com/teknobingo/trust/blob/715c5395536c7b312bc166f09f64a1c0d48bee23/lib/trust/permissions.rb#L155-L161 |
5,491 | teknobingo/trust | lib/trust/permissions.rb | Trust.Permissions.permission_by_member_role | def permission_by_member_role
m = members_role
trace 'authorize_by_member_role?', 0, "#{user.try(:name)}:#{m}"
p = member_permissions[m]
trace 'authorize_by_role?', 1, "permissions: #{p.inspect}"
p && authorization(p)
end | ruby | def permission_by_member_role
m = members_role
trace 'authorize_by_member_role?', 0, "#{user.try(:name)}:#{m}"
p = member_permissions[m]
trace 'authorize_by_role?', 1, "permissions: #{p.inspect}"
p && authorization(p)
end | [
"def",
"permission_by_member_role",
"m",
"=",
"members_role",
"trace",
"'authorize_by_member_role?'",
",",
"0",
",",
"\"#{user.try(:name)}:#{m}\"",
"p",
"=",
"member_permissions",
"[",
"m",
"]",
"trace",
"'authorize_by_role?'",
",",
"1",
",",
"\"permissions: #{p.inspect}\"",
"p",
"&&",
"authorization",
"(",
"p",
")",
"end"
] | Checks is a member is authorized
You will need to implement members_role in permissions yourself | [
"Checks",
"is",
"a",
"member",
"is",
"authorized",
"You",
"will",
"need",
"to",
"implement",
"members_role",
"in",
"permissions",
"yourself"
] | 715c5395536c7b312bc166f09f64a1c0d48bee23 | https://github.com/teknobingo/trust/blob/715c5395536c7b312bc166f09f64a1c0d48bee23/lib/trust/permissions.rb#L264-L270 |
5,492 | ManageIQ/polisher | lib/polisher/gem/state.rb | Polisher.GemState.state | def state(args = {})
return :available if koji_state(args) == :available
state = distgit_state(args)
return :needs_repo if state == :missing_repo
return :needs_branch if state == :missing_branch
return :needs_spec if state == :missing_spec
return :needs_build if state == :available
return :needs_update
end | ruby | def state(args = {})
return :available if koji_state(args) == :available
state = distgit_state(args)
return :needs_repo if state == :missing_repo
return :needs_branch if state == :missing_branch
return :needs_spec if state == :missing_spec
return :needs_build if state == :available
return :needs_update
end | [
"def",
"state",
"(",
"args",
"=",
"{",
"}",
")",
"return",
":available",
"if",
"koji_state",
"(",
"args",
")",
"==",
":available",
"state",
"=",
"distgit_state",
"(",
"args",
")",
"return",
":needs_repo",
"if",
"state",
"==",
":missing_repo",
"return",
":needs_branch",
"if",
"state",
"==",
":missing_branch",
"return",
":needs_spec",
"if",
"state",
"==",
":missing_spec",
"return",
":needs_build",
"if",
"state",
"==",
":available",
"return",
":needs_update",
"end"
] | Return the 'state' of the gem as inferred by
the targets which there are versions for.
If optional :check argument is specified, version
analysis will be restricted to targets satisfying
the specified gem dependency requirements | [
"Return",
"the",
"state",
"of",
"the",
"gem",
"as",
"inferred",
"by",
"the",
"targets",
"which",
"there",
"are",
"versions",
"for",
"."
] | 8c19023c72573999c9dc53ec2e2a3eef11a9531e | https://github.com/ManageIQ/polisher/blob/8c19023c72573999c9dc53ec2e2a3eef11a9531e/lib/polisher/gem/state.rb#L75-L84 |
5,493 | Merovex/verku | lib/verku/source_list.rb | Verku.SourceList.entries | def entries
Dir.entries(source).sort.each_with_object([]) do |entry, buffer|
buffer << source.join(entry) if valid_entry?(entry)
end
end | ruby | def entries
Dir.entries(source).sort.each_with_object([]) do |entry, buffer|
buffer << source.join(entry) if valid_entry?(entry)
end
end | [
"def",
"entries",
"Dir",
".",
"entries",
"(",
"source",
")",
".",
"sort",
".",
"each_with_object",
"(",
"[",
"]",
")",
"do",
"|",
"entry",
",",
"buffer",
"|",
"buffer",
"<<",
"source",
".",
"join",
"(",
"entry",
")",
"if",
"valid_entry?",
"(",
"entry",
")",
"end",
"end"
] | Return a list of all recognized files. | [
"Return",
"a",
"list",
"of",
"all",
"recognized",
"files",
"."
] | 3d247449ec5192d584943c5552f284679a37e3c0 | https://github.com/Merovex/verku/blob/3d247449ec5192d584943c5552f284679a37e3c0/lib/verku/source_list.rb#L48-L52 |
5,494 | Merovex/verku | lib/verku/source_list.rb | Verku.SourceList.valid_directory? | def valid_directory?(entry)
File.directory?(source.join(entry)) && !IGNORE_DIR.include?(File.basename(entry))
end | ruby | def valid_directory?(entry)
File.directory?(source.join(entry)) && !IGNORE_DIR.include?(File.basename(entry))
end | [
"def",
"valid_directory?",
"(",
"entry",
")",
"File",
".",
"directory?",
"(",
"source",
".",
"join",
"(",
"entry",
")",
")",
"&&",
"!",
"IGNORE_DIR",
".",
"include?",
"(",
"File",
".",
"basename",
"(",
"entry",
")",
")",
"end"
] | Check if path is a valid directory. | [
"Check",
"if",
"path",
"is",
"a",
"valid",
"directory",
"."
] | 3d247449ec5192d584943c5552f284679a37e3c0 | https://github.com/Merovex/verku/blob/3d247449ec5192d584943c5552f284679a37e3c0/lib/verku/source_list.rb#L62-L64 |
5,495 | Merovex/verku | lib/verku/source_list.rb | Verku.SourceList.valid_file? | def valid_file?(entry)
ext = File.extname(entry).gsub(/\./, "").downcase
File.file?(source.join(entry)) && EXTENSIONS.include?(ext) && entry !~ IGNORE_FILES
end | ruby | def valid_file?(entry)
ext = File.extname(entry).gsub(/\./, "").downcase
File.file?(source.join(entry)) && EXTENSIONS.include?(ext) && entry !~ IGNORE_FILES
end | [
"def",
"valid_file?",
"(",
"entry",
")",
"ext",
"=",
"File",
".",
"extname",
"(",
"entry",
")",
".",
"gsub",
"(",
"/",
"\\.",
"/",
",",
"\"\"",
")",
".",
"downcase",
"File",
".",
"file?",
"(",
"source",
".",
"join",
"(",
"entry",
")",
")",
"&&",
"EXTENSIONS",
".",
"include?",
"(",
"ext",
")",
"&&",
"entry",
"!~",
"IGNORE_FILES",
"end"
] | Check if path is a valid file. | [
"Check",
"if",
"path",
"is",
"a",
"valid",
"file",
"."
] | 3d247449ec5192d584943c5552f284679a37e3c0 | https://github.com/Merovex/verku/blob/3d247449ec5192d584943c5552f284679a37e3c0/lib/verku/source_list.rb#L68-L71 |
5,496 | andrba/hungryform | lib/hungryform/form.rb | HungryForm.Form.validate | def validate
is_valid = true
pages.each do |page|
# Loop through pages to get all errors
is_valid = false if page.invalid?
end
is_valid
end | ruby | def validate
is_valid = true
pages.each do |page|
# Loop through pages to get all errors
is_valid = false if page.invalid?
end
is_valid
end | [
"def",
"validate",
"is_valid",
"=",
"true",
"pages",
".",
"each",
"do",
"|",
"page",
"|",
"# Loop through pages to get all errors",
"is_valid",
"=",
"false",
"if",
"page",
".",
"invalid?",
"end",
"is_valid",
"end"
] | Entire form validation. Loops through the form pages and
validates each page individually. | [
"Entire",
"form",
"validation",
".",
"Loops",
"through",
"the",
"form",
"pages",
"and",
"validates",
"each",
"page",
"individually",
"."
] | d9d9dad9d8409323910372372c3c7672bd8bf478 | https://github.com/andrba/hungryform/blob/d9d9dad9d8409323910372372c3c7672bd8bf478/lib/hungryform/form.rb#L63-L72 |
5,497 | andrba/hungryform | lib/hungryform/form.rb | HungryForm.Form.values | def values
active_elements = elements.select do |_, el|
el.is_a? Elements::Base::ActiveElement
end
active_elements.each_with_object({}) do |(name, el), o|
o[name.to_sym] = el.value
end
end | ruby | def values
active_elements = elements.select do |_, el|
el.is_a? Elements::Base::ActiveElement
end
active_elements.each_with_object({}) do |(name, el), o|
o[name.to_sym] = el.value
end
end | [
"def",
"values",
"active_elements",
"=",
"elements",
".",
"select",
"do",
"|",
"_",
",",
"el",
"|",
"el",
".",
"is_a?",
"Elements",
"::",
"Base",
"::",
"ActiveElement",
"end",
"active_elements",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"name",
",",
"el",
")",
",",
"o",
"|",
"o",
"[",
"name",
".",
"to_sym",
"]",
"=",
"el",
".",
"value",
"end",
"end"
] | Create a hash of form elements values | [
"Create",
"a",
"hash",
"of",
"form",
"elements",
"values"
] | d9d9dad9d8409323910372372c3c7672bd8bf478 | https://github.com/andrba/hungryform/blob/d9d9dad9d8409323910372372c3c7672bd8bf478/lib/hungryform/form.rb#L98-L106 |
5,498 | razor-x/config_curator | lib/config_curator/cli.rb | ConfigCurator.CLI.install | def install(manifest = 'manifest.yml')
unless File.exist? manifest
logger.fatal { "Manifest file '#{manifest}' does not exist." }
return false
end
collection.load_manifest manifest
result = options[:dryrun] ? collection.install? : collection.install
msg = install_message(result, options[:dryrun])
result ? logger.info(msg) : logger.error(msg)
result
end | ruby | def install(manifest = 'manifest.yml')
unless File.exist? manifest
logger.fatal { "Manifest file '#{manifest}' does not exist." }
return false
end
collection.load_manifest manifest
result = options[:dryrun] ? collection.install? : collection.install
msg = install_message(result, options[:dryrun])
result ? logger.info(msg) : logger.error(msg)
result
end | [
"def",
"install",
"(",
"manifest",
"=",
"'manifest.yml'",
")",
"unless",
"File",
".",
"exist?",
"manifest",
"logger",
".",
"fatal",
"{",
"\"Manifest file '#{manifest}' does not exist.\"",
"}",
"return",
"false",
"end",
"collection",
".",
"load_manifest",
"manifest",
"result",
"=",
"options",
"[",
":dryrun",
"]",
"?",
"collection",
".",
"install?",
":",
"collection",
".",
"install",
"msg",
"=",
"install_message",
"(",
"result",
",",
"options",
"[",
":dryrun",
"]",
")",
"result",
"?",
"logger",
".",
"info",
"(",
"msg",
")",
":",
"logger",
".",
"error",
"(",
"msg",
")",
"result",
"end"
] | Installs the collection.
@param manifest [String] path to the manifest file to use
@return [Boolean] value of {Collection#install} or {Collection#install?} | [
"Installs",
"the",
"collection",
"."
] | b0c0742ba0c36acf66de3eafd23a7d17b210036b | https://github.com/razor-x/config_curator/blob/b0c0742ba0c36acf66de3eafd23a7d17b210036b/lib/config_curator/cli.rb#L20-L32 |
5,499 | ksylvest/attached | lib/attached.rb | Attached.ClassMethods.number_to_size | def number_to_size(number, options = {})
return if number == 0.0 / 1.0
return if number == 1.0 / 0.0
singular = options[:singular] || 1
base = options[:base] || 1024
units = options[:units] || ["byte", "kilobyte", "megabyte", "gigabyte", "terabyte", "petabyte"]
exponent = (Math.log(number) / Math.log(base)).floor
number /= base ** exponent
unit = units[exponent]
number == singular ? unit.gsub!(/s$/, '') : unit.gsub!(/$/, 's')
"#{number} #{unit}"
end | ruby | def number_to_size(number, options = {})
return if number == 0.0 / 1.0
return if number == 1.0 / 0.0
singular = options[:singular] || 1
base = options[:base] || 1024
units = options[:units] || ["byte", "kilobyte", "megabyte", "gigabyte", "terabyte", "petabyte"]
exponent = (Math.log(number) / Math.log(base)).floor
number /= base ** exponent
unit = units[exponent]
number == singular ? unit.gsub!(/s$/, '') : unit.gsub!(/$/, 's')
"#{number} #{unit}"
end | [
"def",
"number_to_size",
"(",
"number",
",",
"options",
"=",
"{",
"}",
")",
"return",
"if",
"number",
"==",
"0.0",
"/",
"1.0",
"return",
"if",
"number",
"==",
"1.0",
"/",
"0.0",
"singular",
"=",
"options",
"[",
":singular",
"]",
"||",
"1",
"base",
"=",
"options",
"[",
":base",
"]",
"||",
"1024",
"units",
"=",
"options",
"[",
":units",
"]",
"||",
"[",
"\"byte\"",
",",
"\"kilobyte\"",
",",
"\"megabyte\"",
",",
"\"gigabyte\"",
",",
"\"terabyte\"",
",",
"\"petabyte\"",
"]",
"exponent",
"=",
"(",
"Math",
".",
"log",
"(",
"number",
")",
"/",
"Math",
".",
"log",
"(",
"base",
")",
")",
".",
"floor",
"number",
"/=",
"base",
"**",
"exponent",
"unit",
"=",
"units",
"[",
"exponent",
"]",
"number",
"==",
"singular",
"?",
"unit",
".",
"gsub!",
"(",
"/",
"/",
",",
"''",
")",
":",
"unit",
".",
"gsub!",
"(",
"/",
"/",
",",
"'s'",
")",
"\"#{number} #{unit}\"",
"end"
] | Convert a number to a human readable size.
Usage:
number_to_size(1) # 1 byte
number_to_size(2) # 2 bytes
number_to_size(1024) # 1 kilobyte
number_to_size(2048) # 2 kilobytes | [
"Convert",
"a",
"number",
"to",
"a",
"human",
"readable",
"size",
"."
] | 6ef5681efd94807d334b12d8229b57ac472a6576 | https://github.com/ksylvest/attached/blob/6ef5681efd94807d334b12d8229b57ac472a6576/lib/attached.rb#L134-L150 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.