id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
|
---|---|---|---|---|---|---|---|---|---|---|---|
7,900 |
postmodern/rprogram
|
lib/rprogram/option_list.rb
|
RProgram.OptionList.method_missing
|
def method_missing(sym,*args,&block)
name = sym.to_s
unless block
if (name =~ /=$/ && args.length == 1)
return self[name.chop.to_sym] = args.first
elsif args.empty?
return self[sym]
end
end
return super(sym,*args,&block)
end
|
ruby
|
def method_missing(sym,*args,&block)
name = sym.to_s
unless block
if (name =~ /=$/ && args.length == 1)
return self[name.chop.to_sym] = args.first
elsif args.empty?
return self[sym]
end
end
return super(sym,*args,&block)
end
|
[
"def",
"method_missing",
"(",
"sym",
",",
"*",
"args",
",",
"&",
"block",
")",
"name",
"=",
"sym",
".",
"to_s",
"unless",
"block",
"if",
"(",
"name",
"=~",
"/",
"/",
"&&",
"args",
".",
"length",
"==",
"1",
")",
"return",
"self",
"[",
"name",
".",
"chop",
".",
"to_sym",
"]",
"=",
"args",
".",
"first",
"elsif",
"args",
".",
"empty?",
"return",
"self",
"[",
"sym",
"]",
"end",
"end",
"return",
"super",
"(",
"sym",
",",
"args",
",",
"block",
")",
"end"
] |
Provides transparent access to the options within the option list.
@example
opt_list = OptionList.new(:name => 'test')
opt_list.name
# => "test"
|
[
"Provides",
"transparent",
"access",
"to",
"the",
"options",
"within",
"the",
"option",
"list",
"."
] |
94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be
|
https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/option_list.rb#L24-L36
|
7,901 |
alihuber/http_archive
|
lib/http_archive/archive.rb
|
HttpArchive.Archive.get_total_data
|
def get_total_data
size = calc_total_size.to_s
load_time = (@pages.first.on_load / 1000.0).to_s
[@pages.first.title, @entries.size.to_s, size, load_time]
end
|
ruby
|
def get_total_data
size = calc_total_size.to_s
load_time = (@pages.first.on_load / 1000.0).to_s
[@pages.first.title, @entries.size.to_s, size, load_time]
end
|
[
"def",
"get_total_data",
"size",
"=",
"calc_total_size",
".",
"to_s",
"load_time",
"=",
"(",
"@pages",
".",
"first",
".",
"on_load",
"/",
"1000.0",
")",
".",
"to_s",
"[",
"@pages",
".",
"first",
".",
"title",
",",
"@entries",
".",
"size",
".",
"to_s",
",",
"size",
",",
"load_time",
"]",
"end"
] |
Gets the common data for a page.
Convenience method that can be used for bulk reading of page data.
@return [Array<page_title, ressource_count, total_download_size, overall_load_time>] An array with page data
@example Example of returned Array
["Software is hard", "26", "0.36", "6.745"]
|
[
"Gets",
"the",
"common",
"data",
"for",
"a",
"page",
".",
"Convenience",
"method",
"that",
"can",
"be",
"used",
"for",
"bulk",
"reading",
"of",
"page",
"data",
"."
] |
3fc1e1f4e206ea6b4a68b75199bdda662a4e153a
|
https://github.com/alihuber/http_archive/blob/3fc1e1f4e206ea6b4a68b75199bdda662a4e153a/lib/http_archive/archive.rb#L70-L75
|
7,902 |
alihuber/http_archive
|
lib/http_archive/archive.rb
|
HttpArchive.Archive.get_row_data
|
def get_row_data
rows = []
@entries.each do |entry|
method = entry.request.http_method
# get part after .com/ if any
url = entry.request.url
if url.end_with?("/")
ressource = entry.request.url
else
r = url.rindex("/")
ressource = url[r..-1]
end
# first 30 characters of the ressource name
ressource = ressource[0, 30]
status = entry.response.status.to_s
code = entry.response.status_text
size = (entry.response.content['size'] / 1000.0).round(2).to_s
duration = (entry.time / 1000.0).to_s
rows << [method, ressource, status, code, size, duration]
end
rows
end
|
ruby
|
def get_row_data
rows = []
@entries.each do |entry|
method = entry.request.http_method
# get part after .com/ if any
url = entry.request.url
if url.end_with?("/")
ressource = entry.request.url
else
r = url.rindex("/")
ressource = url[r..-1]
end
# first 30 characters of the ressource name
ressource = ressource[0, 30]
status = entry.response.status.to_s
code = entry.response.status_text
size = (entry.response.content['size'] / 1000.0).round(2).to_s
duration = (entry.time / 1000.0).to_s
rows << [method, ressource, status, code, size, duration]
end
rows
end
|
[
"def",
"get_row_data",
"rows",
"=",
"[",
"]",
"@entries",
".",
"each",
"do",
"|",
"entry",
"|",
"method",
"=",
"entry",
".",
"request",
".",
"http_method",
"# get part after .com/ if any",
"url",
"=",
"entry",
".",
"request",
".",
"url",
"if",
"url",
".",
"end_with?",
"(",
"\"/\"",
")",
"ressource",
"=",
"entry",
".",
"request",
".",
"url",
"else",
"r",
"=",
"url",
".",
"rindex",
"(",
"\"/\"",
")",
"ressource",
"=",
"url",
"[",
"r",
"..",
"-",
"1",
"]",
"end",
"# first 30 characters of the ressource name",
"ressource",
"=",
"ressource",
"[",
"0",
",",
"30",
"]",
"status",
"=",
"entry",
".",
"response",
".",
"status",
".",
"to_s",
"code",
"=",
"entry",
".",
"response",
".",
"status_text",
"size",
"=",
"(",
"entry",
".",
"response",
".",
"content",
"[",
"'size'",
"]",
"/",
"1000.0",
")",
".",
"round",
"(",
"2",
")",
".",
"to_s",
"duration",
"=",
"(",
"entry",
".",
"time",
"/",
"1000.0",
")",
".",
"to_s",
"rows",
"<<",
"[",
"method",
",",
"ressource",
",",
"status",
",",
"code",
",",
"size",
",",
"duration",
"]",
"end",
"rows",
"end"
] |
Gets the data for a row for all entries.
Convenience method that can be used for bulk reading of entry data.
@return [Array<Array<html_method, ressource_name, status_name, status_code, ressource_size, load_duration>>] An array with row data
@example Example of returned Array
[["GET", "/prototype.js?ver=1.6.1", "200", "OK", "139.85", "1.06"], ... ]
|
[
"Gets",
"the",
"data",
"for",
"a",
"row",
"for",
"all",
"entries",
".",
"Convenience",
"method",
"that",
"can",
"be",
"used",
"for",
"bulk",
"reading",
"of",
"entry",
"data",
"."
] |
3fc1e1f4e206ea6b4a68b75199bdda662a4e153a
|
https://github.com/alihuber/http_archive/blob/3fc1e1f4e206ea6b4a68b75199bdda662a4e153a/lib/http_archive/archive.rb#L83-L105
|
7,903 |
jemmyw/bisques
|
lib/bisques/aws_request.rb
|
Bisques.AwsRequest.make_request
|
def make_request
create_authorization
options = {}
options[:header] = authorization.headers.merge(
'Authorization' => authorization.authorization_header
)
options[:query] = query if query.any?
options[:body] = form_body if body
http_response = @httpclient.request(method, url, options)
@response = AwsResponse.new(self, http_response)
freeze
@response
end
|
ruby
|
def make_request
create_authorization
options = {}
options[:header] = authorization.headers.merge(
'Authorization' => authorization.authorization_header
)
options[:query] = query if query.any?
options[:body] = form_body if body
http_response = @httpclient.request(method, url, options)
@response = AwsResponse.new(self, http_response)
freeze
@response
end
|
[
"def",
"make_request",
"create_authorization",
"options",
"=",
"{",
"}",
"options",
"[",
":header",
"]",
"=",
"authorization",
".",
"headers",
".",
"merge",
"(",
"'Authorization'",
"=>",
"authorization",
".",
"authorization_header",
")",
"options",
"[",
":query",
"]",
"=",
"query",
"if",
"query",
".",
"any?",
"options",
"[",
":body",
"]",
"=",
"form_body",
"if",
"body",
"http_response",
"=",
"@httpclient",
".",
"request",
"(",
"method",
",",
"url",
",",
"options",
")",
"@response",
"=",
"AwsResponse",
".",
"new",
"(",
"self",
",",
"http_response",
")",
"freeze",
"@response",
"end"
] |
Send the HTTP request and get a response. Returns an AwsResponse object.
The instance is frozen once this method is called and cannot be used
again.
|
[
"Send",
"the",
"HTTP",
"request",
"and",
"get",
"a",
"response",
".",
"Returns",
"an",
"AwsResponse",
"object",
".",
"The",
"instance",
"is",
"frozen",
"once",
"this",
"method",
"is",
"called",
"and",
"cannot",
"be",
"used",
"again",
"."
] |
c48ab555f07664752bcbf9e8deb99bd75cbdc41b
|
https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/aws_request.rb#L77-L93
|
7,904 |
jemmyw/bisques
|
lib/bisques/aws_request.rb
|
Bisques.AwsRequest.form_body
|
def form_body
if body.is_a?(Hash)
body.map do |k,v|
[AwsRequest.aws_encode(k), AwsRequest.aws_encode(v)].join("=")
end.join("&")
else
body
end
end
|
ruby
|
def form_body
if body.is_a?(Hash)
body.map do |k,v|
[AwsRequest.aws_encode(k), AwsRequest.aws_encode(v)].join("=")
end.join("&")
else
body
end
end
|
[
"def",
"form_body",
"if",
"body",
".",
"is_a?",
"(",
"Hash",
")",
"body",
".",
"map",
"do",
"|",
"k",
",",
"v",
"|",
"[",
"AwsRequest",
".",
"aws_encode",
"(",
"k",
")",
",",
"AwsRequest",
".",
"aws_encode",
"(",
"v",
")",
"]",
".",
"join",
"(",
"\"=\"",
")",
"end",
".",
"join",
"(",
"\"&\"",
")",
"else",
"body",
"end",
"end"
] |
Encode the form params if the body is given as a Hash.
|
[
"Encode",
"the",
"form",
"params",
"if",
"the",
"body",
"is",
"given",
"as",
"a",
"Hash",
"."
] |
c48ab555f07664752bcbf9e8deb99bd75cbdc41b
|
https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/aws_request.rb#L98-L106
|
7,905 |
jemmyw/bisques
|
lib/bisques/aws_request.rb
|
Bisques.AwsRequest.create_authorization
|
def create_authorization
@authorization = AwsRequestAuthorization.new.tap do |authorization|
authorization.url = url
authorization.method = method
authorization.query = query
authorization.body = form_body
authorization.region = region
authorization.service = service
authorization.credentials = credentials
authorization.headers = headers
end
end
|
ruby
|
def create_authorization
@authorization = AwsRequestAuthorization.new.tap do |authorization|
authorization.url = url
authorization.method = method
authorization.query = query
authorization.body = form_body
authorization.region = region
authorization.service = service
authorization.credentials = credentials
authorization.headers = headers
end
end
|
[
"def",
"create_authorization",
"@authorization",
"=",
"AwsRequestAuthorization",
".",
"new",
".",
"tap",
"do",
"|",
"authorization",
"|",
"authorization",
".",
"url",
"=",
"url",
"authorization",
".",
"method",
"=",
"method",
"authorization",
".",
"query",
"=",
"query",
"authorization",
".",
"body",
"=",
"form_body",
"authorization",
".",
"region",
"=",
"region",
"authorization",
".",
"service",
"=",
"service",
"authorization",
".",
"credentials",
"=",
"credentials",
"authorization",
".",
"headers",
"=",
"headers",
"end",
"end"
] |
Create the AwsRequestAuthorization object for the request.
|
[
"Create",
"the",
"AwsRequestAuthorization",
"object",
"for",
"the",
"request",
"."
] |
c48ab555f07664752bcbf9e8deb99bd75cbdc41b
|
https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/aws_request.rb#L109-L120
|
7,906 |
jemmyw/bisques
|
lib/bisques/queue.rb
|
Bisques.Queue.retrieve
|
def retrieve(poll_time = 1)
response = client.receive_message(url, {"WaitTimeSeconds" => poll_time, "MaxNumberOfMessages" => 1})
raise QueueNotFound.new(self, "not found at #{url}") if response.http_response.status == 404
response.doc.xpath("//Message").map do |element|
attributes = Hash[*element.xpath("Attribute").map do |attr_element|
[attr_element.xpath("Name").text, attr_element.xpath("Value").text]
end.flatten]
Message.new(self, element.xpath("MessageId").text,
element.xpath("ReceiptHandle").text,
element.xpath("Body").text,
attributes
)
end.first
end
|
ruby
|
def retrieve(poll_time = 1)
response = client.receive_message(url, {"WaitTimeSeconds" => poll_time, "MaxNumberOfMessages" => 1})
raise QueueNotFound.new(self, "not found at #{url}") if response.http_response.status == 404
response.doc.xpath("//Message").map do |element|
attributes = Hash[*element.xpath("Attribute").map do |attr_element|
[attr_element.xpath("Name").text, attr_element.xpath("Value").text]
end.flatten]
Message.new(self, element.xpath("MessageId").text,
element.xpath("ReceiptHandle").text,
element.xpath("Body").text,
attributes
)
end.first
end
|
[
"def",
"retrieve",
"(",
"poll_time",
"=",
"1",
")",
"response",
"=",
"client",
".",
"receive_message",
"(",
"url",
",",
"{",
"\"WaitTimeSeconds\"",
"=>",
"poll_time",
",",
"\"MaxNumberOfMessages\"",
"=>",
"1",
"}",
")",
"raise",
"QueueNotFound",
".",
"new",
"(",
"self",
",",
"\"not found at #{url}\"",
")",
"if",
"response",
".",
"http_response",
".",
"status",
"==",
"404",
"response",
".",
"doc",
".",
"xpath",
"(",
"\"//Message\"",
")",
".",
"map",
"do",
"|",
"element",
"|",
"attributes",
"=",
"Hash",
"[",
"element",
".",
"xpath",
"(",
"\"Attribute\"",
")",
".",
"map",
"do",
"|",
"attr_element",
"|",
"[",
"attr_element",
".",
"xpath",
"(",
"\"Name\"",
")",
".",
"text",
",",
"attr_element",
".",
"xpath",
"(",
"\"Value\"",
")",
".",
"text",
"]",
"end",
".",
"flatten",
"]",
"Message",
".",
"new",
"(",
"self",
",",
"element",
".",
"xpath",
"(",
"\"MessageId\"",
")",
".",
"text",
",",
"element",
".",
"xpath",
"(",
"\"ReceiptHandle\"",
")",
".",
"text",
",",
"element",
".",
"xpath",
"(",
"\"Body\"",
")",
".",
"text",
",",
"attributes",
")",
"end",
".",
"first",
"end"
] |
Retrieve a message from the queue. Returns nil if no message is waiting
in the given poll time. Otherwise it returns a Message.
@param [Fixnum] poll_time
@return [Message,nil]
@raise [AwsActionError]
|
[
"Retrieve",
"a",
"message",
"from",
"the",
"queue",
".",
"Returns",
"nil",
"if",
"no",
"message",
"is",
"waiting",
"in",
"the",
"given",
"poll",
"time",
".",
"Otherwise",
"it",
"returns",
"a",
"Message",
"."
] |
c48ab555f07664752bcbf9e8deb99bd75cbdc41b
|
https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/queue.rb#L142-L157
|
7,907 |
NullVoxPopuli/authorizable
|
lib/authorizable/proxy.rb
|
Authorizable.Proxy.process_permission
|
def process_permission(permission, *args)
cached = value_from_cache(permission, *args)
if cached.nil?
evaluate_permission(permission, *args)
else
cached
end
end
|
ruby
|
def process_permission(permission, *args)
cached = value_from_cache(permission, *args)
if cached.nil?
evaluate_permission(permission, *args)
else
cached
end
end
|
[
"def",
"process_permission",
"(",
"permission",
",",
"*",
"args",
")",
"cached",
"=",
"value_from_cache",
"(",
"permission",
",",
"args",
")",
"if",
"cached",
".",
"nil?",
"evaluate_permission",
"(",
"permission",
",",
"args",
")",
"else",
"cached",
"end",
"end"
] |
checks if the permission has already been calculated
otherwise the permission needs to be evaluated
|
[
"checks",
"if",
"the",
"permission",
"has",
"already",
"been",
"calculated",
"otherwise",
"the",
"permission",
"needs",
"to",
"be",
"evaluated"
] |
6a4ef94848861bb79b0ab1454264366aed4e2db8
|
https://github.com/NullVoxPopuli/authorizable/blob/6a4ef94848861bb79b0ab1454264366aed4e2db8/lib/authorizable/proxy.rb#L55-L63
|
7,908 |
NullVoxPopuli/authorizable
|
lib/authorizable/proxy.rb
|
Authorizable.Proxy.value_from_cache
|
def value_from_cache(permission, *args)
# object; Event, Discount, etc
o = args[0]
role = get_role_of(o)
# don't perform the permission evaluation, if we have already computed it
cache.get_for_role(permission, role)
end
|
ruby
|
def value_from_cache(permission, *args)
# object; Event, Discount, etc
o = args[0]
role = get_role_of(o)
# don't perform the permission evaluation, if we have already computed it
cache.get_for_role(permission, role)
end
|
[
"def",
"value_from_cache",
"(",
"permission",
",",
"*",
"args",
")",
"# object; Event, Discount, etc",
"o",
"=",
"args",
"[",
"0",
"]",
"role",
"=",
"get_role_of",
"(",
"o",
")",
"# don't perform the permission evaluation, if we have already computed it",
"cache",
".",
"get_for_role",
"(",
"permission",
",",
"role",
")",
"end"
] |
checks the cache if we have calculated this permission before
@return [Boolean|NilClass]
|
[
"checks",
"the",
"cache",
"if",
"we",
"have",
"calculated",
"this",
"permission",
"before"
] |
6a4ef94848861bb79b0ab1454264366aed4e2db8
|
https://github.com/NullVoxPopuli/authorizable/blob/6a4ef94848861bb79b0ab1454264366aed4e2db8/lib/authorizable/proxy.rb#L67-L74
|
7,909 |
NullVoxPopuli/authorizable
|
lib/authorizable/proxy.rb
|
Authorizable.Proxy.evaluate_permission
|
def evaluate_permission(permission, *args)
# object; Event, Discount, etc
o = args[0]
# default to allow
result = true
role = get_role_of(o)
# evaluate procs
if (proc = PermissionUtilities.has_procs?(permission))
result &= proc.call(o, self)
end
# Here is where the addition of adding collaborations may reside
# finally, determine if the user (self) can do the requested action
result &= allowed_to_perform?(permission, role)
# so we don't need to do everything again
cache.set_for_role(
name: permission,
value: result,
role: role
)
result
end
|
ruby
|
def evaluate_permission(permission, *args)
# object; Event, Discount, etc
o = args[0]
# default to allow
result = true
role = get_role_of(o)
# evaluate procs
if (proc = PermissionUtilities.has_procs?(permission))
result &= proc.call(o, self)
end
# Here is where the addition of adding collaborations may reside
# finally, determine if the user (self) can do the requested action
result &= allowed_to_perform?(permission, role)
# so we don't need to do everything again
cache.set_for_role(
name: permission,
value: result,
role: role
)
result
end
|
[
"def",
"evaluate_permission",
"(",
"permission",
",",
"*",
"args",
")",
"# object; Event, Discount, etc",
"o",
"=",
"args",
"[",
"0",
"]",
"# default to allow",
"result",
"=",
"true",
"role",
"=",
"get_role_of",
"(",
"o",
")",
"# evaluate procs",
"if",
"(",
"proc",
"=",
"PermissionUtilities",
".",
"has_procs?",
"(",
"permission",
")",
")",
"result",
"&=",
"proc",
".",
"call",
"(",
"o",
",",
"self",
")",
"end",
"# Here is where the addition of adding collaborations may reside",
"# finally, determine if the user (self) can do the requested action",
"result",
"&=",
"allowed_to_perform?",
"(",
"permission",
",",
"role",
")",
"# so we don't need to do everything again",
"cache",
".",
"set_for_role",
"(",
"name",
":",
"permission",
",",
"value",
":",
"result",
",",
"role",
":",
"role",
")",
"result",
"end"
] |
performs a full evaluation of the permission
@return [Boolean]
|
[
"performs",
"a",
"full",
"evaluation",
"of",
"the",
"permission"
] |
6a4ef94848861bb79b0ab1454264366aed4e2db8
|
https://github.com/NullVoxPopuli/authorizable/blob/6a4ef94848861bb79b0ab1454264366aed4e2db8/lib/authorizable/proxy.rb#L78-L104
|
7,910 |
NullVoxPopuli/authorizable
|
lib/authorizable/proxy.rb
|
Authorizable.Proxy.has_role_with
|
def has_role_with(object)
if object.respond_to?(:user_id)
if object.user_id == actor.id
return IS_OWNER
else
return IS_UNRELATED
end
end
# hopefully the object passed always responds to user_id
IS_UNRELATED
end
|
ruby
|
def has_role_with(object)
if object.respond_to?(:user_id)
if object.user_id == actor.id
return IS_OWNER
else
return IS_UNRELATED
end
end
# hopefully the object passed always responds to user_id
IS_UNRELATED
end
|
[
"def",
"has_role_with",
"(",
"object",
")",
"if",
"object",
".",
"respond_to?",
"(",
":user_id",
")",
"if",
"object",
".",
"user_id",
"==",
"actor",
".",
"id",
"return",
"IS_OWNER",
"else",
"return",
"IS_UNRELATED",
"end",
"end",
"# hopefully the object passed always responds to user_id",
"IS_UNRELATED",
"end"
] |
This method can also be overridden if one desires to have multiple types of
ownership, such as a collaborator-type relationship
@param [ActiveRecord::Base] object should be the object that is being tested
if the user can perform the action on
@return [Number] true if self owns object
|
[
"This",
"method",
"can",
"also",
"be",
"overridden",
"if",
"one",
"desires",
"to",
"have",
"multiple",
"types",
"of",
"ownership",
"such",
"as",
"a",
"collaborator",
"-",
"type",
"relationship"
] |
6a4ef94848861bb79b0ab1454264366aed4e2db8
|
https://github.com/NullVoxPopuli/authorizable/blob/6a4ef94848861bb79b0ab1454264366aed4e2db8/lib/authorizable/proxy.rb#L144-L154
|
7,911 |
nanodeath/threadz
|
lib/threadz/thread_pool.rb
|
Threadz.ThreadPool.spawn_thread
|
def spawn_thread
Thread.new do
while true
x = @queue.shift
if x == Directive::SUICIDE_PILL
@worker_threads_count.decrement
Thread.current.terminate
end
Thread.pass
begin
x.job.call(x)
rescue StandardError => e
$stderr.puts "Threadz: Error in thread, but restarting with next job: #{e.inspect}\n#{e.backtrace.join("\n")}"
end
end
end
@worker_threads_count.increment
end
|
ruby
|
def spawn_thread
Thread.new do
while true
x = @queue.shift
if x == Directive::SUICIDE_PILL
@worker_threads_count.decrement
Thread.current.terminate
end
Thread.pass
begin
x.job.call(x)
rescue StandardError => e
$stderr.puts "Threadz: Error in thread, but restarting with next job: #{e.inspect}\n#{e.backtrace.join("\n")}"
end
end
end
@worker_threads_count.increment
end
|
[
"def",
"spawn_thread",
"Thread",
".",
"new",
"do",
"while",
"true",
"x",
"=",
"@queue",
".",
"shift",
"if",
"x",
"==",
"Directive",
"::",
"SUICIDE_PILL",
"@worker_threads_count",
".",
"decrement",
"Thread",
".",
"current",
".",
"terminate",
"end",
"Thread",
".",
"pass",
"begin",
"x",
".",
"job",
".",
"call",
"(",
"x",
")",
"rescue",
"StandardError",
"=>",
"e",
"$stderr",
".",
"puts",
"\"Threadz: Error in thread, but restarting with next job: #{e.inspect}\\n#{e.backtrace.join(\"\\n\")}\"",
"end",
"end",
"end",
"@worker_threads_count",
".",
"increment",
"end"
] |
Spin up a new thread
|
[
"Spin",
"up",
"a",
"new",
"thread"
] |
5d96e052567076d5e86690f3d3703f1082330dd5
|
https://github.com/nanodeath/threadz/blob/5d96e052567076d5e86690f3d3703f1082330dd5/lib/threadz/thread_pool.rb#L77-L94
|
7,912 |
nanodeath/threadz
|
lib/threadz/thread_pool.rb
|
Threadz.ThreadPool.spawn_watch_thread
|
def spawn_watch_thread
@watch_thread = Thread.new do
while true
# If there are idle threads and we're above minimum
if @queue.num_waiting > 0 && @worker_threads_count.value > @min_size # documented
@killscore += THREADS_IDLE_SCORE * @queue.num_waiting
# If there are no threads idle and we have room for more
elsif(@queue.num_waiting == 0 && @worker_threads_count.value < @max_size) # documented
@killscore -= THREADS_BUSY_SCORE * @queue.length
else
# Decay
if @killscore != 0 # documented
@killscore *= 0.9
end
if @killscore.abs < 1
@killscore = 0
end
end
if @killscore.abs >= @killthreshold
@killscore > 0 ? kill_thread : spawn_thread
@killscore = 0
end
Threadz.dputs "killscore: #{@killscore}. waiting: #{@queue.num_waiting}. threads length: #{@worker_threads_count.value}. min/max: [#{@min_size}, #{@max_size}]"
sleep 0.1
end
end
end
|
ruby
|
def spawn_watch_thread
@watch_thread = Thread.new do
while true
# If there are idle threads and we're above minimum
if @queue.num_waiting > 0 && @worker_threads_count.value > @min_size # documented
@killscore += THREADS_IDLE_SCORE * @queue.num_waiting
# If there are no threads idle and we have room for more
elsif(@queue.num_waiting == 0 && @worker_threads_count.value < @max_size) # documented
@killscore -= THREADS_BUSY_SCORE * @queue.length
else
# Decay
if @killscore != 0 # documented
@killscore *= 0.9
end
if @killscore.abs < 1
@killscore = 0
end
end
if @killscore.abs >= @killthreshold
@killscore > 0 ? kill_thread : spawn_thread
@killscore = 0
end
Threadz.dputs "killscore: #{@killscore}. waiting: #{@queue.num_waiting}. threads length: #{@worker_threads_count.value}. min/max: [#{@min_size}, #{@max_size}]"
sleep 0.1
end
end
end
|
[
"def",
"spawn_watch_thread",
"@watch_thread",
"=",
"Thread",
".",
"new",
"do",
"while",
"true",
"# If there are idle threads and we're above minimum",
"if",
"@queue",
".",
"num_waiting",
">",
"0",
"&&",
"@worker_threads_count",
".",
"value",
">",
"@min_size",
"# documented",
"@killscore",
"+=",
"THREADS_IDLE_SCORE",
"*",
"@queue",
".",
"num_waiting",
"# If there are no threads idle and we have room for more",
"elsif",
"(",
"@queue",
".",
"num_waiting",
"==",
"0",
"&&",
"@worker_threads_count",
".",
"value",
"<",
"@max_size",
")",
"# documented",
"@killscore",
"-=",
"THREADS_BUSY_SCORE",
"*",
"@queue",
".",
"length",
"else",
"# Decay",
"if",
"@killscore",
"!=",
"0",
"# documented",
"@killscore",
"*=",
"0.9",
"end",
"if",
"@killscore",
".",
"abs",
"<",
"1",
"@killscore",
"=",
"0",
"end",
"end",
"if",
"@killscore",
".",
"abs",
">=",
"@killthreshold",
"@killscore",
">",
"0",
"?",
"kill_thread",
":",
"spawn_thread",
"@killscore",
"=",
"0",
"end",
"Threadz",
".",
"dputs",
"\"killscore: #{@killscore}. waiting: #{@queue.num_waiting}. threads length: #{@worker_threads_count.value}. min/max: [#{@min_size}, #{@max_size}]\"",
"sleep",
"0.1",
"end",
"end",
"end"
] |
This thread watches over the pool and allocated and deallocates threads
as necessary
|
[
"This",
"thread",
"watches",
"over",
"the",
"pool",
"and",
"allocated",
"and",
"deallocates",
"threads",
"as",
"necessary"
] |
5d96e052567076d5e86690f3d3703f1082330dd5
|
https://github.com/nanodeath/threadz/blob/5d96e052567076d5e86690f3d3703f1082330dd5/lib/threadz/thread_pool.rb#L106-L134
|
7,913 |
jduckett/duck_map
|
lib/duck_map/array_helper.rb
|
DuckMap.ArrayHelper.convert_to
|
def convert_to(values, type)
buffer = []
if values.kind_of?(Array)
values.each do |value|
begin
if type == :string
buffer.push(value.to_s)
elsif type == :symbol
buffer.push(value.to_sym)
end
rescue Exception => e
end
end
else
buffer = values
end
return buffer
end
|
ruby
|
def convert_to(values, type)
buffer = []
if values.kind_of?(Array)
values.each do |value|
begin
if type == :string
buffer.push(value.to_s)
elsif type == :symbol
buffer.push(value.to_sym)
end
rescue Exception => e
end
end
else
buffer = values
end
return buffer
end
|
[
"def",
"convert_to",
"(",
"values",
",",
"type",
")",
"buffer",
"=",
"[",
"]",
"if",
"values",
".",
"kind_of?",
"(",
"Array",
")",
"values",
".",
"each",
"do",
"|",
"value",
"|",
"begin",
"if",
"type",
"==",
":string",
"buffer",
".",
"push",
"(",
"value",
".",
"to_s",
")",
"elsif",
"type",
"==",
":symbol",
"buffer",
".",
"push",
"(",
"value",
".",
"to_sym",
")",
"end",
"rescue",
"Exception",
"=>",
"e",
"end",
"end",
"else",
"buffer",
"=",
"values",
"end",
"return",
"buffer",
"end"
] |
Ensures all values in an Array are of a certain type. This is meant to be used internally
by DuckMap modules and classes.
values = ["new_book", "edit_book", "create_book", "destroy_book"]
values = obj.convert_to(values, :symbol)
puts values #=> [:new_book, :edit_book, :create_book, :destroy_book]
@param [Array] values The Array to inspect and convert.
@param [Symbol] type Valid values are :string and :symbol.
- :string converts all values to a String.
- :symbol converts all values to a Symbol.
@return [Array]
|
[
"Ensures",
"all",
"values",
"in",
"an",
"Array",
"are",
"of",
"a",
"certain",
"type",
".",
"This",
"is",
"meant",
"to",
"be",
"used",
"internally",
"by",
"DuckMap",
"modules",
"and",
"classes",
"."
] |
c510acfa95e8ad4afb1501366058ae88a73704df
|
https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/array_helper.rb#L19-L46
|
7,914 |
kwatch/baby_erubis
|
lib/baby_erubis.rb
|
BabyErubis.Template.from_file
|
def from_file(filename, encoding='utf-8')
mode = "rb:#{encoding}"
mode = "rb" if RUBY_VERSION < '1.9'
input = File.open(filename, mode) {|f| f.read() }
compile(parse(input), filename, 1)
return self
end
|
ruby
|
def from_file(filename, encoding='utf-8')
mode = "rb:#{encoding}"
mode = "rb" if RUBY_VERSION < '1.9'
input = File.open(filename, mode) {|f| f.read() }
compile(parse(input), filename, 1)
return self
end
|
[
"def",
"from_file",
"(",
"filename",
",",
"encoding",
"=",
"'utf-8'",
")",
"mode",
"=",
"\"rb:#{encoding}\"",
"mode",
"=",
"\"rb\"",
"if",
"RUBY_VERSION",
"<",
"'1.9'",
"input",
"=",
"File",
".",
"open",
"(",
"filename",
",",
"mode",
")",
"{",
"|",
"f",
"|",
"f",
".",
"read",
"(",
")",
"}",
"compile",
"(",
"parse",
"(",
"input",
")",
",",
"filename",
",",
"1",
")",
"return",
"self",
"end"
] |
Ruby 2.1 feature
|
[
"Ruby",
"2",
".",
"1",
"feature"
] |
247e105643094942572bb20f517423122fcb5eab
|
https://github.com/kwatch/baby_erubis/blob/247e105643094942572bb20f517423122fcb5eab/lib/baby_erubis.rb#L46-L52
|
7,915 |
kostyantyn/school_friend
|
lib/school_friend/session.rb
|
SchoolFriend.Session.additional_params
|
def additional_params
@additional_params ||= if session_scope?
if oauth2_session?
{application_key: application_key}
else
{application_key: application_key, session_key: options[:session_key]}
end
else
{application_key: application_key}
end
end
|
ruby
|
def additional_params
@additional_params ||= if session_scope?
if oauth2_session?
{application_key: application_key}
else
{application_key: application_key, session_key: options[:session_key]}
end
else
{application_key: application_key}
end
end
|
[
"def",
"additional_params",
"@additional_params",
"||=",
"if",
"session_scope?",
"if",
"oauth2_session?",
"{",
"application_key",
":",
"application_key",
"}",
"else",
"{",
"application_key",
":",
"application_key",
",",
"session_key",
":",
"options",
"[",
":session_key",
"]",
"}",
"end",
"else",
"{",
"application_key",
":",
"application_key",
"}",
"end",
"end"
] |
Returns additional params which are required for all requests.
Depends on request scope.
@return [Hash]
|
[
"Returns",
"additional",
"params",
"which",
"are",
"required",
"for",
"all",
"requests",
".",
"Depends",
"on",
"request",
"scope",
"."
] |
4cfd829bc6ba4b6a9148e6565e5328d5f2ba91e9
|
https://github.com/kostyantyn/school_friend/blob/4cfd829bc6ba4b6a9148e6565e5328d5f2ba91e9/lib/school_friend/session.rb#L164-L174
|
7,916 |
kostyantyn/school_friend
|
lib/school_friend/session.rb
|
SchoolFriend.Session.api_call
|
def api_call(method, params = {}, force_session_call = false)
raise RequireSessionScopeError.new('This API call requires session scope') if force_session_call and application_scope?
uri = build_uri(method, params)
Net::HTTP.get_response(uri)
end
|
ruby
|
def api_call(method, params = {}, force_session_call = false)
raise RequireSessionScopeError.new('This API call requires session scope') if force_session_call and application_scope?
uri = build_uri(method, params)
Net::HTTP.get_response(uri)
end
|
[
"def",
"api_call",
"(",
"method",
",",
"params",
"=",
"{",
"}",
",",
"force_session_call",
"=",
"false",
")",
"raise",
"RequireSessionScopeError",
".",
"new",
"(",
"'This API call requires session scope'",
")",
"if",
"force_session_call",
"and",
"application_scope?",
"uri",
"=",
"build_uri",
"(",
"method",
",",
"params",
")",
"Net",
"::",
"HTTP",
".",
"get_response",
"(",
"uri",
")",
"end"
] |
Performs API call to Odnoklassniki
@example Performs API call in current scope
school_friend = SchoolFriend::Session.new
school_friend.api_call('widget.getWidgets', wids: 'mobile-header,mobile-footer') # Net::HTTPResponse
@example Force performs API call in session scope
school_friend = SchoolFriend::Session.new
school_friend.api_call('widget.getWidgets', {wids: 'mobile-header,mobile-footer'}, true) # SchoolFriend::Session::RequireSessionScopeError
@param [String] method API method
@param [Hash] params params which should be sent to portal
@param [FalseClass, TrueClass] force_session_call says if this call should be performed in session scope
@return [Net::HTTPResponse]
|
[
"Performs",
"API",
"call",
"to",
"Odnoklassniki"
] |
4cfd829bc6ba4b6a9148e6565e5328d5f2ba91e9
|
https://github.com/kostyantyn/school_friend/blob/4cfd829bc6ba4b6a9148e6565e5328d5f2ba91e9/lib/school_friend/session.rb#L191-L196
|
7,917 |
kostyantyn/school_friend
|
lib/school_friend/session.rb
|
SchoolFriend.Session.build_uri
|
def build_uri(method, params = {})
uri = URI(api_server)
uri.path = '/api/' + method.sub('.', '/')
uri.query = URI.encode_www_form(sign(params))
SchoolFriend.logger.debug "API Request: #{uri}"
uri
end
|
ruby
|
def build_uri(method, params = {})
uri = URI(api_server)
uri.path = '/api/' + method.sub('.', '/')
uri.query = URI.encode_www_form(sign(params))
SchoolFriend.logger.debug "API Request: #{uri}"
uri
end
|
[
"def",
"build_uri",
"(",
"method",
",",
"params",
"=",
"{",
"}",
")",
"uri",
"=",
"URI",
"(",
"api_server",
")",
"uri",
".",
"path",
"=",
"'/api/'",
"+",
"method",
".",
"sub",
"(",
"'.'",
",",
"'/'",
")",
"uri",
".",
"query",
"=",
"URI",
".",
"encode_www_form",
"(",
"sign",
"(",
"params",
")",
")",
"SchoolFriend",
".",
"logger",
".",
"debug",
"\"API Request: #{uri}\"",
"uri",
"end"
] |
Builds URI object
@param [String] method request method
@param [Hash] params request params
@return [URI::HTTP]
|
[
"Builds",
"URI",
"object"
] |
4cfd829bc6ba4b6a9148e6565e5328d5f2ba91e9
|
https://github.com/kostyantyn/school_friend/blob/4cfd829bc6ba4b6a9148e6565e5328d5f2ba91e9/lib/school_friend/session.rb#L203-L211
|
7,918 |
NullVoxPopuli/lazy_crud
|
lib/lazy_crud/instance_methods.rb
|
LazyCrud.InstanceMethods.undestroy
|
def undestroy
@resource = resource_proxy(true).find(params[:id])
set_resource_instance
@resource.deleted_at = nil
@resource.save
respond_with(@resource, location: { action: :index })
# flash[:notice] = "#{resource_name} has been undeleted"
# redirect_to action: :index
end
|
ruby
|
def undestroy
@resource = resource_proxy(true).find(params[:id])
set_resource_instance
@resource.deleted_at = nil
@resource.save
respond_with(@resource, location: { action: :index })
# flash[:notice] = "#{resource_name} has been undeleted"
# redirect_to action: :index
end
|
[
"def",
"undestroy",
"@resource",
"=",
"resource_proxy",
"(",
"true",
")",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"set_resource_instance",
"@resource",
".",
"deleted_at",
"=",
"nil",
"@resource",
".",
"save",
"respond_with",
"(",
"@resource",
",",
"location",
":",
"{",
"action",
":",
":index",
"}",
")",
"# flash[:notice] = \"#{resource_name} has been undeleted\"",
"# redirect_to action: :index",
"end"
] |
only works if deleting of resources occurs by setting
the deleted_at field
|
[
"only",
"works",
"if",
"deleting",
"of",
"resources",
"occurs",
"by",
"setting",
"the",
"deleted_at",
"field"
] |
80997de5de9eba4f96121c2bdb11fc4e4b8b754a
|
https://github.com/NullVoxPopuli/lazy_crud/blob/80997de5de9eba4f96121c2bdb11fc4e4b8b754a/lib/lazy_crud/instance_methods.rb#L64-L75
|
7,919 |
NullVoxPopuli/lazy_crud
|
lib/lazy_crud/instance_methods.rb
|
LazyCrud.InstanceMethods.resource_proxy
|
def resource_proxy(with_deleted = false)
proxy = if parent_instance.present?
parent_instance.send(resource_plural_name)
else
self.class.resource_class
end
if with_deleted and proxy.respond_to?(:with_deleted)
proxy = proxy.with_deleted
end
proxy
end
|
ruby
|
def resource_proxy(with_deleted = false)
proxy = if parent_instance.present?
parent_instance.send(resource_plural_name)
else
self.class.resource_class
end
if with_deleted and proxy.respond_to?(:with_deleted)
proxy = proxy.with_deleted
end
proxy
end
|
[
"def",
"resource_proxy",
"(",
"with_deleted",
"=",
"false",
")",
"proxy",
"=",
"if",
"parent_instance",
".",
"present?",
"parent_instance",
".",
"send",
"(",
"resource_plural_name",
")",
"else",
"self",
".",
"class",
".",
"resource_class",
"end",
"if",
"with_deleted",
"and",
"proxy",
".",
"respond_to?",
"(",
":with_deleted",
")",
"proxy",
"=",
"proxy",
".",
"with_deleted",
"end",
"proxy",
"end"
] |
determines if we want to use the parent class if available or
if we just use the resource class
|
[
"determines",
"if",
"we",
"want",
"to",
"use",
"the",
"parent",
"class",
"if",
"available",
"or",
"if",
"we",
"just",
"use",
"the",
"resource",
"class"
] |
80997de5de9eba4f96121c2bdb11fc4e4b8b754a
|
https://github.com/NullVoxPopuli/lazy_crud/blob/80997de5de9eba4f96121c2bdb11fc4e4b8b754a/lib/lazy_crud/instance_methods.rb#L95-L107
|
7,920 |
m-31/puppetdb_query
|
lib/puppetdb_query/parser.rb
|
PuppetDBQuery.Parser.read_maximal_term
|
def read_maximal_term(priority)
return nil if empty?
logger.debug "read maximal term (#{priority})"
first = read_minimal_term
term = add_next_infix_terms(priority, first)
logger.debug "read maximal term: #{term}"
term
end
|
ruby
|
def read_maximal_term(priority)
return nil if empty?
logger.debug "read maximal term (#{priority})"
first = read_minimal_term
term = add_next_infix_terms(priority, first)
logger.debug "read maximal term: #{term}"
term
end
|
[
"def",
"read_maximal_term",
"(",
"priority",
")",
"return",
"nil",
"if",
"empty?",
"logger",
".",
"debug",
"\"read maximal term (#{priority})\"",
"first",
"=",
"read_minimal_term",
"term",
"=",
"add_next_infix_terms",
"(",
"priority",
",",
"first",
")",
"logger",
".",
"debug",
"\"read maximal term: #{term}\"",
"term",
"end"
] |
Reads next maximal term. The following input doesn't make the term more complete.
Respects the priority of operators by comparing it to the given value.
|
[
"Reads",
"next",
"maximal",
"term",
".",
"The",
"following",
"input",
"doesn",
"t",
"make",
"the",
"term",
"more",
"complete",
".",
"Respects",
"the",
"priority",
"of",
"operators",
"by",
"comparing",
"it",
"to",
"the",
"given",
"value",
"."
] |
58103c91f291de8ce28d679256e50ae391b93ecb
|
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/parser.rb#L63-L70
|
7,921 |
innku/kublog
|
app/helpers/kublog/application_helper.rb
|
Kublog.ApplicationHelper.error_messages_for
|
def error_messages_for(*objects)
options = objects.extract_options!
options[:header_message] ||= I18n.t(:"activerecord.errors.header", :default => "Invalid Fields")
options[:message] ||= I18n.t(:"activerecord.errors.message", :default => "Correct the following errors and try again.")
messages = objects.compact.map { |o| o.errors.full_messages }.flatten
unless messages.empty?
content_tag(:div, :class => "error_messages") do
list_items = messages.map { |msg| content_tag(:li, msg) }
content_tag(:h2, options[:header_message]) + content_tag(:p, options[:message]) + content_tag(:ul, list_items.join.html_safe)
end
end
end
|
ruby
|
def error_messages_for(*objects)
options = objects.extract_options!
options[:header_message] ||= I18n.t(:"activerecord.errors.header", :default => "Invalid Fields")
options[:message] ||= I18n.t(:"activerecord.errors.message", :default => "Correct the following errors and try again.")
messages = objects.compact.map { |o| o.errors.full_messages }.flatten
unless messages.empty?
content_tag(:div, :class => "error_messages") do
list_items = messages.map { |msg| content_tag(:li, msg) }
content_tag(:h2, options[:header_message]) + content_tag(:p, options[:message]) + content_tag(:ul, list_items.join.html_safe)
end
end
end
|
[
"def",
"error_messages_for",
"(",
"*",
"objects",
")",
"options",
"=",
"objects",
".",
"extract_options!",
"options",
"[",
":header_message",
"]",
"||=",
"I18n",
".",
"t",
"(",
":\"",
"\"",
",",
":default",
"=>",
"\"Invalid Fields\"",
")",
"options",
"[",
":message",
"]",
"||=",
"I18n",
".",
"t",
"(",
":\"",
"\"",
",",
":default",
"=>",
"\"Correct the following errors and try again.\"",
")",
"messages",
"=",
"objects",
".",
"compact",
".",
"map",
"{",
"|",
"o",
"|",
"o",
".",
"errors",
".",
"full_messages",
"}",
".",
"flatten",
"unless",
"messages",
".",
"empty?",
"content_tag",
"(",
":div",
",",
":class",
"=>",
"\"error_messages\"",
")",
"do",
"list_items",
"=",
"messages",
".",
"map",
"{",
"|",
"msg",
"|",
"content_tag",
"(",
":li",
",",
"msg",
")",
"}",
"content_tag",
"(",
":h2",
",",
"options",
"[",
":header_message",
"]",
")",
"+",
"content_tag",
"(",
":p",
",",
"options",
"[",
":message",
"]",
")",
"+",
"content_tag",
"(",
":ul",
",",
"list_items",
".",
"join",
".",
"html_safe",
")",
"end",
"end",
"end"
] |
Nifty generators errors helper code
|
[
"Nifty",
"generators",
"errors",
"helper",
"code"
] |
51b53cc3e1dd742053aed0b13bab915016d9a768
|
https://github.com/innku/kublog/blob/51b53cc3e1dd742053aed0b13bab915016d9a768/app/helpers/kublog/application_helper.rb#L5-L16
|
7,922 |
rob-lane/shiny_themes
|
lib/shiny_themes/renders_theme.rb
|
ShinyThemes.RendersTheme.update_current_theme
|
def update_current_theme(name, options = {})
self.class.renders_theme(name, options)
Rails.application.config.theme.name = current_theme_name
Rails.application.config.theme.layout = current_theme_layout
ShinyThemes::Engine.theme_config.save unless options[:dont_save]
self.class.theme # return current theme object
end
|
ruby
|
def update_current_theme(name, options = {})
self.class.renders_theme(name, options)
Rails.application.config.theme.name = current_theme_name
Rails.application.config.theme.layout = current_theme_layout
ShinyThemes::Engine.theme_config.save unless options[:dont_save]
self.class.theme # return current theme object
end
|
[
"def",
"update_current_theme",
"(",
"name",
",",
"options",
"=",
"{",
"}",
")",
"self",
".",
"class",
".",
"renders_theme",
"(",
"name",
",",
"options",
")",
"Rails",
".",
"application",
".",
"config",
".",
"theme",
".",
"name",
"=",
"current_theme_name",
"Rails",
".",
"application",
".",
"config",
".",
"theme",
".",
"layout",
"=",
"current_theme_layout",
"ShinyThemes",
"::",
"Engine",
".",
"theme_config",
".",
"save",
"unless",
"options",
"[",
":dont_save",
"]",
"self",
".",
"class",
".",
"theme",
"# return current theme object",
"end"
] |
Update the current theme for the controller and optionally save
@param name [String] The name of the new theme
@param options [Hash] Options hash
@option options [String] :layout ('application') Default layout for theme
@option options [Boolean] :dont_save (false) Dont save the update to the theme.yml config
@return (Theme) the theme for the controller
|
[
"Update",
"the",
"current",
"theme",
"for",
"the",
"controller",
"and",
"optionally",
"save"
] |
8c9e9d6bab1db4c63ddcbeb52b6f4577f4680699
|
https://github.com/rob-lane/shiny_themes/blob/8c9e9d6bab1db4c63ddcbeb52b6f4577f4680699/lib/shiny_themes/renders_theme.rb#L34-L40
|
7,923 |
wilson/revenant
|
lib/locks/mysql.rb
|
Revenant.MySQL.acquire_lock
|
def acquire_lock(lock_name)
begin
acquired = false
sql = lock_query(lock_name)
connection.query(sql) do |result|
acquired = result.fetch_row.first == "1"
end
acquired
rescue ::Exception
false
end
end
|
ruby
|
def acquire_lock(lock_name)
begin
acquired = false
sql = lock_query(lock_name)
connection.query(sql) do |result|
acquired = result.fetch_row.first == "1"
end
acquired
rescue ::Exception
false
end
end
|
[
"def",
"acquire_lock",
"(",
"lock_name",
")",
"begin",
"acquired",
"=",
"false",
"sql",
"=",
"lock_query",
"(",
"lock_name",
")",
"connection",
".",
"query",
"(",
"sql",
")",
"do",
"|",
"result",
"|",
"acquired",
"=",
"result",
".",
"fetch_row",
".",
"first",
"==",
"\"1\"",
"end",
"acquired",
"rescue",
"::",
"Exception",
"false",
"end",
"end"
] |
Expects the connection to behave like an instance of +Mysql+
If you need something else, replace +acquire_lock+ with your own code.
Or define your own lock_function while configuring a new Revenant task.
|
[
"Expects",
"the",
"connection",
"to",
"behave",
"like",
"an",
"instance",
"of",
"+",
"Mysql",
"+",
"If",
"you",
"need",
"something",
"else",
"replace",
"+",
"acquire_lock",
"+",
"with",
"your",
"own",
"code",
".",
"Or",
"define",
"your",
"own",
"lock_function",
"while",
"configuring",
"a",
"new",
"Revenant",
"task",
"."
] |
80fe65742de54ce0c5a8e6c56cea7003fe286746
|
https://github.com/wilson/revenant/blob/80fe65742de54ce0c5a8e6c56cea7003fe286746/lib/locks/mysql.rb#L21-L32
|
7,924 |
rob-lane/shiny_themes
|
lib/shiny_themes/theme_config.rb
|
ShinyThemes.ThemeConfig.load
|
def load
new_config = full_config[Rails.env].try(:deep_symbolize_keys!) || {}
# Honor values in config file over defaults
@defaults.reject! { |k, _| new_config.keys.include?(k) }
Rails.application.config.theme.merge!(@defaults.merge(new_config))
end
|
ruby
|
def load
new_config = full_config[Rails.env].try(:deep_symbolize_keys!) || {}
# Honor values in config file over defaults
@defaults.reject! { |k, _| new_config.keys.include?(k) }
Rails.application.config.theme.merge!(@defaults.merge(new_config))
end
|
[
"def",
"load",
"new_config",
"=",
"full_config",
"[",
"Rails",
".",
"env",
"]",
".",
"try",
"(",
":deep_symbolize_keys!",
")",
"||",
"{",
"}",
"# Honor values in config file over defaults",
"@defaults",
".",
"reject!",
"{",
"|",
"k",
",",
"_",
"|",
"new_config",
".",
"keys",
".",
"include?",
"(",
"k",
")",
"}",
"Rails",
".",
"application",
".",
"config",
".",
"theme",
".",
"merge!",
"(",
"@defaults",
".",
"merge",
"(",
"new_config",
")",
")",
"end"
] |
Create the ordered options, populate with provided hash and load YAML file
options.
@param default_options [Hash] (Hash.new) - Options to populate the theme
config with.
@options default_options [String] :path The path relative to the rails root
where templates are installed
@options default_options [Array(String)] :asset_directories Names of
directories containing assets for the theme relative to the 'assets'
directory.
Load the theme.yml file and merge it with the theme configuration
|
[
"Create",
"the",
"ordered",
"options",
"populate",
"with",
"provided",
"hash",
"and",
"load",
"YAML",
"file",
"options",
"."
] |
8c9e9d6bab1db4c63ddcbeb52b6f4577f4680699
|
https://github.com/rob-lane/shiny_themes/blob/8c9e9d6bab1db4c63ddcbeb52b6f4577f4680699/lib/shiny_themes/theme_config.rb#L21-L26
|
7,925 |
rob-lane/shiny_themes
|
lib/shiny_themes/theme_config.rb
|
ShinyThemes.ThemeConfig.save
|
def save
# Don't save default values
save_config = Rails.application.config.theme.reject { |k, _| @defaults.keys.include?(k) }
full_config[Rails.env].merge!(save_config)
File.open(config_pathname, 'w') { |f| f << full_config.to_yaml }
end
|
ruby
|
def save
# Don't save default values
save_config = Rails.application.config.theme.reject { |k, _| @defaults.keys.include?(k) }
full_config[Rails.env].merge!(save_config)
File.open(config_pathname, 'w') { |f| f << full_config.to_yaml }
end
|
[
"def",
"save",
"# Don't save default values",
"save_config",
"=",
"Rails",
".",
"application",
".",
"config",
".",
"theme",
".",
"reject",
"{",
"|",
"k",
",",
"_",
"|",
"@defaults",
".",
"keys",
".",
"include?",
"(",
"k",
")",
"}",
"full_config",
"[",
"Rails",
".",
"env",
"]",
".",
"merge!",
"(",
"save_config",
")",
"File",
".",
"open",
"(",
"config_pathname",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
"<<",
"full_config",
".",
"to_yaml",
"}",
"end"
] |
Save the current state of the theme config to the theme.yml file
|
[
"Save",
"the",
"current",
"state",
"of",
"the",
"theme",
"config",
"to",
"the",
"theme",
".",
"yml",
"file"
] |
8c9e9d6bab1db4c63ddcbeb52b6f4577f4680699
|
https://github.com/rob-lane/shiny_themes/blob/8c9e9d6bab1db4c63ddcbeb52b6f4577f4680699/lib/shiny_themes/theme_config.rb#L29-L34
|
7,926 |
jarhart/rattler
|
lib/rattler/parsers/super.rb
|
Rattler::Parsers.Super.parse
|
def parse(scanner, rules, scope = ParserScope.empty)
rules.inherited_rule(rule_name).parse(scanner, rules, scope)
end
|
ruby
|
def parse(scanner, rules, scope = ParserScope.empty)
rules.inherited_rule(rule_name).parse(scanner, rules, scope)
end
|
[
"def",
"parse",
"(",
"scanner",
",",
"rules",
",",
"scope",
"=",
"ParserScope",
".",
"empty",
")",
"rules",
".",
"inherited_rule",
"(",
"rule_name",
")",
".",
"parse",
"(",
"scanner",
",",
"rules",
",",
"scope",
")",
"end"
] |
Apply the parse rule of the same name inherited from a super-grammar.
@param (see Match#parse)
@return the result of applying parse rule of the same name inherited from
a super-grammar
|
[
"Apply",
"the",
"parse",
"rule",
"of",
"the",
"same",
"name",
"inherited",
"from",
"a",
"super",
"-",
"grammar",
"."
] |
8b4efde2a05e9e790955bb635d4a1a9615893719
|
https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/parsers/super.rb#L23-L25
|
7,927 |
jrochkind/borrow_direct
|
lib/borrow_direct/find_item.rb
|
BorrowDirect.FindItem.exact_search_request_hash
|
def exact_search_request_hash(type, value)
# turn it into an array if it's not one already
values = Array(value)
hash = {
"PartnershipId" => Defaults.partnership_id,
"ExactSearch" => []
}
values.each do |value|
hash["ExactSearch"] << {
"Type" => type.to_s.upcase,
"Value" => value
}
end
return hash
end
|
ruby
|
def exact_search_request_hash(type, value)
# turn it into an array if it's not one already
values = Array(value)
hash = {
"PartnershipId" => Defaults.partnership_id,
"ExactSearch" => []
}
values.each do |value|
hash["ExactSearch"] << {
"Type" => type.to_s.upcase,
"Value" => value
}
end
return hash
end
|
[
"def",
"exact_search_request_hash",
"(",
"type",
",",
"value",
")",
"# turn it into an array if it's not one already",
"values",
"=",
"Array",
"(",
"value",
")",
"hash",
"=",
"{",
"\"PartnershipId\"",
"=>",
"Defaults",
".",
"partnership_id",
",",
"\"ExactSearch\"",
"=>",
"[",
"]",
"}",
"values",
".",
"each",
"do",
"|",
"value",
"|",
"hash",
"[",
"\"ExactSearch\"",
"]",
"<<",
"{",
"\"Type\"",
"=>",
"type",
".",
"to_s",
".",
"upcase",
",",
"\"Value\"",
"=>",
"value",
"}",
"end",
"return",
"hash",
"end"
] |
Produce BD request hash for exact search of type eg "ISBN"
value can be a singel value, or an array of values. For array,
BD will "OR" them.
|
[
"Produce",
"BD",
"request",
"hash",
"for",
"exact",
"search",
"of",
"type",
"eg",
"ISBN",
"value",
"can",
"be",
"a",
"singel",
"value",
"or",
"an",
"array",
"of",
"values",
".",
"For",
"array",
"BD",
"will",
"OR",
"them",
"."
] |
f2f53760e15d742a5c5584dd641f20dea315f99f
|
https://github.com/jrochkind/borrow_direct/blob/f2f53760e15d742a5c5584dd641f20dea315f99f/lib/borrow_direct/find_item.rb#L78-L95
|
7,928 |
atomicobject/hardmock
|
lib/hardmock/expectation.rb
|
Hardmock.Expectation.raises
|
def raises(err=nil)
case err
when Exception
@options[:raises] = err
when String
@options[:raises] = RuntimeError.new(err)
else
@options[:raises] = RuntimeError.new("An Error")
end
self
end
|
ruby
|
def raises(err=nil)
case err
when Exception
@options[:raises] = err
when String
@options[:raises] = RuntimeError.new(err)
else
@options[:raises] = RuntimeError.new("An Error")
end
self
end
|
[
"def",
"raises",
"(",
"err",
"=",
"nil",
")",
"case",
"err",
"when",
"Exception",
"@options",
"[",
":raises",
"]",
"=",
"err",
"when",
"String",
"@options",
"[",
":raises",
"]",
"=",
"RuntimeError",
".",
"new",
"(",
"err",
")",
"else",
"@options",
"[",
":raises",
"]",
"=",
"RuntimeError",
".",
"new",
"(",
"\"An Error\"",
")",
"end",
"self",
"end"
] |
Rig an expected method to raise an exception when the mock is invoked.
Eg,
@cash_machine.expects.withdraw(20,:dollars).raises "Insufficient funds"
The argument can be:
* an Exception -- will be used directly
* a String -- will be used as the message for a RuntimeError
* nothing -- RuntimeError.new("An Error") will be raised
|
[
"Rig",
"an",
"expected",
"method",
"to",
"raise",
"an",
"exception",
"when",
"the",
"mock",
"is",
"invoked",
"."
] |
a2c01c2cbd28f56a71cc824f04b40ea1d14be367
|
https://github.com/atomicobject/hardmock/blob/a2c01c2cbd28f56a71cc824f04b40ea1d14be367/lib/hardmock/expectation.rb#L86-L96
|
7,929 |
atomicobject/hardmock
|
lib/hardmock/expectation.rb
|
Hardmock.Expectation.yields
|
def yields(*items)
@options[:suppress_arguments_to_block] = true
if items.empty?
# Yield once
@options[:block] = lambda do |block|
if block.arity != 0 and block.arity != -1
raise ExpectationError.new("The given block was expected to have no parameter count; instead, got #{block.arity} to <#{to_s}>")
end
block.call
end
else
# Yield one or more specific items
@options[:block] = lambda do |block|
items.each do |item|
if item.kind_of?(Array)
if block.arity == item.size
# Unfold the array into the block's arguments:
block.call *item
elsif block.arity == 1
# Just pass the array in
block.call item
else
# Size mismatch
raise ExpectationError.new("Can't pass #{item.inspect} to block with arity #{block.arity} to <#{to_s}>")
end
else
if block.arity != 1
# Size mismatch
raise ExpectationError.new("Can't pass #{item.inspect} to block with arity #{block.arity} to <#{to_s}>")
end
block.call item
end
end
end
end
self
end
|
ruby
|
def yields(*items)
@options[:suppress_arguments_to_block] = true
if items.empty?
# Yield once
@options[:block] = lambda do |block|
if block.arity != 0 and block.arity != -1
raise ExpectationError.new("The given block was expected to have no parameter count; instead, got #{block.arity} to <#{to_s}>")
end
block.call
end
else
# Yield one or more specific items
@options[:block] = lambda do |block|
items.each do |item|
if item.kind_of?(Array)
if block.arity == item.size
# Unfold the array into the block's arguments:
block.call *item
elsif block.arity == 1
# Just pass the array in
block.call item
else
# Size mismatch
raise ExpectationError.new("Can't pass #{item.inspect} to block with arity #{block.arity} to <#{to_s}>")
end
else
if block.arity != 1
# Size mismatch
raise ExpectationError.new("Can't pass #{item.inspect} to block with arity #{block.arity} to <#{to_s}>")
end
block.call item
end
end
end
end
self
end
|
[
"def",
"yields",
"(",
"*",
"items",
")",
"@options",
"[",
":suppress_arguments_to_block",
"]",
"=",
"true",
"if",
"items",
".",
"empty?",
"# Yield once",
"@options",
"[",
":block",
"]",
"=",
"lambda",
"do",
"|",
"block",
"|",
"if",
"block",
".",
"arity",
"!=",
"0",
"and",
"block",
".",
"arity",
"!=",
"-",
"1",
"raise",
"ExpectationError",
".",
"new",
"(",
"\"The given block was expected to have no parameter count; instead, got #{block.arity} to <#{to_s}>\"",
")",
"end",
"block",
".",
"call",
"end",
"else",
"# Yield one or more specific items",
"@options",
"[",
":block",
"]",
"=",
"lambda",
"do",
"|",
"block",
"|",
"items",
".",
"each",
"do",
"|",
"item",
"|",
"if",
"item",
".",
"kind_of?",
"(",
"Array",
")",
"if",
"block",
".",
"arity",
"==",
"item",
".",
"size",
"# Unfold the array into the block's arguments:",
"block",
".",
"call",
"item",
"elsif",
"block",
".",
"arity",
"==",
"1",
"# Just pass the array in",
"block",
".",
"call",
"item",
"else",
"# Size mismatch",
"raise",
"ExpectationError",
".",
"new",
"(",
"\"Can't pass #{item.inspect} to block with arity #{block.arity} to <#{to_s}>\"",
")",
"end",
"else",
"if",
"block",
".",
"arity",
"!=",
"1",
"# Size mismatch",
"raise",
"ExpectationError",
".",
"new",
"(",
"\"Can't pass #{item.inspect} to block with arity #{block.arity} to <#{to_s}>\"",
")",
"end",
"block",
".",
"call",
"item",
"end",
"end",
"end",
"end",
"self",
"end"
] |
Used when an expected method accepts a block at runtime.
When the expected method is invoked, the block passed to
that method will be invoked as well.
NOTE: ExpectationError will be thrown upon running the expected method
if the arguments you set up in +yields+ do not properly match up with
the actual block that ends up getting passed.
== Examples
<b>Single invocation</b>: The block passed to +lock_down+ gets invoked
once with no arguments:
@safe_zone.expects.lock_down.yields
# (works on code that looks like:)
@safe_zone.lock_down do
# ... this block invoked once
end
<b>Multi-parameter blocks:</b> The block passed to +each_item+ gets
invoked twice, with <tt>:item1</tt> the first time, and with
<tt>:item2</tt> the second time:
@fruit_basket.expects.each_with_index.yields [:apple,1], [:orange,2]
# (works on code that looks like:)
@fruit_basket.each_with_index do |fruit,index|
# ... this block invoked with fruit=:apple, index=1,
# ... and then with fruit=:orange, index=2
end
<b>Arrays can be passed as arguments too</b>... if the block
takes a single argument and you want to pass a series of arrays into it,
that will work as well:
@list_provider.expects.each_list.yields [1,2,3], [4,5,6]
# (works on code that looks like:)
@list_provider.each_list do |list|
# ... list is [1,2,3] the first time
# ... list is [4,5,6] the second time
end
<b>Return value</b>: You can set the return value for the method that
accepts the block like so:
@cruncher.expects.do_things.yields(:bean1,:bean2).returns("The Results")
<b>Raising errors</b>: You can set the raised exception for the method that
accepts the block. NOTE: the error will be raised _after_ the block has
been invoked.
# :bean1 and :bean2 will be passed to the block, then an error is raised:
@cruncher.expects.do_things.yields(:bean1,:bean2).raises("Too crunchy")
|
[
"Used",
"when",
"an",
"expected",
"method",
"accepts",
"a",
"block",
"at",
"runtime",
".",
"When",
"the",
"expected",
"method",
"is",
"invoked",
"the",
"block",
"passed",
"to",
"that",
"method",
"will",
"be",
"invoked",
"as",
"well",
"."
] |
a2c01c2cbd28f56a71cc824f04b40ea1d14be367
|
https://github.com/atomicobject/hardmock/blob/a2c01c2cbd28f56a71cc824f04b40ea1d14be367/lib/hardmock/expectation.rb#L182-L218
|
7,930 |
roja/words
|
lib/words.rb
|
Words.Wordnet.find
|
def find(term)
raise NoWordnetConnection, "There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object." unless connected?
homographs = @wordnet_connection.homographs(term)
Homographs.new(homographs, @wordnet_connection) unless homographs.nil?
end
|
ruby
|
def find(term)
raise NoWordnetConnection, "There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object." unless connected?
homographs = @wordnet_connection.homographs(term)
Homographs.new(homographs, @wordnet_connection) unless homographs.nil?
end
|
[
"def",
"find",
"(",
"term",
")",
"raise",
"NoWordnetConnection",
",",
"\"There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object.\"",
"unless",
"connected?",
"homographs",
"=",
"@wordnet_connection",
".",
"homographs",
"(",
"term",
")",
"Homographs",
".",
"new",
"(",
"homographs",
",",
"@wordnet_connection",
")",
"unless",
"homographs",
".",
"nil?",
"end"
] |
Constructs a new wordnet connection object.
@param [Symbol] connector_type Specifies the connector type or mode desired. Current supported connectors are :pure and :tokyo.
@param [String, Symbol] wordnet_path Specifies the directory within which the wordnet dictionary can be found. It can be set to :search to attempt to locate wordnet automatically.
@param [String, Symbol] data_path Specifies the directory within which constructed datasets can be found (tokyo index, evocations etc...) It can be set to :default to use the standard location inside the gem directory.
@return [Wordnet] The wordnet connection object.
@raise [BadWordnetConnector] If an invalid connector type is provided.
Locates the set of homographs within wordnet specific to the term entered.
@param [String] term The specific term that is desired from within wordnet. This is caps insensative & we do a small amount of cleanup.
@return [Homographs] An object encaptulating the homographs of the desired term. If the term cannot be located within wordnet then nil is returned.
@raise [NoWordnetConnection] If there is currently no wordnet connection.
|
[
"Constructs",
"a",
"new",
"wordnet",
"connection",
"object",
"."
] |
4d6302e7218533fcc2afb4cd993686dd56fe2cde
|
https://github.com/roja/words/blob/4d6302e7218533fcc2afb4cd993686dd56fe2cde/lib/words.rb#L65-L71
|
7,931 |
bjh/griddle
|
lib/griddle/point.rb
|
Griddle.Point.to_rectangle
|
def to_rectangle(point)
d = delta(point)
Rectangle.new(
row,
col,
d.col + 1,
d.row + 1
)
end
|
ruby
|
def to_rectangle(point)
d = delta(point)
Rectangle.new(
row,
col,
d.col + 1,
d.row + 1
)
end
|
[
"def",
"to_rectangle",
"(",
"point",
")",
"d",
"=",
"delta",
"(",
"point",
")",
"Rectangle",
".",
"new",
"(",
"row",
",",
"col",
",",
"d",
".",
"col",
"+",
"1",
",",
"d",
".",
"row",
"+",
"1",
")",
"end"
] |
`point` is used to calculate the width and height
of the new rectangle
|
[
"point",
"is",
"used",
"to",
"calculate",
"the",
"width",
"and",
"height",
"of",
"the",
"new",
"rectangle"
] |
c924bcb56172c282cfa246560d8b2051d48e8884
|
https://github.com/bjh/griddle/blob/c924bcb56172c282cfa246560d8b2051d48e8884/lib/griddle/point.rb#L34-L43
|
7,932 |
medihack/make_voteable
|
lib/make_voteable/voter.rb
|
MakeVoteable.Voter.up_vote
|
def up_vote(voteable)
check_voteable(voteable)
voting = fetch_voting(voteable)
if voting
if voting.up_vote
raise Exceptions::AlreadyVotedError.new(true)
else
voting.up_vote = true
voteable.down_votes -= 1
self.down_votes -= 1 if has_attribute?(:down_votes)
end
else
voting = Voting.create(:voteable => voteable, :voter_id => self.id, :voter_type => self.class.to_s, :up_vote => true)
end
voteable.up_votes += 1
self.up_votes += 1 if has_attribute?(:up_votes)
Voting.transaction do
save
voteable.save
voting.save
end
true
end
|
ruby
|
def up_vote(voteable)
check_voteable(voteable)
voting = fetch_voting(voteable)
if voting
if voting.up_vote
raise Exceptions::AlreadyVotedError.new(true)
else
voting.up_vote = true
voteable.down_votes -= 1
self.down_votes -= 1 if has_attribute?(:down_votes)
end
else
voting = Voting.create(:voteable => voteable, :voter_id => self.id, :voter_type => self.class.to_s, :up_vote => true)
end
voteable.up_votes += 1
self.up_votes += 1 if has_attribute?(:up_votes)
Voting.transaction do
save
voteable.save
voting.save
end
true
end
|
[
"def",
"up_vote",
"(",
"voteable",
")",
"check_voteable",
"(",
"voteable",
")",
"voting",
"=",
"fetch_voting",
"(",
"voteable",
")",
"if",
"voting",
"if",
"voting",
".",
"up_vote",
"raise",
"Exceptions",
"::",
"AlreadyVotedError",
".",
"new",
"(",
"true",
")",
"else",
"voting",
".",
"up_vote",
"=",
"true",
"voteable",
".",
"down_votes",
"-=",
"1",
"self",
".",
"down_votes",
"-=",
"1",
"if",
"has_attribute?",
"(",
":down_votes",
")",
"end",
"else",
"voting",
"=",
"Voting",
".",
"create",
"(",
":voteable",
"=>",
"voteable",
",",
":voter_id",
"=>",
"self",
".",
"id",
",",
":voter_type",
"=>",
"self",
".",
"class",
".",
"to_s",
",",
":up_vote",
"=>",
"true",
")",
"end",
"voteable",
".",
"up_votes",
"+=",
"1",
"self",
".",
"up_votes",
"+=",
"1",
"if",
"has_attribute?",
"(",
":up_votes",
")",
"Voting",
".",
"transaction",
"do",
"save",
"voteable",
".",
"save",
"voting",
".",
"save",
"end",
"true",
"end"
] |
Up vote a +voteable+.
Raises an AlreadyVotedError if the voter already up voted the voteable.
Changes a down vote to an up vote if the the voter already down voted the voteable.
|
[
"Up",
"vote",
"a",
"+",
"voteable",
"+",
".",
"Raises",
"an",
"AlreadyVotedError",
"if",
"the",
"voter",
"already",
"up",
"voted",
"the",
"voteable",
".",
"Changes",
"a",
"down",
"vote",
"to",
"an",
"up",
"vote",
"if",
"the",
"the",
"voter",
"already",
"down",
"voted",
"the",
"voteable",
"."
] |
3cf3f7ca1c8db075a6a51e101c1b38ef724facd2
|
https://github.com/medihack/make_voteable/blob/3cf3f7ca1c8db075a6a51e101c1b38ef724facd2/lib/make_voteable/voter.rb#L18-L45
|
7,933 |
medihack/make_voteable
|
lib/make_voteable/voter.rb
|
MakeVoteable.Voter.up_vote!
|
def up_vote!(voteable)
begin
up_vote(voteable)
success = true
rescue Exceptions::AlreadyVotedError
success = false
end
success
end
|
ruby
|
def up_vote!(voteable)
begin
up_vote(voteable)
success = true
rescue Exceptions::AlreadyVotedError
success = false
end
success
end
|
[
"def",
"up_vote!",
"(",
"voteable",
")",
"begin",
"up_vote",
"(",
"voteable",
")",
"success",
"=",
"true",
"rescue",
"Exceptions",
"::",
"AlreadyVotedError",
"success",
"=",
"false",
"end",
"success",
"end"
] |
Up votes the +voteable+, but doesn't raise an error if the votelable was already up voted.
The vote is simply ignored then.
|
[
"Up",
"votes",
"the",
"+",
"voteable",
"+",
"but",
"doesn",
"t",
"raise",
"an",
"error",
"if",
"the",
"votelable",
"was",
"already",
"up",
"voted",
".",
"The",
"vote",
"is",
"simply",
"ignored",
"then",
"."
] |
3cf3f7ca1c8db075a6a51e101c1b38ef724facd2
|
https://github.com/medihack/make_voteable/blob/3cf3f7ca1c8db075a6a51e101c1b38ef724facd2/lib/make_voteable/voter.rb#L49-L57
|
7,934 |
medihack/make_voteable
|
lib/make_voteable/voter.rb
|
MakeVoteable.Voter.down_vote!
|
def down_vote!(voteable)
begin
down_vote(voteable)
success = true
rescue Exceptions::AlreadyVotedError
success = false
end
success
end
|
ruby
|
def down_vote!(voteable)
begin
down_vote(voteable)
success = true
rescue Exceptions::AlreadyVotedError
success = false
end
success
end
|
[
"def",
"down_vote!",
"(",
"voteable",
")",
"begin",
"down_vote",
"(",
"voteable",
")",
"success",
"=",
"true",
"rescue",
"Exceptions",
"::",
"AlreadyVotedError",
"success",
"=",
"false",
"end",
"success",
"end"
] |
Down votes the +voteable+, but doesn't raise an error if the votelable was already down voted.
The vote is simply ignored then.
|
[
"Down",
"votes",
"the",
"+",
"voteable",
"+",
"but",
"doesn",
"t",
"raise",
"an",
"error",
"if",
"the",
"votelable",
"was",
"already",
"down",
"voted",
".",
"The",
"vote",
"is",
"simply",
"ignored",
"then",
"."
] |
3cf3f7ca1c8db075a6a51e101c1b38ef724facd2
|
https://github.com/medihack/make_voteable/blob/3cf3f7ca1c8db075a6a51e101c1b38ef724facd2/lib/make_voteable/voter.rb#L93-L101
|
7,935 |
medihack/make_voteable
|
lib/make_voteable/voter.rb
|
MakeVoteable.Voter.unvote
|
def unvote(voteable)
check_voteable(voteable)
voting = fetch_voting(voteable)
raise Exceptions::NotVotedError unless voting
if voting.up_vote
voteable.up_votes -= 1
self.up_votes -= 1 if has_attribute?(:up_votes)
else
voteable.down_votes -= 1
self.down_votes -= 1 if has_attribute?(:down_votes)
end
Voting.transaction do
save
voteable.save
voting.destroy
end
true
end
|
ruby
|
def unvote(voteable)
check_voteable(voteable)
voting = fetch_voting(voteable)
raise Exceptions::NotVotedError unless voting
if voting.up_vote
voteable.up_votes -= 1
self.up_votes -= 1 if has_attribute?(:up_votes)
else
voteable.down_votes -= 1
self.down_votes -= 1 if has_attribute?(:down_votes)
end
Voting.transaction do
save
voteable.save
voting.destroy
end
true
end
|
[
"def",
"unvote",
"(",
"voteable",
")",
"check_voteable",
"(",
"voteable",
")",
"voting",
"=",
"fetch_voting",
"(",
"voteable",
")",
"raise",
"Exceptions",
"::",
"NotVotedError",
"unless",
"voting",
"if",
"voting",
".",
"up_vote",
"voteable",
".",
"up_votes",
"-=",
"1",
"self",
".",
"up_votes",
"-=",
"1",
"if",
"has_attribute?",
"(",
":up_votes",
")",
"else",
"voteable",
".",
"down_votes",
"-=",
"1",
"self",
".",
"down_votes",
"-=",
"1",
"if",
"has_attribute?",
"(",
":down_votes",
")",
"end",
"Voting",
".",
"transaction",
"do",
"save",
"voteable",
".",
"save",
"voting",
".",
"destroy",
"end",
"true",
"end"
] |
Clears an already done vote on a +voteable+.
Raises a NotVotedError if the voter didn't voted for the voteable.
|
[
"Clears",
"an",
"already",
"done",
"vote",
"on",
"a",
"+",
"voteable",
"+",
".",
"Raises",
"a",
"NotVotedError",
"if",
"the",
"voter",
"didn",
"t",
"voted",
"for",
"the",
"voteable",
"."
] |
3cf3f7ca1c8db075a6a51e101c1b38ef724facd2
|
https://github.com/medihack/make_voteable/blob/3cf3f7ca1c8db075a6a51e101c1b38ef724facd2/lib/make_voteable/voter.rb#L105-L127
|
7,936 |
medihack/make_voteable
|
lib/make_voteable/voter.rb
|
MakeVoteable.Voter.unvote!
|
def unvote!(voteable)
begin
unvote(voteable)
success = true
rescue Exceptions::NotVotedError
success = false
end
success
end
|
ruby
|
def unvote!(voteable)
begin
unvote(voteable)
success = true
rescue Exceptions::NotVotedError
success = false
end
success
end
|
[
"def",
"unvote!",
"(",
"voteable",
")",
"begin",
"unvote",
"(",
"voteable",
")",
"success",
"=",
"true",
"rescue",
"Exceptions",
"::",
"NotVotedError",
"success",
"=",
"false",
"end",
"success",
"end"
] |
Clears an already done vote on a +voteable+, but doesn't raise an error if
the voteable was not voted. It ignores the unvote then.
|
[
"Clears",
"an",
"already",
"done",
"vote",
"on",
"a",
"+",
"voteable",
"+",
"but",
"doesn",
"t",
"raise",
"an",
"error",
"if",
"the",
"voteable",
"was",
"not",
"voted",
".",
"It",
"ignores",
"the",
"unvote",
"then",
"."
] |
3cf3f7ca1c8db075a6a51e101c1b38ef724facd2
|
https://github.com/medihack/make_voteable/blob/3cf3f7ca1c8db075a6a51e101c1b38ef724facd2/lib/make_voteable/voter.rb#L131-L139
|
7,937 |
medihack/make_voteable
|
lib/make_voteable/voter.rb
|
MakeVoteable.Voter.down_voted?
|
def down_voted?(voteable)
check_voteable(voteable)
voting = fetch_voting(voteable)
return false if voting.nil?
return true if voting.has_attribute?(:up_vote) && !voting.up_vote
false
end
|
ruby
|
def down_voted?(voteable)
check_voteable(voteable)
voting = fetch_voting(voteable)
return false if voting.nil?
return true if voting.has_attribute?(:up_vote) && !voting.up_vote
false
end
|
[
"def",
"down_voted?",
"(",
"voteable",
")",
"check_voteable",
"(",
"voteable",
")",
"voting",
"=",
"fetch_voting",
"(",
"voteable",
")",
"return",
"false",
"if",
"voting",
".",
"nil?",
"return",
"true",
"if",
"voting",
".",
"has_attribute?",
"(",
":up_vote",
")",
"&&",
"!",
"voting",
".",
"up_vote",
"false",
"end"
] |
Returns true if the voter down voted the +voteable+.
|
[
"Returns",
"true",
"if",
"the",
"voter",
"down",
"voted",
"the",
"+",
"voteable",
"+",
"."
] |
3cf3f7ca1c8db075a6a51e101c1b38ef724facd2
|
https://github.com/medihack/make_voteable/blob/3cf3f7ca1c8db075a6a51e101c1b38ef724facd2/lib/make_voteable/voter.rb#L158-L164
|
7,938 |
mkfs/mindset
|
lib/mindset/connection.rb
|
Mindset.LoopbackConnection.read_packet_buffer
|
def read_packet_buffer
packets = @data[:wave][@wave_idx, 64].map { |val|
Packet.factory(:wave, val) }
@wave_idx += 64
@wave_idx = 0 if @wave_idx >= @data[:wave].count
if @counter == 7
packets << Packet.factory(:delta, @data[:delta][@esense_idx])
packets << Packet.factory(:theta, @data[:theta][@esense_idx])
packets << Packet.factory(:lo_alpha, @data[:lo_alpha][@esense_idx])
packets << Packet.factory(:hi_alpha, @data[:hi_alpha][@esense_idx])
packets << Packet.factory(:lo_beta, @data[:lo_beta][@esense_idx])
packets << Packet.factory(:hi_beta, @data[:hi_beta][@esense_idx])
packets << Packet.factory(:lo_gamma, @data[:lo_gamma][@esense_idx])
packets << Packet.factory(:mid_gamma, @data[:mid_gamma][@esense_idx])
packets << Packet.factory(:signal_quality,
@data[:signal_quality][@esense_idx])
packets << Packet.factory(:attention, @data[:attention][@esense_idx])
packets << Packet.factory(:meditation, @data[:meditation][@esense_idx])
packets << Packet.factory(:blink, @data[:blink][@esense_idx])
@esense_idx += 1
@esense_idx = 0 if @esense_idx >= @data[:delta].count
end
@counter = (@counter + 1) % 8
packets
end
|
ruby
|
def read_packet_buffer
packets = @data[:wave][@wave_idx, 64].map { |val|
Packet.factory(:wave, val) }
@wave_idx += 64
@wave_idx = 0 if @wave_idx >= @data[:wave].count
if @counter == 7
packets << Packet.factory(:delta, @data[:delta][@esense_idx])
packets << Packet.factory(:theta, @data[:theta][@esense_idx])
packets << Packet.factory(:lo_alpha, @data[:lo_alpha][@esense_idx])
packets << Packet.factory(:hi_alpha, @data[:hi_alpha][@esense_idx])
packets << Packet.factory(:lo_beta, @data[:lo_beta][@esense_idx])
packets << Packet.factory(:hi_beta, @data[:hi_beta][@esense_idx])
packets << Packet.factory(:lo_gamma, @data[:lo_gamma][@esense_idx])
packets << Packet.factory(:mid_gamma, @data[:mid_gamma][@esense_idx])
packets << Packet.factory(:signal_quality,
@data[:signal_quality][@esense_idx])
packets << Packet.factory(:attention, @data[:attention][@esense_idx])
packets << Packet.factory(:meditation, @data[:meditation][@esense_idx])
packets << Packet.factory(:blink, @data[:blink][@esense_idx])
@esense_idx += 1
@esense_idx = 0 if @esense_idx >= @data[:delta].count
end
@counter = (@counter + 1) % 8
packets
end
|
[
"def",
"read_packet_buffer",
"packets",
"=",
"@data",
"[",
":wave",
"]",
"[",
"@wave_idx",
",",
"64",
"]",
".",
"map",
"{",
"|",
"val",
"|",
"Packet",
".",
"factory",
"(",
":wave",
",",
"val",
")",
"}",
"@wave_idx",
"+=",
"64",
"@wave_idx",
"=",
"0",
"if",
"@wave_idx",
">=",
"@data",
"[",
":wave",
"]",
".",
"count",
"if",
"@counter",
"==",
"7",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":delta",
",",
"@data",
"[",
":delta",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":theta",
",",
"@data",
"[",
":theta",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":lo_alpha",
",",
"@data",
"[",
":lo_alpha",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":hi_alpha",
",",
"@data",
"[",
":hi_alpha",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":lo_beta",
",",
"@data",
"[",
":lo_beta",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":hi_beta",
",",
"@data",
"[",
":hi_beta",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":lo_gamma",
",",
"@data",
"[",
":lo_gamma",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":mid_gamma",
",",
"@data",
"[",
":mid_gamma",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":signal_quality",
",",
"@data",
"[",
":signal_quality",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":attention",
",",
"@data",
"[",
":attention",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":meditation",
",",
"@data",
"[",
":meditation",
"]",
"[",
"@esense_idx",
"]",
")",
"packets",
"<<",
"Packet",
".",
"factory",
"(",
":blink",
",",
"@data",
"[",
":blink",
"]",
"[",
"@esense_idx",
"]",
")",
"@esense_idx",
"+=",
"1",
"@esense_idx",
"=",
"0",
"if",
"@esense_idx",
">=",
"@data",
"[",
":delta",
"]",
".",
"count",
"end",
"@counter",
"=",
"(",
"@counter",
"+",
"1",
")",
"%",
"8",
"packets",
"end"
] |
=begin rdoc
Simulate a read of the Mindset device by returning an Array of Packet objects.
This assumes it will be called 8 times a second.
According to the MDT, Mindset packets are sent at the following intervals:
1 packet per second: eSense, ASIC EEG, POOR_SIGNAL
512 packets per second: RAW
Each read will therefore return 64 RAW packets. Every eighth read will also
return 1 eSense, ASIC_EEG, and POOR_SIGNAL packet.
=end
|
[
"=",
"begin",
"rdoc",
"Simulate",
"a",
"read",
"of",
"the",
"Mindset",
"device",
"by",
"returning",
"an",
"Array",
"of",
"Packet",
"objects",
".",
"This",
"assumes",
"it",
"will",
"be",
"called",
"8",
"times",
"a",
"second",
"."
] |
1b8a6b9c1773290828ba126065c1327ffdffabf1
|
https://github.com/mkfs/mindset/blob/1b8a6b9c1773290828ba126065c1327ffdffabf1/lib/mindset/connection.rb#L193-L219
|
7,939 |
notjosh/danger-package_json_lockdown
|
lib/package_json_lockdown/plugin.rb
|
Danger.DangerPackageJsonLockdown.verify
|
def verify(package_json)
inspect(package_json).each do |suspicious|
warn(
"`#{suspicious[:package]}` doesn't specify fixed version number",
file: package_json,
line: suspicious[:line]
)
end
end
|
ruby
|
def verify(package_json)
inspect(package_json).each do |suspicious|
warn(
"`#{suspicious[:package]}` doesn't specify fixed version number",
file: package_json,
line: suspicious[:line]
)
end
end
|
[
"def",
"verify",
"(",
"package_json",
")",
"inspect",
"(",
"package_json",
")",
".",
"each",
"do",
"|",
"suspicious",
"|",
"warn",
"(",
"\"`#{suspicious[:package]}` doesn't specify fixed version number\"",
",",
"file",
":",
"package_json",
",",
"line",
":",
"suspicious",
"[",
":line",
"]",
")",
"end",
"end"
] |
Verifies the supplied `package.json` file
@param [string] package_json
Path to `package.json`, relative to current directory
@return [void]
|
[
"Verifies",
"the",
"supplied",
"package",
".",
"json",
"file"
] |
7cdd25864da877fe90bc33350db22324f394cbfc
|
https://github.com/notjosh/danger-package_json_lockdown/blob/7cdd25864da877fe90bc33350db22324f394cbfc/lib/package_json_lockdown/plugin.rb#L64-L72
|
7,940 |
notjosh/danger-package_json_lockdown
|
lib/package_json_lockdown/plugin.rb
|
Danger.DangerPackageJsonLockdown.inspect
|
def inspect(package_json)
json = JSON.parse(File.read(package_json))
suspicious_packages = []
dependency_keys.each do |dependency_key|
next unless json.key?(dependency_key)
results = find_something_suspicious(json[dependency_key], package_json)
suspicious_packages.push(*results)
end
suspicious_packages
end
|
ruby
|
def inspect(package_json)
json = JSON.parse(File.read(package_json))
suspicious_packages = []
dependency_keys.each do |dependency_key|
next unless json.key?(dependency_key)
results = find_something_suspicious(json[dependency_key], package_json)
suspicious_packages.push(*results)
end
suspicious_packages
end
|
[
"def",
"inspect",
"(",
"package_json",
")",
"json",
"=",
"JSON",
".",
"parse",
"(",
"File",
".",
"read",
"(",
"package_json",
")",
")",
"suspicious_packages",
"=",
"[",
"]",
"dependency_keys",
".",
"each",
"do",
"|",
"dependency_key",
"|",
"next",
"unless",
"json",
".",
"key?",
"(",
"dependency_key",
")",
"results",
"=",
"find_something_suspicious",
"(",
"json",
"[",
"dependency_key",
"]",
",",
"package_json",
")",
"suspicious_packages",
".",
"push",
"(",
"results",
")",
"end",
"suspicious_packages",
"end"
] |
Inspects the supplied `package.json` file and returns problems
@param [string] package_json
Path to `package.json`, relative to current directory
@return [Array<{Symbol => String}>]
- `:package`: the offending package name
- `:version`: the version as written in `package.json`
- `:line`: (probably) the line number.
|
[
"Inspects",
"the",
"supplied",
"package",
".",
"json",
"file",
"and",
"returns",
"problems"
] |
7cdd25864da877fe90bc33350db22324f394cbfc
|
https://github.com/notjosh/danger-package_json_lockdown/blob/7cdd25864da877fe90bc33350db22324f394cbfc/lib/package_json_lockdown/plugin.rb#L81-L94
|
7,941 |
jemmyw/bisques
|
lib/bisques/queue_listener.rb
|
Bisques.QueueListener.listen
|
def listen(&block)
return if @listening
@listening = true
@thread = Thread.new do
while @listening
message = @queue.retrieve(@poll_time)
block.call(message) if message.present?
end
end
end
|
ruby
|
def listen(&block)
return if @listening
@listening = true
@thread = Thread.new do
while @listening
message = @queue.retrieve(@poll_time)
block.call(message) if message.present?
end
end
end
|
[
"def",
"listen",
"(",
"&",
"block",
")",
"return",
"if",
"@listening",
"@listening",
"=",
"true",
"@thread",
"=",
"Thread",
".",
"new",
"do",
"while",
"@listening",
"message",
"=",
"@queue",
".",
"retrieve",
"(",
"@poll_time",
")",
"block",
".",
"call",
"(",
"message",
")",
"if",
"message",
".",
"present?",
"end",
"end",
"end"
] |
Listen for messages. This is asynchronous and returns immediately.
@example
queue = bisques.find_or_create_queue("my queue")
listener = QueuedListener.new(queue)
listener.listen do |message|
puts "Received #{message.object}"
message.delete
end
while true; sleep 1; end # Process messages forever
@note Note that the block you give to this method is executed in a new thread.
@yield [Message] a message received from the {Queue}
|
[
"Listen",
"for",
"messages",
".",
"This",
"is",
"asynchronous",
"and",
"returns",
"immediately",
"."
] |
c48ab555f07664752bcbf9e8deb99bd75cbdc41b
|
https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/queue_listener.rb#L34-L44
|
7,942 |
mirrec/token_field
|
lib/token_field/form_builder.rb
|
TokenField.FormBuilder.token_field
|
def token_field(attribute_name, options = {})
association_type = @object.send(attribute_name).respond_to?(:each) ? :many : :one
model_name = options.fetch(:model) { attribute_name.to_s.gsub(/_ids?/, "") }.to_s
association = attribute_name.to_s.gsub(/_ids?/, "").to_sym
token_url = options.fetch(:token_url) { "/#{model_name.pluralize}/token.json" }
token_url_is_function = options.fetch(:token_url_is_function) { false }
append_to_id = options[:append_to_id]
token_method = options.fetch(:token_method) { :to_token }
token_limit = nil
token_limit = 1 if association_type == :one
id = @object.send(:id)
html_id = "#{@object_name}_#{attribute_name.to_s}"
if append_to_id == :id && id
html_id << "_#{id}"
elsif append_to_id && append_to_id != :id
html_id << "_#{append_to_id}"
end
html_id = html_id.parameterize.underscore
results = []
if association_type == :one && @object.public_send(association)
results << @object.public_send(association)
elsif association_type == :many && @object.public_send(association.to_s.pluralize).count > 0
@object.public_send(association.to_s.pluralize).each { |record| results << record }
end
data_pre = results.map{ |result| result.public_send(token_method) }
value = data_pre.map{ |row| row[:id] }.join(',')
on_add = options[:on_add] ? "#{options[:on_add]}" : "false"
on_delete = options[:on_delete] ? "#{options[:on_delete]}" : "false"
token_url = "'#{token_url}'" unless token_url_is_function
js_content = "
jQuery.noConflict();
jQuery(function() {
jQuery('##{html_id}').tokenInput(#{token_url}, {
crossDomain: false,
tokenLimit: #{token_limit.nil? ? "null" : token_limit.to_i},
preventDuplicates: true,
prePopulate: jQuery('##{attribute_name}').data('pre'),
theme: 'facebook',
hintText: '"+t('helpers.token_field.hint_text')+"',
searchingText: '"+t('helpers.token_field.searching_text')+"',
noResultsText: '"+t('helpers.token_field.no_results_text')+"',
onAdd: "+on_add+",
onDelete: "+on_delete+"
});
});
"
script = content_tag(:script, js_content.html_safe, :type => Mime::JS)
text_field("#{attribute_name}", "data-pre" => data_pre.to_json, :value => value, :id => html_id) + script
end
|
ruby
|
def token_field(attribute_name, options = {})
association_type = @object.send(attribute_name).respond_to?(:each) ? :many : :one
model_name = options.fetch(:model) { attribute_name.to_s.gsub(/_ids?/, "") }.to_s
association = attribute_name.to_s.gsub(/_ids?/, "").to_sym
token_url = options.fetch(:token_url) { "/#{model_name.pluralize}/token.json" }
token_url_is_function = options.fetch(:token_url_is_function) { false }
append_to_id = options[:append_to_id]
token_method = options.fetch(:token_method) { :to_token }
token_limit = nil
token_limit = 1 if association_type == :one
id = @object.send(:id)
html_id = "#{@object_name}_#{attribute_name.to_s}"
if append_to_id == :id && id
html_id << "_#{id}"
elsif append_to_id && append_to_id != :id
html_id << "_#{append_to_id}"
end
html_id = html_id.parameterize.underscore
results = []
if association_type == :one && @object.public_send(association)
results << @object.public_send(association)
elsif association_type == :many && @object.public_send(association.to_s.pluralize).count > 0
@object.public_send(association.to_s.pluralize).each { |record| results << record }
end
data_pre = results.map{ |result| result.public_send(token_method) }
value = data_pre.map{ |row| row[:id] }.join(',')
on_add = options[:on_add] ? "#{options[:on_add]}" : "false"
on_delete = options[:on_delete] ? "#{options[:on_delete]}" : "false"
token_url = "'#{token_url}'" unless token_url_is_function
js_content = "
jQuery.noConflict();
jQuery(function() {
jQuery('##{html_id}').tokenInput(#{token_url}, {
crossDomain: false,
tokenLimit: #{token_limit.nil? ? "null" : token_limit.to_i},
preventDuplicates: true,
prePopulate: jQuery('##{attribute_name}').data('pre'),
theme: 'facebook',
hintText: '"+t('helpers.token_field.hint_text')+"',
searchingText: '"+t('helpers.token_field.searching_text')+"',
noResultsText: '"+t('helpers.token_field.no_results_text')+"',
onAdd: "+on_add+",
onDelete: "+on_delete+"
});
});
"
script = content_tag(:script, js_content.html_safe, :type => Mime::JS)
text_field("#{attribute_name}", "data-pre" => data_pre.to_json, :value => value, :id => html_id) + script
end
|
[
"def",
"token_field",
"(",
"attribute_name",
",",
"options",
"=",
"{",
"}",
")",
"association_type",
"=",
"@object",
".",
"send",
"(",
"attribute_name",
")",
".",
"respond_to?",
"(",
":each",
")",
"?",
":many",
":",
":one",
"model_name",
"=",
"options",
".",
"fetch",
"(",
":model",
")",
"{",
"attribute_name",
".",
"to_s",
".",
"gsub",
"(",
"/",
"/",
",",
"\"\"",
")",
"}",
".",
"to_s",
"association",
"=",
"attribute_name",
".",
"to_s",
".",
"gsub",
"(",
"/",
"/",
",",
"\"\"",
")",
".",
"to_sym",
"token_url",
"=",
"options",
".",
"fetch",
"(",
":token_url",
")",
"{",
"\"/#{model_name.pluralize}/token.json\"",
"}",
"token_url_is_function",
"=",
"options",
".",
"fetch",
"(",
":token_url_is_function",
")",
"{",
"false",
"}",
"append_to_id",
"=",
"options",
"[",
":append_to_id",
"]",
"token_method",
"=",
"options",
".",
"fetch",
"(",
":token_method",
")",
"{",
":to_token",
"}",
"token_limit",
"=",
"nil",
"token_limit",
"=",
"1",
"if",
"association_type",
"==",
":one",
"id",
"=",
"@object",
".",
"send",
"(",
":id",
")",
"html_id",
"=",
"\"#{@object_name}_#{attribute_name.to_s}\"",
"if",
"append_to_id",
"==",
":id",
"&&",
"id",
"html_id",
"<<",
"\"_#{id}\"",
"elsif",
"append_to_id",
"&&",
"append_to_id",
"!=",
":id",
"html_id",
"<<",
"\"_#{append_to_id}\"",
"end",
"html_id",
"=",
"html_id",
".",
"parameterize",
".",
"underscore",
"results",
"=",
"[",
"]",
"if",
"association_type",
"==",
":one",
"&&",
"@object",
".",
"public_send",
"(",
"association",
")",
"results",
"<<",
"@object",
".",
"public_send",
"(",
"association",
")",
"elsif",
"association_type",
"==",
":many",
"&&",
"@object",
".",
"public_send",
"(",
"association",
".",
"to_s",
".",
"pluralize",
")",
".",
"count",
">",
"0",
"@object",
".",
"public_send",
"(",
"association",
".",
"to_s",
".",
"pluralize",
")",
".",
"each",
"{",
"|",
"record",
"|",
"results",
"<<",
"record",
"}",
"end",
"data_pre",
"=",
"results",
".",
"map",
"{",
"|",
"result",
"|",
"result",
".",
"public_send",
"(",
"token_method",
")",
"}",
"value",
"=",
"data_pre",
".",
"map",
"{",
"|",
"row",
"|",
"row",
"[",
":id",
"]",
"}",
".",
"join",
"(",
"','",
")",
"on_add",
"=",
"options",
"[",
":on_add",
"]",
"?",
"\"#{options[:on_add]}\"",
":",
"\"false\"",
"on_delete",
"=",
"options",
"[",
":on_delete",
"]",
"?",
"\"#{options[:on_delete]}\"",
":",
"\"false\"",
"token_url",
"=",
"\"'#{token_url}'\"",
"unless",
"token_url_is_function",
"js_content",
"=",
"\"\n jQuery.noConflict();\n jQuery(function() {\n jQuery('##{html_id}').tokenInput(#{token_url}, {\n crossDomain: false,\n tokenLimit: #{token_limit.nil? ? \"null\" : token_limit.to_i},\n preventDuplicates: true,\n prePopulate: jQuery('##{attribute_name}').data('pre'),\n theme: 'facebook',\n hintText: '\"",
"+",
"t",
"(",
"'helpers.token_field.hint_text'",
")",
"+",
"\"',\n searchingText: '\"",
"+",
"t",
"(",
"'helpers.token_field.searching_text'",
")",
"+",
"\"',\n noResultsText: '\"",
"+",
"t",
"(",
"'helpers.token_field.no_results_text'",
")",
"+",
"\"',\n onAdd: \"",
"+",
"on_add",
"+",
"\",\n onDelete: \"",
"+",
"on_delete",
"+",
"\"\n });\n });\n \"",
"script",
"=",
"content_tag",
"(",
":script",
",",
"js_content",
".",
"html_safe",
",",
":type",
"=>",
"Mime",
"::",
"JS",
")",
"text_field",
"(",
"\"#{attribute_name}\"",
",",
"\"data-pre\"",
"=>",
"data_pre",
".",
"to_json",
",",
":value",
"=>",
"value",
",",
":id",
"=>",
"html_id",
")",
"+",
"script",
"end"
] |
form_for helper for token input with jquery token input plugin
for has_many and belongs_to association
http://railscasts.com/episodes/258-token-fields
http://loopj.com/jquery-tokeninput/
helper will render standard text field input with javascript.
javascript will change standard input to token field input
EXAMPLE
class Category < ActiveRecord::Base
attr_accessible :name, :parent_id, :product_ids
has_many :products
# method for converting array of categories to array of hashes in format that token input accepts
def to_token
{:id => id, :name => name}
end
end
class Product < ActiveRecord::Base
attr_accessible :name, :category_id
belongs_to :category
end
class CategoriesController < ApplicationController
# action for autocomplete
def token
categories = Category.where("categories.name like ?", "%#{params[:q]}%")
respond_to do |format|
format.json { render :json => categories.map(&:to_token) }
end
end
# rest of the class
end
then in routes add route for token ajax call
MyApplication::Application.routes.draw do
resources :categories do
collection do
get :token # route for token -> token_categories_path
end
end
end
then in view we call token_field
token_field input will be default expects, that Category model exists
<%= form_for @product do |f| %>
<%= f.token_field :category_id %>
<% end %>
possible options:
in case the association roles where given like this
class Product < ActiveRecord::Base
belongs_to :cat, :class_name => 'Category', :foreign_key => :cat_id
end
then right model need to be specified
<%= f.token_field :cat_id, :model => :category %>
We can use token_input also for mapping category to products
we will use ActiveRecord method product_ids which be default return array of ids from association
<%= form_for @category do |f| %>
<%= f.token_field :product_ids %>
<% end %>
in model we have to change product_ids= method like this
class Category < ActiveRecord::Base
has_many :products
alias_method :product_ids_old=, :product_ids=
def product_ids=(ids)
ids = ids.split(",").map(&:to_i) if ids.is_a?(String)
self.product_ids_old=ids
end
# rest of the class...
end
|
[
"form_for",
"helper",
"for",
"token",
"input",
"with",
"jquery",
"token",
"input",
"plugin",
"for",
"has_many",
"and",
"belongs_to",
"association"
] |
a4abed90ef18890afeac5363b4f791e66f3fe62e
|
https://github.com/mirrec/token_field/blob/a4abed90ef18890afeac5363b4f791e66f3fe62e/lib/token_field/form_builder.rb#L94-L151
|
7,943 |
26fe/tree.rb
|
lib/tree_rb/input_plugins/html_page/dom_walker.rb
|
TreeRb.DomWalker.process_node
|
def process_node(node, level=1)
entries = node.children
@visitor.enter_node(node)
entries.each do |entry|
unless is_leaf?(entry)
process_node(entry, level+1)
else
@visitor.visit_leaf(entry)
end
end
@visitor.exit_node(node)
end
|
ruby
|
def process_node(node, level=1)
entries = node.children
@visitor.enter_node(node)
entries.each do |entry|
unless is_leaf?(entry)
process_node(entry, level+1)
else
@visitor.visit_leaf(entry)
end
end
@visitor.exit_node(node)
end
|
[
"def",
"process_node",
"(",
"node",
",",
"level",
"=",
"1",
")",
"entries",
"=",
"node",
".",
"children",
"@visitor",
".",
"enter_node",
"(",
"node",
")",
"entries",
".",
"each",
"do",
"|",
"entry",
"|",
"unless",
"is_leaf?",
"(",
"entry",
")",
"process_node",
"(",
"entry",
",",
"level",
"+",
"1",
")",
"else",
"@visitor",
".",
"visit_leaf",
"(",
"entry",
")",
"end",
"end",
"@visitor",
".",
"exit_node",
"(",
"node",
")",
"end"
] |
recurse on nodes
|
[
"recurse",
"on",
"nodes"
] |
5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b
|
https://github.com/26fe/tree.rb/blob/5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b/lib/tree_rb/input_plugins/html_page/dom_walker.rb#L18-L29
|
7,944 |
marcmo/cxxproject
|
lib/cxxproject/buildingblocks/linkable.rb
|
Cxxproject.Linkable.handle_whole_archive
|
def handle_whole_archive(building_block, res, linker, flag)
if is_whole_archive(building_block)
res.push(flag) if flag and !flag.empty?
end
end
|
ruby
|
def handle_whole_archive(building_block, res, linker, flag)
if is_whole_archive(building_block)
res.push(flag) if flag and !flag.empty?
end
end
|
[
"def",
"handle_whole_archive",
"(",
"building_block",
",",
"res",
",",
"linker",
",",
"flag",
")",
"if",
"is_whole_archive",
"(",
"building_block",
")",
"res",
".",
"push",
"(",
"flag",
")",
"if",
"flag",
"and",
"!",
"flag",
".",
"empty?",
"end",
"end"
] |
res the array with command line arguments that is used as result
linker the linker hash
sym the symbol that is used to fish out a value from the linker
|
[
"res",
"the",
"array",
"with",
"command",
"line",
"arguments",
"that",
"is",
"used",
"as",
"result",
"linker",
"the",
"linker",
"hash",
"sym",
"the",
"symbol",
"that",
"is",
"used",
"to",
"fish",
"out",
"a",
"value",
"from",
"the",
"linker"
] |
3740a09d6a143acd96bde3d2ff79055a6b810da4
|
https://github.com/marcmo/cxxproject/blob/3740a09d6a143acd96bde3d2ff79055a6b810da4/lib/cxxproject/buildingblocks/linkable.rb#L152-L156
|
7,945 |
marcmo/cxxproject
|
lib/cxxproject/buildingblocks/linkable.rb
|
Cxxproject.Linkable.convert_to_rake
|
def convert_to_rake()
object_multitask = prepare_tasks_for_objects()
res = typed_file_task get_rake_task_type(), get_task_name => object_multitask do
cmd = calc_command_line
Dir.chdir(@project_dir) do
mapfileStr = @mapfile ? " >#{@mapfile}" : ""
rd, wr = IO.pipe
cmdLinePrint = cmd
printCmd(cmdLinePrint, "Linking #{executable_name}", false) #OK
cmd << {
:out=> @mapfile ? "#{@mapfile}" : wr, # > xy.map
:err=>wr
}
sp = spawn(*cmd)
cmd.pop
# for console print
cmd << " >#{@mapfile}" if @mapfile
consoleOutput = ProcessHelper.readOutput(sp, rd, wr)
process_result(cmdLinePrint, consoleOutput, @tcs[:LINKER][:ERROR_PARSER], nil)
check_config_file()
post_link_hook(@tcs[:LINKER])
end
end
res.tags = tags
res.immediate_output = true
res.enhance(@config_files)
res.enhance([@project_dir + "/" + @linker_script]) if @linker_script
add_output_dir_dependency(get_task_name, res, true)
add_grouping_tasks(get_task_name)
setup_rake_dependencies(res, object_multitask)
# check that all source libs are checked even if they are not a real rake dependency (can happen if "build this project only")
begin
libChecker = task get_task_name+"LibChecker" do
if File.exists?(get_task_name) # otherwise the task will be executed anyway
all_dependencies.each do |bb|
if bb and StaticLibrary === bb
f = bb.get_task_name # = abs path of library
if not File.exists?(f) or File.mtime(f) > File.mtime(get_task_name)
def res.needed?
true
end
break
end
end
end
end
end
rescue
def res.needed?
true
end
end
libChecker.transparent_timestamp = true
res.enhance([libChecker])
return res
end
|
ruby
|
def convert_to_rake()
object_multitask = prepare_tasks_for_objects()
res = typed_file_task get_rake_task_type(), get_task_name => object_multitask do
cmd = calc_command_line
Dir.chdir(@project_dir) do
mapfileStr = @mapfile ? " >#{@mapfile}" : ""
rd, wr = IO.pipe
cmdLinePrint = cmd
printCmd(cmdLinePrint, "Linking #{executable_name}", false) #OK
cmd << {
:out=> @mapfile ? "#{@mapfile}" : wr, # > xy.map
:err=>wr
}
sp = spawn(*cmd)
cmd.pop
# for console print
cmd << " >#{@mapfile}" if @mapfile
consoleOutput = ProcessHelper.readOutput(sp, rd, wr)
process_result(cmdLinePrint, consoleOutput, @tcs[:LINKER][:ERROR_PARSER], nil)
check_config_file()
post_link_hook(@tcs[:LINKER])
end
end
res.tags = tags
res.immediate_output = true
res.enhance(@config_files)
res.enhance([@project_dir + "/" + @linker_script]) if @linker_script
add_output_dir_dependency(get_task_name, res, true)
add_grouping_tasks(get_task_name)
setup_rake_dependencies(res, object_multitask)
# check that all source libs are checked even if they are not a real rake dependency (can happen if "build this project only")
begin
libChecker = task get_task_name+"LibChecker" do
if File.exists?(get_task_name) # otherwise the task will be executed anyway
all_dependencies.each do |bb|
if bb and StaticLibrary === bb
f = bb.get_task_name # = abs path of library
if not File.exists?(f) or File.mtime(f) > File.mtime(get_task_name)
def res.needed?
true
end
break
end
end
end
end
end
rescue
def res.needed?
true
end
end
libChecker.transparent_timestamp = true
res.enhance([libChecker])
return res
end
|
[
"def",
"convert_to_rake",
"(",
")",
"object_multitask",
"=",
"prepare_tasks_for_objects",
"(",
")",
"res",
"=",
"typed_file_task",
"get_rake_task_type",
"(",
")",
",",
"get_task_name",
"=>",
"object_multitask",
"do",
"cmd",
"=",
"calc_command_line",
"Dir",
".",
"chdir",
"(",
"@project_dir",
")",
"do",
"mapfileStr",
"=",
"@mapfile",
"?",
"\" >#{@mapfile}\"",
":",
"\"\"",
"rd",
",",
"wr",
"=",
"IO",
".",
"pipe",
"cmdLinePrint",
"=",
"cmd",
"printCmd",
"(",
"cmdLinePrint",
",",
"\"Linking #{executable_name}\"",
",",
"false",
")",
"#OK",
"cmd",
"<<",
"{",
":out",
"=>",
"@mapfile",
"?",
"\"#{@mapfile}\"",
":",
"wr",
",",
"# > xy.map",
":err",
"=>",
"wr",
"}",
"sp",
"=",
"spawn",
"(",
"cmd",
")",
"cmd",
".",
"pop",
"# for console print",
"cmd",
"<<",
"\" >#{@mapfile}\"",
"if",
"@mapfile",
"consoleOutput",
"=",
"ProcessHelper",
".",
"readOutput",
"(",
"sp",
",",
"rd",
",",
"wr",
")",
"process_result",
"(",
"cmdLinePrint",
",",
"consoleOutput",
",",
"@tcs",
"[",
":LINKER",
"]",
"[",
":ERROR_PARSER",
"]",
",",
"nil",
")",
"check_config_file",
"(",
")",
"post_link_hook",
"(",
"@tcs",
"[",
":LINKER",
"]",
")",
"end",
"end",
"res",
".",
"tags",
"=",
"tags",
"res",
".",
"immediate_output",
"=",
"true",
"res",
".",
"enhance",
"(",
"@config_files",
")",
"res",
".",
"enhance",
"(",
"[",
"@project_dir",
"+",
"\"/\"",
"+",
"@linker_script",
"]",
")",
"if",
"@linker_script",
"add_output_dir_dependency",
"(",
"get_task_name",
",",
"res",
",",
"true",
")",
"add_grouping_tasks",
"(",
"get_task_name",
")",
"setup_rake_dependencies",
"(",
"res",
",",
"object_multitask",
")",
"# check that all source libs are checked even if they are not a real rake dependency (can happen if \"build this project only\")",
"begin",
"libChecker",
"=",
"task",
"get_task_name",
"+",
"\"LibChecker\"",
"do",
"if",
"File",
".",
"exists?",
"(",
"get_task_name",
")",
"# otherwise the task will be executed anyway",
"all_dependencies",
".",
"each",
"do",
"|",
"bb",
"|",
"if",
"bb",
"and",
"StaticLibrary",
"===",
"bb",
"f",
"=",
"bb",
".",
"get_task_name",
"# = abs path of library",
"if",
"not",
"File",
".",
"exists?",
"(",
"f",
")",
"or",
"File",
".",
"mtime",
"(",
"f",
")",
">",
"File",
".",
"mtime",
"(",
"get_task_name",
")",
"def",
"res",
".",
"needed?",
"true",
"end",
"break",
"end",
"end",
"end",
"end",
"end",
"rescue",
"def",
"res",
".",
"needed?",
"true",
"end",
"end",
"libChecker",
".",
"transparent_timestamp",
"=",
"true",
"res",
".",
"enhance",
"(",
"[",
"libChecker",
"]",
")",
"return",
"res",
"end"
] |
create a task that will link an executable from a set of object files
|
[
"create",
"a",
"task",
"that",
"will",
"link",
"an",
"executable",
"from",
"a",
"set",
"of",
"object",
"files"
] |
3740a09d6a143acd96bde3d2ff79055a6b810da4
|
https://github.com/marcmo/cxxproject/blob/3740a09d6a143acd96bde3d2ff79055a6b810da4/lib/cxxproject/buildingblocks/linkable.rb#L181-L241
|
7,946 |
marcmo/cxxproject
|
lib/cxxproject/buildingblocks/linkable.rb
|
Cxxproject.SharedLibrary.post_link_hook
|
def post_link_hook(linker)
basic_name = get_basic_name(linker)
soname = get_soname(linker)
symlink_lib_to basic_name
symlink_lib_to soname
end
|
ruby
|
def post_link_hook(linker)
basic_name = get_basic_name(linker)
soname = get_soname(linker)
symlink_lib_to basic_name
symlink_lib_to soname
end
|
[
"def",
"post_link_hook",
"(",
"linker",
")",
"basic_name",
"=",
"get_basic_name",
"(",
"linker",
")",
"soname",
"=",
"get_soname",
"(",
"linker",
")",
"symlink_lib_to",
"basic_name",
"symlink_lib_to",
"soname",
"end"
] |
Some symbolic links
ln -s libfoo.so libfoo.1.2.so
ln -s libfoo.1.so libfoo.1.2.so
|
[
"Some",
"symbolic",
"links",
"ln",
"-",
"s",
"libfoo",
".",
"so",
"libfoo",
".",
"1",
".",
"2",
".",
"so",
"ln",
"-",
"s",
"libfoo",
".",
"1",
".",
"so",
"libfoo",
".",
"1",
".",
"2",
".",
"so"
] |
3740a09d6a143acd96bde3d2ff79055a6b810da4
|
https://github.com/marcmo/cxxproject/blob/3740a09d6a143acd96bde3d2ff79055a6b810da4/lib/cxxproject/buildingblocks/linkable.rb#L355-L360
|
7,947 |
jduckett/duck_map
|
lib/duck_map/attributes.rb
|
DuckMap.Attributes.sitemap_attributes
|
def sitemap_attributes(key = :default)
key = key.blank? ? :default : key.to_sym
# if the key exists and has a Hash value, cool. Otherwise, go back to :default.
# self.class.sitemap_attributes should ALWAYS return a Hash, so, no need to test for that.
# however, key may or may not be a Hash. should test for that.
unless self.class.sitemap_attributes[key].kind_of?(Hash)
key = :default
end
# the :default Hash SHOULD ALWAYS be there. If not, this might cause an exception!!
return self.class.sitemap_attributes[key]
end
|
ruby
|
def sitemap_attributes(key = :default)
key = key.blank? ? :default : key.to_sym
# if the key exists and has a Hash value, cool. Otherwise, go back to :default.
# self.class.sitemap_attributes should ALWAYS return a Hash, so, no need to test for that.
# however, key may or may not be a Hash. should test for that.
unless self.class.sitemap_attributes[key].kind_of?(Hash)
key = :default
end
# the :default Hash SHOULD ALWAYS be there. If not, this might cause an exception!!
return self.class.sitemap_attributes[key]
end
|
[
"def",
"sitemap_attributes",
"(",
"key",
"=",
":default",
")",
"key",
"=",
"key",
".",
"blank?",
"?",
":default",
":",
"key",
".",
"to_sym",
"# if the key exists and has a Hash value, cool. Otherwise, go back to :default.",
"# self.class.sitemap_attributes should ALWAYS return a Hash, so, no need to test for that.",
"# however, key may or may not be a Hash. should test for that.",
"unless",
"self",
".",
"class",
".",
"sitemap_attributes",
"[",
"key",
"]",
".",
"kind_of?",
"(",
"Hash",
")",
"key",
"=",
":default",
"end",
"# the :default Hash SHOULD ALWAYS be there. If not, this might cause an exception!!",
"return",
"self",
".",
"class",
".",
"sitemap_attributes",
"[",
"key",
"]",
"end"
] |
Returns a Hash associated with a key. The Hash represents all of the attributes for
a given action name on a controller.
acts_as_sitemap :index, title: "my title" # index is the key
sitemap_attributes("index") # index is the key
@return [Hash]
|
[
"Returns",
"a",
"Hash",
"associated",
"with",
"a",
"key",
".",
"The",
"Hash",
"represents",
"all",
"of",
"the",
"attributes",
"for",
"a",
"given",
"action",
"name",
"on",
"a",
"controller",
"."
] |
c510acfa95e8ad4afb1501366058ae88a73704df
|
https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/attributes.rb#L122-L134
|
7,948 |
mikiobraun/jblas-ruby
|
lib/jblas/mixin_general.rb
|
JBLAS.MatrixGeneralMixin.hcat
|
def hcat(y)
unless self.dims[0] == y.dims[0]
raise ArgumentError, "Matrices must have same number of rows"
end
DoubleMatrix.concat_horizontally(self, y)
end
|
ruby
|
def hcat(y)
unless self.dims[0] == y.dims[0]
raise ArgumentError, "Matrices must have same number of rows"
end
DoubleMatrix.concat_horizontally(self, y)
end
|
[
"def",
"hcat",
"(",
"y",
")",
"unless",
"self",
".",
"dims",
"[",
"0",
"]",
"==",
"y",
".",
"dims",
"[",
"0",
"]",
"raise",
"ArgumentError",
",",
"\"Matrices must have same number of rows\"",
"end",
"DoubleMatrix",
".",
"concat_horizontally",
"(",
"self",
",",
"y",
")",
"end"
] |
Return a new matrix which consists of the _self_ and _y_ side by
side. In general the hcat method should be used sparingly as it
creates a new matrix and copies everything on each use. You
should always ask yourself if an array of vectors or matrices
doesn't serve you better. That said, you _can_ do funny things
with +inject+. For example,
a = mat[1,2,3]
[a, 2*a, 3*a].inject {|s,x| s = s.hcat(x)}
=> 1.0 2.0 3.0
2.0 4.0 6.0
3.0 6.0 9.0
|
[
"Return",
"a",
"new",
"matrix",
"which",
"consists",
"of",
"the",
"_self_",
"and",
"_y_",
"side",
"by",
"side",
".",
"In",
"general",
"the",
"hcat",
"method",
"should",
"be",
"used",
"sparingly",
"as",
"it",
"creates",
"a",
"new",
"matrix",
"and",
"copies",
"everything",
"on",
"each",
"use",
".",
"You",
"should",
"always",
"ask",
"yourself",
"if",
"an",
"array",
"of",
"vectors",
"or",
"matrices",
"doesn",
"t",
"serve",
"you",
"better",
".",
"That",
"said",
"you",
"_can_",
"do",
"funny",
"things",
"with",
"+",
"inject",
"+",
".",
"For",
"example"
] |
7233976c9e3b210e30bc36ead2b1e05ab3383fec
|
https://github.com/mikiobraun/jblas-ruby/blob/7233976c9e3b210e30bc36ead2b1e05ab3383fec/lib/jblas/mixin_general.rb#L114-L119
|
7,949 |
mikiobraun/jblas-ruby
|
lib/jblas/mixin_general.rb
|
JBLAS.MatrixGeneralMixin.vcat
|
def vcat(y)
unless self.dims[1] == y.dims[1]
raise ArgumentError, "Matrices must have same number of columns"
end
DoubleMatrix.concat_vertically(self, y)
end
|
ruby
|
def vcat(y)
unless self.dims[1] == y.dims[1]
raise ArgumentError, "Matrices must have same number of columns"
end
DoubleMatrix.concat_vertically(self, y)
end
|
[
"def",
"vcat",
"(",
"y",
")",
"unless",
"self",
".",
"dims",
"[",
"1",
"]",
"==",
"y",
".",
"dims",
"[",
"1",
"]",
"raise",
"ArgumentError",
",",
"\"Matrices must have same number of columns\"",
"end",
"DoubleMatrix",
".",
"concat_vertically",
"(",
"self",
",",
"y",
")",
"end"
] |
Return a new matrix which consists of the _self_ on top of _y_.
In general the hcat methods should be used sparingly. You
should always ask yourself if an array of vectors or matrices
doesn't serve you better. See also hcat.
|
[
"Return",
"a",
"new",
"matrix",
"which",
"consists",
"of",
"the",
"_self_",
"on",
"top",
"of",
"_y_",
".",
"In",
"general",
"the",
"hcat",
"methods",
"should",
"be",
"used",
"sparingly",
".",
"You",
"should",
"always",
"ask",
"yourself",
"if",
"an",
"array",
"of",
"vectors",
"or",
"matrices",
"doesn",
"t",
"serve",
"you",
"better",
".",
"See",
"also",
"hcat",
"."
] |
7233976c9e3b210e30bc36ead2b1e05ab3383fec
|
https://github.com/mikiobraun/jblas-ruby/blob/7233976c9e3b210e30bc36ead2b1e05ab3383fec/lib/jblas/mixin_general.rb#L125-L130
|
7,950 |
postmodern/rprogram
|
lib/rprogram/option.rb
|
RProgram.Option.arguments
|
def arguments(value)
case value
when true
[@flag]
when false, nil
[]
else
value = super(value)
if @multiple
args = []
value.each do |arg|
args += Array(@formatter.call(self,[arg]))
end
return args
else
value = [value.join(@separator)] if @separator
return Array(@formatter.call(self,value))
end
end
end
|
ruby
|
def arguments(value)
case value
when true
[@flag]
when false, nil
[]
else
value = super(value)
if @multiple
args = []
value.each do |arg|
args += Array(@formatter.call(self,[arg]))
end
return args
else
value = [value.join(@separator)] if @separator
return Array(@formatter.call(self,value))
end
end
end
|
[
"def",
"arguments",
"(",
"value",
")",
"case",
"value",
"when",
"true",
"[",
"@flag",
"]",
"when",
"false",
",",
"nil",
"[",
"]",
"else",
"value",
"=",
"super",
"(",
"value",
")",
"if",
"@multiple",
"args",
"=",
"[",
"]",
"value",
".",
"each",
"do",
"|",
"arg",
"|",
"args",
"+=",
"Array",
"(",
"@formatter",
".",
"call",
"(",
"self",
",",
"[",
"arg",
"]",
")",
")",
"end",
"return",
"args",
"else",
"value",
"=",
"[",
"value",
".",
"join",
"(",
"@separator",
")",
"]",
"if",
"@separator",
"return",
"Array",
"(",
"@formatter",
".",
"call",
"(",
"self",
",",
"value",
")",
")",
"end",
"end",
"end"
] |
Creates a new Option object with. If a block is given it will be
used for the custom formatting of the option. If a block is not given,
the option will use the default_format when generating the arguments.
@param [Hash] options
Additional options.
@option options [String] :flag
The command-line flag to use.
@option options [true, false] :equals (false)
Implies the option maybe formated as `--flag=value`.
@option options [true, false] :multiple (false)
Specifies the option maybe given an Array of values.
@option options [String] :separator
The separator to use for formating multiple arguments into one
`String`. Cannot be used with the `:multiple` option.
@option options [true, false] :sub_options (false)
Specifies that the option contains sub-options.
@yield [option, value]
If a block is given, it will be used to format each value of the
option.
@yieldparam [Option] option
The option that is being formatted.
@yieldparam [String, Array] value
The value to format for the option. May be an Array, if multiple
values are allowed with the option.
Formats the arguments for the option.
@param [Hash, Array, String] value
The arguments to format.
@return [Array]
The formatted arguments of the option.
|
[
"Creates",
"a",
"new",
"Option",
"object",
"with",
".",
"If",
"a",
"block",
"is",
"given",
"it",
"will",
"be",
"used",
"for",
"the",
"custom",
"formatting",
"of",
"the",
"option",
".",
"If",
"a",
"block",
"is",
"not",
"given",
"the",
"option",
"will",
"use",
"the",
"default_format",
"when",
"generating",
"the",
"arguments",
"."
] |
94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be
|
https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/option.rb#L88-L111
|
7,951 |
loveablelobster/specify_cli
|
lib/specify/database.rb
|
Specify.Database.close
|
def close
return if sessions.empty?
sessions.each do |session|
session.close
session.delete_observer self
end
# TODO: should close database connection
end
|
ruby
|
def close
return if sessions.empty?
sessions.each do |session|
session.close
session.delete_observer self
end
# TODO: should close database connection
end
|
[
"def",
"close",
"return",
"if",
"sessions",
".",
"empty?",
"sessions",
".",
"each",
"do",
"|",
"session",
"|",
"session",
".",
"close",
"session",
".",
"delete_observer",
"self",
"end",
"# TODO: should close database connection",
"end"
] |
Closes all sessions.
|
[
"Closes",
"all",
"sessions",
"."
] |
79c390307172f1cd8aa288fdde8fb0fc99ad2b91
|
https://github.com/loveablelobster/specify_cli/blob/79c390307172f1cd8aa288fdde8fb0fc99ad2b91/lib/specify/database.rb#L82-L89
|
7,952 |
boston-library/mei
|
lib/mei/web_service_base.rb
|
Mei.WebServiceBase.get_json
|
def get_json(url)
r = Mei::WebServiceBase.fetch(url)
JSON.parse(r.body)
end
|
ruby
|
def get_json(url)
r = Mei::WebServiceBase.fetch(url)
JSON.parse(r.body)
end
|
[
"def",
"get_json",
"(",
"url",
")",
"r",
"=",
"Mei",
"::",
"WebServiceBase",
".",
"fetch",
"(",
"url",
")",
"JSON",
".",
"parse",
"(",
"r",
".",
"body",
")",
"end"
] |
mix-in to retreive and parse JSON content from the web
|
[
"mix",
"-",
"in",
"to",
"retreive",
"and",
"parse",
"JSON",
"content",
"from",
"the",
"web"
] |
57279df72a2f45d0fb79fd31c22f495b3a0ae290
|
https://github.com/boston-library/mei/blob/57279df72a2f45d0fb79fd31c22f495b3a0ae290/lib/mei/web_service_base.rb#L34-L37
|
7,953 |
birarda/logan
|
lib/logan/comment.rb
|
Logan.Comment.creator=
|
def creator=(creator)
@creator = creator.is_a?(Hash) ? Logan::Person.new(creator) : creator
end
|
ruby
|
def creator=(creator)
@creator = creator.is_a?(Hash) ? Logan::Person.new(creator) : creator
end
|
[
"def",
"creator",
"=",
"(",
"creator",
")",
"@creator",
"=",
"creator",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"Logan",
"::",
"Person",
".",
"new",
"(",
"creator",
")",
":",
"creator",
"end"
] |
sets the creator for this todo
@param [Object] creator person hash from API or <Logan::Person> object
|
[
"sets",
"the",
"creator",
"for",
"this",
"todo"
] |
c007081c7dbb5b98ef5312db78f84867c6075ab0
|
https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/comment.rb#L28-L30
|
7,954 |
birarda/logan
|
lib/logan/todo.rb
|
Logan.Todo.assignee=
|
def assignee=(assignee)
@assignee = assignee.is_a?(Hash) ? Logan::Person.new(assignee) : assignee
end
|
ruby
|
def assignee=(assignee)
@assignee = assignee.is_a?(Hash) ? Logan::Person.new(assignee) : assignee
end
|
[
"def",
"assignee",
"=",
"(",
"assignee",
")",
"@assignee",
"=",
"assignee",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"Logan",
"::",
"Person",
".",
"new",
"(",
"assignee",
")",
":",
"assignee",
"end"
] |
sets the assignee for this todo
@param [Object] assignee person hash from API or <Logan::Person> object
@return [Logan::Person] the assignee for this todo
|
[
"sets",
"the",
"assignee",
"for",
"this",
"todo"
] |
c007081c7dbb5b98ef5312db78f84867c6075ab0
|
https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/todo.rb#L86-L88
|
7,955 |
birarda/logan
|
lib/logan/todo.rb
|
Logan.Todo.create_comment
|
def create_comment(comment)
post_params = {
:body => comment.post_json,
:headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'})
}
response = Logan::Client.post "/projects/#{@project_id}/todos/#{@id}/comments.json", post_params
Logan::Comment.new response
end
|
ruby
|
def create_comment(comment)
post_params = {
:body => comment.post_json,
:headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'})
}
response = Logan::Client.post "/projects/#{@project_id}/todos/#{@id}/comments.json", post_params
Logan::Comment.new response
end
|
[
"def",
"create_comment",
"(",
"comment",
")",
"post_params",
"=",
"{",
":body",
"=>",
"comment",
".",
"post_json",
",",
":headers",
"=>",
"Logan",
"::",
"Client",
".",
"headers",
".",
"merge",
"(",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"}",
"response",
"=",
"Logan",
"::",
"Client",
".",
"post",
"\"/projects/#{@project_id}/todos/#{@id}/comments.json\"",
",",
"post_params",
"Logan",
"::",
"Comment",
".",
"new",
"response",
"end"
] |
create a create in this todo list via the Basecamp API
@param [Logan::Comment] todo the comment instance to create in this todo lost
@return [Logan::Comment] the created comment returned from the Basecamp API
|
[
"create",
"a",
"create",
"in",
"this",
"todo",
"list",
"via",
"the",
"Basecamp",
"API"
] |
c007081c7dbb5b98ef5312db78f84867c6075ab0
|
https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/todo.rb#L94-L102
|
7,956 |
EmmanuelOga/firering
|
lib/firering/data/room.rb
|
Firering.Room.today_transcript
|
def today_transcript(&callback)
connection.http(:get, "/room/#{id}/transcript.json") do |data, http|
callback.call(data[:messages].map { |msg| Firering::Message.instantiate(connection, msg) }) if callback
end
end
|
ruby
|
def today_transcript(&callback)
connection.http(:get, "/room/#{id}/transcript.json") do |data, http|
callback.call(data[:messages].map { |msg| Firering::Message.instantiate(connection, msg) }) if callback
end
end
|
[
"def",
"today_transcript",
"(",
"&",
"callback",
")",
"connection",
".",
"http",
"(",
":get",
",",
"\"/room/#{id}/transcript.json\"",
")",
"do",
"|",
"data",
",",
"http",
"|",
"callback",
".",
"call",
"(",
"data",
"[",
":messages",
"]",
".",
"map",
"{",
"|",
"msg",
"|",
"Firering",
"::",
"Message",
".",
"instantiate",
"(",
"connection",
",",
"msg",
")",
"}",
")",
"if",
"callback",
"end",
"end"
] |
Returns all the messages sent today to a room.
|
[
"Returns",
"all",
"the",
"messages",
"sent",
"today",
"to",
"a",
"room",
"."
] |
9e13dc3399f7429713b5213c5ee77bedf01def31
|
https://github.com/EmmanuelOga/firering/blob/9e13dc3399f7429713b5213c5ee77bedf01def31/lib/firering/data/room.rb#L50-L54
|
7,957 |
EmmanuelOga/firering
|
lib/firering/data/room.rb
|
Firering.Room.transcript
|
def transcript(year, month, day, &callback)
connection.http(:get, "/room/#{id}/transcript/#{year}/#{month}/#{day}.json") do |data, http|
callback.call(data[:messages].map { |msg| Firering::Message.instantiate(connection, msg) }) if callback
end
end
|
ruby
|
def transcript(year, month, day, &callback)
connection.http(:get, "/room/#{id}/transcript/#{year}/#{month}/#{day}.json") do |data, http|
callback.call(data[:messages].map { |msg| Firering::Message.instantiate(connection, msg) }) if callback
end
end
|
[
"def",
"transcript",
"(",
"year",
",",
"month",
",",
"day",
",",
"&",
"callback",
")",
"connection",
".",
"http",
"(",
":get",
",",
"\"/room/#{id}/transcript/#{year}/#{month}/#{day}.json\"",
")",
"do",
"|",
"data",
",",
"http",
"|",
"callback",
".",
"call",
"(",
"data",
"[",
":messages",
"]",
".",
"map",
"{",
"|",
"msg",
"|",
"Firering",
"::",
"Message",
".",
"instantiate",
"(",
"connection",
",",
"msg",
")",
"}",
")",
"if",
"callback",
"end",
"end"
] |
Returns all the messages sent on a specific date to a room.
|
[
"Returns",
"all",
"the",
"messages",
"sent",
"on",
"a",
"specific",
"date",
"to",
"a",
"room",
"."
] |
9e13dc3399f7429713b5213c5ee77bedf01def31
|
https://github.com/EmmanuelOga/firering/blob/9e13dc3399f7429713b5213c5ee77bedf01def31/lib/firering/data/room.rb#L57-L61
|
7,958 |
EmmanuelOga/firering
|
lib/firering/data/room.rb
|
Firering.Room.speak
|
def speak(data, &callback)
connection.http(:post, "/room/#{id}/speak.json", "message" => data) do |data, http| # Response Status: 201 Created
callback.call(Firering::Message.instantiate(connection, data, "message")) if callback
end
end
|
ruby
|
def speak(data, &callback)
connection.http(:post, "/room/#{id}/speak.json", "message" => data) do |data, http| # Response Status: 201 Created
callback.call(Firering::Message.instantiate(connection, data, "message")) if callback
end
end
|
[
"def",
"speak",
"(",
"data",
",",
"&",
"callback",
")",
"connection",
".",
"http",
"(",
":post",
",",
"\"/room/#{id}/speak.json\"",
",",
"\"message\"",
"=>",
"data",
")",
"do",
"|",
"data",
",",
"http",
"|",
"# Response Status: 201 Created",
"callback",
".",
"call",
"(",
"Firering",
"::",
"Message",
".",
"instantiate",
"(",
"connection",
",",
"data",
",",
"\"message\"",
")",
")",
"if",
"callback",
"end",
"end"
] |
Sends a new message with the currently authenticated user as the sender.
The XML for the new message is returned on a successful request.
The valid types are:
* TextMessage (regular chat message)
* PasteMessage (pre-formatted message, rendered in a fixed-width font)
* SoundMessage (plays a sound as determined by the message, which can be either “rimshot”, “crickets”, or “trombone”)
* TweetMessage (a Twitter status URL to be fetched and inserted into the chat)
If an explicit type is omitted, it will be inferred from the content (e.g.,
if the message contains new line characters, it will be considered a paste).
:type => "TextMessage", :body => "Hello"
|
[
"Sends",
"a",
"new",
"message",
"with",
"the",
"currently",
"authenticated",
"user",
"as",
"the",
"sender",
".",
"The",
"XML",
"for",
"the",
"new",
"message",
"is",
"returned",
"on",
"a",
"successful",
"request",
"."
] |
9e13dc3399f7429713b5213c5ee77bedf01def31
|
https://github.com/EmmanuelOga/firering/blob/9e13dc3399f7429713b5213c5ee77bedf01def31/lib/firering/data/room.rb#L97-L101
|
7,959 |
mirego/emotions
|
lib/emotions/emotion.rb
|
Emotions.Emotion.ensure_valid_emotion_name
|
def ensure_valid_emotion_name
unless Emotions.emotions.include?(emotion.try(:to_sym))
errors.add :emotion, I18n.t(:invalid, scope: [:errors, :messages])
end
end
|
ruby
|
def ensure_valid_emotion_name
unless Emotions.emotions.include?(emotion.try(:to_sym))
errors.add :emotion, I18n.t(:invalid, scope: [:errors, :messages])
end
end
|
[
"def",
"ensure_valid_emotion_name",
"unless",
"Emotions",
".",
"emotions",
".",
"include?",
"(",
"emotion",
".",
"try",
"(",
":to_sym",
")",
")",
"errors",
".",
"add",
":emotion",
",",
"I18n",
".",
"t",
"(",
":invalid",
",",
"scope",
":",
"[",
":errors",
",",
":messages",
"]",
")",
"end",
"end"
] |
Make sure we're using an allowed emotion name
|
[
"Make",
"sure",
"we",
"re",
"using",
"an",
"allowed",
"emotion",
"name"
] |
f0adc687dbdac906d9fcebfb0f3bf6afb6fa5d56
|
https://github.com/mirego/emotions/blob/f0adc687dbdac906d9fcebfb0f3bf6afb6fa5d56/lib/emotions/emotion.rb#L33-L37
|
7,960 |
asaaki/sjekksum
|
lib/sjekksum/isbn10.rb
|
Sjekksum.ISBN10.of
|
def of number
raise_on_type_mismatch number
digits = convert_number_to_digits(number)[0..9]
sum = digits.reverse_each.with_index.reduce(0) do |check, (digit, idx)|
check += digit * (idx+2)
end
check = (11 - sum % 11) % 11
check == 10 ? "X" : check
end
|
ruby
|
def of number
raise_on_type_mismatch number
digits = convert_number_to_digits(number)[0..9]
sum = digits.reverse_each.with_index.reduce(0) do |check, (digit, idx)|
check += digit * (idx+2)
end
check = (11 - sum % 11) % 11
check == 10 ? "X" : check
end
|
[
"def",
"of",
"number",
"raise_on_type_mismatch",
"number",
"digits",
"=",
"convert_number_to_digits",
"(",
"number",
")",
"[",
"0",
"..",
"9",
"]",
"sum",
"=",
"digits",
".",
"reverse_each",
".",
"with_index",
".",
"reduce",
"(",
"0",
")",
"do",
"|",
"check",
",",
"(",
"digit",
",",
"idx",
")",
"|",
"check",
"+=",
"digit",
"*",
"(",
"idx",
"+",
"2",
")",
"end",
"check",
"=",
"(",
"11",
"-",
"sum",
"%",
"11",
")",
"%",
"11",
"check",
"==",
"10",
"?",
"\"X\"",
":",
"check",
"end"
] |
Calculates ISBN-10 checksum
@example
Sjekksum::ISBN10.of("147743025") #=> 3
Sjekksum::ISBN10.of("193435600") #=> "X"
@param number [Integer, String] number for which the checksum should be calculated
@return [Integer, String] calculated checksum
|
[
"Calculates",
"ISBN",
"-",
"10",
"checksum"
] |
47a21c19dcffc67a3bef11d4f2de7c167fd20087
|
https://github.com/asaaki/sjekksum/blob/47a21c19dcffc67a3bef11d4f2de7c167fd20087/lib/sjekksum/isbn10.rb#L21-L31
|
7,961 |
asaaki/sjekksum
|
lib/sjekksum/isbn10.rb
|
Sjekksum.ISBN10.valid?
|
def valid? number
raise_on_type_mismatch number
num, check = split_isbn_number(number)
convert_number_to_digits(num).length == 9 && self.of(num) == check
end
|
ruby
|
def valid? number
raise_on_type_mismatch number
num, check = split_isbn_number(number)
convert_number_to_digits(num).length == 9 && self.of(num) == check
end
|
[
"def",
"valid?",
"number",
"raise_on_type_mismatch",
"number",
"num",
",",
"check",
"=",
"split_isbn_number",
"(",
"number",
")",
"convert_number_to_digits",
"(",
"num",
")",
".",
"length",
"==",
"9",
"&&",
"self",
".",
"of",
"(",
"num",
")",
"==",
"check",
"end"
] |
ISBN-10 validation of provided number
@example
Sjekksum::ISBN10.valid?("1477430253") #=> true
Sjekksum::ISBN10.valid?("193435600X") #=> true
@param number [Integer, String] number with included checksum
@return [Boolean]
|
[
"ISBN",
"-",
"10",
"validation",
"of",
"provided",
"number"
] |
47a21c19dcffc67a3bef11d4f2de7c167fd20087
|
https://github.com/asaaki/sjekksum/blob/47a21c19dcffc67a3bef11d4f2de7c167fd20087/lib/sjekksum/isbn10.rb#L44-L48
|
7,962 |
asaaki/sjekksum
|
lib/sjekksum/isbn10.rb
|
Sjekksum.ISBN10.convert
|
def convert number
raise_on_type_mismatch number
check = self.of(number)
if number.is_a?(String) or check.is_a?(String)
number.to_s << self.of(number).to_s
else
convert_to_int(number) * 10 + self.of(number)
end
end
|
ruby
|
def convert number
raise_on_type_mismatch number
check = self.of(number)
if number.is_a?(String) or check.is_a?(String)
number.to_s << self.of(number).to_s
else
convert_to_int(number) * 10 + self.of(number)
end
end
|
[
"def",
"convert",
"number",
"raise_on_type_mismatch",
"number",
"check",
"=",
"self",
".",
"of",
"(",
"number",
")",
"if",
"number",
".",
"is_a?",
"(",
"String",
")",
"or",
"check",
".",
"is_a?",
"(",
"String",
")",
"number",
".",
"to_s",
"<<",
"self",
".",
"of",
"(",
"number",
")",
".",
"to_s",
"else",
"convert_to_int",
"(",
"number",
")",
"*",
"10",
"+",
"self",
".",
"of",
"(",
"number",
")",
"end",
"end"
] |
Transforms a number by appending the ISBN-10 checksum digit
@example
Sjekksum::ISBN10.convert("147743025") #=> "1477430253"
Sjekksum::ISBN10.convert("193435600") #=> "193435600X"
@param number [Integer, String] number without a checksum
@return [Integer, String] final number including the checksum
|
[
"Transforms",
"a",
"number",
"by",
"appending",
"the",
"ISBN",
"-",
"10",
"checksum",
"digit"
] |
47a21c19dcffc67a3bef11d4f2de7c167fd20087
|
https://github.com/asaaki/sjekksum/blob/47a21c19dcffc67a3bef11d4f2de7c167fd20087/lib/sjekksum/isbn10.rb#L61-L69
|
7,963 |
carboncalculated/calculated
|
lib/calculated/session.rb
|
Calculated.Session.api_call
|
def api_call(method, path, params ={}, &proc)
if cache = caching? && (@cache[cache_key(path, params)])
return cache
else
if @logging
Calculated::Logging.log_calculated_api(method, path, params) do
api_call_without_logging(method, path, params, &proc)
end
else
api_call_without_logging(method, path, params, &proc)
end
end
end
|
ruby
|
def api_call(method, path, params ={}, &proc)
if cache = caching? && (@cache[cache_key(path, params)])
return cache
else
if @logging
Calculated::Logging.log_calculated_api(method, path, params) do
api_call_without_logging(method, path, params, &proc)
end
else
api_call_without_logging(method, path, params, &proc)
end
end
end
|
[
"def",
"api_call",
"(",
"method",
",",
"path",
",",
"params",
"=",
"{",
"}",
",",
"&",
"proc",
")",
"if",
"cache",
"=",
"caching?",
"&&",
"(",
"@cache",
"[",
"cache_key",
"(",
"path",
",",
"params",
")",
"]",
")",
"return",
"cache",
"else",
"if",
"@logging",
"Calculated",
"::",
"Logging",
".",
"log_calculated_api",
"(",
"method",
",",
"path",
",",
"params",
")",
"do",
"api_call_without_logging",
"(",
"method",
",",
"path",
",",
"params",
",",
"proc",
")",
"end",
"else",
"api_call_without_logging",
"(",
"method",
",",
"path",
",",
"params",
",",
"proc",
")",
"end",
"end",
"end"
] |
if we caching and we have the same cache lets try and get the
cache; otherwise we will make the request logging if need be
|
[
"if",
"we",
"caching",
"and",
"we",
"have",
"the",
"same",
"cache",
"lets",
"try",
"and",
"get",
"the",
"cache",
";",
"otherwise",
"we",
"will",
"make",
"the",
"request",
"logging",
"if",
"need",
"be"
] |
0234d89b515db26add000f88c594f6d3fb5edd5e
|
https://github.com/carboncalculated/calculated/blob/0234d89b515db26add000f88c594f6d3fb5edd5e/lib/calculated/session.rb#L64-L76
|
7,964 |
mattnichols/ice_cube_cron
|
lib/ice_cube_cron/expression_parser.rb
|
IceCubeCron.ExpressionParser.split_parts_and_interval
|
def split_parts_and_interval(expression_str)
interval = nil
parts = expression_str.split(/ +/).map do |part|
part, part_interval = part.split('/')
interval = part_interval unless part_interval.blank?
next nil if part.blank? || part == '*'
part
end
[parts, interval]
end
|
ruby
|
def split_parts_and_interval(expression_str)
interval = nil
parts = expression_str.split(/ +/).map do |part|
part, part_interval = part.split('/')
interval = part_interval unless part_interval.blank?
next nil if part.blank? || part == '*'
part
end
[parts, interval]
end
|
[
"def",
"split_parts_and_interval",
"(",
"expression_str",
")",
"interval",
"=",
"nil",
"parts",
"=",
"expression_str",
".",
"split",
"(",
"/",
"/",
")",
".",
"map",
"do",
"|",
"part",
"|",
"part",
",",
"part_interval",
"=",
"part",
".",
"split",
"(",
"'/'",
")",
"interval",
"=",
"part_interval",
"unless",
"part_interval",
".",
"blank?",
"next",
"nil",
"if",
"part",
".",
"blank?",
"||",
"part",
"==",
"'*'",
"part",
"end",
"[",
"parts",
",",
"interval",
"]",
"end"
] |
Split a cron string and extract the LAST interval that appears
|
[
"Split",
"a",
"cron",
"string",
"and",
"extract",
"the",
"LAST",
"interval",
"that",
"appears"
] |
9b406a40b5d15b03a3e58cb0ec64ca4a85a85cd0
|
https://github.com/mattnichols/ice_cube_cron/blob/9b406a40b5d15b03a3e58cb0ec64ca4a85a85cd0/lib/ice_cube_cron/expression_parser.rb#L158-L169
|
7,965 |
mattnichols/ice_cube_cron
|
lib/ice_cube_cron/expression_parser.rb
|
IceCubeCron.ExpressionParser.string_to_expression_parts
|
def string_to_expression_parts(expression_str)
return {} if expression_str.nil?
parts, interval = split_parts_and_interval(expression_str)
expression_parts = ::Hash[EXPRESSION_PART_KEYS.zip(parts)]
expression_parts.select! do |_key, value|
!value.nil?
end
expression_parts[:interval] = interval unless interval.nil?
expression_parts
end
|
ruby
|
def string_to_expression_parts(expression_str)
return {} if expression_str.nil?
parts, interval = split_parts_and_interval(expression_str)
expression_parts = ::Hash[EXPRESSION_PART_KEYS.zip(parts)]
expression_parts.select! do |_key, value|
!value.nil?
end
expression_parts[:interval] = interval unless interval.nil?
expression_parts
end
|
[
"def",
"string_to_expression_parts",
"(",
"expression_str",
")",
"return",
"{",
"}",
"if",
"expression_str",
".",
"nil?",
"parts",
",",
"interval",
"=",
"split_parts_and_interval",
"(",
"expression_str",
")",
"expression_parts",
"=",
"::",
"Hash",
"[",
"EXPRESSION_PART_KEYS",
".",
"zip",
"(",
"parts",
")",
"]",
"expression_parts",
".",
"select!",
"do",
"|",
"_key",
",",
"value",
"|",
"!",
"value",
".",
"nil?",
"end",
"expression_parts",
"[",
":interval",
"]",
"=",
"interval",
"unless",
"interval",
".",
"nil?",
"expression_parts",
"end"
] |
Split string expression into parts
|
[
"Split",
"string",
"expression",
"into",
"parts"
] |
9b406a40b5d15b03a3e58cb0ec64ca4a85a85cd0
|
https://github.com/mattnichols/ice_cube_cron/blob/9b406a40b5d15b03a3e58cb0ec64ca4a85a85cd0/lib/ice_cube_cron/expression_parser.rb#L174-L186
|
7,966 |
jarhart/rattler
|
lib/rattler/parsers/assert.rb
|
Rattler::Parsers.Assert.parse
|
def parse(scanner, rules, scope = ParserScope.empty)
pos = scanner.pos
result = (child.parse(scanner, rules, scope) && true)
scanner.pos = pos
result
end
|
ruby
|
def parse(scanner, rules, scope = ParserScope.empty)
pos = scanner.pos
result = (child.parse(scanner, rules, scope) && true)
scanner.pos = pos
result
end
|
[
"def",
"parse",
"(",
"scanner",
",",
"rules",
",",
"scope",
"=",
"ParserScope",
".",
"empty",
")",
"pos",
"=",
"scanner",
".",
"pos",
"result",
"=",
"(",
"child",
".",
"parse",
"(",
"scanner",
",",
"rules",
",",
"scope",
")",
"&&",
"true",
")",
"scanner",
".",
"pos",
"=",
"pos",
"result",
"end"
] |
Succeed or fail like the decorated parser but do not consume any input
and return +true+ on success.
@param (see Match#parse)
@return [Boolean] +true+ if the decorated parser succeeds
|
[
"Succeed",
"or",
"fail",
"like",
"the",
"decorated",
"parser",
"but",
"do",
"not",
"consume",
"any",
"input",
"and",
"return",
"+",
"true",
"+",
"on",
"success",
"."
] |
8b4efde2a05e9e790955bb635d4a1a9615893719
|
https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/parsers/assert.rb#L15-L20
|
7,967 |
marcmo/cxxproject
|
lib/cxxproject/buildingblocks/shared_libs_helper.rb
|
Cxxproject.OsxSharedLibs.post_link_hook
|
def post_link_hook(linker, bb)
basic_name = get_basic_name(linker, bb)
symlink_lib_to(basic_name, bb)
end
|
ruby
|
def post_link_hook(linker, bb)
basic_name = get_basic_name(linker, bb)
symlink_lib_to(basic_name, bb)
end
|
[
"def",
"post_link_hook",
"(",
"linker",
",",
"bb",
")",
"basic_name",
"=",
"get_basic_name",
"(",
"linker",
",",
"bb",
")",
"symlink_lib_to",
"(",
"basic_name",
",",
"bb",
")",
"end"
] |
Some symbolic links
ln -s foo.dylib foo.A.dylib
|
[
"Some",
"symbolic",
"links",
"ln",
"-",
"s",
"foo",
".",
"dylib",
"foo",
".",
"A",
".",
"dylib"
] |
3740a09d6a143acd96bde3d2ff79055a6b810da4
|
https://github.com/marcmo/cxxproject/blob/3740a09d6a143acd96bde3d2ff79055a6b810da4/lib/cxxproject/buildingblocks/shared_libs_helper.rb#L38-L41
|
7,968 |
matteolc/t2_airtime
|
lib/t2_airtime/api.rb
|
T2Airtime.API.transaction_list
|
def transaction_list(start = (Time.now - 24.hours), stop = Time.now, msisdn = nil, destination = nil, code = nil)
@params = {
stop_date: to_yyyymmdd(stop),
start_date: to_yyyymmdd(start)
}
code && !code.empty? && @params[:code] = code
msisdn && !msisdn.empty? && @params[:msisdn] = msisdn
destination && !destination.empty? && @params[:destination_msisdn] = destination
run_action :trans_list
end
|
ruby
|
def transaction_list(start = (Time.now - 24.hours), stop = Time.now, msisdn = nil, destination = nil, code = nil)
@params = {
stop_date: to_yyyymmdd(stop),
start_date: to_yyyymmdd(start)
}
code && !code.empty? && @params[:code] = code
msisdn && !msisdn.empty? && @params[:msisdn] = msisdn
destination && !destination.empty? && @params[:destination_msisdn] = destination
run_action :trans_list
end
|
[
"def",
"transaction_list",
"(",
"start",
"=",
"(",
"Time",
".",
"now",
"-",
"24",
".",
"hours",
")",
",",
"stop",
"=",
"Time",
".",
"now",
",",
"msisdn",
"=",
"nil",
",",
"destination",
"=",
"nil",
",",
"code",
"=",
"nil",
")",
"@params",
"=",
"{",
"stop_date",
":",
"to_yyyymmdd",
"(",
"stop",
")",
",",
"start_date",
":",
"to_yyyymmdd",
"(",
"start",
")",
"}",
"code",
"&&",
"!",
"code",
".",
"empty?",
"&&",
"@params",
"[",
":code",
"]",
"=",
"code",
"msisdn",
"&&",
"!",
"msisdn",
".",
"empty?",
"&&",
"@params",
"[",
":msisdn",
"]",
"=",
"msisdn",
"destination",
"&&",
"!",
"destination",
".",
"empty?",
"&&",
"@params",
"[",
":destination_msisdn",
"]",
"=",
"destination",
"run_action",
":trans_list",
"end"
] |
This method is used to retrieve the list of transactions performed within
the date range by the MSISDN if set. Note that both dates are included
during the search.
parameters
==========
msisdn
------
The format must be international with or without the ‘+’ or ‘00’:
“6012345678” or “+6012345678” or “006012345678” (Malaysia)
destination_msisdn
------------------
The format must be international with or without the ‘+’ or ‘00’:
“6012345678” or “+6012345678” or “006012345678” (Malaysia)
code
----
The error_code of the transactions to search for. E.g “0” to search for
only all successful transactions. If left empty, all transactions will be
returned(Failed and successful).
start_date
----------
Defines the start date of the search. Format must be YYYY-MM-DD.
stop_date
---------
Defines the end date of the search (included). Format must be YYYY-MM-DD.
|
[
"This",
"method",
"is",
"used",
"to",
"retrieve",
"the",
"list",
"of",
"transactions",
"performed",
"within",
"the",
"date",
"range",
"by",
"the",
"MSISDN",
"if",
"set",
".",
"Note",
"that",
"both",
"dates",
"are",
"included",
"during",
"the",
"search",
"."
] |
4aba93d9f92dfae280a59958cccdd04f3fa5e994
|
https://github.com/matteolc/t2_airtime/blob/4aba93d9f92dfae280a59958cccdd04f3fa5e994/lib/t2_airtime/api.rb#L178-L187
|
7,969 |
profitbricks/profitbricks-sdk-ruby
|
lib/profitbricks/server.rb
|
ProfitBricks.Server.detach_volume
|
def detach_volume(volume_id)
volume = ProfitBricks::Volume.get(datacenterId, nil, volume_id)
volume.detach(id)
end
|
ruby
|
def detach_volume(volume_id)
volume = ProfitBricks::Volume.get(datacenterId, nil, volume_id)
volume.detach(id)
end
|
[
"def",
"detach_volume",
"(",
"volume_id",
")",
"volume",
"=",
"ProfitBricks",
"::",
"Volume",
".",
"get",
"(",
"datacenterId",
",",
"nil",
",",
"volume_id",
")",
"volume",
".",
"detach",
"(",
"id",
")",
"end"
] |
Detach volume from server.
|
[
"Detach",
"volume",
"from",
"server",
"."
] |
03a379e412b0e6c0789ed14f2449f18bda622742
|
https://github.com/profitbricks/profitbricks-sdk-ruby/blob/03a379e412b0e6c0789ed14f2449f18bda622742/lib/profitbricks/server.rb#L62-L65
|
7,970 |
jduckett/duck_map
|
lib/duck_map/controller_helpers.rb
|
DuckMap.ControllerHelpers.sitemap_setup
|
def sitemap_setup(options = {})
rows = []
DuckMap.logger.debug "sitemap_setup: action_name => #{options[:action_name]} source => #{options[:source]} model => #{options[:model]}"
attributes = self.sitemap_attributes(options[:action_name])
DuckMap.logger.debug "sitemap_setup: attributes => #{attributes}"
if attributes.kind_of?(Hash) && attributes[:handler].kind_of?(Hash) && !attributes[:handler][:action_name].blank?
config = {handler: attributes[:handler]}.merge(options)
rows = self.send(attributes[:handler][:action_name], config)
end
return rows
end
|
ruby
|
def sitemap_setup(options = {})
rows = []
DuckMap.logger.debug "sitemap_setup: action_name => #{options[:action_name]} source => #{options[:source]} model => #{options[:model]}"
attributes = self.sitemap_attributes(options[:action_name])
DuckMap.logger.debug "sitemap_setup: attributes => #{attributes}"
if attributes.kind_of?(Hash) && attributes[:handler].kind_of?(Hash) && !attributes[:handler][:action_name].blank?
config = {handler: attributes[:handler]}.merge(options)
rows = self.send(attributes[:handler][:action_name], config)
end
return rows
end
|
[
"def",
"sitemap_setup",
"(",
"options",
"=",
"{",
"}",
")",
"rows",
"=",
"[",
"]",
"DuckMap",
".",
"logger",
".",
"debug",
"\"sitemap_setup: action_name => #{options[:action_name]} source => #{options[:source]} model => #{options[:model]}\"",
"attributes",
"=",
"self",
".",
"sitemap_attributes",
"(",
"options",
"[",
":action_name",
"]",
")",
"DuckMap",
".",
"logger",
".",
"debug",
"\"sitemap_setup: attributes => #{attributes}\"",
"if",
"attributes",
".",
"kind_of?",
"(",
"Hash",
")",
"&&",
"attributes",
"[",
":handler",
"]",
".",
"kind_of?",
"(",
"Hash",
")",
"&&",
"!",
"attributes",
"[",
":handler",
"]",
"[",
":action_name",
"]",
".",
"blank?",
"config",
"=",
"{",
"handler",
":",
"attributes",
"[",
":handler",
"]",
"}",
".",
"merge",
"(",
"options",
")",
"rows",
"=",
"self",
".",
"send",
"(",
"attributes",
"[",
":handler",
"]",
"[",
":action_name",
"]",
",",
"config",
")",
"end",
"return",
"rows",
"end"
] |
Determines all of the attributes defined for a controller, then, calls the handler method on the controller
to generate and return an Array of Hashes representing all of the url nodes to be included in the sitemap
for the current route being processed.
@return [Array] An Array of Hashes.
|
[
"Determines",
"all",
"of",
"the",
"attributes",
"defined",
"for",
"a",
"controller",
"then",
"calls",
"the",
"handler",
"method",
"on",
"the",
"controller",
"to",
"generate",
"and",
"return",
"an",
"Array",
"of",
"Hashes",
"representing",
"all",
"of",
"the",
"url",
"nodes",
"to",
"be",
"included",
"in",
"the",
"sitemap",
"for",
"the",
"current",
"route",
"being",
"processed",
"."
] |
c510acfa95e8ad4afb1501366058ae88a73704df
|
https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/controller_helpers.rb#L93-L108
|
7,971 |
jarhart/rattler
|
lib/rattler/util/parser_cli.rb
|
Rattler::Util.ParserCLI.run
|
def run
show_result @parser_class.parse!(ARGF.read)
rescue Rattler::Runtime::SyntaxError => e
puts e
end
|
ruby
|
def run
show_result @parser_class.parse!(ARGF.read)
rescue Rattler::Runtime::SyntaxError => e
puts e
end
|
[
"def",
"run",
"show_result",
"@parser_class",
".",
"parse!",
"(",
"ARGF",
".",
"read",
")",
"rescue",
"Rattler",
"::",
"Runtime",
"::",
"SyntaxError",
"=>",
"e",
"puts",
"e",
"end"
] |
Create a new command line interface for the given parser class
@param [Class] parser_class the parser class to run the command line
interface for
Run the command line interface
|
[
"Create",
"a",
"new",
"command",
"line",
"interface",
"for",
"the",
"given",
"parser",
"class"
] |
8b4efde2a05e9e790955bb635d4a1a9615893719
|
https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/util/parser_cli.rb#L65-L69
|
7,972 |
jdee/pattern_patch
|
lib/pattern_patch.rb
|
PatternPatch.Methods.patch
|
def patch(name)
raise ConfigurationError, "patch_dir has not been set" if patch_dir.nil?
raise ConfigurationError, "patch_dir is not a directory" unless Dir.exist?(patch_dir)
Patch.from_yaml File.join(patch_dir, "#{name}.yml")
end
|
ruby
|
def patch(name)
raise ConfigurationError, "patch_dir has not been set" if patch_dir.nil?
raise ConfigurationError, "patch_dir is not a directory" unless Dir.exist?(patch_dir)
Patch.from_yaml File.join(patch_dir, "#{name}.yml")
end
|
[
"def",
"patch",
"(",
"name",
")",
"raise",
"ConfigurationError",
",",
"\"patch_dir has not been set\"",
"if",
"patch_dir",
".",
"nil?",
"raise",
"ConfigurationError",
",",
"\"patch_dir is not a directory\"",
"unless",
"Dir",
".",
"exist?",
"(",
"patch_dir",
")",
"Patch",
".",
"from_yaml",
"File",
".",
"join",
"(",
"patch_dir",
",",
"\"#{name}.yml\"",
")",
"end"
] |
Loads a patch from the patch_dir
@param name [#to_s] Name of a patch to load from the patch_dir
@return [Patch] A patch loaded from the patch_dir
@raise [ConfigurationError] If patch_dir is nil or is not a valid directory path
|
[
"Loads",
"a",
"patch",
"from",
"the",
"patch_dir"
] |
0cd99d338fed2208f31239e511efa47d17099fc3
|
https://github.com/jdee/pattern_patch/blob/0cd99d338fed2208f31239e511efa47d17099fc3/lib/pattern_patch.rb#L47-L51
|
7,973 |
jarhart/rattler
|
lib/rattler/runner.rb
|
Rattler.Runner.run
|
def run
if result = analyze
synthesize(result)
else
puts parser.failure
exit ERRNO_PARSE_ERROR
end
end
|
ruby
|
def run
if result = analyze
synthesize(result)
else
puts parser.failure
exit ERRNO_PARSE_ERROR
end
end
|
[
"def",
"run",
"if",
"result",
"=",
"analyze",
"synthesize",
"(",
"result",
")",
"else",
"puts",
"parser",
".",
"failure",
"exit",
"ERRNO_PARSE_ERROR",
"end",
"end"
] |
Create a new command-line parser.
@param [Array<String>] args the command-line arguments
Run the command-line parser.
|
[
"Create",
"a",
"new",
"command",
"-",
"line",
"parser",
"."
] |
8b4efde2a05e9e790955bb635d4a1a9615893719
|
https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/runner.rb#L48-L55
|
7,974 |
elifoster/weatheruby
|
lib/weather/planner.rb
|
Weather.Planner.get_dewpoints
|
def get_dewpoints(start_date, end_date, location)
response = get_planner_response(start_date, end_date, location)
return response['response']['error'] unless response['response']['error'].nil?
highs = response['trip']['dewpoint_high']
lows = response['trip']['dewpoint_low']
{
high: {
imperial: {
minimum: highs['min']['F'].to_i,
maximum: highs['max']['F'].to_i,
average: highs['avg']['F'].to_i
},
metric: {
minimum: highs['min']['C'].to_i,
maximum: highs['max']['C'].to_i,
average: highs['avg']['C'].to_i
}
},
low: {
imperial: {
minimum: lows['min']['F'].to_i,
maximum: lows['max']['F'].to_i,
average: lows['avg']['F'].to_i
},
metric: {
minimum: lows['min']['C'].to_i,
maximum: lows['max']['C'].to_i,
average: lows['avg']['C'].to_i
}
}
}
end
|
ruby
|
def get_dewpoints(start_date, end_date, location)
response = get_planner_response(start_date, end_date, location)
return response['response']['error'] unless response['response']['error'].nil?
highs = response['trip']['dewpoint_high']
lows = response['trip']['dewpoint_low']
{
high: {
imperial: {
minimum: highs['min']['F'].to_i,
maximum: highs['max']['F'].to_i,
average: highs['avg']['F'].to_i
},
metric: {
minimum: highs['min']['C'].to_i,
maximum: highs['max']['C'].to_i,
average: highs['avg']['C'].to_i
}
},
low: {
imperial: {
minimum: lows['min']['F'].to_i,
maximum: lows['max']['F'].to_i,
average: lows['avg']['F'].to_i
},
metric: {
minimum: lows['min']['C'].to_i,
maximum: lows['max']['C'].to_i,
average: lows['avg']['C'].to_i
}
}
}
end
|
[
"def",
"get_dewpoints",
"(",
"start_date",
",",
"end_date",
",",
"location",
")",
"response",
"=",
"get_planner_response",
"(",
"start_date",
",",
"end_date",
",",
"location",
")",
"return",
"response",
"[",
"'response'",
"]",
"[",
"'error'",
"]",
"unless",
"response",
"[",
"'response'",
"]",
"[",
"'error'",
"]",
".",
"nil?",
"highs",
"=",
"response",
"[",
"'trip'",
"]",
"[",
"'dewpoint_high'",
"]",
"lows",
"=",
"response",
"[",
"'trip'",
"]",
"[",
"'dewpoint_low'",
"]",
"{",
"high",
":",
"{",
"imperial",
":",
"{",
"minimum",
":",
"highs",
"[",
"'min'",
"]",
"[",
"'F'",
"]",
".",
"to_i",
",",
"maximum",
":",
"highs",
"[",
"'max'",
"]",
"[",
"'F'",
"]",
".",
"to_i",
",",
"average",
":",
"highs",
"[",
"'avg'",
"]",
"[",
"'F'",
"]",
".",
"to_i",
"}",
",",
"metric",
":",
"{",
"minimum",
":",
"highs",
"[",
"'min'",
"]",
"[",
"'C'",
"]",
".",
"to_i",
",",
"maximum",
":",
"highs",
"[",
"'max'",
"]",
"[",
"'C'",
"]",
".",
"to_i",
",",
"average",
":",
"highs",
"[",
"'avg'",
"]",
"[",
"'C'",
"]",
".",
"to_i",
"}",
"}",
",",
"low",
":",
"{",
"imperial",
":",
"{",
"minimum",
":",
"lows",
"[",
"'min'",
"]",
"[",
"'F'",
"]",
".",
"to_i",
",",
"maximum",
":",
"lows",
"[",
"'max'",
"]",
"[",
"'F'",
"]",
".",
"to_i",
",",
"average",
":",
"lows",
"[",
"'avg'",
"]",
"[",
"'F'",
"]",
".",
"to_i",
"}",
",",
"metric",
":",
"{",
"minimum",
":",
"lows",
"[",
"'min'",
"]",
"[",
"'C'",
"]",
".",
"to_i",
",",
"maximum",
":",
"lows",
"[",
"'max'",
"]",
"[",
"'C'",
"]",
".",
"to_i",
",",
"average",
":",
"lows",
"[",
"'avg'",
"]",
"[",
"'C'",
"]",
".",
"to_i",
"}",
"}",
"}",
"end"
] |
Gets the dewpoint highs and lows for the date range.
@param (see #get_planner_response)
@return [Hash<Symbol, Hash<Symbol, Hash<Symbol, Integer>>>] Highs and lows minimum, average, and maximum for both
metric and imperial systems.
@return [String] The error if possible.
@todo Raise an error instead of returning a String.
|
[
"Gets",
"the",
"dewpoint",
"highs",
"and",
"lows",
"for",
"the",
"date",
"range",
"."
] |
4d97db082448765b67ef5112c89346e502a74858
|
https://github.com/elifoster/weatheruby/blob/4d97db082448765b67ef5112c89346e502a74858/lib/weather/planner.rb#L135-L167
|
7,975 |
elifoster/weatheruby
|
lib/weather/planner.rb
|
Weather.Planner.get_planner_response
|
def get_planner_response(start_date, end_date, location)
start = start_date.strftime('%m%d')
final = end_date.strftime('%m%d')
get("planner_#{start}#{final}", location)
end
|
ruby
|
def get_planner_response(start_date, end_date, location)
start = start_date.strftime('%m%d')
final = end_date.strftime('%m%d')
get("planner_#{start}#{final}", location)
end
|
[
"def",
"get_planner_response",
"(",
"start_date",
",",
"end_date",
",",
"location",
")",
"start",
"=",
"start_date",
".",
"strftime",
"(",
"'%m%d'",
")",
"final",
"=",
"end_date",
".",
"strftime",
"(",
"'%m%d'",
")",
"get",
"(",
"\"planner_#{start}#{final}\"",
",",
"location",
")",
"end"
] |
Gets the full planner API response.
@param start_date [DateTime] The date to start at. Only month and day actually matter.
@param end_date [DateTime] The date to end at. Only month and day actually matter.
@param location [String] The location to get the planner data for.
@since 0.5.0
@return (see Weatheruby#get)
|
[
"Gets",
"the",
"full",
"planner",
"API",
"response",
"."
] |
4d97db082448765b67ef5112c89346e502a74858
|
https://github.com/elifoster/weatheruby/blob/4d97db082448765b67ef5112c89346e502a74858/lib/weather/planner.rb#L244-L248
|
7,976 |
jrochkind/borrow_direct
|
lib/borrow_direct/util.rb
|
BorrowDirect.Util.hash_key_path
|
def hash_key_path(hash, *path)
result = nil
path.each do |key|
return nil unless hash.respond_to? :"[]"
result = hash = hash[key]
end
return result
end
|
ruby
|
def hash_key_path(hash, *path)
result = nil
path.each do |key|
return nil unless hash.respond_to? :"[]"
result = hash = hash[key]
end
return result
end
|
[
"def",
"hash_key_path",
"(",
"hash",
",",
"*",
"path",
")",
"result",
"=",
"nil",
"path",
".",
"each",
"do",
"|",
"key",
"|",
"return",
"nil",
"unless",
"hash",
".",
"respond_to?",
":\"",
"\"",
"result",
"=",
"hash",
"=",
"hash",
"[",
"key",
"]",
"end",
"return",
"result",
"end"
] |
A utility method that lets you access a nested hash,
returning nil if any intermediate hashes are unavailable.
|
[
"A",
"utility",
"method",
"that",
"lets",
"you",
"access",
"a",
"nested",
"hash",
"returning",
"nil",
"if",
"any",
"intermediate",
"hashes",
"are",
"unavailable",
"."
] |
f2f53760e15d742a5c5584dd641f20dea315f99f
|
https://github.com/jrochkind/borrow_direct/blob/f2f53760e15d742a5c5584dd641f20dea315f99f/lib/borrow_direct/util.rb#L5-L14
|
7,977 |
anthonator/dirigible
|
lib/dirigible/configuration.rb
|
Dirigible.Configuration.options
|
def options
VALID_OPTION_KEYS.inject({}) do |option, key|
option.merge!(key => send(key))
end
end
|
ruby
|
def options
VALID_OPTION_KEYS.inject({}) do |option, key|
option.merge!(key => send(key))
end
end
|
[
"def",
"options",
"VALID_OPTION_KEYS",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"option",
",",
"key",
"|",
"option",
".",
"merge!",
"(",
"key",
"=>",
"send",
"(",
"key",
")",
")",
"end",
"end"
] |
Create a hash of options and their values.
|
[
"Create",
"a",
"hash",
"of",
"options",
"and",
"their",
"values",
"."
] |
829b265ae4e54e3d4b284900b2a51a707afb6105
|
https://github.com/anthonator/dirigible/blob/829b265ae4e54e3d4b284900b2a51a707afb6105/lib/dirigible/configuration.rb#L46-L50
|
7,978 |
birarda/logan
|
lib/logan/project_template.rb
|
Logan.ProjectTemplate.create_project
|
def create_project( name, description = nil)
post_params = {
:body => {name: name, description: description}.to_json,
:headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'})
}
response = Logan::Client.post "/project_templates/#{@id}/projects.json", post_params
Logan::Project.new response
end
|
ruby
|
def create_project( name, description = nil)
post_params = {
:body => {name: name, description: description}.to_json,
:headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'})
}
response = Logan::Client.post "/project_templates/#{@id}/projects.json", post_params
Logan::Project.new response
end
|
[
"def",
"create_project",
"(",
"name",
",",
"description",
"=",
"nil",
")",
"post_params",
"=",
"{",
":body",
"=>",
"{",
"name",
":",
"name",
",",
"description",
":",
"description",
"}",
".",
"to_json",
",",
":headers",
"=>",
"Logan",
"::",
"Client",
".",
"headers",
".",
"merge",
"(",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"}",
"response",
"=",
"Logan",
"::",
"Client",
".",
"post",
"\"/project_templates/#{@id}/projects.json\"",
",",
"post_params",
"Logan",
"::",
"Project",
".",
"new",
"response",
"end"
] |
create a project based on this project template via Basecamp API
@param [String] name name for the new project
@param [String] description description for the new project
@return [Logan::Project] project instance from Basecamp API response
|
[
"create",
"a",
"project",
"based",
"on",
"this",
"project",
"template",
"via",
"Basecamp",
"API"
] |
c007081c7dbb5b98ef5312db78f84867c6075ab0
|
https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/project_template.rb#L16-L24
|
7,979 |
jduckett/duck_map
|
lib/duck_map/config.rb
|
DuckMap.ConfigHelpers.log_level
|
def log_level(value, options = {})
DuckMap::Logger.log_level = value
if options.has_key?(:full)
DuckMap.logger.full_exception = options[:full]
end
end
|
ruby
|
def log_level(value, options = {})
DuckMap::Logger.log_level = value
if options.has_key?(:full)
DuckMap.logger.full_exception = options[:full]
end
end
|
[
"def",
"log_level",
"(",
"value",
",",
"options",
"=",
"{",
"}",
")",
"DuckMap",
"::",
"Logger",
".",
"log_level",
"=",
"value",
"if",
"options",
".",
"has_key?",
"(",
":full",
")",
"DuckMap",
".",
"logger",
".",
"full_exception",
"=",
"options",
"[",
":full",
"]",
"end",
"end"
] |
Sets the logging level.
# sets the logging level to :debug and full stack traces for exceptions.
MyApp::Application.routes.draw do
log_level :debug, full: true
end
@param [Symbol] value The logger level to use. Valid values are:
- :debug
- :info
- :warn
- :error
- :fatal
- :unknown
@param [Hash] options Options Hash.
@option options [Symbol] :full Including full: true will include full stack traces for exceptions.
Otherwise, stack traces are stripped and attempt to only include application traces.
|
[
"Sets",
"the",
"logging",
"level",
"."
] |
c510acfa95e8ad4afb1501366058ae88a73704df
|
https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/config.rb#L242-L247
|
7,980 |
postmodern/rprogram
|
lib/rprogram/task.rb
|
RProgram.Task.leading_non_options
|
def leading_non_options
args = []
# add the task leading non-options
@options.each do |name,value|
non_opt = get_non_option(name)
if (non_opt && non_opt.leading?)
args += non_opt.arguments(value)
end
end
# add all leading subtask non-options
@subtasks.each_value do |task|
args += task.leading_non_options
end
return args
end
|
ruby
|
def leading_non_options
args = []
# add the task leading non-options
@options.each do |name,value|
non_opt = get_non_option(name)
if (non_opt && non_opt.leading?)
args += non_opt.arguments(value)
end
end
# add all leading subtask non-options
@subtasks.each_value do |task|
args += task.leading_non_options
end
return args
end
|
[
"def",
"leading_non_options",
"args",
"=",
"[",
"]",
"# add the task leading non-options",
"@options",
".",
"each",
"do",
"|",
"name",
",",
"value",
"|",
"non_opt",
"=",
"get_non_option",
"(",
"name",
")",
"if",
"(",
"non_opt",
"&&",
"non_opt",
".",
"leading?",
")",
"args",
"+=",
"non_opt",
".",
"arguments",
"(",
"value",
")",
"end",
"end",
"# add all leading subtask non-options",
"@subtasks",
".",
"each_value",
"do",
"|",
"task",
"|",
"args",
"+=",
"task",
".",
"leading_non_options",
"end",
"return",
"args",
"end"
] |
Generates the command-line arguments for all leading non-options.
@return [Array]
The command-line arguments generated from all the leading
non-options of the task and it's sub-tasks.
|
[
"Generates",
"the",
"command",
"-",
"line",
"arguments",
"for",
"all",
"leading",
"non",
"-",
"options",
"."
] |
94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be
|
https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/task.rb#L208-L226
|
7,981 |
postmodern/rprogram
|
lib/rprogram/task.rb
|
RProgram.Task.options
|
def options
args = []
# add all subtask options
@subtasks.each_value do |task|
args += task.arguments
end
# add the task options
@options.each do |name,value|
opt = get_option(name)
args += opt.arguments(value) if opt
end
return args
end
|
ruby
|
def options
args = []
# add all subtask options
@subtasks.each_value do |task|
args += task.arguments
end
# add the task options
@options.each do |name,value|
opt = get_option(name)
args += opt.arguments(value) if opt
end
return args
end
|
[
"def",
"options",
"args",
"=",
"[",
"]",
"# add all subtask options",
"@subtasks",
".",
"each_value",
"do",
"|",
"task",
"|",
"args",
"+=",
"task",
".",
"arguments",
"end",
"# add the task options",
"@options",
".",
"each",
"do",
"|",
"name",
",",
"value",
"|",
"opt",
"=",
"get_option",
"(",
"name",
")",
"args",
"+=",
"opt",
".",
"arguments",
"(",
"value",
")",
"if",
"opt",
"end",
"return",
"args",
"end"
] |
Generates the command-line arguments from all options.
@return [Array]
The command-line arguments generated from all the options of the
task and it's sub-tasks.
|
[
"Generates",
"the",
"command",
"-",
"line",
"arguments",
"from",
"all",
"options",
"."
] |
94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be
|
https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/task.rb#L235-L250
|
7,982 |
postmodern/rprogram
|
lib/rprogram/task.rb
|
RProgram.Task.tailing_non_options
|
def tailing_non_options
args = []
# add all tailing subtask non-options
@subtasks.each_value do |task|
args += task.tailing_non_options
end
# add the task tailing non-options
@options.each do |name,value|
non_opt = get_non_option(name)
if (non_opt && non_opt.tailing?)
args += non_opt.arguments(value)
end
end
return args
end
|
ruby
|
def tailing_non_options
args = []
# add all tailing subtask non-options
@subtasks.each_value do |task|
args += task.tailing_non_options
end
# add the task tailing non-options
@options.each do |name,value|
non_opt = get_non_option(name)
if (non_opt && non_opt.tailing?)
args += non_opt.arguments(value)
end
end
return args
end
|
[
"def",
"tailing_non_options",
"args",
"=",
"[",
"]",
"# add all tailing subtask non-options",
"@subtasks",
".",
"each_value",
"do",
"|",
"task",
"|",
"args",
"+=",
"task",
".",
"tailing_non_options",
"end",
"# add the task tailing non-options",
"@options",
".",
"each",
"do",
"|",
"name",
",",
"value",
"|",
"non_opt",
"=",
"get_non_option",
"(",
"name",
")",
"if",
"(",
"non_opt",
"&&",
"non_opt",
".",
"tailing?",
")",
"args",
"+=",
"non_opt",
".",
"arguments",
"(",
"value",
")",
"end",
"end",
"return",
"args",
"end"
] |
Generates the command-line arguments from all tailing non-options.
@return [Array]
The command-line arguments generated from all the tailing
non-options of the task and it's sub-tasks.
|
[
"Generates",
"the",
"command",
"-",
"line",
"arguments",
"from",
"all",
"tailing",
"non",
"-",
"options",
"."
] |
94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be
|
https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/task.rb#L259-L277
|
7,983 |
postmodern/rprogram
|
lib/rprogram/task.rb
|
RProgram.Task.arguments
|
def arguments
tailing_args = tailing_non_options
if tailing_args.any? { |arg| arg[0,1] == '-' }
tailing_args.unshift('--')
end
return leading_non_options + options + tailing_args
end
|
ruby
|
def arguments
tailing_args = tailing_non_options
if tailing_args.any? { |arg| arg[0,1] == '-' }
tailing_args.unshift('--')
end
return leading_non_options + options + tailing_args
end
|
[
"def",
"arguments",
"tailing_args",
"=",
"tailing_non_options",
"if",
"tailing_args",
".",
"any?",
"{",
"|",
"arg",
"|",
"arg",
"[",
"0",
",",
"1",
"]",
"==",
"'-'",
"}",
"tailing_args",
".",
"unshift",
"(",
"'--'",
")",
"end",
"return",
"leading_non_options",
"+",
"options",
"+",
"tailing_args",
"end"
] |
Generates the command-line arguments from the task.
@return [Array]
The command-line arguments compiled from the leading non-options,
options and tailing non-options of the task and it's sub-tasks.
|
[
"Generates",
"the",
"command",
"-",
"line",
"arguments",
"from",
"the",
"task",
"."
] |
94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be
|
https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/task.rb#L286-L294
|
7,984 |
jarhart/rattler
|
lib/rattler/compiler/optimizer/optimization_sequence.rb
|
Rattler::Compiler::Optimizer.OptimizationSequence.deep_apply
|
def deep_apply(parser, context)
parser = apply(parser, context)
apply(parser.map_children { |child|
deep_apply(child, child_context(parser, context))
}, context)
end
|
ruby
|
def deep_apply(parser, context)
parser = apply(parser, context)
apply(parser.map_children { |child|
deep_apply(child, child_context(parser, context))
}, context)
end
|
[
"def",
"deep_apply",
"(",
"parser",
",",
"context",
")",
"parser",
"=",
"apply",
"(",
"parser",
",",
"context",
")",
"apply",
"(",
"parser",
".",
"map_children",
"{",
"|",
"child",
"|",
"deep_apply",
"(",
"child",
",",
"child_context",
"(",
"parser",
",",
"context",
")",
")",
"}",
",",
"context",
")",
"end"
] |
Apply the optimzations to +parser+'s children, then to +parser+, in
+context+.
@param [Rattler::Parsers::Parser] parser the parser to be optimized
@param [Rattler::Compiler::Optimizer::OptimizationContext] context
@return [Rattler::Parsers::Parser] the optimized parser
|
[
"Apply",
"the",
"optimzations",
"to",
"+",
"parser",
"+",
"s",
"children",
"then",
"to",
"+",
"parser",
"+",
"in",
"+",
"context",
"+",
"."
] |
8b4efde2a05e9e790955bb635d4a1a9615893719
|
https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/compiler/optimizer/optimization_sequence.rb#L25-L30
|
7,985 |
jarhart/rattler
|
lib/rattler/parsers/choice.rb
|
Rattler::Parsers.Choice.parse
|
def parse(scanner, rules, scope = ParserScope.empty)
for child in children
if r = child.parse(scanner, rules, scope)
return r
end
end
false
end
|
ruby
|
def parse(scanner, rules, scope = ParserScope.empty)
for child in children
if r = child.parse(scanner, rules, scope)
return r
end
end
false
end
|
[
"def",
"parse",
"(",
"scanner",
",",
"rules",
",",
"scope",
"=",
"ParserScope",
".",
"empty",
")",
"for",
"child",
"in",
"children",
"if",
"r",
"=",
"child",
".",
"parse",
"(",
"scanner",
",",
"rules",
",",
"scope",
")",
"return",
"r",
"end",
"end",
"false",
"end"
] |
Try each parser in order until one succeeds and return that result.
@param (see Match#parse)
@return the result of the first parser that matches, or +false+
|
[
"Try",
"each",
"parser",
"in",
"order",
"until",
"one",
"succeeds",
"and",
"return",
"that",
"result",
"."
] |
8b4efde2a05e9e790955bb635d4a1a9615893719
|
https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/parsers/choice.rb#L21-L28
|
7,986 |
erikh/archive
|
lib/archive/compress.rb
|
Archive.Compress.compress
|
def compress(files, verbose=false)
if files.any? { |f| !File.file?(f) }
raise ArgumentError, "Files supplied must all be real, actual files -- not directories or symlinks."
end
configure_archive
compress_files(files, verbose)
free_archive
end
|
ruby
|
def compress(files, verbose=false)
if files.any? { |f| !File.file?(f) }
raise ArgumentError, "Files supplied must all be real, actual files -- not directories or symlinks."
end
configure_archive
compress_files(files, verbose)
free_archive
end
|
[
"def",
"compress",
"(",
"files",
",",
"verbose",
"=",
"false",
")",
"if",
"files",
".",
"any?",
"{",
"|",
"f",
"|",
"!",
"File",
".",
"file?",
"(",
"f",
")",
"}",
"raise",
"ArgumentError",
",",
"\"Files supplied must all be real, actual files -- not directories or symlinks.\"",
"end",
"configure_archive",
"compress_files",
"(",
"files",
",",
"verbose",
")",
"free_archive",
"end"
] |
Create a new Compress object. Takes a filename as string, and args as
hash.
args is a hash that contains two values, :type and :compression.
* :type may be :tar or :zip
* :compression may be :gzip, :bzip2, or nil (no compression)
If the type :zip is selected, no compression will be used. Additionally,
files in the .zip will all be stored as binary files.
The default set of arguments is
{ :type => :tar, :compression => :gzip }
Run the compression. Files are an array of filenames. Optional flag for
verbosity; if true, will print each file it adds to the archive to
stdout.
Files must be real files. No symlinks, directories, unix sockets,
character devices, etc. This method will raise ArgumentError if you
provide any.
|
[
"Create",
"a",
"new",
"Compress",
"object",
".",
"Takes",
"a",
"filename",
"as",
"string",
"and",
"args",
"as",
"hash",
"."
] |
b120f120ce881d194b5418ec0e5c08fd1dd6d144
|
https://github.com/erikh/archive/blob/b120f120ce881d194b5418ec0e5c08fd1dd6d144/lib/archive/compress.rb#L53-L61
|
7,987 |
nyk/catflap
|
lib/catflap/http.rb
|
CfWebserver.CfApiServlet.do_POST
|
def do_POST(req, resp)
# Split the path into piece
path = req.path[1..-1].split('/')
# We don't want to cache catflap login page so set response headers.
# Chrome and FF respect the no-store, while IE respects no-cache.
resp['Cache-Control'] = 'no-cache, no-store'
resp['Pragma'] = 'no-cache' # Legacy
resp['Expires'] = '-1' # Microsoft advises this for older IE browsers.
response_class = CfRestService.const_get 'CfRestService'
raise "#{response_class} not a Class" unless response_class.is_a?(Class)
raise HTTPStatus::NotFound unless path[1]
response_method = path[1].to_sym
# Make sure the method exists in the class
raise HTTPStatus::NotFound unless response_class
.respond_to? response_method
if :sync == response_method
resp.body = response_class.send response_method, req, resp, @cf
end
if :knock == response_method
resp.body = response_class.send response_method, req, resp, @cf
end
# Remaining path segments get passed in as arguments to the method
if path.length > 2
resp.body = response_class.send response_method, req, resp,
@cf, path[1..-1]
else
resp.body = response_class.send response_method, req, resp, @cf
end
raise HTTPStatus::OK
end
|
ruby
|
def do_POST(req, resp)
# Split the path into piece
path = req.path[1..-1].split('/')
# We don't want to cache catflap login page so set response headers.
# Chrome and FF respect the no-store, while IE respects no-cache.
resp['Cache-Control'] = 'no-cache, no-store'
resp['Pragma'] = 'no-cache' # Legacy
resp['Expires'] = '-1' # Microsoft advises this for older IE browsers.
response_class = CfRestService.const_get 'CfRestService'
raise "#{response_class} not a Class" unless response_class.is_a?(Class)
raise HTTPStatus::NotFound unless path[1]
response_method = path[1].to_sym
# Make sure the method exists in the class
raise HTTPStatus::NotFound unless response_class
.respond_to? response_method
if :sync == response_method
resp.body = response_class.send response_method, req, resp, @cf
end
if :knock == response_method
resp.body = response_class.send response_method, req, resp, @cf
end
# Remaining path segments get passed in as arguments to the method
if path.length > 2
resp.body = response_class.send response_method, req, resp,
@cf, path[1..-1]
else
resp.body = response_class.send response_method, req, resp, @cf
end
raise HTTPStatus::OK
end
|
[
"def",
"do_POST",
"(",
"req",
",",
"resp",
")",
"# Split the path into piece",
"path",
"=",
"req",
".",
"path",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"split",
"(",
"'/'",
")",
"# We don't want to cache catflap login page so set response headers.",
"# Chrome and FF respect the no-store, while IE respects no-cache.",
"resp",
"[",
"'Cache-Control'",
"]",
"=",
"'no-cache, no-store'",
"resp",
"[",
"'Pragma'",
"]",
"=",
"'no-cache'",
"# Legacy",
"resp",
"[",
"'Expires'",
"]",
"=",
"'-1'",
"# Microsoft advises this for older IE browsers.",
"response_class",
"=",
"CfRestService",
".",
"const_get",
"'CfRestService'",
"raise",
"\"#{response_class} not a Class\"",
"unless",
"response_class",
".",
"is_a?",
"(",
"Class",
")",
"raise",
"HTTPStatus",
"::",
"NotFound",
"unless",
"path",
"[",
"1",
"]",
"response_method",
"=",
"path",
"[",
"1",
"]",
".",
"to_sym",
"# Make sure the method exists in the class",
"raise",
"HTTPStatus",
"::",
"NotFound",
"unless",
"response_class",
".",
"respond_to?",
"response_method",
"if",
":sync",
"==",
"response_method",
"resp",
".",
"body",
"=",
"response_class",
".",
"send",
"response_method",
",",
"req",
",",
"resp",
",",
"@cf",
"end",
"if",
":knock",
"==",
"response_method",
"resp",
".",
"body",
"=",
"response_class",
".",
"send",
"response_method",
",",
"req",
",",
"resp",
",",
"@cf",
"end",
"# Remaining path segments get passed in as arguments to the method",
"if",
"path",
".",
"length",
">",
"2",
"resp",
".",
"body",
"=",
"response_class",
".",
"send",
"response_method",
",",
"req",
",",
"resp",
",",
"@cf",
",",
"path",
"[",
"1",
"..",
"-",
"1",
"]",
"else",
"resp",
".",
"body",
"=",
"response_class",
".",
"send",
"response_method",
",",
"req",
",",
"resp",
",",
"@cf",
"end",
"raise",
"HTTPStatus",
"::",
"OK",
"end"
] |
Initializer to construct a new CfApiServlet object.
@param [HTTPServer] server a WEBrick HTTP server object.
@param [Catflap] cf a fully instantiated Catflap object.
@return void
Implementation of HTTPServlet::AbstractServlet method to handle GET
method requests.
@param [HTTPRequest] req a WEBrick::HTTPRequest object.
@param [HTTPResponse] resp a WEBrick::HTTPResponse object.
@return void
rubocop:disable Style/MethodName
|
[
"Initializer",
"to",
"construct",
"a",
"new",
"CfApiServlet",
"object",
"."
] |
e146e5df6d8d0085c127bf3ab77bfecfa9af78d9
|
https://github.com/nyk/catflap/blob/e146e5df6d8d0085c127bf3ab77bfecfa9af78d9/lib/catflap/http.rb#L161-L198
|
7,988 |
KDEJewellers/aptly-api
|
lib/aptly/snapshot.rb
|
Aptly.Snapshot.update!
|
def update!(**kwords)
kwords = kwords.map { |k, v| [k.to_s.capitalize, v] }.to_h
response = @connection.send(:put,
"/snapshots/#{self.Name}",
body: JSON.generate(kwords))
hash = JSON.parse(response.body, symbolize_names: true)
return nil if hash == marshal_dump
marshal_load(hash)
self
end
|
ruby
|
def update!(**kwords)
kwords = kwords.map { |k, v| [k.to_s.capitalize, v] }.to_h
response = @connection.send(:put,
"/snapshots/#{self.Name}",
body: JSON.generate(kwords))
hash = JSON.parse(response.body, symbolize_names: true)
return nil if hash == marshal_dump
marshal_load(hash)
self
end
|
[
"def",
"update!",
"(",
"**",
"kwords",
")",
"kwords",
"=",
"kwords",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"k",
".",
"to_s",
".",
"capitalize",
",",
"v",
"]",
"}",
".",
"to_h",
"response",
"=",
"@connection",
".",
"send",
"(",
":put",
",",
"\"/snapshots/#{self.Name}\"",
",",
"body",
":",
"JSON",
".",
"generate",
"(",
"kwords",
")",
")",
"hash",
"=",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
",",
"symbolize_names",
":",
"true",
")",
"return",
"nil",
"if",
"hash",
"==",
"marshal_dump",
"marshal_load",
"(",
"hash",
")",
"self",
"end"
] |
Updates this snapshot
@return [self] if the instance data was mutated
@return [nil] if the instance data was not mutated
|
[
"Updates",
"this",
"snapshot"
] |
71a13417618d81ca0dcb7834559de1f31ec46e29
|
https://github.com/KDEJewellers/aptly-api/blob/71a13417618d81ca0dcb7834559de1f31ec46e29/lib/aptly/snapshot.rb#L13-L22
|
7,989 |
KDEJewellers/aptly-api
|
lib/aptly/snapshot.rb
|
Aptly.Snapshot.diff
|
def diff(other_snapshot)
endpoint = "/snapshots/#{self.Name}/diff/#{other_snapshot.Name}"
response = @connection.send(:get, endpoint)
JSON.parse(response.body)
end
|
ruby
|
def diff(other_snapshot)
endpoint = "/snapshots/#{self.Name}/diff/#{other_snapshot.Name}"
response = @connection.send(:get, endpoint)
JSON.parse(response.body)
end
|
[
"def",
"diff",
"(",
"other_snapshot",
")",
"endpoint",
"=",
"\"/snapshots/#{self.Name}/diff/#{other_snapshot.Name}\"",
"response",
"=",
"@connection",
".",
"send",
"(",
":get",
",",
"endpoint",
")",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"end"
] |
Find differences between this and another snapshot
@param other_snapshot [Snapshot] to diff against
@return [Array<Hash>] diff between the two snashots
|
[
"Find",
"differences",
"between",
"this",
"and",
"another",
"snapshot"
] |
71a13417618d81ca0dcb7834559de1f31ec46e29
|
https://github.com/KDEJewellers/aptly-api/blob/71a13417618d81ca0dcb7834559de1f31ec46e29/lib/aptly/snapshot.rb#L33-L37
|
7,990 |
experteer/codeqa
|
lib/codeqa/configuration.rb
|
Codeqa.Configuration.git_root_till_home
|
def git_root_till_home
Pathname.new(Dir.pwd).ascend do |dir_pathname|
return dir_pathname if File.directory?("#{dir_pathname}/.git")
return nil if dir_pathname.to_s == home_dir
end
end
|
ruby
|
def git_root_till_home
Pathname.new(Dir.pwd).ascend do |dir_pathname|
return dir_pathname if File.directory?("#{dir_pathname}/.git")
return nil if dir_pathname.to_s == home_dir
end
end
|
[
"def",
"git_root_till_home",
"Pathname",
".",
"new",
"(",
"Dir",
".",
"pwd",
")",
".",
"ascend",
"do",
"|",
"dir_pathname",
"|",
"return",
"dir_pathname",
"if",
"File",
".",
"directory?",
"(",
"\"#{dir_pathname}/.git\"",
")",
"return",
"nil",
"if",
"dir_pathname",
".",
"to_s",
"==",
"home_dir",
"end",
"end"
] |
ascend from the current dir till I find a .git folder or reach home_dir
|
[
"ascend",
"from",
"the",
"current",
"dir",
"till",
"I",
"find",
"a",
".",
"git",
"folder",
"or",
"reach",
"home_dir"
] |
199fa9b686737293a3c20148ad708a60e6fef667
|
https://github.com/experteer/codeqa/blob/199fa9b686737293a3c20148ad708a60e6fef667/lib/codeqa/configuration.rb#L61-L66
|
7,991 |
m-31/puppetdb_query
|
lib/puppetdb_query/mongodb.rb
|
PuppetDBQuery.MongoDB.node_properties
|
def node_properties
collection = connection[node_properties_collection]
result = {}
collection.find.batch_size(999).each do |values|
id = values.delete('_id')
result[id] = values
end
result
end
|
ruby
|
def node_properties
collection = connection[node_properties_collection]
result = {}
collection.find.batch_size(999).each do |values|
id = values.delete('_id')
result[id] = values
end
result
end
|
[
"def",
"node_properties",
"collection",
"=",
"connection",
"[",
"node_properties_collection",
"]",
"result",
"=",
"{",
"}",
"collection",
".",
"find",
".",
"batch_size",
"(",
"999",
")",
".",
"each",
"do",
"|",
"values",
"|",
"id",
"=",
"values",
".",
"delete",
"(",
"'_id'",
")",
"result",
"[",
"id",
"]",
"=",
"values",
"end",
"result",
"end"
] |
initialize access to mongodb
You might want to adjust the logging level, for example:
::Mongo::Logger.logger.level = logger.level
@param connection mongodb connection, should already be switched to correct database
@param nodes symbol for collection that contains nodes with their facts
@param node_properties symbol for collection for nodes with their update timestamps
@param meta symbol for collection with update metadata
get all nodes and their update dates
|
[
"initialize",
"access",
"to",
"mongodb"
] |
58103c91f291de8ce28d679256e50ae391b93ecb
|
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L47-L55
|
7,992 |
m-31/puppetdb_query
|
lib/puppetdb_query/mongodb.rb
|
PuppetDBQuery.MongoDB.all_nodes
|
def all_nodes
collection = connection[nodes_collection]
collection.find.batch_size(999).projection(_id: 1).map { |k| k[:_id] }
end
|
ruby
|
def all_nodes
collection = connection[nodes_collection]
collection.find.batch_size(999).projection(_id: 1).map { |k| k[:_id] }
end
|
[
"def",
"all_nodes",
"collection",
"=",
"connection",
"[",
"nodes_collection",
"]",
"collection",
".",
"find",
".",
"batch_size",
"(",
"999",
")",
".",
"projection",
"(",
"_id",
":",
"1",
")",
".",
"map",
"{",
"|",
"k",
"|",
"k",
"[",
":_id",
"]",
"}",
"end"
] |
get all node names
|
[
"get",
"all",
"node",
"names"
] |
58103c91f291de8ce28d679256e50ae391b93ecb
|
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L58-L61
|
7,993 |
m-31/puppetdb_query
|
lib/puppetdb_query/mongodb.rb
|
PuppetDBQuery.MongoDB.query_nodes
|
def query_nodes(query)
collection = connection[nodes_collection]
collection.find(query).batch_size(999).projection(_id: 1).map { |k| k[:_id] }
end
|
ruby
|
def query_nodes(query)
collection = connection[nodes_collection]
collection.find(query).batch_size(999).projection(_id: 1).map { |k| k[:_id] }
end
|
[
"def",
"query_nodes",
"(",
"query",
")",
"collection",
"=",
"connection",
"[",
"nodes_collection",
"]",
"collection",
".",
"find",
"(",
"query",
")",
".",
"batch_size",
"(",
"999",
")",
".",
"projection",
"(",
"_id",
":",
"1",
")",
".",
"map",
"{",
"|",
"k",
"|",
"k",
"[",
":_id",
"]",
"}",
"end"
] |
get node names that fulfill given mongodb query
@param query mongodb query
|
[
"get",
"node",
"names",
"that",
"fulfill",
"given",
"mongodb",
"query"
] |
58103c91f291de8ce28d679256e50ae391b93ecb
|
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L66-L69
|
7,994 |
m-31/puppetdb_query
|
lib/puppetdb_query/mongodb.rb
|
PuppetDBQuery.MongoDB.query_facts
|
def query_facts(query, facts = [])
fields = Hash[facts.collect { |fact| [fact.to_sym, 1] }]
collection = connection[nodes_collection]
result = {}
collection.find(query).batch_size(999).projection(fields).each do |values|
id = values.delete('_id')
result[id] = values
end
result
end
|
ruby
|
def query_facts(query, facts = [])
fields = Hash[facts.collect { |fact| [fact.to_sym, 1] }]
collection = connection[nodes_collection]
result = {}
collection.find(query).batch_size(999).projection(fields).each do |values|
id = values.delete('_id')
result[id] = values
end
result
end
|
[
"def",
"query_facts",
"(",
"query",
",",
"facts",
"=",
"[",
"]",
")",
"fields",
"=",
"Hash",
"[",
"facts",
".",
"collect",
"{",
"|",
"fact",
"|",
"[",
"fact",
".",
"to_sym",
",",
"1",
"]",
"}",
"]",
"collection",
"=",
"connection",
"[",
"nodes_collection",
"]",
"result",
"=",
"{",
"}",
"collection",
".",
"find",
"(",
"query",
")",
".",
"batch_size",
"(",
"999",
")",
".",
"projection",
"(",
"fields",
")",
".",
"each",
"do",
"|",
"values",
"|",
"id",
"=",
"values",
".",
"delete",
"(",
"'_id'",
")",
"result",
"[",
"id",
"]",
"=",
"values",
"end",
"result",
"end"
] |
get nodes and their facts that fulfill given mongodb query
@param query mongodb query
@param facts [Array<String>] get these facts in the result, eg ['fqdn'], empty for all
|
[
"get",
"nodes",
"and",
"their",
"facts",
"that",
"fulfill",
"given",
"mongodb",
"query"
] |
58103c91f291de8ce28d679256e50ae391b93ecb
|
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L75-L84
|
7,995 |
m-31/puppetdb_query
|
lib/puppetdb_query/mongodb.rb
|
PuppetDBQuery.MongoDB.query_facts_exist
|
def query_facts_exist(query, facts = [])
result = query_facts(query, facts)
unless facts.empty?
result.keep_if do |_k, v|
facts.any? { |f| !v[f].nil? }
end
end
result
end
|
ruby
|
def query_facts_exist(query, facts = [])
result = query_facts(query, facts)
unless facts.empty?
result.keep_if do |_k, v|
facts.any? { |f| !v[f].nil? }
end
end
result
end
|
[
"def",
"query_facts_exist",
"(",
"query",
",",
"facts",
"=",
"[",
"]",
")",
"result",
"=",
"query_facts",
"(",
"query",
",",
"facts",
")",
"unless",
"facts",
".",
"empty?",
"result",
".",
"keep_if",
"do",
"|",
"_k",
",",
"v",
"|",
"facts",
".",
"any?",
"{",
"|",
"f",
"|",
"!",
"v",
"[",
"f",
"]",
".",
"nil?",
"}",
"end",
"end",
"result",
"end"
] |
get nodes and their facts that fulfill given mongodb query and have at least one
value for one the given fact names
@param query mongodb query
@param facts [Array<String>] get these facts in the result, eg ['fqdn'], empty for all
|
[
"get",
"nodes",
"and",
"their",
"facts",
"that",
"fulfill",
"given",
"mongodb",
"query",
"and",
"have",
"at",
"least",
"one",
"value",
"for",
"one",
"the",
"given",
"fact",
"names"
] |
58103c91f291de8ce28d679256e50ae391b93ecb
|
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L91-L99
|
7,996 |
m-31/puppetdb_query
|
lib/puppetdb_query/mongodb.rb
|
PuppetDBQuery.MongoDB.search_facts
|
def search_facts(query, pattern, facts = [], facts_found = [], check_names = false)
collection = connection[nodes_collection]
result = {}
collection.find(query).batch_size(999).each do |values|
id = values.delete('_id')
found = {}
values.each do |k, v|
if v =~ pattern
found[k] = v
elsif check_names && k =~ pattern
found[k] = v
end
end
next if found.empty?
facts_found.concat(found.keys).uniq!
facts.each do |f|
found[f] = values[f]
end
result[id] = found
end
result
end
|
ruby
|
def search_facts(query, pattern, facts = [], facts_found = [], check_names = false)
collection = connection[nodes_collection]
result = {}
collection.find(query).batch_size(999).each do |values|
id = values.delete('_id')
found = {}
values.each do |k, v|
if v =~ pattern
found[k] = v
elsif check_names && k =~ pattern
found[k] = v
end
end
next if found.empty?
facts_found.concat(found.keys).uniq!
facts.each do |f|
found[f] = values[f]
end
result[id] = found
end
result
end
|
[
"def",
"search_facts",
"(",
"query",
",",
"pattern",
",",
"facts",
"=",
"[",
"]",
",",
"facts_found",
"=",
"[",
"]",
",",
"check_names",
"=",
"false",
")",
"collection",
"=",
"connection",
"[",
"nodes_collection",
"]",
"result",
"=",
"{",
"}",
"collection",
".",
"find",
"(",
"query",
")",
".",
"batch_size",
"(",
"999",
")",
".",
"each",
"do",
"|",
"values",
"|",
"id",
"=",
"values",
".",
"delete",
"(",
"'_id'",
")",
"found",
"=",
"{",
"}",
"values",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"if",
"v",
"=~",
"pattern",
"found",
"[",
"k",
"]",
"=",
"v",
"elsif",
"check_names",
"&&",
"k",
"=~",
"pattern",
"found",
"[",
"k",
"]",
"=",
"v",
"end",
"end",
"next",
"if",
"found",
".",
"empty?",
"facts_found",
".",
"concat",
"(",
"found",
".",
"keys",
")",
".",
"uniq!",
"facts",
".",
"each",
"do",
"|",
"f",
"|",
"found",
"[",
"f",
"]",
"=",
"values",
"[",
"f",
"]",
"end",
"result",
"[",
"id",
"]",
"=",
"found",
"end",
"result",
"end"
] |
get nodes and their facts for a pattern
@param query mongodb query
@param pattern [RegExp] search for
@param facts [Array<String>] get these facts in the result, eg ['fqdn'], empty for all
@param facts_found [Array<String>] fact names are added to this array
@param check_names [Boolean] also search fact names
|
[
"get",
"nodes",
"and",
"their",
"facts",
"for",
"a",
"pattern"
] |
58103c91f291de8ce28d679256e50ae391b93ecb
|
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L108-L129
|
7,997 |
m-31/puppetdb_query
|
lib/puppetdb_query/mongodb.rb
|
PuppetDBQuery.MongoDB.single_node_facts
|
def single_node_facts(node, facts)
fields = Hash[facts.collect { |fact| [fact.to_sym, 1] }]
collection = connection[nodes_collection]
result = collection.find(_id: node).limit(1).batch_size(1).projection(fields).to_a.first
result.delete("_id") if result
result
end
|
ruby
|
def single_node_facts(node, facts)
fields = Hash[facts.collect { |fact| [fact.to_sym, 1] }]
collection = connection[nodes_collection]
result = collection.find(_id: node).limit(1).batch_size(1).projection(fields).to_a.first
result.delete("_id") if result
result
end
|
[
"def",
"single_node_facts",
"(",
"node",
",",
"facts",
")",
"fields",
"=",
"Hash",
"[",
"facts",
".",
"collect",
"{",
"|",
"fact",
"|",
"[",
"fact",
".",
"to_sym",
",",
"1",
"]",
"}",
"]",
"collection",
"=",
"connection",
"[",
"nodes_collection",
"]",
"result",
"=",
"collection",
".",
"find",
"(",
"_id",
":",
"node",
")",
".",
"limit",
"(",
"1",
")",
".",
"batch_size",
"(",
"1",
")",
".",
"projection",
"(",
"fields",
")",
".",
"to_a",
".",
"first",
"result",
".",
"delete",
"(",
"\"_id\"",
")",
"if",
"result",
"result",
"end"
] |
get facts for given node name
@param node [String] node name
@param facts [Array<String>] get these facts in the result, eg ['fqdn'], empty for all
|
[
"get",
"facts",
"for",
"given",
"node",
"name"
] |
58103c91f291de8ce28d679256e50ae391b93ecb
|
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L135-L141
|
7,998 |
m-31/puppetdb_query
|
lib/puppetdb_query/mongodb.rb
|
PuppetDBQuery.MongoDB.meta
|
def meta
collection = connection[meta_collection]
result = collection.find.first
result.delete(:_id)
result
end
|
ruby
|
def meta
collection = connection[meta_collection]
result = collection.find.first
result.delete(:_id)
result
end
|
[
"def",
"meta",
"collection",
"=",
"connection",
"[",
"meta_collection",
"]",
"result",
"=",
"collection",
".",
"find",
".",
"first",
"result",
".",
"delete",
"(",
":_id",
")",
"result",
"end"
] |
get meta informations about updates
|
[
"get",
"meta",
"informations",
"about",
"updates"
] |
58103c91f291de8ce28d679256e50ae391b93ecb
|
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L158-L163
|
7,999 |
m-31/puppetdb_query
|
lib/puppetdb_query/mongodb.rb
|
PuppetDBQuery.MongoDB.node_update
|
def node_update(node, facts)
logger.debug " updating #{node}"
connection[nodes_collection].find(_id: node).replace_one(facts,
upsert: true,
bypass_document_validation: true,
check_keys: false,
validating_keys: false)
rescue ::Mongo::Error::OperationFailure => e
logger.warn " updating #{node} failed with: #{e.message}"
# mongodb doesn't support keys with a dot
# see https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names
# as a dirty workaround we delete the document and insert it ;-)
# The dotted field .. in .. is not valid for storage. (57)
# .. is an illegal key in MongoDB. Keys may not start with '$' or contain a '.'.
# (BSON::String::IllegalKey)
raise e unless e.message =~ /The dotted field / || e.message =~ /is an illegal key/
logger.warn " we transform the dots into underline characters"
begin
facts = Hash[facts.map { |k, v| [k.tr('.', '_'), v] }]
connection[nodes_collection].find(_id: node).replace_one(facts,
upsert: true,
bypass_document_validation: true,
check_keys: false,
validating_keys: false)
rescue
logger.error " inserting node #{node} failed again with: #{e.message}"
end
end
|
ruby
|
def node_update(node, facts)
logger.debug " updating #{node}"
connection[nodes_collection].find(_id: node).replace_one(facts,
upsert: true,
bypass_document_validation: true,
check_keys: false,
validating_keys: false)
rescue ::Mongo::Error::OperationFailure => e
logger.warn " updating #{node} failed with: #{e.message}"
# mongodb doesn't support keys with a dot
# see https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names
# as a dirty workaround we delete the document and insert it ;-)
# The dotted field .. in .. is not valid for storage. (57)
# .. is an illegal key in MongoDB. Keys may not start with '$' or contain a '.'.
# (BSON::String::IllegalKey)
raise e unless e.message =~ /The dotted field / || e.message =~ /is an illegal key/
logger.warn " we transform the dots into underline characters"
begin
facts = Hash[facts.map { |k, v| [k.tr('.', '_'), v] }]
connection[nodes_collection].find(_id: node).replace_one(facts,
upsert: true,
bypass_document_validation: true,
check_keys: false,
validating_keys: false)
rescue
logger.error " inserting node #{node} failed again with: #{e.message}"
end
end
|
[
"def",
"node_update",
"(",
"node",
",",
"facts",
")",
"logger",
".",
"debug",
"\" updating #{node}\"",
"connection",
"[",
"nodes_collection",
"]",
".",
"find",
"(",
"_id",
":",
"node",
")",
".",
"replace_one",
"(",
"facts",
",",
"upsert",
":",
"true",
",",
"bypass_document_validation",
":",
"true",
",",
"check_keys",
":",
"false",
",",
"validating_keys",
":",
"false",
")",
"rescue",
"::",
"Mongo",
"::",
"Error",
"::",
"OperationFailure",
"=>",
"e",
"logger",
".",
"warn",
"\" updating #{node} failed with: #{e.message}\"",
"# mongodb doesn't support keys with a dot",
"# see https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names",
"# as a dirty workaround we delete the document and insert it ;-)",
"# The dotted field .. in .. is not valid for storage. (57)",
"# .. is an illegal key in MongoDB. Keys may not start with '$' or contain a '.'.",
"# (BSON::String::IllegalKey)",
"raise",
"e",
"unless",
"e",
".",
"message",
"=~",
"/",
"/",
"||",
"e",
".",
"message",
"=~",
"/",
"/",
"logger",
".",
"warn",
"\" we transform the dots into underline characters\"",
"begin",
"facts",
"=",
"Hash",
"[",
"facts",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"k",
".",
"tr",
"(",
"'.'",
",",
"'_'",
")",
",",
"v",
"]",
"}",
"]",
"connection",
"[",
"nodes_collection",
"]",
".",
"find",
"(",
"_id",
":",
"node",
")",
".",
"replace_one",
"(",
"facts",
",",
"upsert",
":",
"true",
",",
"bypass_document_validation",
":",
"true",
",",
"check_keys",
":",
"false",
",",
"validating_keys",
":",
"false",
")",
"rescue",
"logger",
".",
"error",
"\" inserting node #{node} failed again with: #{e.message}\"",
"end",
"end"
] |
update or insert facts for given node name
@param node [String] node name
@param facts [Hash] facts for the node
|
[
"update",
"or",
"insert",
"facts",
"for",
"given",
"node",
"name"
] |
58103c91f291de8ce28d679256e50ae391b93ecb
|
https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/mongodb.rb#L169-L196
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.