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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
10,000
|
ideonetwork/lato-blog
|
app/controllers/lato_blog/back/posts_controller.rb
|
LatoBlog.Back::PostsController.destroy
|
def destroy
@post = LatoBlog::Post.find_by(id: params[:id])
return unless check_post_presence
unless @post.destroy
flash[:danger] = @post.post_parent.errors.full_messages.to_sentence
redirect_to lato_blog.edit_post_path(@post.id)
return
end
flash[:success] = LANGUAGES[:lato_blog][:flashes][:post_destroy_success]
redirect_to lato_blog.posts_path(status: 'deleted')
end
|
ruby
|
def destroy
@post = LatoBlog::Post.find_by(id: params[:id])
return unless check_post_presence
unless @post.destroy
flash[:danger] = @post.post_parent.errors.full_messages.to_sentence
redirect_to lato_blog.edit_post_path(@post.id)
return
end
flash[:success] = LANGUAGES[:lato_blog][:flashes][:post_destroy_success]
redirect_to lato_blog.posts_path(status: 'deleted')
end
|
[
"def",
"destroy",
"@post",
"=",
"LatoBlog",
"::",
"Post",
".",
"find_by",
"(",
"id",
":",
"params",
"[",
":id",
"]",
")",
"return",
"unless",
"check_post_presence",
"unless",
"@post",
".",
"destroy",
"flash",
"[",
":danger",
"]",
"=",
"@post",
".",
"post_parent",
".",
"errors",
".",
"full_messages",
".",
"to_sentence",
"redirect_to",
"lato_blog",
".",
"edit_post_path",
"(",
"@post",
".",
"id",
")",
"return",
"end",
"flash",
"[",
":success",
"]",
"=",
"LANGUAGES",
"[",
":lato_blog",
"]",
"[",
":flashes",
"]",
"[",
":post_destroy_success",
"]",
"redirect_to",
"lato_blog",
".",
"posts_path",
"(",
"status",
":",
"'deleted'",
")",
"end"
] |
This function destroyes a post.
|
[
"This",
"function",
"destroyes",
"a",
"post",
"."
] |
a0d92de299a0e285851743b9d4a902f611187cba
|
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/posts_controller.rb#L175-L187
|
10,001
|
ideonetwork/lato-blog
|
app/controllers/lato_blog/back/posts_controller.rb
|
LatoBlog.Back::PostsController.destroy_all_deleted
|
def destroy_all_deleted
@posts = LatoBlog::Post.deleted
if !@posts || @posts.empty?
flash[:warning] = LANGUAGES[:lato_blog][:flashes][:deleted_posts_not_found]
redirect_to lato_blog.posts_path(status: 'deleted')
return
end
@posts.each do |post|
unless post.destroy
flash[:danger] = post.errors.full_messages.to_sentence
redirect_to lato_blog.edit_post_path(post.id)
return
end
end
flash[:success] = LANGUAGES[:lato_blog][:flashes][:deleted_posts_destroy_success]
redirect_to lato_blog.posts_path(status: 'deleted')
end
|
ruby
|
def destroy_all_deleted
@posts = LatoBlog::Post.deleted
if !@posts || @posts.empty?
flash[:warning] = LANGUAGES[:lato_blog][:flashes][:deleted_posts_not_found]
redirect_to lato_blog.posts_path(status: 'deleted')
return
end
@posts.each do |post|
unless post.destroy
flash[:danger] = post.errors.full_messages.to_sentence
redirect_to lato_blog.edit_post_path(post.id)
return
end
end
flash[:success] = LANGUAGES[:lato_blog][:flashes][:deleted_posts_destroy_success]
redirect_to lato_blog.posts_path(status: 'deleted')
end
|
[
"def",
"destroy_all_deleted",
"@posts",
"=",
"LatoBlog",
"::",
"Post",
".",
"deleted",
"if",
"!",
"@posts",
"||",
"@posts",
".",
"empty?",
"flash",
"[",
":warning",
"]",
"=",
"LANGUAGES",
"[",
":lato_blog",
"]",
"[",
":flashes",
"]",
"[",
":deleted_posts_not_found",
"]",
"redirect_to",
"lato_blog",
".",
"posts_path",
"(",
"status",
":",
"'deleted'",
")",
"return",
"end",
"@posts",
".",
"each",
"do",
"|",
"post",
"|",
"unless",
"post",
".",
"destroy",
"flash",
"[",
":danger",
"]",
"=",
"post",
".",
"errors",
".",
"full_messages",
".",
"to_sentence",
"redirect_to",
"lato_blog",
".",
"edit_post_path",
"(",
"post",
".",
"id",
")",
"return",
"end",
"end",
"flash",
"[",
":success",
"]",
"=",
"LANGUAGES",
"[",
":lato_blog",
"]",
"[",
":flashes",
"]",
"[",
":deleted_posts_destroy_success",
"]",
"redirect_to",
"lato_blog",
".",
"posts_path",
"(",
"status",
":",
"'deleted'",
")",
"end"
] |
Tis function destroyes all posts with status deleted.
|
[
"Tis",
"function",
"destroyes",
"all",
"posts",
"with",
"status",
"deleted",
"."
] |
a0d92de299a0e285851743b9d4a902f611187cba
|
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/posts_controller.rb#L190-L209
|
10,002
|
ideonetwork/lato-blog
|
app/controllers/lato_blog/back/posts_controller.rb
|
LatoBlog.Back::PostsController.update_field
|
def update_field(field, value)
case field.typology
when 'text'
update_field_text(field, value)
when 'textarea'
update_field_textarea(field, value)
when 'datetime'
update_field_datetime(field, value)
when 'editor'
update_field_editor(field, value)
when 'geolocalization'
update_field_geolocalization(field, value)
when 'image'
update_field_image(field, value)
when 'gallery'
update_field_gallery(field, value)
when 'youtube'
update_field_youtube(field, value)
when 'composed'
update_field_composed(field, value)
when 'relay'
update_field_relay(field, value)
end
end
|
ruby
|
def update_field(field, value)
case field.typology
when 'text'
update_field_text(field, value)
when 'textarea'
update_field_textarea(field, value)
when 'datetime'
update_field_datetime(field, value)
when 'editor'
update_field_editor(field, value)
when 'geolocalization'
update_field_geolocalization(field, value)
when 'image'
update_field_image(field, value)
when 'gallery'
update_field_gallery(field, value)
when 'youtube'
update_field_youtube(field, value)
when 'composed'
update_field_composed(field, value)
when 'relay'
update_field_relay(field, value)
end
end
|
[
"def",
"update_field",
"(",
"field",
",",
"value",
")",
"case",
"field",
".",
"typology",
"when",
"'text'",
"update_field_text",
"(",
"field",
",",
"value",
")",
"when",
"'textarea'",
"update_field_textarea",
"(",
"field",
",",
"value",
")",
"when",
"'datetime'",
"update_field_datetime",
"(",
"field",
",",
"value",
")",
"when",
"'editor'",
"update_field_editor",
"(",
"field",
",",
"value",
")",
"when",
"'geolocalization'",
"update_field_geolocalization",
"(",
"field",
",",
"value",
")",
"when",
"'image'",
"update_field_image",
"(",
"field",
",",
"value",
")",
"when",
"'gallery'",
"update_field_gallery",
"(",
"field",
",",
"value",
")",
"when",
"'youtube'",
"update_field_youtube",
"(",
"field",
",",
"value",
")",
"when",
"'composed'",
"update_field_composed",
"(",
"field",
",",
"value",
")",
"when",
"'relay'",
"update_field_relay",
"(",
"field",
",",
"value",
")",
"end",
"end"
] |
This function updates a single field from its key and value.
|
[
"This",
"function",
"updates",
"a",
"single",
"field",
"from",
"its",
"key",
"and",
"value",
"."
] |
a0d92de299a0e285851743b9d4a902f611187cba
|
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/posts_controller.rb#L249-L272
|
10,003
|
kellysutton/bliptv
|
lib/bliptv/video.rb
|
BlipTV.Video.get_attributes
|
def get_attributes
url = URI.parse('http://www.blip.tv/')
res = Net::HTTP.start(url.host, url.port) {|http|
http.get("http://www.blip.tv/file/#{@id.to_s}?skin=api")
}
hash = Hash.from_xml(res.body)
if hash["response"]["status"] != "OK"
raise VideoResponseError.new(hash["response"]["notice"])
end
if hash["response"]["payload"]["asset"].is_a?(Array)
return hash["response"]["payload"]["asset"][0] # there may be several assets. In that case, read the first one
else
return hash["response"]["payload"]["asset"]
end
end
|
ruby
|
def get_attributes
url = URI.parse('http://www.blip.tv/')
res = Net::HTTP.start(url.host, url.port) {|http|
http.get("http://www.blip.tv/file/#{@id.to_s}?skin=api")
}
hash = Hash.from_xml(res.body)
if hash["response"]["status"] != "OK"
raise VideoResponseError.new(hash["response"]["notice"])
end
if hash["response"]["payload"]["asset"].is_a?(Array)
return hash["response"]["payload"]["asset"][0] # there may be several assets. In that case, read the first one
else
return hash["response"]["payload"]["asset"]
end
end
|
[
"def",
"get_attributes",
"url",
"=",
"URI",
".",
"parse",
"(",
"'http://www.blip.tv/'",
")",
"res",
"=",
"Net",
"::",
"HTTP",
".",
"start",
"(",
"url",
".",
"host",
",",
"url",
".",
"port",
")",
"{",
"|",
"http",
"|",
"http",
".",
"get",
"(",
"\"http://www.blip.tv/file/#{@id.to_s}?skin=api\"",
")",
"}",
"hash",
"=",
"Hash",
".",
"from_xml",
"(",
"res",
".",
"body",
")",
"if",
"hash",
"[",
"\"response\"",
"]",
"[",
"\"status\"",
"]",
"!=",
"\"OK\"",
"raise",
"VideoResponseError",
".",
"new",
"(",
"hash",
"[",
"\"response\"",
"]",
"[",
"\"notice\"",
"]",
")",
"end",
"if",
"hash",
"[",
"\"response\"",
"]",
"[",
"\"payload\"",
"]",
"[",
"\"asset\"",
"]",
".",
"is_a?",
"(",
"Array",
")",
"return",
"hash",
"[",
"\"response\"",
"]",
"[",
"\"payload\"",
"]",
"[",
"\"asset\"",
"]",
"[",
"0",
"]",
"# there may be several assets. In that case, read the first one",
"else",
"return",
"hash",
"[",
"\"response\"",
"]",
"[",
"\"payload\"",
"]",
"[",
"\"asset\"",
"]",
"end",
"end"
] |
fire off a HTTP GET response to Blip.tv
In the future, this should probably be rolled into the
BlipTV::Request class, so that all exception raising and
network communication exists in instances of that class.
|
[
"fire",
"off",
"a",
"HTTP",
"GET",
"response",
"to",
"Blip",
".",
"tv"
] |
4fd0d6132ded3069401d0fdf2f35726b71d3c64d
|
https://github.com/kellysutton/bliptv/blob/4fd0d6132ded3069401d0fdf2f35726b71d3c64d/lib/bliptv/video.rb#L84-L101
|
10,004
|
kellysutton/bliptv
|
lib/bliptv/video.rb
|
BlipTV.Video.delete!
|
def delete!(creds = {}, section = "file", reason = "because")
BlipTV::ApiSpec.check_attributes('videos.delete', creds)
reason = reason.gsub(" ", "%20") # TODO write a method to handle this and other illegalities of URL
if creds[:username] && !creds[:userlogin]
creds[:userlogin] = creds[:username]
end
url, path = "www.blip.tv", "/?userlogin=#{creds[:userlogin]}&password=#{creds[:password]}&cmd=delete&s=file&id=#{@id}&reason=#{reason}&skin=api"
request = Net::HTTP.get(url, path)
hash = Hash.from_xml(request)
make_sure_video_was_deleted(hash)
end
|
ruby
|
def delete!(creds = {}, section = "file", reason = "because")
BlipTV::ApiSpec.check_attributes('videos.delete', creds)
reason = reason.gsub(" ", "%20") # TODO write a method to handle this and other illegalities of URL
if creds[:username] && !creds[:userlogin]
creds[:userlogin] = creds[:username]
end
url, path = "www.blip.tv", "/?userlogin=#{creds[:userlogin]}&password=#{creds[:password]}&cmd=delete&s=file&id=#{@id}&reason=#{reason}&skin=api"
request = Net::HTTP.get(url, path)
hash = Hash.from_xml(request)
make_sure_video_was_deleted(hash)
end
|
[
"def",
"delete!",
"(",
"creds",
"=",
"{",
"}",
",",
"section",
"=",
"\"file\"",
",",
"reason",
"=",
"\"because\"",
")",
"BlipTV",
"::",
"ApiSpec",
".",
"check_attributes",
"(",
"'videos.delete'",
",",
"creds",
")",
"reason",
"=",
"reason",
".",
"gsub",
"(",
"\" \"",
",",
"\"%20\"",
")",
"# TODO write a method to handle this and other illegalities of URL",
"if",
"creds",
"[",
":username",
"]",
"&&",
"!",
"creds",
"[",
":userlogin",
"]",
"creds",
"[",
":userlogin",
"]",
"=",
"creds",
"[",
":username",
"]",
"end",
"url",
",",
"path",
"=",
"\"www.blip.tv\"",
",",
"\"/?userlogin=#{creds[:userlogin]}&password=#{creds[:password]}&cmd=delete&s=file&id=#{@id}&reason=#{reason}&skin=api\"",
"request",
"=",
"Net",
"::",
"HTTP",
".",
"get",
"(",
"url",
",",
"path",
")",
"hash",
"=",
"Hash",
".",
"from_xml",
"(",
"request",
")",
"make_sure_video_was_deleted",
"(",
"hash",
")",
"end"
] |
delete! will delete the file from Blip.tv
|
[
"delete!",
"will",
"delete",
"the",
"file",
"from",
"Blip",
".",
"tv"
] |
4fd0d6132ded3069401d0fdf2f35726b71d3c64d
|
https://github.com/kellysutton/bliptv/blob/4fd0d6132ded3069401d0fdf2f35726b71d3c64d/lib/bliptv/video.rb#L114-L127
|
10,005
|
payout/rester
|
lib/rester/service.rb
|
Rester.Service._response
|
def _response(status, body=nil, headers={})
body = [body].compact
headers = headers.merge("Content-Type" => "application/json")
Rack::Response.new(body, status, headers).finish
end
|
ruby
|
def _response(status, body=nil, headers={})
body = [body].compact
headers = headers.merge("Content-Type" => "application/json")
Rack::Response.new(body, status, headers).finish
end
|
[
"def",
"_response",
"(",
"status",
",",
"body",
"=",
"nil",
",",
"headers",
"=",
"{",
"}",
")",
"body",
"=",
"[",
"body",
"]",
".",
"compact",
"headers",
"=",
"headers",
".",
"merge",
"(",
"\"Content-Type\"",
"=>",
"\"application/json\"",
")",
"Rack",
"::",
"Response",
".",
"new",
"(",
"body",
",",
"status",
",",
"headers",
")",
".",
"finish",
"end"
] |
Returns a valid rack response.
|
[
"Returns",
"a",
"valid",
"rack",
"response",
"."
] |
404a45fa17e7f92e167a08c0bd90382dafd43cc5
|
https://github.com/payout/rester/blob/404a45fa17e7f92e167a08c0bd90382dafd43cc5/lib/rester/service.rb#L215-L219
|
10,006
|
theablefew/ablerc
|
lib/ablerc/dsl.rb
|
Ablerc.DSL.option
|
def option(name, behaviors = {}, &block)
Ablerc.options << Ablerc::Option.new(name, behaviors, &block)
end
|
ruby
|
def option(name, behaviors = {}, &block)
Ablerc.options << Ablerc::Option.new(name, behaviors, &block)
end
|
[
"def",
"option",
"(",
"name",
",",
"behaviors",
"=",
"{",
"}",
",",
"&",
"block",
")",
"Ablerc",
".",
"options",
"<<",
"Ablerc",
"::",
"Option",
".",
"new",
"(",
"name",
",",
"behaviors",
",",
"block",
")",
"end"
] |
Describe the options available
==== Parameters
* <tt>name</tt> - A valid name for the option
* <tt>behaviors</tt> - Behaviors used to for this option
* <tt>block</tt> - A proc that should be run against the option value.
==== Options
* <tt>allow</tt> - The option value must be in this list
* <tt>boolean</tt> - The option will accept <tt>true</tt>, <tt>false</tt>, <tt>0</tt>, <tt>1</tt>
|
[
"Describe",
"the",
"options",
"available"
] |
21ef74d92ef584c82a65b50cf9c908c13864b9e1
|
https://github.com/theablefew/ablerc/blob/21ef74d92ef584c82a65b50cf9c908c13864b9e1/lib/ablerc/dsl.rb#L35-L37
|
10,007
|
michaelmior/mipper
|
lib/mipper/variable.rb
|
MIPPeR.Variable.value
|
def value
# Model must be solved to have a value
return nil unless @model && @model.status == :optimized
value = @model.variable_value self
case @type
when :integer
value.round
when :binary
[false, true][value.round]
else
value
end
end
|
ruby
|
def value
# Model must be solved to have a value
return nil unless @model && @model.status == :optimized
value = @model.variable_value self
case @type
when :integer
value.round
when :binary
[false, true][value.round]
else
value
end
end
|
[
"def",
"value",
"# Model must be solved to have a value",
"return",
"nil",
"unless",
"@model",
"&&",
"@model",
".",
"status",
"==",
":optimized",
"value",
"=",
"@model",
".",
"variable_value",
"self",
"case",
"@type",
"when",
":integer",
"value",
".",
"round",
"when",
":binary",
"[",
"false",
",",
"true",
"]",
"[",
"value",
".",
"round",
"]",
"else",
"value",
"end",
"end"
] |
Get the final value of this variable
|
[
"Get",
"the",
"final",
"value",
"of",
"this",
"variable"
] |
4ab7f8b32c27f33fc5121756554a0a28d2077e06
|
https://github.com/michaelmior/mipper/blob/4ab7f8b32c27f33fc5121756554a0a28d2077e06/lib/mipper/variable.rb#L32-L46
|
10,008
|
mrakobeze/vrtk
|
src/vrtk/applets/version_applet.rb
|
VRTK::Applets.VersionApplet.run_parse
|
def run_parse
obj = {
'name' => VRTK::NAME,
'version' => VRTK::VERSION,
'codename' => VRTK::CODENAME,
'ffmpeg' => ffmpeg_version,
'magick' => magick_version,
'license' => VRTK::LICENSE
}
puts JSON.pretty_unparse obj
end
|
ruby
|
def run_parse
obj = {
'name' => VRTK::NAME,
'version' => VRTK::VERSION,
'codename' => VRTK::CODENAME,
'ffmpeg' => ffmpeg_version,
'magick' => magick_version,
'license' => VRTK::LICENSE
}
puts JSON.pretty_unparse obj
end
|
[
"def",
"run_parse",
"obj",
"=",
"{",
"'name'",
"=>",
"VRTK",
"::",
"NAME",
",",
"'version'",
"=>",
"VRTK",
"::",
"VERSION",
",",
"'codename'",
"=>",
"VRTK",
"::",
"CODENAME",
",",
"'ffmpeg'",
"=>",
"ffmpeg_version",
",",
"'magick'",
"=>",
"magick_version",
",",
"'license'",
"=>",
"VRTK",
"::",
"LICENSE",
"}",
"puts",
"JSON",
".",
"pretty_unparse",
"obj",
"end"
] |
noinspection RubyStringKeysInHashInspection,RubyResolve
|
[
"noinspection",
"RubyStringKeysInHashInspection",
"RubyResolve"
] |
444052951949e3faab01f6292345dcd0a789f005
|
https://github.com/mrakobeze/vrtk/blob/444052951949e3faab01f6292345dcd0a789f005/src/vrtk/applets/version_applet.rb#L34-L45
|
10,009
|
justinkim/tf2r
|
lib/tf2r/scraper.rb
|
TF2R.Scraper.scrape_main_page
|
def scrape_main_page
page = fetch('http://tf2r.com/raffles.html')
# All raffle links begin with 'tf2r.com/k'
raffle_links = page.links_with(href: /tf2r\.com\/k/)
raffle_links.map! { |x| x.uri.to_s }
raffle_links.reverse!
end
|
ruby
|
def scrape_main_page
page = fetch('http://tf2r.com/raffles.html')
# All raffle links begin with 'tf2r.com/k'
raffle_links = page.links_with(href: /tf2r\.com\/k/)
raffle_links.map! { |x| x.uri.to_s }
raffle_links.reverse!
end
|
[
"def",
"scrape_main_page",
"page",
"=",
"fetch",
"(",
"'http://tf2r.com/raffles.html'",
")",
"# All raffle links begin with 'tf2r.com/k'",
"raffle_links",
"=",
"page",
".",
"links_with",
"(",
"href",
":",
"/",
"\\.",
"\\/",
"/",
")",
"raffle_links",
".",
"map!",
"{",
"|",
"x",
"|",
"x",
".",
"uri",
".",
"to_s",
"}",
"raffle_links",
".",
"reverse!",
"end"
] |
Scrapes TF2R for all active raffles.
See http://tf2r.com/raffles.html
@example
s.scrape_main_page #=> ['http://tf2r.com/kold.html',
'http://tf2r.com/knew.html',
'http://tf2r.com/knewest.html']
@return [Hash] String links of all active raffles in chronological
order (oldest to newest by creation time).
|
[
"Scrapes",
"TF2R",
"for",
"all",
"active",
"raffles",
"."
] |
20d9648fe1048d9b2a34064821d8c95aaff505da
|
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/scraper.rb#L59-L66
|
10,010
|
justinkim/tf2r
|
lib/tf2r/scraper.rb
|
TF2R.Scraper.scrape_raffle_for_creator
|
def scrape_raffle_for_creator(page)
# Reag classed some things "raffle_infomation". That's spelled right.
infos = page.parser.css('.raffle_infomation')
# The main 'a' element, containing the creator's username.
user_anchor = infos[2].css('a')[0]
steam_id = extract_steam_id(user_anchor.attribute('href').to_s)
username = user_anchor.text
avatar_link = infos[1].css('img')[0].attribute('src').to_s
posrep = /(\d+)/.match(infos.css('.upvb').text)[1].to_i
negrep = /(\d+)/.match(infos.css('.downvb').text)[1].to_i
# The creator's username color. Corresponds to rank.
color = extract_color(user_anchor.attribute('style').to_s)
{steam_id: steam_id, username: username, avatar_link: avatar_link,
posrep: posrep, negrep: negrep, color: color}
end
|
ruby
|
def scrape_raffle_for_creator(page)
# Reag classed some things "raffle_infomation". That's spelled right.
infos = page.parser.css('.raffle_infomation')
# The main 'a' element, containing the creator's username.
user_anchor = infos[2].css('a')[0]
steam_id = extract_steam_id(user_anchor.attribute('href').to_s)
username = user_anchor.text
avatar_link = infos[1].css('img')[0].attribute('src').to_s
posrep = /(\d+)/.match(infos.css('.upvb').text)[1].to_i
negrep = /(\d+)/.match(infos.css('.downvb').text)[1].to_i
# The creator's username color. Corresponds to rank.
color = extract_color(user_anchor.attribute('style').to_s)
{steam_id: steam_id, username: username, avatar_link: avatar_link,
posrep: posrep, negrep: negrep, color: color}
end
|
[
"def",
"scrape_raffle_for_creator",
"(",
"page",
")",
"# Reag classed some things \"raffle_infomation\". That's spelled right.",
"infos",
"=",
"page",
".",
"parser",
".",
"css",
"(",
"'.raffle_infomation'",
")",
"# The main 'a' element, containing the creator's username.",
"user_anchor",
"=",
"infos",
"[",
"2",
"]",
".",
"css",
"(",
"'a'",
")",
"[",
"0",
"]",
"steam_id",
"=",
"extract_steam_id",
"(",
"user_anchor",
".",
"attribute",
"(",
"'href'",
")",
".",
"to_s",
")",
"username",
"=",
"user_anchor",
".",
"text",
"avatar_link",
"=",
"infos",
"[",
"1",
"]",
".",
"css",
"(",
"'img'",
")",
"[",
"0",
"]",
".",
"attribute",
"(",
"'src'",
")",
".",
"to_s",
"posrep",
"=",
"/",
"\\d",
"/",
".",
"match",
"(",
"infos",
".",
"css",
"(",
"'.upvb'",
")",
".",
"text",
")",
"[",
"1",
"]",
".",
"to_i",
"negrep",
"=",
"/",
"\\d",
"/",
".",
"match",
"(",
"infos",
".",
"css",
"(",
"'.downvb'",
")",
".",
"text",
")",
"[",
"1",
"]",
".",
"to_i",
"# The creator's username color. Corresponds to rank.",
"color",
"=",
"extract_color",
"(",
"user_anchor",
".",
"attribute",
"(",
"'style'",
")",
".",
"to_s",
")",
"{",
"steam_id",
":",
"steam_id",
",",
"username",
":",
"username",
",",
"avatar_link",
":",
"avatar_link",
",",
"posrep",
":",
"posrep",
",",
"negrep",
":",
"negrep",
",",
"color",
":",
"color",
"}",
"end"
] |
Scrapes a raffle page for information about the creator.
@example
p = s.fetch('http://tf2r.com/kstzcbd.html')
s.scrape_raffle_for_creator(p) #=>
{:steam_id=>76561198061719848,
:username=>"Yulli",
:avatar_link=>"http://media.steampowered.com/steamcommunity/public/images/avatars/bc/bc9dc4302d23f2e2f37f59c59f29c27dbc8cade6_full.jpg",
:posrep=>11458,
:negrep=>0,
:color=>"70b01b"}
@param page [Mechanize::Page] the raffle page.
@return [Hash] a representation of a user, the raffle creator.
* :steam_id (+Fixnum+) — the creator's SteamID64.
* :username (+String+) — the creator's username.
* :avatar_link (+String+) — a link to the creator's avatar.
* :posrep (+Fixnum+) — the creator's positive rep.
* :negrep (+Fixnum+) — the creator's negative rep.
* :color (+String+) — hex color code of the creator's username.
|
[
"Scrapes",
"a",
"raffle",
"page",
"for",
"information",
"about",
"the",
"creator",
"."
] |
20d9648fe1048d9b2a34064821d8c95aaff505da
|
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/scraper.rb#L99-L117
|
10,011
|
justinkim/tf2r
|
lib/tf2r/scraper.rb
|
TF2R.Scraper.scrape_raffle_for_raffle
|
def scrape_raffle_for_raffle(page)
# Reag classed some things "raffle_infomation". That's spelled right.
infos = page.parser.css('.raffle_infomation')
# Elements of the main raffle info table.
raffle_tds = infos[3].css('td')
# 'kabc123' for http://tf2r.com/kabc123.html'
link_snippet = extract_link_snippet(page.uri.path)
title = extract_title(infos[0].text)
description = raffle_tds[1].text
# This doesn't work right now, because Miz just displays "10%" in the
# page HTML and updates it with JS after a call to the API.
# win_chance = /(.+)%/.match(infos.css('#winc').text)[1].to_f / 100
start_time = extract_start_time(raffle_tds[9])
end_time = extract_end_time(raffle_tds[11])
{link_snippet: link_snippet, title: title, description: description,
start_time: start_time, end_time: end_time}
end
|
ruby
|
def scrape_raffle_for_raffle(page)
# Reag classed some things "raffle_infomation". That's spelled right.
infos = page.parser.css('.raffle_infomation')
# Elements of the main raffle info table.
raffle_tds = infos[3].css('td')
# 'kabc123' for http://tf2r.com/kabc123.html'
link_snippet = extract_link_snippet(page.uri.path)
title = extract_title(infos[0].text)
description = raffle_tds[1].text
# This doesn't work right now, because Miz just displays "10%" in the
# page HTML and updates it with JS after a call to the API.
# win_chance = /(.+)%/.match(infos.css('#winc').text)[1].to_f / 100
start_time = extract_start_time(raffle_tds[9])
end_time = extract_end_time(raffle_tds[11])
{link_snippet: link_snippet, title: title, description: description,
start_time: start_time, end_time: end_time}
end
|
[
"def",
"scrape_raffle_for_raffle",
"(",
"page",
")",
"# Reag classed some things \"raffle_infomation\". That's spelled right.",
"infos",
"=",
"page",
".",
"parser",
".",
"css",
"(",
"'.raffle_infomation'",
")",
"# Elements of the main raffle info table.",
"raffle_tds",
"=",
"infos",
"[",
"3",
"]",
".",
"css",
"(",
"'td'",
")",
"# 'kabc123' for http://tf2r.com/kabc123.html'",
"link_snippet",
"=",
"extract_link_snippet",
"(",
"page",
".",
"uri",
".",
"path",
")",
"title",
"=",
"extract_title",
"(",
"infos",
"[",
"0",
"]",
".",
"text",
")",
"description",
"=",
"raffle_tds",
"[",
"1",
"]",
".",
"text",
"# This doesn't work right now, because Miz just displays \"10%\" in the",
"# page HTML and updates it with JS after a call to the API.",
"# win_chance = /(.+)%/.match(infos.css('#winc').text)[1].to_f / 100",
"start_time",
"=",
"extract_start_time",
"(",
"raffle_tds",
"[",
"9",
"]",
")",
"end_time",
"=",
"extract_end_time",
"(",
"raffle_tds",
"[",
"11",
"]",
")",
"{",
"link_snippet",
":",
"link_snippet",
",",
"title",
":",
"title",
",",
"description",
":",
"description",
",",
"start_time",
":",
"start_time",
",",
"end_time",
":",
"end_time",
"}",
"end"
] |
Scrapes a raffle page for some information about the raffle.
The information is incomplete. This should be used in conjunction with
the API as part of TF2R::Raffle.
@example
p = s.fetch('http://tf2r.com/kstzcbd.html')
s.scrape_raffle_for_raffle(p) #=>
{:link_snippet=>"kstzcbd",
:title=>"Just one refined [1 hour]",
:description=>"Plain and simple.",
:start_time=>2012-10-29 09:51:45 -0400,
:end_time=>2012-10-29 09:53:01 -0400}
@param page [Mechanize::Page] the raffle page.
@return [Hash] a partial representation of the raffle.
* :link_snippet (+String+) — the "raffle id" in the URL.
* :title (+String+) — the raffle's title.
* :description (+String+) — the raffle's "message".
* :start_time (+Time+) — the creation time of the raffle.
* :end_time (+Time+) — the projects/observed end time for the raffle.
|
[
"Scrapes",
"a",
"raffle",
"page",
"for",
"some",
"information",
"about",
"the",
"raffle",
"."
] |
20d9648fe1048d9b2a34064821d8c95aaff505da
|
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/scraper.rb#L140-L161
|
10,012
|
justinkim/tf2r
|
lib/tf2r/scraper.rb
|
TF2R.Scraper.scrape_raffle_for_participants
|
def scrape_raffle_for_participants(page)
participants = []
participant_divs = page.parser.css('.pentry')
participant_divs.each do |participant|
user_anchor = participant.children[1]
steam_id = extract_steam_id(user_anchor.to_s)
username = participant.text
color = extract_color(user_anchor.children[0].attribute('style'))
participants << {steam_id: steam_id, username: username, color: color}
end
participants.reverse!
end
|
ruby
|
def scrape_raffle_for_participants(page)
participants = []
participant_divs = page.parser.css('.pentry')
participant_divs.each do |participant|
user_anchor = participant.children[1]
steam_id = extract_steam_id(user_anchor.to_s)
username = participant.text
color = extract_color(user_anchor.children[0].attribute('style'))
participants << {steam_id: steam_id, username: username, color: color}
end
participants.reverse!
end
|
[
"def",
"scrape_raffle_for_participants",
"(",
"page",
")",
"participants",
"=",
"[",
"]",
"participant_divs",
"=",
"page",
".",
"parser",
".",
"css",
"(",
"'.pentry'",
")",
"participant_divs",
".",
"each",
"do",
"|",
"participant",
"|",
"user_anchor",
"=",
"participant",
".",
"children",
"[",
"1",
"]",
"steam_id",
"=",
"extract_steam_id",
"(",
"user_anchor",
".",
"to_s",
")",
"username",
"=",
"participant",
".",
"text",
"color",
"=",
"extract_color",
"(",
"user_anchor",
".",
"children",
"[",
"0",
"]",
".",
"attribute",
"(",
"'style'",
")",
")",
"participants",
"<<",
"{",
"steam_id",
":",
"steam_id",
",",
"username",
":",
"username",
",",
"color",
":",
"color",
"}",
"end",
"participants",
".",
"reverse!",
"end"
] |
Scrapes a raffle page for all the participants.
This should rarely be used. This will only be necessary in the case that
a raffle has maximum entries greater than 2500.
@param page [Mechanize::Page] the raffle page.
@return [Array] contains Hashes representing each of the participants,
in chronological order (first entered to last).
* :steam_id (+Fixnum+) — the participant's SteamID64.
* :username (+String+) — the participant's username.
* :color (+String+) — hex color code of the participant's username.
|
[
"Scrapes",
"a",
"raffle",
"page",
"for",
"all",
"the",
"participants",
"."
] |
20d9648fe1048d9b2a34064821d8c95aaff505da
|
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/scraper.rb#L174-L187
|
10,013
|
justinkim/tf2r
|
lib/tf2r/scraper.rb
|
TF2R.Scraper.scrape_user
|
def scrape_user(user_page)
if user_page.parser.css('.profile_info').empty?
raise InvalidUserPage, 'The given page does not correspond to any user.'
else
infos = user_page.parser.css('.raffle_infomation') #sic
user_anchor = infos[1].css('a')[0]
steam_id = extract_steam_id(user_page.uri.to_s)
username = /TF2R Item Raffles - (.+)/.match(user_page.title)[1]
avatar_link = infos[0].css('img')[0].attribute('src').to_s
posrep = infos.css('.upvb').text.to_i
negrep = infos.css('.downvb').text.to_i
color = extract_color(user_anchor.attribute('style').to_s)
end
{steam_id: steam_id, username: username, avatar_link: avatar_link,
posrep: posrep, negrep: negrep, color: color}
end
|
ruby
|
def scrape_user(user_page)
if user_page.parser.css('.profile_info').empty?
raise InvalidUserPage, 'The given page does not correspond to any user.'
else
infos = user_page.parser.css('.raffle_infomation') #sic
user_anchor = infos[1].css('a')[0]
steam_id = extract_steam_id(user_page.uri.to_s)
username = /TF2R Item Raffles - (.+)/.match(user_page.title)[1]
avatar_link = infos[0].css('img')[0].attribute('src').to_s
posrep = infos.css('.upvb').text.to_i
negrep = infos.css('.downvb').text.to_i
color = extract_color(user_anchor.attribute('style').to_s)
end
{steam_id: steam_id, username: username, avatar_link: avatar_link,
posrep: posrep, negrep: negrep, color: color}
end
|
[
"def",
"scrape_user",
"(",
"user_page",
")",
"if",
"user_page",
".",
"parser",
".",
"css",
"(",
"'.profile_info'",
")",
".",
"empty?",
"raise",
"InvalidUserPage",
",",
"'The given page does not correspond to any user.'",
"else",
"infos",
"=",
"user_page",
".",
"parser",
".",
"css",
"(",
"'.raffle_infomation'",
")",
"#sic",
"user_anchor",
"=",
"infos",
"[",
"1",
"]",
".",
"css",
"(",
"'a'",
")",
"[",
"0",
"]",
"steam_id",
"=",
"extract_steam_id",
"(",
"user_page",
".",
"uri",
".",
"to_s",
")",
"username",
"=",
"/",
"/",
".",
"match",
"(",
"user_page",
".",
"title",
")",
"[",
"1",
"]",
"avatar_link",
"=",
"infos",
"[",
"0",
"]",
".",
"css",
"(",
"'img'",
")",
"[",
"0",
"]",
".",
"attribute",
"(",
"'src'",
")",
".",
"to_s",
"posrep",
"=",
"infos",
".",
"css",
"(",
"'.upvb'",
")",
".",
"text",
".",
"to_i",
"negrep",
"=",
"infos",
".",
"css",
"(",
"'.downvb'",
")",
".",
"text",
".",
"to_i",
"color",
"=",
"extract_color",
"(",
"user_anchor",
".",
"attribute",
"(",
"'style'",
")",
".",
"to_s",
")",
"end",
"{",
"steam_id",
":",
"steam_id",
",",
"username",
":",
"username",
",",
"avatar_link",
":",
"avatar_link",
",",
"posrep",
":",
"posrep",
",",
"negrep",
":",
"negrep",
",",
"color",
":",
"color",
"}",
"end"
] |
Scrapes a user page for information about the user.
@example
p = s.fetch('http://tf2r.com/user/76561198061719848.html')
s.scrape_user(p) #=>
{:steam_id=>76561198061719848,
:username=>"Yulli",
:avatar_link=>"http://media.steampowered.com/steamcommunity/public/images/avatars/bc/bc9dc4302d23f2e2f37f59c59f29c27dbc8cade6_full.jpg",
:posrep=>11459,
:negrep=>0,
:color=>"70b01b"}
@param user_page [Mechanize::Page] the user page.
@return [Hash] a representation of the user.
* :steam_id (+Fixnum+) — the user's SteamID64.
* :username (+String+) — the user's username.
* :avatar_link (+String+) — a link to the user's avatar.
* :posrep (+Fixnum+) — the user's positive rep.
* :negrep (+Fixnum+) — the user's negative rep.
* :color (+String+) — hex color code of the user's username.
|
[
"Scrapes",
"a",
"user",
"page",
"for",
"information",
"about",
"the",
"user",
"."
] |
20d9648fe1048d9b2a34064821d8c95aaff505da
|
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/scraper.rb#L209-L228
|
10,014
|
justinkim/tf2r
|
lib/tf2r/scraper.rb
|
TF2R.Scraper.scrape_ranks
|
def scrape_ranks(info_page)
rank_divs = info_page.parser.css('#ranks').children
ranks = rank_divs.select { |div| div.children.size == 3 }
ranks.map { |div| extract_rank(div) }
end
|
ruby
|
def scrape_ranks(info_page)
rank_divs = info_page.parser.css('#ranks').children
ranks = rank_divs.select { |div| div.children.size == 3 }
ranks.map { |div| extract_rank(div) }
end
|
[
"def",
"scrape_ranks",
"(",
"info_page",
")",
"rank_divs",
"=",
"info_page",
".",
"parser",
".",
"css",
"(",
"'#ranks'",
")",
".",
"children",
"ranks",
"=",
"rank_divs",
".",
"select",
"{",
"|",
"div",
"|",
"div",
".",
"children",
".",
"size",
"==",
"3",
"}",
"ranks",
".",
"map",
"{",
"|",
"div",
"|",
"extract_rank",
"(",
"div",
")",
"}",
"end"
] |
Scrapes the TF2R info page for available user ranks.
See http://tf2r.com/info.html.
@example
p = s.fetch('http://tf2r.com/info.html')
s.scrape_user(p) #=>
[{:color=>"ebe2ca", :name=>"User",
:description=>"Every new or existing user has this rank."}, ...]
@param info_page [Mechanize::Page] the info page.
@return [Array] contains Hashes representing each of the ranks.
* :name (+String+) — the rank's name.
* :description (+String+) — the rank's description.
* :color (+String+) — the rank's hex color code.
|
[
"Scrapes",
"the",
"TF2R",
"info",
"page",
"for",
"available",
"user",
"ranks",
"."
] |
20d9648fe1048d9b2a34064821d8c95aaff505da
|
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/scraper.rb#L245-L249
|
10,015
|
betaworks/slack-bot-manager
|
lib/slack-bot-manager/manager/connection.rb
|
SlackBotManager.Connection.start
|
def start
# Clear RTM connections
storage.delete_all(teams_key)
# Start a new connection for each team
storage.get_all(tokens_key).each do |id, token|
create(id, token)
end
end
|
ruby
|
def start
# Clear RTM connections
storage.delete_all(teams_key)
# Start a new connection for each team
storage.get_all(tokens_key).each do |id, token|
create(id, token)
end
end
|
[
"def",
"start",
"# Clear RTM connections",
"storage",
".",
"delete_all",
"(",
"teams_key",
")",
"# Start a new connection for each team",
"storage",
".",
"get_all",
"(",
"tokens_key",
")",
".",
"each",
"do",
"|",
"id",
",",
"token",
"|",
"create",
"(",
"id",
",",
"token",
")",
"end",
"end"
] |
Create websocket connections for active tokens
|
[
"Create",
"websocket",
"connections",
"for",
"active",
"tokens"
] |
cb59bd1c80abd3ede0520017708891486f733e40
|
https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/manager/connection.rb#L74-L82
|
10,016
|
betaworks/slack-bot-manager
|
lib/slack-bot-manager/manager/connection.rb
|
SlackBotManager.Connection.stop
|
def stop
# Thread wrapped to ensure no lock issues on shutdown
thr = Thread.new do
conns = storage.get_all(teams_key)
storage.pipeline do
conns.each { |k, _| storage.set(teams_key, k, 'destroy') }
end
info('Stopped.')
end
thr.join
end
|
ruby
|
def stop
# Thread wrapped to ensure no lock issues on shutdown
thr = Thread.new do
conns = storage.get_all(teams_key)
storage.pipeline do
conns.each { |k, _| storage.set(teams_key, k, 'destroy') }
end
info('Stopped.')
end
thr.join
end
|
[
"def",
"stop",
"# Thread wrapped to ensure no lock issues on shutdown",
"thr",
"=",
"Thread",
".",
"new",
"do",
"conns",
"=",
"storage",
".",
"get_all",
"(",
"teams_key",
")",
"storage",
".",
"pipeline",
"do",
"conns",
".",
"each",
"{",
"|",
"k",
",",
"_",
"|",
"storage",
".",
"set",
"(",
"teams_key",
",",
"k",
",",
"'destroy'",
")",
"}",
"end",
"info",
"(",
"'Stopped.'",
")",
"end",
"thr",
".",
"join",
"end"
] |
Remove all connections from app, will disconnect in monitor loop
|
[
"Remove",
"all",
"connections",
"from",
"app",
"will",
"disconnect",
"in",
"monitor",
"loop"
] |
cb59bd1c80abd3ede0520017708891486f733e40
|
https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/manager/connection.rb#L85-L95
|
10,017
|
betaworks/slack-bot-manager
|
lib/slack-bot-manager/manager/connection.rb
|
SlackBotManager.Connection.restart
|
def restart
conns = storage.get_all(teams_key)
storage.pipeline do
conns.each { |k, _| storage.set(teams_key, k, 'restart') }
end
end
|
ruby
|
def restart
conns = storage.get_all(teams_key)
storage.pipeline do
conns.each { |k, _| storage.set(teams_key, k, 'restart') }
end
end
|
[
"def",
"restart",
"conns",
"=",
"storage",
".",
"get_all",
"(",
"teams_key",
")",
"storage",
".",
"pipeline",
"do",
"conns",
".",
"each",
"{",
"|",
"k",
",",
"_",
"|",
"storage",
".",
"set",
"(",
"teams_key",
",",
"k",
",",
"'restart'",
")",
"}",
"end",
"end"
] |
Issue restart status on all RTM connections
will re-connect in monitor loop
|
[
"Issue",
"restart",
"status",
"on",
"all",
"RTM",
"connections",
"will",
"re",
"-",
"connect",
"in",
"monitor",
"loop"
] |
cb59bd1c80abd3ede0520017708891486f733e40
|
https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/manager/connection.rb#L99-L104
|
10,018
|
betaworks/slack-bot-manager
|
lib/slack-bot-manager/manager/connection.rb
|
SlackBotManager.Connection.find_connection
|
def find_connection(id)
connections.each do |_, conn|
return (conn.connected? ? conn : false) if conn && conn.id == id
end
false
end
|
ruby
|
def find_connection(id)
connections.each do |_, conn|
return (conn.connected? ? conn : false) if conn && conn.id == id
end
false
end
|
[
"def",
"find_connection",
"(",
"id",
")",
"connections",
".",
"each",
"do",
"|",
"_",
",",
"conn",
"|",
"return",
"(",
"conn",
".",
"connected?",
"?",
"conn",
":",
"false",
")",
"if",
"conn",
"&&",
"conn",
".",
"id",
"==",
"id",
"end",
"false",
"end"
] |
Find the connection based on id and has active connection
|
[
"Find",
"the",
"connection",
"based",
"on",
"id",
"and",
"has",
"active",
"connection"
] |
cb59bd1c80abd3ede0520017708891486f733e40
|
https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/manager/connection.rb#L114-L119
|
10,019
|
betaworks/slack-bot-manager
|
lib/slack-bot-manager/manager/connection.rb
|
SlackBotManager.Connection.create
|
def create(id, token)
fail SlackBotManager::TokenAlreadyConnected if find_connection(id)
# Create connection
conn = SlackBotManager::Client.new(token)
conn.connect
# Add to connections using a uniq token
if conn
cid = [id, Time.now.to_i].join(':')
connections[cid] = conn
info("Connected: #{id} (Connection: #{cid})")
storage.set(teams_key, id, 'active')
end
rescue => err
on_error(err)
end
|
ruby
|
def create(id, token)
fail SlackBotManager::TokenAlreadyConnected if find_connection(id)
# Create connection
conn = SlackBotManager::Client.new(token)
conn.connect
# Add to connections using a uniq token
if conn
cid = [id, Time.now.to_i].join(':')
connections[cid] = conn
info("Connected: #{id} (Connection: #{cid})")
storage.set(teams_key, id, 'active')
end
rescue => err
on_error(err)
end
|
[
"def",
"create",
"(",
"id",
",",
"token",
")",
"fail",
"SlackBotManager",
"::",
"TokenAlreadyConnected",
"if",
"find_connection",
"(",
"id",
")",
"# Create connection",
"conn",
"=",
"SlackBotManager",
"::",
"Client",
".",
"new",
"(",
"token",
")",
"conn",
".",
"connect",
"# Add to connections using a uniq token",
"if",
"conn",
"cid",
"=",
"[",
"id",
",",
"Time",
".",
"now",
".",
"to_i",
"]",
".",
"join",
"(",
"':'",
")",
"connections",
"[",
"cid",
"]",
"=",
"conn",
"info",
"(",
"\"Connected: #{id} (Connection: #{cid})\"",
")",
"storage",
".",
"set",
"(",
"teams_key",
",",
"id",
",",
"'active'",
")",
"end",
"rescue",
"=>",
"err",
"on_error",
"(",
"err",
")",
"end"
] |
Create new connection if not exist
|
[
"Create",
"new",
"connection",
"if",
"not",
"exist"
] |
cb59bd1c80abd3ede0520017708891486f733e40
|
https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/manager/connection.rb#L122-L138
|
10,020
|
betaworks/slack-bot-manager
|
lib/slack-bot-manager/manager/connection.rb
|
SlackBotManager.Connection.destroy
|
def destroy(*args)
options = args.extract_options!
# Get connection or search for connection with cid
if options[:cid]
conn = connections[options[:cid]]
cid = options[:cid]
elsif options[:id]
conn, cid = find_connection(options[:id])
end
return false unless conn && cid
# Kill connection, remove from keys, and delete from list
begin
thr = Thread.new do
storage.delete(teams_key, conn.id) rescue nil
storage.delete(tokens_key, conn.id) rescue nil if options[:remove_token]
end
thr.join
connections.delete(cid)
rescue
nil
end
rescue => err
on_error(err)
end
|
ruby
|
def destroy(*args)
options = args.extract_options!
# Get connection or search for connection with cid
if options[:cid]
conn = connections[options[:cid]]
cid = options[:cid]
elsif options[:id]
conn, cid = find_connection(options[:id])
end
return false unless conn && cid
# Kill connection, remove from keys, and delete from list
begin
thr = Thread.new do
storage.delete(teams_key, conn.id) rescue nil
storage.delete(tokens_key, conn.id) rescue nil if options[:remove_token]
end
thr.join
connections.delete(cid)
rescue
nil
end
rescue => err
on_error(err)
end
|
[
"def",
"destroy",
"(",
"*",
"args",
")",
"options",
"=",
"args",
".",
"extract_options!",
"# Get connection or search for connection with cid",
"if",
"options",
"[",
":cid",
"]",
"conn",
"=",
"connections",
"[",
"options",
"[",
":cid",
"]",
"]",
"cid",
"=",
"options",
"[",
":cid",
"]",
"elsif",
"options",
"[",
":id",
"]",
"conn",
",",
"cid",
"=",
"find_connection",
"(",
"options",
"[",
":id",
"]",
")",
"end",
"return",
"false",
"unless",
"conn",
"&&",
"cid",
"# Kill connection, remove from keys, and delete from list",
"begin",
"thr",
"=",
"Thread",
".",
"new",
"do",
"storage",
".",
"delete",
"(",
"teams_key",
",",
"conn",
".",
"id",
")",
"rescue",
"nil",
"storage",
".",
"delete",
"(",
"tokens_key",
",",
"conn",
".",
"id",
")",
"rescue",
"nil",
"if",
"options",
"[",
":remove_token",
"]",
"end",
"thr",
".",
"join",
"connections",
".",
"delete",
"(",
"cid",
")",
"rescue",
"nil",
"end",
"rescue",
"=>",
"err",
"on_error",
"(",
"err",
")",
"end"
] |
Disconnect from a RTM connection
|
[
"Disconnect",
"from",
"a",
"RTM",
"connection"
] |
cb59bd1c80abd3ede0520017708891486f733e40
|
https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/manager/connection.rb#L141-L166
|
10,021
|
kristianmandrup/controll
|
lib/controll/flow/action/path_action.rb
|
Controll::Flow::Action.PathAction.method_missing
|
def method_missing(method_name, *args, &block)
if controller.respond_to? method_name
controller.send method_name, *args, &block
else
super
end
end
|
ruby
|
def method_missing(method_name, *args, &block)
if controller.respond_to? method_name
controller.send method_name, *args, &block
else
super
end
end
|
[
"def",
"method_missing",
"(",
"method_name",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"controller",
".",
"respond_to?",
"method_name",
"controller",
".",
"send",
"method_name",
",",
"args",
",",
"block",
"else",
"super",
"end",
"end"
] |
useful for path helpers used in event maps
|
[
"useful",
"for",
"path",
"helpers",
"used",
"in",
"event",
"maps"
] |
99f25c1153ff7d04fab64391977e7140ce5b3d37
|
https://github.com/kristianmandrup/controll/blob/99f25c1153ff7d04fab64391977e7140ce5b3d37/lib/controll/flow/action/path_action.rb#L16-L22
|
10,022
|
ashiksp/smart_que
|
lib/smart_que/publisher.rb
|
SmartQue.Publisher.publish
|
def publish(queue, payload = {})
# Check queue name includes in the configured list
# Return if queue doesn't exist
if queue_list.include? queue
# Publish sms to queue
begin
x_direct.publish(
payload.to_json,
mandatory: true,
routing_key: get_queue(queue).name
)
log_message("Publish status: success, Queue : #{queue}, Content : #{payload}")
:success
rescue => ex
log_message("Publish error:#{ex.message}")
:error
end
else
log_message("Publish status: failed, Queue(#{queue}) doesn't exist.")
log_message("Content : #{payload}")
raise QueueNotFoundError
end
end
|
ruby
|
def publish(queue, payload = {})
# Check queue name includes in the configured list
# Return if queue doesn't exist
if queue_list.include? queue
# Publish sms to queue
begin
x_direct.publish(
payload.to_json,
mandatory: true,
routing_key: get_queue(queue).name
)
log_message("Publish status: success, Queue : #{queue}, Content : #{payload}")
:success
rescue => ex
log_message("Publish error:#{ex.message}")
:error
end
else
log_message("Publish status: failed, Queue(#{queue}) doesn't exist.")
log_message("Content : #{payload}")
raise QueueNotFoundError
end
end
|
[
"def",
"publish",
"(",
"queue",
",",
"payload",
"=",
"{",
"}",
")",
"# Check queue name includes in the configured list",
"# Return if queue doesn't exist",
"if",
"queue_list",
".",
"include?",
"queue",
"# Publish sms to queue",
"begin",
"x_direct",
".",
"publish",
"(",
"payload",
".",
"to_json",
",",
"mandatory",
":",
"true",
",",
"routing_key",
":",
"get_queue",
"(",
"queue",
")",
".",
"name",
")",
"log_message",
"(",
"\"Publish status: success, Queue : #{queue}, Content : #{payload}\"",
")",
":success",
"rescue",
"=>",
"ex",
"log_message",
"(",
"\"Publish error:#{ex.message}\"",
")",
":error",
"end",
"else",
"log_message",
"(",
"\"Publish status: failed, Queue(#{queue}) doesn't exist.\"",
")",
"log_message",
"(",
"\"Content : #{payload}\"",
")",
"raise",
"QueueNotFoundError",
"end",
"end"
] |
Initialize
Instance methods
Publish message to the respective queue
|
[
"Initialize",
"Instance",
"methods",
"Publish",
"message",
"to",
"the",
"respective",
"queue"
] |
3b16451e38c430f05c0ac5fb111cfc96e4dc34b8
|
https://github.com/ashiksp/smart_que/blob/3b16451e38c430f05c0ac5fb111cfc96e4dc34b8/lib/smart_que/publisher.rb#L16-L38
|
10,023
|
ashiksp/smart_que
|
lib/smart_que/publisher.rb
|
SmartQue.Publisher.unicast
|
def unicast(q_name, payload = {})
begin
x_default.publish(
payload.to_json,
routing_key: dot_formatted(q_name)
)
log_message("unicast status: success, Queue : #{q_name}, Content : #{payload}")
:success
rescue => ex
log_message("Unicast error:#{ex.message}")
:error
end
end
|
ruby
|
def unicast(q_name, payload = {})
begin
x_default.publish(
payload.to_json,
routing_key: dot_formatted(q_name)
)
log_message("unicast status: success, Queue : #{q_name}, Content : #{payload}")
:success
rescue => ex
log_message("Unicast error:#{ex.message}")
:error
end
end
|
[
"def",
"unicast",
"(",
"q_name",
",",
"payload",
"=",
"{",
"}",
")",
"begin",
"x_default",
".",
"publish",
"(",
"payload",
".",
"to_json",
",",
"routing_key",
":",
"dot_formatted",
"(",
"q_name",
")",
")",
"log_message",
"(",
"\"unicast status: success, Queue : #{q_name}, Content : #{payload}\"",
")",
":success",
"rescue",
"=>",
"ex",
"log_message",
"(",
"\"Unicast error:#{ex.message}\"",
")",
":error",
"end",
"end"
] |
unicast message to queues
|
[
"unicast",
"message",
"to",
"queues"
] |
3b16451e38c430f05c0ac5fb111cfc96e4dc34b8
|
https://github.com/ashiksp/smart_que/blob/3b16451e38c430f05c0ac5fb111cfc96e4dc34b8/lib/smart_que/publisher.rb#L41-L53
|
10,024
|
ashiksp/smart_que
|
lib/smart_que/publisher.rb
|
SmartQue.Publisher.multicast
|
def multicast(topic, payload = {})
begin
x_topic.publish(
payload.to_json,
routing_key: dot_formatted(topic)
)
log_message("multicast status: success, Topic : #{topic}, Content : #{payload}")
:success
rescue => ex
log_message("Multicast error:#{ex.message}")
:error
end
end
|
ruby
|
def multicast(topic, payload = {})
begin
x_topic.publish(
payload.to_json,
routing_key: dot_formatted(topic)
)
log_message("multicast status: success, Topic : #{topic}, Content : #{payload}")
:success
rescue => ex
log_message("Multicast error:#{ex.message}")
:error
end
end
|
[
"def",
"multicast",
"(",
"topic",
",",
"payload",
"=",
"{",
"}",
")",
"begin",
"x_topic",
".",
"publish",
"(",
"payload",
".",
"to_json",
",",
"routing_key",
":",
"dot_formatted",
"(",
"topic",
")",
")",
"log_message",
"(",
"\"multicast status: success, Topic : #{topic}, Content : #{payload}\"",
")",
":success",
"rescue",
"=>",
"ex",
"log_message",
"(",
"\"Multicast error:#{ex.message}\"",
")",
":error",
"end",
"end"
] |
multicast message to queues based on topic subscription
|
[
"multicast",
"message",
"to",
"queues",
"based",
"on",
"topic",
"subscription"
] |
3b16451e38c430f05c0ac5fb111cfc96e4dc34b8
|
https://github.com/ashiksp/smart_que/blob/3b16451e38c430f05c0ac5fb111cfc96e4dc34b8/lib/smart_que/publisher.rb#L57-L69
|
10,025
|
celldee/ffi-rxs
|
lib/ffi-rxs/poll_items.rb
|
XS.PollItems.clean
|
def clean
if @dirty
@store = FFI::MemoryPointer.new @element_size, @items.size, true
# copy over
offset = 0
@items.each do |item|
LibC.memcpy(@store + offset, item.pointer, @element_size)
offset += @element_size
end
@dirty = false
end
end
|
ruby
|
def clean
if @dirty
@store = FFI::MemoryPointer.new @element_size, @items.size, true
# copy over
offset = 0
@items.each do |item|
LibC.memcpy(@store + offset, item.pointer, @element_size)
offset += @element_size
end
@dirty = false
end
end
|
[
"def",
"clean",
"if",
"@dirty",
"@store",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"@element_size",
",",
"@items",
".",
"size",
",",
"true",
"# copy over",
"offset",
"=",
"0",
"@items",
".",
"each",
"do",
"|",
"item",
"|",
"LibC",
".",
"memcpy",
"(",
"@store",
"+",
"offset",
",",
"item",
".",
"pointer",
",",
"@element_size",
")",
"offset",
"+=",
"@element_size",
"end",
"@dirty",
"=",
"false",
"end",
"end"
] |
Allocate a contiguous chunk of memory and copy over the PollItem structs
to this block. Note that the old +@store+ value goes out of scope so when
it is garbage collected that native memory should be automatically freed.
|
[
"Allocate",
"a",
"contiguous",
"chunk",
"of",
"memory",
"and",
"copy",
"over",
"the",
"PollItem",
"structs",
"to",
"this",
"block",
".",
"Note",
"that",
"the",
"old",
"+"
] |
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
|
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/poll_items.rb#L105-L118
|
10,026
|
pione/ruby-xes
|
lib/xes/attribute.rb
|
XES.Attribute.format_value
|
def format_value
case @type
when "string"
@value
when "date"
@value.kind_of?(Time) ? @value.iso8601(3) : @value
when "int"
@value.kind_of?(Integer) ? @value : @value.to_i
when "float"
@value.kind_of?(Float) ? @value : @value.to_f
when "boolean"
@value
when "id"
@value
end.to_s
end
|
ruby
|
def format_value
case @type
when "string"
@value
when "date"
@value.kind_of?(Time) ? @value.iso8601(3) : @value
when "int"
@value.kind_of?(Integer) ? @value : @value.to_i
when "float"
@value.kind_of?(Float) ? @value : @value.to_f
when "boolean"
@value
when "id"
@value
end.to_s
end
|
[
"def",
"format_value",
"case",
"@type",
"when",
"\"string\"",
"@value",
"when",
"\"date\"",
"@value",
".",
"kind_of?",
"(",
"Time",
")",
"?",
"@value",
".",
"iso8601",
"(",
"3",
")",
":",
"@value",
"when",
"\"int\"",
"@value",
".",
"kind_of?",
"(",
"Integer",
")",
"?",
"@value",
":",
"@value",
".",
"to_i",
"when",
"\"float\"",
"@value",
".",
"kind_of?",
"(",
"Float",
")",
"?",
"@value",
":",
"@value",
".",
"to_f",
"when",
"\"boolean\"",
"@value",
"when",
"\"id\"",
"@value",
"end",
".",
"to_s",
"end"
] |
Format the value.
@return [String]
|
[
"Format",
"the",
"value",
"."
] |
61501a8fd8027708f670264a150b1ce74fdccd74
|
https://github.com/pione/ruby-xes/blob/61501a8fd8027708f670264a150b1ce74fdccd74/lib/xes/attribute.rb#L98-L113
|
10,027
|
choonkeat/active_params
|
lib/active_params/parser.rb
|
ActiveParams.Parser.combine_hashes
|
def combine_hashes(array_of_hashes)
array_of_hashes.select {|v| v.kind_of?(Hash) }.
inject({}) {|sum, hash| hash.inject(sum) {|sum,(k,v)| sum.merge(k => v) } }
end
|
ruby
|
def combine_hashes(array_of_hashes)
array_of_hashes.select {|v| v.kind_of?(Hash) }.
inject({}) {|sum, hash| hash.inject(sum) {|sum,(k,v)| sum.merge(k => v) } }
end
|
[
"def",
"combine_hashes",
"(",
"array_of_hashes",
")",
"array_of_hashes",
".",
"select",
"{",
"|",
"v",
"|",
"v",
".",
"kind_of?",
"(",
"Hash",
")",
"}",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"sum",
",",
"hash",
"|",
"hash",
".",
"inject",
"(",
"sum",
")",
"{",
"|",
"sum",
",",
"(",
"k",
",",
"v",
")",
"|",
"sum",
".",
"merge",
"(",
"k",
"=>",
"v",
")",
"}",
"}",
"end"
] |
to obtain a hash of all possible keys
|
[
"to",
"obtain",
"a",
"hash",
"of",
"all",
"possible",
"keys"
] |
e0fa9dc928bbb363aa72ee4bb717e75ba6bfc6ce
|
https://github.com/choonkeat/active_params/blob/e0fa9dc928bbb363aa72ee4bb717e75ba6bfc6ce/lib/active_params/parser.rb#L4-L7
|
10,028
|
NYULibraries/citero-jruby
|
lib/citero-jruby/base.rb
|
Citero.Base.from
|
def from format
#Formats are enums in java, so they are all uppercase
@citero = @citero::from(Formats::valueOf(format.upcase))
self
#rescue any exceptions, if the error is not caught in JAR, most likely a
#problem with the data
rescue Exception => e
raise TypeError, "Mismatched data for #{format}"
end
|
ruby
|
def from format
#Formats are enums in java, so they are all uppercase
@citero = @citero::from(Formats::valueOf(format.upcase))
self
#rescue any exceptions, if the error is not caught in JAR, most likely a
#problem with the data
rescue Exception => e
raise TypeError, "Mismatched data for #{format}"
end
|
[
"def",
"from",
"format",
"#Formats are enums in java, so they are all uppercase",
"@citero",
"=",
"@citero",
"::",
"from",
"(",
"Formats",
"::",
"valueOf",
"(",
"format",
".",
"upcase",
")",
")",
"self",
"#rescue any exceptions, if the error is not caught in JAR, most likely a ",
"#problem with the data",
"rescue",
"Exception",
"=>",
"e",
"raise",
"TypeError",
",",
"\"Mismatched data for #{format}\"",
"end"
] |
The constructor, takes input data taken from the parent module
and creates an instance of the Citero java object.
Returns itself for builder patttern.
The from method is private, it takes in a format and gets
the appropriate Format java class and then calls
the from method in the Citero java object and stores its
return value in an instance variable.
Returns itself.
|
[
"The",
"constructor",
"takes",
"input",
"data",
"taken",
"from",
"the",
"parent",
"module",
"and",
"creates",
"an",
"instance",
"of",
"the",
"Citero",
"java",
"object",
".",
"Returns",
"itself",
"for",
"builder",
"patttern",
".",
"The",
"from",
"method",
"is",
"private",
"it",
"takes",
"in",
"a",
"format",
"and",
"gets",
"the",
"appropriate",
"Format",
"java",
"class",
"and",
"then",
"calls",
"the",
"from",
"method",
"in",
"the",
"Citero",
"java",
"object",
"and",
"stores",
"its",
"return",
"value",
"in",
"an",
"instance",
"variable",
".",
"Returns",
"itself",
"."
] |
ddf1142a8a05cb1e7153d1887239fe913df563ce
|
https://github.com/NYULibraries/citero-jruby/blob/ddf1142a8a05cb1e7153d1887239fe913df563ce/lib/citero-jruby/base.rb#L54-L62
|
10,029
|
NYULibraries/citero-jruby
|
lib/citero-jruby/base.rb
|
Citero.Base.to
|
def to format
#Formats are enums in java, so they are all uppercase
if to_formats.include? format
@citero::to(Formats::valueOf(format.upcase))
else
@citero::to(CitationStyles::valueOf(format.upcase))
end
#rescue any exceptions, if the error is not caught in JAR, most likely a
#problem with the source format
rescue Exception => e
raise ArgumentError, "Missing a source format. Use from_[format] first."
end
|
ruby
|
def to format
#Formats are enums in java, so they are all uppercase
if to_formats.include? format
@citero::to(Formats::valueOf(format.upcase))
else
@citero::to(CitationStyles::valueOf(format.upcase))
end
#rescue any exceptions, if the error is not caught in JAR, most likely a
#problem with the source format
rescue Exception => e
raise ArgumentError, "Missing a source format. Use from_[format] first."
end
|
[
"def",
"to",
"format",
"#Formats are enums in java, so they are all uppercase",
"if",
"to_formats",
".",
"include?",
"format",
"@citero",
"::",
"to",
"(",
"Formats",
"::",
"valueOf",
"(",
"format",
".",
"upcase",
")",
")",
"else",
"@citero",
"::",
"to",
"(",
"CitationStyles",
"::",
"valueOf",
"(",
"format",
".",
"upcase",
")",
")",
"end",
"#rescue any exceptions, if the error is not caught in JAR, most likely a ",
"#problem with the source format",
"rescue",
"Exception",
"=>",
"e",
"raise",
"ArgumentError",
",",
"\"Missing a source format. Use from_[format] first.\"",
"end"
] |
The to method is private, it takes in a format and gets
the appropriate Format java class and then calls
the to method in the Citero java object and returns the
return value as a string.
|
[
"The",
"to",
"method",
"is",
"private",
"it",
"takes",
"in",
"a",
"format",
"and",
"gets",
"the",
"appropriate",
"Format",
"java",
"class",
"and",
"then",
"calls",
"the",
"to",
"method",
"in",
"the",
"Citero",
"java",
"object",
"and",
"returns",
"the",
"return",
"value",
"as",
"a",
"string",
"."
] |
ddf1142a8a05cb1e7153d1887239fe913df563ce
|
https://github.com/NYULibraries/citero-jruby/blob/ddf1142a8a05cb1e7153d1887239fe913df563ce/lib/citero-jruby/base.rb#L69-L80
|
10,030
|
postmodern/data_paths
|
lib/data_paths/finders.rb
|
DataPaths.Finders.each_data_path
|
def each_data_path(path)
return enum_for(:each_data_path,path) unless block_given?
DataPaths.paths.each do |dir|
full_path = File.join(dir,path)
yield(full_path) if File.exists?(full_path)
end
end
|
ruby
|
def each_data_path(path)
return enum_for(:each_data_path,path) unless block_given?
DataPaths.paths.each do |dir|
full_path = File.join(dir,path)
yield(full_path) if File.exists?(full_path)
end
end
|
[
"def",
"each_data_path",
"(",
"path",
")",
"return",
"enum_for",
"(",
":each_data_path",
",",
"path",
")",
"unless",
"block_given?",
"DataPaths",
".",
"paths",
".",
"each",
"do",
"|",
"dir",
"|",
"full_path",
"=",
"File",
".",
"join",
"(",
"dir",
",",
"path",
")",
"yield",
"(",
"full_path",
")",
"if",
"File",
".",
"exists?",
"(",
"full_path",
")",
"end",
"end"
] |
Passes all existing data paths for the specified path,
within the data directories, to the given block.
@param [String] path
The path to search for in all data directories.
@yield [potential_path]
The given block will be passed every existing combination of the
given path and the data directories.
@yieldparam [String] potential_path
An existing data path.
@return [Enumerator]
If no block is given, an Enumerator object will be returned.
|
[
"Passes",
"all",
"existing",
"data",
"paths",
"for",
"the",
"specified",
"path",
"within",
"the",
"data",
"directories",
"to",
"the",
"given",
"block",
"."
] |
17938884593b458b90b591a353686945884749d6
|
https://github.com/postmodern/data_paths/blob/17938884593b458b90b591a353686945884749d6/lib/data_paths/finders.rb#L24-L32
|
10,031
|
postmodern/data_paths
|
lib/data_paths/finders.rb
|
DataPaths.Finders.each_data_file
|
def each_data_file(path)
return enum_for(:each_data_file,path) unless block_given?
each_data_path(path) do |full_path|
yield(full_path) if File.file?(full_path)
end
end
|
ruby
|
def each_data_file(path)
return enum_for(:each_data_file,path) unless block_given?
each_data_path(path) do |full_path|
yield(full_path) if File.file?(full_path)
end
end
|
[
"def",
"each_data_file",
"(",
"path",
")",
"return",
"enum_for",
"(",
":each_data_file",
",",
"path",
")",
"unless",
"block_given?",
"each_data_path",
"(",
"path",
")",
"do",
"|",
"full_path",
"|",
"yield",
"(",
"full_path",
")",
"if",
"File",
".",
"file?",
"(",
"full_path",
")",
"end",
"end"
] |
Finds all occurrences of a given file path, within all data
directories.
@param [String] path
The file path to search for.
@yield [data_file]
If a block is given, it will be passed every found path.
@yieldparam [String] data_file
The path of a file within a data directory.
@return [Enumerator]
If no block is given, an Enumerator object will be returned.
|
[
"Finds",
"all",
"occurrences",
"of",
"a",
"given",
"file",
"path",
"within",
"all",
"data",
"directories",
"."
] |
17938884593b458b90b591a353686945884749d6
|
https://github.com/postmodern/data_paths/blob/17938884593b458b90b591a353686945884749d6/lib/data_paths/finders.rb#L126-L132
|
10,032
|
postmodern/data_paths
|
lib/data_paths/finders.rb
|
DataPaths.Finders.each_data_dir
|
def each_data_dir(path)
return enum_for(:each_data_dir,path) unless block_given?
each_data_path(path) do |full_path|
yield(full_path) if File.directory?(full_path)
end
end
|
ruby
|
def each_data_dir(path)
return enum_for(:each_data_dir,path) unless block_given?
each_data_path(path) do |full_path|
yield(full_path) if File.directory?(full_path)
end
end
|
[
"def",
"each_data_dir",
"(",
"path",
")",
"return",
"enum_for",
"(",
":each_data_dir",
",",
"path",
")",
"unless",
"block_given?",
"each_data_path",
"(",
"path",
")",
"do",
"|",
"full_path",
"|",
"yield",
"(",
"full_path",
")",
"if",
"File",
".",
"directory?",
"(",
"full_path",
")",
"end",
"end"
] |
Finds all occurrences of a given directory path, within all data
directories.
@param [String] path
The directory path to search for.
@yield [data_dir]
If a block is given, it will be passed every found path.
@yieldparam [String] data_dir
The path of a directory within a data directory.
@return [Enumerator]
If no block is given, an Enumerator object will be returned.
|
[
"Finds",
"all",
"occurrences",
"of",
"a",
"given",
"directory",
"path",
"within",
"all",
"data",
"directories",
"."
] |
17938884593b458b90b591a353686945884749d6
|
https://github.com/postmodern/data_paths/blob/17938884593b458b90b591a353686945884749d6/lib/data_paths/finders.rb#L182-L188
|
10,033
|
postmodern/data_paths
|
lib/data_paths/finders.rb
|
DataPaths.Finders.glob_data_paths
|
def glob_data_paths(pattern,&block)
return enum_for(:glob_data_paths,pattern).to_a unless block_given?
DataPaths.paths.each do |path|
Dir.glob(File.join(path,pattern),&block)
end
end
|
ruby
|
def glob_data_paths(pattern,&block)
return enum_for(:glob_data_paths,pattern).to_a unless block_given?
DataPaths.paths.each do |path|
Dir.glob(File.join(path,pattern),&block)
end
end
|
[
"def",
"glob_data_paths",
"(",
"pattern",
",",
"&",
"block",
")",
"return",
"enum_for",
"(",
":glob_data_paths",
",",
"pattern",
")",
".",
"to_a",
"unless",
"block_given?",
"DataPaths",
".",
"paths",
".",
"each",
"do",
"|",
"path",
"|",
"Dir",
".",
"glob",
"(",
"File",
".",
"join",
"(",
"path",
",",
"pattern",
")",
",",
"block",
")",
"end",
"end"
] |
Finds all paths that match a given pattern, within all data
directories.
@param [String] pattern
The path glob pattern to search with.
@yield [path]
If a block is given, it will be passed every matching path.
@yieldparam [String] path
The path of a matching file within a data directory.
@return [Array<String>]
If no block is given, the matching paths found within all data
directories will be returned.
@since 0.3.0
|
[
"Finds",
"all",
"paths",
"that",
"match",
"a",
"given",
"pattern",
"within",
"all",
"data",
"directories",
"."
] |
17938884593b458b90b591a353686945884749d6
|
https://github.com/postmodern/data_paths/blob/17938884593b458b90b591a353686945884749d6/lib/data_paths/finders.rb#L224-L230
|
10,034
|
brianpattison/motion-loco
|
lib/motion-loco/resizable.rb
|
Loco.Resizable.initWithFrame
|
def initWithFrame(properties={})
if properties.is_a? Hash
# Set the initial property values from the given hash
super(CGRect.new)
initialize_bindings
set_properties(properties)
else
super(properties)
end
view_setup
self
end
|
ruby
|
def initWithFrame(properties={})
if properties.is_a? Hash
# Set the initial property values from the given hash
super(CGRect.new)
initialize_bindings
set_properties(properties)
else
super(properties)
end
view_setup
self
end
|
[
"def",
"initWithFrame",
"(",
"properties",
"=",
"{",
"}",
")",
"if",
"properties",
".",
"is_a?",
"Hash",
"# Set the initial property values from the given hash",
"super",
"(",
"CGRect",
".",
"new",
")",
"initialize_bindings",
"set_properties",
"(",
"properties",
")",
"else",
"super",
"(",
"properties",
")",
"end",
"view_setup",
"self",
"end"
] |
Create new instance from a hash of properties with values.
@param [Object] frame The CGRect or a Hash of properties.
|
[
"Create",
"new",
"instance",
"from",
"a",
"hash",
"of",
"properties",
"with",
"values",
"."
] |
d6f4ca32d6e13dc4d325d2838c0e2685fa0fa4f6
|
https://github.com/brianpattison/motion-loco/blob/d6f4ca32d6e13dc4d325d2838c0e2685fa0fa4f6/lib/motion-loco/resizable.rb#L113-L125
|
10,035
|
karlfreeman/multi_sync
|
lib/multi_sync/client.rb
|
MultiSync.Client.add_target
|
def add_target(clazz, options = {})
# TODO: friendly pool names?
pool_name = Celluloid.uuid
supervisor.pool(clazz, as: pool_name, args: [options], size: MultiSync.target_pool_size)
pool_name
end
|
ruby
|
def add_target(clazz, options = {})
# TODO: friendly pool names?
pool_name = Celluloid.uuid
supervisor.pool(clazz, as: pool_name, args: [options], size: MultiSync.target_pool_size)
pool_name
end
|
[
"def",
"add_target",
"(",
"clazz",
",",
"options",
"=",
"{",
"}",
")",
"# TODO: friendly pool names?",
"pool_name",
"=",
"Celluloid",
".",
"uuid",
"supervisor",
".",
"pool",
"(",
"clazz",
",",
"as",
":",
"pool_name",
",",
"args",
":",
"[",
"options",
"]",
",",
"size",
":",
"MultiSync",
".",
"target_pool_size",
")",
"pool_name",
"end"
] |
Initialize a new Client object
@param options [Hash]
|
[
"Initialize",
"a",
"new",
"Client",
"object"
] |
a24b0865a00093701d2b04888a930b453185686d
|
https://github.com/karlfreeman/multi_sync/blob/a24b0865a00093701d2b04888a930b453185686d/lib/multi_sync/client.rb#L39-L44
|
10,036
|
charypar/cyclical
|
lib/cyclical/rules/yearly_rule.rb
|
Cyclical.YearlyRule.potential_next
|
def potential_next(current, base)
candidate = super(current, base)
return candidate if (base.year - candidate.year).to_i % @interval == 0
years = ((base.year - candidate.year).to_i % @interval)
(candidate + years.years).beginning_of_year
end
|
ruby
|
def potential_next(current, base)
candidate = super(current, base)
return candidate if (base.year - candidate.year).to_i % @interval == 0
years = ((base.year - candidate.year).to_i % @interval)
(candidate + years.years).beginning_of_year
end
|
[
"def",
"potential_next",
"(",
"current",
",",
"base",
")",
"candidate",
"=",
"super",
"(",
"current",
",",
"base",
")",
"return",
"candidate",
"if",
"(",
"base",
".",
"year",
"-",
"candidate",
".",
"year",
")",
".",
"to_i",
"%",
"@interval",
"==",
"0",
"years",
"=",
"(",
"(",
"base",
".",
"year",
"-",
"candidate",
".",
"year",
")",
".",
"to_i",
"%",
"@interval",
")",
"(",
"candidate",
"+",
"years",
".",
"years",
")",
".",
"beginning_of_year",
"end"
] |
closest valid date
|
[
"closest",
"valid",
"date"
] |
8e45b8f83e2dd59fcad01e220412bb361867f5c6
|
https://github.com/charypar/cyclical/blob/8e45b8f83e2dd59fcad01e220412bb361867f5c6/lib/cyclical/rules/yearly_rule.rb#L26-L33
|
10,037
|
sanichi/icu_tournament
|
lib/icu_tournament/tournament.rb
|
ICU.Tournament.fed=
|
def fed=(fed)
obj = ICU::Federation.find(fed)
@fed = obj ? obj.code : nil
raise "invalid tournament federation (#{fed})" if @fed.nil? && fed.to_s.strip.length > 0
end
|
ruby
|
def fed=(fed)
obj = ICU::Federation.find(fed)
@fed = obj ? obj.code : nil
raise "invalid tournament federation (#{fed})" if @fed.nil? && fed.to_s.strip.length > 0
end
|
[
"def",
"fed",
"=",
"(",
"fed",
")",
"obj",
"=",
"ICU",
"::",
"Federation",
".",
"find",
"(",
"fed",
")",
"@fed",
"=",
"obj",
"?",
"obj",
".",
"code",
":",
"nil",
"raise",
"\"invalid tournament federation (#{fed})\"",
"if",
"@fed",
".",
"nil?",
"&&",
"fed",
".",
"to_s",
".",
"strip",
".",
"length",
">",
"0",
"end"
] |
Constructor. Name and start date must be supplied. Other attributes are optional.
Set the tournament federation. Can be _nil_.
|
[
"Constructor",
".",
"Name",
"and",
"start",
"date",
"must",
"be",
"supplied",
".",
"Other",
"attributes",
"are",
"optional",
".",
"Set",
"the",
"tournament",
"federation",
".",
"Can",
"be",
"_nil_",
"."
] |
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
|
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L218-L222
|
10,038
|
sanichi/icu_tournament
|
lib/icu_tournament/tournament.rb
|
ICU.Tournament.add_round_date
|
def add_round_date(round_date)
round_date = round_date.to_s.strip
parsed_date = Util::Date.parse(round_date)
raise "invalid round date (#{round_date})" unless parsed_date
@round_dates << parsed_date
end
|
ruby
|
def add_round_date(round_date)
round_date = round_date.to_s.strip
parsed_date = Util::Date.parse(round_date)
raise "invalid round date (#{round_date})" unless parsed_date
@round_dates << parsed_date
end
|
[
"def",
"add_round_date",
"(",
"round_date",
")",
"round_date",
"=",
"round_date",
".",
"to_s",
".",
"strip",
"parsed_date",
"=",
"Util",
"::",
"Date",
".",
"parse",
"(",
"round_date",
")",
"raise",
"\"invalid round date (#{round_date})\"",
"unless",
"parsed_date",
"@round_dates",
"<<",
"parsed_date",
"end"
] |
Add a round date.
|
[
"Add",
"a",
"round",
"date",
"."
] |
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
|
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L225-L230
|
10,039
|
sanichi/icu_tournament
|
lib/icu_tournament/tournament.rb
|
ICU.Tournament.tie_breaks=
|
def tie_breaks=(tie_breaks)
raise "argument error - always set tie breaks to an array" unless tie_breaks.class == Array
@tie_breaks = tie_breaks.map do |str|
tb = ICU::TieBreak.identify(str)
raise "invalid tie break method '#{str}'" unless tb
tb.id
end
end
|
ruby
|
def tie_breaks=(tie_breaks)
raise "argument error - always set tie breaks to an array" unless tie_breaks.class == Array
@tie_breaks = tie_breaks.map do |str|
tb = ICU::TieBreak.identify(str)
raise "invalid tie break method '#{str}'" unless tb
tb.id
end
end
|
[
"def",
"tie_breaks",
"=",
"(",
"tie_breaks",
")",
"raise",
"\"argument error - always set tie breaks to an array\"",
"unless",
"tie_breaks",
".",
"class",
"==",
"Array",
"@tie_breaks",
"=",
"tie_breaks",
".",
"map",
"do",
"|",
"str",
"|",
"tb",
"=",
"ICU",
"::",
"TieBreak",
".",
"identify",
"(",
"str",
")",
"raise",
"\"invalid tie break method '#{str}'\"",
"unless",
"tb",
"tb",
".",
"id",
"end",
"end"
] |
Canonicalise the names in the tie break array.
|
[
"Canonicalise",
"the",
"names",
"in",
"the",
"tie",
"break",
"array",
"."
] |
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
|
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L271-L278
|
10,040
|
sanichi/icu_tournament
|
lib/icu_tournament/tournament.rb
|
ICU.Tournament.add_player
|
def add_player(player)
raise "invalid player" unless player.class == ICU::Player
raise "player number (#{player.num}) should be unique" if @player[player.num]
@player[player.num] = player
end
|
ruby
|
def add_player(player)
raise "invalid player" unless player.class == ICU::Player
raise "player number (#{player.num}) should be unique" if @player[player.num]
@player[player.num] = player
end
|
[
"def",
"add_player",
"(",
"player",
")",
"raise",
"\"invalid player\"",
"unless",
"player",
".",
"class",
"==",
"ICU",
"::",
"Player",
"raise",
"\"player number (#{player.num}) should be unique\"",
"if",
"@player",
"[",
"player",
".",
"num",
"]",
"@player",
"[",
"player",
".",
"num",
"]",
"=",
"player",
"end"
] |
Add a new player to the tournament. Must have a unique player number.
|
[
"Add",
"a",
"new",
"player",
"to",
"the",
"tournament",
".",
"Must",
"have",
"a",
"unique",
"player",
"number",
"."
] |
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
|
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L281-L285
|
10,041
|
sanichi/icu_tournament
|
lib/icu_tournament/tournament.rb
|
ICU.Tournament.rerank
|
def rerank
tie_break_methods, tie_break_order, tie_break_hash = tie_break_data
@player.values.sort do |a,b|
cmp = 0
tie_break_methods.each do |m|
cmp = (tie_break_hash[m][a.num] <=> tie_break_hash[m][b.num]) * tie_break_order[m] if cmp == 0
end
cmp
end.each_with_index do |p,i|
p.rank = i + 1
end
self
end
|
ruby
|
def rerank
tie_break_methods, tie_break_order, tie_break_hash = tie_break_data
@player.values.sort do |a,b|
cmp = 0
tie_break_methods.each do |m|
cmp = (tie_break_hash[m][a.num] <=> tie_break_hash[m][b.num]) * tie_break_order[m] if cmp == 0
end
cmp
end.each_with_index do |p,i|
p.rank = i + 1
end
self
end
|
[
"def",
"rerank",
"tie_break_methods",
",",
"tie_break_order",
",",
"tie_break_hash",
"=",
"tie_break_data",
"@player",
".",
"values",
".",
"sort",
"do",
"|",
"a",
",",
"b",
"|",
"cmp",
"=",
"0",
"tie_break_methods",
".",
"each",
"do",
"|",
"m",
"|",
"cmp",
"=",
"(",
"tie_break_hash",
"[",
"m",
"]",
"[",
"a",
".",
"num",
"]",
"<=>",
"tie_break_hash",
"[",
"m",
"]",
"[",
"b",
".",
"num",
"]",
")",
"*",
"tie_break_order",
"[",
"m",
"]",
"if",
"cmp",
"==",
"0",
"end",
"cmp",
"end",
".",
"each_with_index",
"do",
"|",
"p",
",",
"i",
"|",
"p",
".",
"rank",
"=",
"i",
"+",
"1",
"end",
"self",
"end"
] |
Rerank the tournament by score first and if necessary using a configurable tie breaker method.
|
[
"Rerank",
"the",
"tournament",
"by",
"score",
"first",
"and",
"if",
"necessary",
"using",
"a",
"configurable",
"tie",
"breaker",
"method",
"."
] |
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
|
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L319-L331
|
10,042
|
sanichi/icu_tournament
|
lib/icu_tournament/tournament.rb
|
ICU.Tournament.renumber
|
def renumber(criterion = :rank)
if (criterion.class == Hash)
# Undocumentted feature - supply your own hash.
map = criterion
else
# Official way of reordering.
map = Hash.new
# Renumber by rank only if possible.
criterion = criterion.to_s.downcase
if criterion == 'rank'
begin check_ranks rescue criterion = 'name' end
end
# Decide how to renumber.
if criterion == 'rank'
# Renumber by rank.
@player.values.each{ |p| map[p.num] = p.rank }
elsif criterion == 'order'
# Just keep the existing numbers in order.
@player.values.sort_by{ |p| p.num }.each_with_index{ |p, i| map[p.num] = i + 1 }
else
# Renumber by name alphabetically.
@player.values.sort_by{ |p| p.name }.each_with_index{ |p, i| map[p.num] = i + 1 }
end
end
# Apply renumbering.
@teams.each{ |t| t.renumber(map) }
@player = @player.values.inject({}) do |hash, player|
player.renumber(map)
hash[player.num] = player
hash
end
# Return self for chaining.
self
end
|
ruby
|
def renumber(criterion = :rank)
if (criterion.class == Hash)
# Undocumentted feature - supply your own hash.
map = criterion
else
# Official way of reordering.
map = Hash.new
# Renumber by rank only if possible.
criterion = criterion.to_s.downcase
if criterion == 'rank'
begin check_ranks rescue criterion = 'name' end
end
# Decide how to renumber.
if criterion == 'rank'
# Renumber by rank.
@player.values.each{ |p| map[p.num] = p.rank }
elsif criterion == 'order'
# Just keep the existing numbers in order.
@player.values.sort_by{ |p| p.num }.each_with_index{ |p, i| map[p.num] = i + 1 }
else
# Renumber by name alphabetically.
@player.values.sort_by{ |p| p.name }.each_with_index{ |p, i| map[p.num] = i + 1 }
end
end
# Apply renumbering.
@teams.each{ |t| t.renumber(map) }
@player = @player.values.inject({}) do |hash, player|
player.renumber(map)
hash[player.num] = player
hash
end
# Return self for chaining.
self
end
|
[
"def",
"renumber",
"(",
"criterion",
"=",
":rank",
")",
"if",
"(",
"criterion",
".",
"class",
"==",
"Hash",
")",
"# Undocumentted feature - supply your own hash.",
"map",
"=",
"criterion",
"else",
"# Official way of reordering.",
"map",
"=",
"Hash",
".",
"new",
"# Renumber by rank only if possible.",
"criterion",
"=",
"criterion",
".",
"to_s",
".",
"downcase",
"if",
"criterion",
"==",
"'rank'",
"begin",
"check_ranks",
"rescue",
"criterion",
"=",
"'name'",
"end",
"end",
"# Decide how to renumber.",
"if",
"criterion",
"==",
"'rank'",
"# Renumber by rank.",
"@player",
".",
"values",
".",
"each",
"{",
"|",
"p",
"|",
"map",
"[",
"p",
".",
"num",
"]",
"=",
"p",
".",
"rank",
"}",
"elsif",
"criterion",
"==",
"'order'",
"# Just keep the existing numbers in order.",
"@player",
".",
"values",
".",
"sort_by",
"{",
"|",
"p",
"|",
"p",
".",
"num",
"}",
".",
"each_with_index",
"{",
"|",
"p",
",",
"i",
"|",
"map",
"[",
"p",
".",
"num",
"]",
"=",
"i",
"+",
"1",
"}",
"else",
"# Renumber by name alphabetically.",
"@player",
".",
"values",
".",
"sort_by",
"{",
"|",
"p",
"|",
"p",
".",
"name",
"}",
".",
"each_with_index",
"{",
"|",
"p",
",",
"i",
"|",
"map",
"[",
"p",
".",
"num",
"]",
"=",
"i",
"+",
"1",
"}",
"end",
"end",
"# Apply renumbering.",
"@teams",
".",
"each",
"{",
"|",
"t",
"|",
"t",
".",
"renumber",
"(",
"map",
")",
"}",
"@player",
"=",
"@player",
".",
"values",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"hash",
",",
"player",
"|",
"player",
".",
"renumber",
"(",
"map",
")",
"hash",
"[",
"player",
".",
"num",
"]",
"=",
"player",
"hash",
"end",
"# Return self for chaining.",
"self",
"end"
] |
Renumber the players according to a given criterion.
|
[
"Renumber",
"the",
"players",
"according",
"to",
"a",
"given",
"criterion",
"."
] |
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
|
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L343-L380
|
10,043
|
sanichi/icu_tournament
|
lib/icu_tournament/tournament.rb
|
ICU.Tournament.validate!
|
def validate!(options={})
begin check_ranks rescue rerank end if options[:rerank]
check_players
check_rounds
check_dates
check_teams
check_ranks(:allow_none => true)
check_type(options[:type]) if options[:type]
true
end
|
ruby
|
def validate!(options={})
begin check_ranks rescue rerank end if options[:rerank]
check_players
check_rounds
check_dates
check_teams
check_ranks(:allow_none => true)
check_type(options[:type]) if options[:type]
true
end
|
[
"def",
"validate!",
"(",
"options",
"=",
"{",
"}",
")",
"begin",
"check_ranks",
"rescue",
"rerank",
"end",
"if",
"options",
"[",
":rerank",
"]",
"check_players",
"check_rounds",
"check_dates",
"check_teams",
"check_ranks",
"(",
":allow_none",
"=>",
"true",
")",
"check_type",
"(",
"options",
"[",
":type",
"]",
")",
"if",
"options",
"[",
":type",
"]",
"true",
"end"
] |
Raise an exception if a tournament is not valid. The _rerank_ option can be set to _true_
to rank the tournament just prior to the test if ranking data is missing or inconsistent.
|
[
"Raise",
"an",
"exception",
"if",
"a",
"tournament",
"is",
"not",
"valid",
".",
"The",
"_rerank_",
"option",
"can",
"be",
"set",
"to",
"_true_",
"to",
"rank",
"the",
"tournament",
"just",
"prior",
"to",
"the",
"test",
"if",
"ranking",
"data",
"is",
"missing",
"or",
"inconsistent",
"."
] |
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
|
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L395-L404
|
10,044
|
sanichi/icu_tournament
|
lib/icu_tournament/tournament.rb
|
ICU.Tournament.serialize
|
def serialize(format, arg={})
serializer = case format.to_s.downcase
when 'krause' then ICU::Tournament::Krause.new
when 'foreigncsv' then ICU::Tournament::ForeignCSV.new
when 'spexport' then ICU::Tournament::SPExport.new
when '' then raise "no format supplied"
else raise "unsupported serialisation format: '#{format}'"
end
serializer.serialize(self, arg)
end
|
ruby
|
def serialize(format, arg={})
serializer = case format.to_s.downcase
when 'krause' then ICU::Tournament::Krause.new
when 'foreigncsv' then ICU::Tournament::ForeignCSV.new
when 'spexport' then ICU::Tournament::SPExport.new
when '' then raise "no format supplied"
else raise "unsupported serialisation format: '#{format}'"
end
serializer.serialize(self, arg)
end
|
[
"def",
"serialize",
"(",
"format",
",",
"arg",
"=",
"{",
"}",
")",
"serializer",
"=",
"case",
"format",
".",
"to_s",
".",
"downcase",
"when",
"'krause'",
"then",
"ICU",
"::",
"Tournament",
"::",
"Krause",
".",
"new",
"when",
"'foreigncsv'",
"then",
"ICU",
"::",
"Tournament",
"::",
"ForeignCSV",
".",
"new",
"when",
"'spexport'",
"then",
"ICU",
"::",
"Tournament",
"::",
"SPExport",
".",
"new",
"when",
"''",
"then",
"raise",
"\"no format supplied\"",
"else",
"raise",
"\"unsupported serialisation format: '#{format}'\"",
"end",
"serializer",
".",
"serialize",
"(",
"self",
",",
"arg",
")",
"end"
] |
Convenience method to serialise the tournament into a supported format.
Throws an exception unless the name of a supported format is supplied
or if the tournament is unsuitable for serialisation in that format.
|
[
"Convenience",
"method",
"to",
"serialise",
"the",
"tournament",
"into",
"a",
"supported",
"format",
".",
"Throws",
"an",
"exception",
"unless",
"the",
"name",
"of",
"a",
"supported",
"format",
"is",
"supplied",
"or",
"if",
"the",
"tournament",
"is",
"unsuitable",
"for",
"serialisation",
"in",
"that",
"format",
"."
] |
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
|
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L423-L432
|
10,045
|
sanichi/icu_tournament
|
lib/icu_tournament/tournament.rb
|
ICU.Tournament.check_players
|
def check_players
raise "the number of players (#{@player.size}) must be at least 2" if @player.size < 2
ids = Hash.new
fide_ids = Hash.new
@player.each do |num, p|
if p.id
raise "duplicate ICU IDs, players #{p.num} and #{ids[p.id]}" if ids[p.id]
ids[p.id] = num
end
if p.fide_id
raise "duplicate FIDE IDs, players #{p.num} and #{fide_ids[p.fide_id]}" if fide_ids[p.fide_id]
fide_ids[p.fide_id] = num
end
return if p.results.size == 0
p.results.each do |r|
next unless r.opponent
opponent = @player[r.opponent]
raise "opponent #{r.opponent} of player #{num} is not in the tournament" unless opponent
o = opponent.find_result(r.round)
raise "opponent #{r.opponent} of player #{num} has no result in round #{r.round}" unless o
score = r.rateable || o.rateable ? [] : [:score]
raise "opponent's result (#{o.inspect}) is not reverse of player's (#{r.inspect})" unless o.reverse.eql?(r, :except => score)
end
end
end
|
ruby
|
def check_players
raise "the number of players (#{@player.size}) must be at least 2" if @player.size < 2
ids = Hash.new
fide_ids = Hash.new
@player.each do |num, p|
if p.id
raise "duplicate ICU IDs, players #{p.num} and #{ids[p.id]}" if ids[p.id]
ids[p.id] = num
end
if p.fide_id
raise "duplicate FIDE IDs, players #{p.num} and #{fide_ids[p.fide_id]}" if fide_ids[p.fide_id]
fide_ids[p.fide_id] = num
end
return if p.results.size == 0
p.results.each do |r|
next unless r.opponent
opponent = @player[r.opponent]
raise "opponent #{r.opponent} of player #{num} is not in the tournament" unless opponent
o = opponent.find_result(r.round)
raise "opponent #{r.opponent} of player #{num} has no result in round #{r.round}" unless o
score = r.rateable || o.rateable ? [] : [:score]
raise "opponent's result (#{o.inspect}) is not reverse of player's (#{r.inspect})" unless o.reverse.eql?(r, :except => score)
end
end
end
|
[
"def",
"check_players",
"raise",
"\"the number of players (#{@player.size}) must be at least 2\"",
"if",
"@player",
".",
"size",
"<",
"2",
"ids",
"=",
"Hash",
".",
"new",
"fide_ids",
"=",
"Hash",
".",
"new",
"@player",
".",
"each",
"do",
"|",
"num",
",",
"p",
"|",
"if",
"p",
".",
"id",
"raise",
"\"duplicate ICU IDs, players #{p.num} and #{ids[p.id]}\"",
"if",
"ids",
"[",
"p",
".",
"id",
"]",
"ids",
"[",
"p",
".",
"id",
"]",
"=",
"num",
"end",
"if",
"p",
".",
"fide_id",
"raise",
"\"duplicate FIDE IDs, players #{p.num} and #{fide_ids[p.fide_id]}\"",
"if",
"fide_ids",
"[",
"p",
".",
"fide_id",
"]",
"fide_ids",
"[",
"p",
".",
"fide_id",
"]",
"=",
"num",
"end",
"return",
"if",
"p",
".",
"results",
".",
"size",
"==",
"0",
"p",
".",
"results",
".",
"each",
"do",
"|",
"r",
"|",
"next",
"unless",
"r",
".",
"opponent",
"opponent",
"=",
"@player",
"[",
"r",
".",
"opponent",
"]",
"raise",
"\"opponent #{r.opponent} of player #{num} is not in the tournament\"",
"unless",
"opponent",
"o",
"=",
"opponent",
".",
"find_result",
"(",
"r",
".",
"round",
")",
"raise",
"\"opponent #{r.opponent} of player #{num} has no result in round #{r.round}\"",
"unless",
"o",
"score",
"=",
"r",
".",
"rateable",
"||",
"o",
".",
"rateable",
"?",
"[",
"]",
":",
"[",
":score",
"]",
"raise",
"\"opponent's result (#{o.inspect}) is not reverse of player's (#{r.inspect})\"",
"unless",
"o",
".",
"reverse",
".",
"eql?",
"(",
"r",
",",
":except",
"=>",
"score",
")",
"end",
"end",
"end"
] |
Check players.
|
[
"Check",
"players",
"."
] |
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
|
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L449-L473
|
10,046
|
sanichi/icu_tournament
|
lib/icu_tournament/tournament.rb
|
ICU.Tournament.check_rounds
|
def check_rounds
round = Hash.new
round_last = last_round
@player.values.each do |p|
p.results.each do |r|
round[r.round] = true
end
end
(1..round_last).each { |r| raise "there are no results for round #{r}" unless round[r] }
if rounds
raise "declared number of rounds is #{rounds} but there are results in later rounds, such as #{round_last}" if rounds < round_last
raise "declared number of rounds is #{rounds} but there are no results with rounds greater than #{round_last}" if rounds > round_last
else
self.rounds = round_last
end
end
|
ruby
|
def check_rounds
round = Hash.new
round_last = last_round
@player.values.each do |p|
p.results.each do |r|
round[r.round] = true
end
end
(1..round_last).each { |r| raise "there are no results for round #{r}" unless round[r] }
if rounds
raise "declared number of rounds is #{rounds} but there are results in later rounds, such as #{round_last}" if rounds < round_last
raise "declared number of rounds is #{rounds} but there are no results with rounds greater than #{round_last}" if rounds > round_last
else
self.rounds = round_last
end
end
|
[
"def",
"check_rounds",
"round",
"=",
"Hash",
".",
"new",
"round_last",
"=",
"last_round",
"@player",
".",
"values",
".",
"each",
"do",
"|",
"p",
"|",
"p",
".",
"results",
".",
"each",
"do",
"|",
"r",
"|",
"round",
"[",
"r",
".",
"round",
"]",
"=",
"true",
"end",
"end",
"(",
"1",
"..",
"round_last",
")",
".",
"each",
"{",
"|",
"r",
"|",
"raise",
"\"there are no results for round #{r}\"",
"unless",
"round",
"[",
"r",
"]",
"}",
"if",
"rounds",
"raise",
"\"declared number of rounds is #{rounds} but there are results in later rounds, such as #{round_last}\"",
"if",
"rounds",
"<",
"round_last",
"raise",
"\"declared number of rounds is #{rounds} but there are no results with rounds greater than #{round_last}\"",
"if",
"rounds",
">",
"round_last",
"else",
"self",
".",
"rounds",
"=",
"round_last",
"end",
"end"
] |
Round should go from 1 to a maximum, there should be at least one result in every round and,
if the number of rounds has been set, it should agree with the largest round from the results.
|
[
"Round",
"should",
"go",
"from",
"1",
"to",
"a",
"maximum",
"there",
"should",
"be",
"at",
"least",
"one",
"result",
"in",
"every",
"round",
"and",
"if",
"the",
"number",
"of",
"rounds",
"has",
"been",
"set",
"it",
"should",
"agree",
"with",
"the",
"largest",
"round",
"from",
"the",
"results",
"."
] |
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
|
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L477-L492
|
10,047
|
sanichi/icu_tournament
|
lib/icu_tournament/tournament.rb
|
ICU.Tournament.check_dates
|
def check_dates
raise "start date (#{start}) is after end date (#{finish})" if @start && @finish && @start > @finish
if @round_dates.size > 0
raise "the number of round dates (#{@round_dates.size}) does not match the number of rounds (#{@rounds})" unless @round_dates.size == @rounds
raise "the date of the first round (#{@round_dates[0]}) does not match the start (#{@start}) of the tournament" if @start && @start != @round_dates[0]
raise "the date of the last round (#{@round_dates[-1]}) does not match the end (#{@finish}) of the tournament" if @finish && @finish != @round_dates[-1]
(2..@round_dates.size).to_a.each do |r|
#puts "#{@round_dates[r-2]} => #{@round_dates[r-1]}"
raise "the date of round #{r-1} (#{@round_dates[r-2]}) is after the date of round #{r} (#{@round_dates[r-1]}) of the tournament" if @round_dates[r-2] > @round_dates[r-1]
end
@finish = @round_dates[-1] unless @finish
end
end
|
ruby
|
def check_dates
raise "start date (#{start}) is after end date (#{finish})" if @start && @finish && @start > @finish
if @round_dates.size > 0
raise "the number of round dates (#{@round_dates.size}) does not match the number of rounds (#{@rounds})" unless @round_dates.size == @rounds
raise "the date of the first round (#{@round_dates[0]}) does not match the start (#{@start}) of the tournament" if @start && @start != @round_dates[0]
raise "the date of the last round (#{@round_dates[-1]}) does not match the end (#{@finish}) of the tournament" if @finish && @finish != @round_dates[-1]
(2..@round_dates.size).to_a.each do |r|
#puts "#{@round_dates[r-2]} => #{@round_dates[r-1]}"
raise "the date of round #{r-1} (#{@round_dates[r-2]}) is after the date of round #{r} (#{@round_dates[r-1]}) of the tournament" if @round_dates[r-2] > @round_dates[r-1]
end
@finish = @round_dates[-1] unless @finish
end
end
|
[
"def",
"check_dates",
"raise",
"\"start date (#{start}) is after end date (#{finish})\"",
"if",
"@start",
"&&",
"@finish",
"&&",
"@start",
">",
"@finish",
"if",
"@round_dates",
".",
"size",
">",
"0",
"raise",
"\"the number of round dates (#{@round_dates.size}) does not match the number of rounds (#{@rounds})\"",
"unless",
"@round_dates",
".",
"size",
"==",
"@rounds",
"raise",
"\"the date of the first round (#{@round_dates[0]}) does not match the start (#{@start}) of the tournament\"",
"if",
"@start",
"&&",
"@start",
"!=",
"@round_dates",
"[",
"0",
"]",
"raise",
"\"the date of the last round (#{@round_dates[-1]}) does not match the end (#{@finish}) of the tournament\"",
"if",
"@finish",
"&&",
"@finish",
"!=",
"@round_dates",
"[",
"-",
"1",
"]",
"(",
"2",
"..",
"@round_dates",
".",
"size",
")",
".",
"to_a",
".",
"each",
"do",
"|",
"r",
"|",
"#puts \"#{@round_dates[r-2]} => #{@round_dates[r-1]}\"",
"raise",
"\"the date of round #{r-1} (#{@round_dates[r-2]}) is after the date of round #{r} (#{@round_dates[r-1]}) of the tournament\"",
"if",
"@round_dates",
"[",
"r",
"-",
"2",
"]",
">",
"@round_dates",
"[",
"r",
"-",
"1",
"]",
"end",
"@finish",
"=",
"@round_dates",
"[",
"-",
"1",
"]",
"unless",
"@finish",
"end",
"end"
] |
Check dates are consistent.
|
[
"Check",
"dates",
"are",
"consistent",
"."
] |
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
|
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L495-L507
|
10,048
|
sanichi/icu_tournament
|
lib/icu_tournament/tournament.rb
|
ICU.Tournament.check_type
|
def check_type(type)
if type.respond_to?(:validate!)
type.validate!(self)
elsif klass = self.class.factory(type.to_s)
klass.new.validate!(self)
else
raise "invalid type supplied for validation check"
end
end
|
ruby
|
def check_type(type)
if type.respond_to?(:validate!)
type.validate!(self)
elsif klass = self.class.factory(type.to_s)
klass.new.validate!(self)
else
raise "invalid type supplied for validation check"
end
end
|
[
"def",
"check_type",
"(",
"type",
")",
"if",
"type",
".",
"respond_to?",
"(",
":validate!",
")",
"type",
".",
"validate!",
"(",
"self",
")",
"elsif",
"klass",
"=",
"self",
".",
"class",
".",
"factory",
"(",
"type",
".",
"to_s",
")",
"klass",
".",
"new",
".",
"validate!",
"(",
"self",
")",
"else",
"raise",
"\"invalid type supplied for validation check\"",
"end",
"end"
] |
Validate against a specific type.
|
[
"Validate",
"against",
"a",
"specific",
"type",
"."
] |
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
|
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L555-L563
|
10,049
|
sanichi/icu_tournament
|
lib/icu_tournament/tournament.rb
|
ICU.Tournament.tie_break_score
|
def tie_break_score(hash, method, player, rounds)
case method
when :score then player.points
when :wins then player.results.inject(0) { |t,r| t + (r.opponent && r.score == 'W' ? 1 : 0) }
when :blacks then player.results.inject(0) { |t,r| t + (r.opponent && r.colour == 'B' ? 1 : 0) }
when :buchholz then player.results.inject(0.0) { |t,r| t + (r.opponent ? hash[:opp_score][r.opponent] : 0.0) }
when :neustadtl then player.results.inject(0.0) { |t,r| t + (r.opponent ? hash[:opp_score][r.opponent] * r.points : 0.0) }
when :opp_score then player.results.inject(0.0) { |t,r| t + (r.opponent ? r.points : 0.5) } + (rounds - player.results.size) * 0.5
when :progressive then (1..rounds).inject(0.0) { |t,n| r = player.find_result(n); s = r ? r.points : 0.0; t + s * (rounds + 1 - n) }
when :ratings then player.results.inject(0) { |t,r| t + (r.opponent && (@player[r.opponent].fide_rating || @player[r.opponent].rating) ? (@player[r.opponent].fide_rating || @player[r.opponent].rating) : 0) }
when :harkness, :modified_median
scores = player.results.map{ |r| r.opponent ? hash[:opp_score][r.opponent] : 0.0 }.sort
1.upto(rounds - player.results.size) { scores << 0.0 }
half = rounds / 2.0
times = rounds >= 9 ? 2 : 1
if method == :harkness || player.points == half
1.upto(times) { scores.shift; scores.pop }
else
1.upto(times) { scores.send(player.points > half ? :shift : :pop) }
end
scores.inject(0.0) { |t,s| t + s }
else player.name
end
end
|
ruby
|
def tie_break_score(hash, method, player, rounds)
case method
when :score then player.points
when :wins then player.results.inject(0) { |t,r| t + (r.opponent && r.score == 'W' ? 1 : 0) }
when :blacks then player.results.inject(0) { |t,r| t + (r.opponent && r.colour == 'B' ? 1 : 0) }
when :buchholz then player.results.inject(0.0) { |t,r| t + (r.opponent ? hash[:opp_score][r.opponent] : 0.0) }
when :neustadtl then player.results.inject(0.0) { |t,r| t + (r.opponent ? hash[:opp_score][r.opponent] * r.points : 0.0) }
when :opp_score then player.results.inject(0.0) { |t,r| t + (r.opponent ? r.points : 0.5) } + (rounds - player.results.size) * 0.5
when :progressive then (1..rounds).inject(0.0) { |t,n| r = player.find_result(n); s = r ? r.points : 0.0; t + s * (rounds + 1 - n) }
when :ratings then player.results.inject(0) { |t,r| t + (r.opponent && (@player[r.opponent].fide_rating || @player[r.opponent].rating) ? (@player[r.opponent].fide_rating || @player[r.opponent].rating) : 0) }
when :harkness, :modified_median
scores = player.results.map{ |r| r.opponent ? hash[:opp_score][r.opponent] : 0.0 }.sort
1.upto(rounds - player.results.size) { scores << 0.0 }
half = rounds / 2.0
times = rounds >= 9 ? 2 : 1
if method == :harkness || player.points == half
1.upto(times) { scores.shift; scores.pop }
else
1.upto(times) { scores.send(player.points > half ? :shift : :pop) }
end
scores.inject(0.0) { |t,s| t + s }
else player.name
end
end
|
[
"def",
"tie_break_score",
"(",
"hash",
",",
"method",
",",
"player",
",",
"rounds",
")",
"case",
"method",
"when",
":score",
"then",
"player",
".",
"points",
"when",
":wins",
"then",
"player",
".",
"results",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"t",
",",
"r",
"|",
"t",
"+",
"(",
"r",
".",
"opponent",
"&&",
"r",
".",
"score",
"==",
"'W'",
"?",
"1",
":",
"0",
")",
"}",
"when",
":blacks",
"then",
"player",
".",
"results",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"t",
",",
"r",
"|",
"t",
"+",
"(",
"r",
".",
"opponent",
"&&",
"r",
".",
"colour",
"==",
"'B'",
"?",
"1",
":",
"0",
")",
"}",
"when",
":buchholz",
"then",
"player",
".",
"results",
".",
"inject",
"(",
"0.0",
")",
"{",
"|",
"t",
",",
"r",
"|",
"t",
"+",
"(",
"r",
".",
"opponent",
"?",
"hash",
"[",
":opp_score",
"]",
"[",
"r",
".",
"opponent",
"]",
":",
"0.0",
")",
"}",
"when",
":neustadtl",
"then",
"player",
".",
"results",
".",
"inject",
"(",
"0.0",
")",
"{",
"|",
"t",
",",
"r",
"|",
"t",
"+",
"(",
"r",
".",
"opponent",
"?",
"hash",
"[",
":opp_score",
"]",
"[",
"r",
".",
"opponent",
"]",
"*",
"r",
".",
"points",
":",
"0.0",
")",
"}",
"when",
":opp_score",
"then",
"player",
".",
"results",
".",
"inject",
"(",
"0.0",
")",
"{",
"|",
"t",
",",
"r",
"|",
"t",
"+",
"(",
"r",
".",
"opponent",
"?",
"r",
".",
"points",
":",
"0.5",
")",
"}",
"+",
"(",
"rounds",
"-",
"player",
".",
"results",
".",
"size",
")",
"*",
"0.5",
"when",
":progressive",
"then",
"(",
"1",
"..",
"rounds",
")",
".",
"inject",
"(",
"0.0",
")",
"{",
"|",
"t",
",",
"n",
"|",
"r",
"=",
"player",
".",
"find_result",
"(",
"n",
")",
";",
"s",
"=",
"r",
"?",
"r",
".",
"points",
":",
"0.0",
";",
"t",
"+",
"s",
"*",
"(",
"rounds",
"+",
"1",
"-",
"n",
")",
"}",
"when",
":ratings",
"then",
"player",
".",
"results",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"t",
",",
"r",
"|",
"t",
"+",
"(",
"r",
".",
"opponent",
"&&",
"(",
"@player",
"[",
"r",
".",
"opponent",
"]",
".",
"fide_rating",
"||",
"@player",
"[",
"r",
".",
"opponent",
"]",
".",
"rating",
")",
"?",
"(",
"@player",
"[",
"r",
".",
"opponent",
"]",
".",
"fide_rating",
"||",
"@player",
"[",
"r",
".",
"opponent",
"]",
".",
"rating",
")",
":",
"0",
")",
"}",
"when",
":harkness",
",",
":modified_median",
"scores",
"=",
"player",
".",
"results",
".",
"map",
"{",
"|",
"r",
"|",
"r",
".",
"opponent",
"?",
"hash",
"[",
":opp_score",
"]",
"[",
"r",
".",
"opponent",
"]",
":",
"0.0",
"}",
".",
"sort",
"1",
".",
"upto",
"(",
"rounds",
"-",
"player",
".",
"results",
".",
"size",
")",
"{",
"scores",
"<<",
"0.0",
"}",
"half",
"=",
"rounds",
"/",
"2.0",
"times",
"=",
"rounds",
">=",
"9",
"?",
"2",
":",
"1",
"if",
"method",
"==",
":harkness",
"||",
"player",
".",
"points",
"==",
"half",
"1",
".",
"upto",
"(",
"times",
")",
"{",
"scores",
".",
"shift",
";",
"scores",
".",
"pop",
"}",
"else",
"1",
".",
"upto",
"(",
"times",
")",
"{",
"scores",
".",
"send",
"(",
"player",
".",
"points",
">",
"half",
"?",
":shift",
":",
":pop",
")",
"}",
"end",
"scores",
".",
"inject",
"(",
"0.0",
")",
"{",
"|",
"t",
",",
"s",
"|",
"t",
"+",
"s",
"}",
"else",
"player",
".",
"name",
"end",
"end"
] |
Return a tie break score for a given player and a given tie break method.
|
[
"Return",
"a",
"tie",
"break",
"score",
"for",
"a",
"given",
"player",
"and",
"a",
"given",
"tie",
"break",
"method",
"."
] |
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
|
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L611-L634
|
10,050
|
spikegrobstein/capnotify
|
lib/capnotify/plugin.rb
|
Capnotify.Plugin.deployed_by
|
def deployed_by
username = nil
scm = fetch(:scm, nil)
if scm
if scm.to_sym == :git
username = `git config user.name`.chomp
username = nil if $? != 0 || username.strip == ''
end
end
username || `whoami`.chomp
end
|
ruby
|
def deployed_by
username = nil
scm = fetch(:scm, nil)
if scm
if scm.to_sym == :git
username = `git config user.name`.chomp
username = nil if $? != 0 || username.strip == ''
end
end
username || `whoami`.chomp
end
|
[
"def",
"deployed_by",
"username",
"=",
"nil",
"scm",
"=",
"fetch",
"(",
":scm",
",",
"nil",
")",
"if",
"scm",
"if",
"scm",
".",
"to_sym",
"==",
":git",
"username",
"=",
"`",
"`",
".",
"chomp",
"username",
"=",
"nil",
"if",
"$?",
"!=",
"0",
"||",
"username",
".",
"strip",
"==",
"''",
"end",
"end",
"username",
"||",
"`",
"`",
".",
"chomp",
"end"
] |
get the name of the deploying user
currently this only supports git.
if reading the git user.name, fall back on `whoami`
|
[
"get",
"the",
"name",
"of",
"the",
"deploying",
"user",
"currently",
"this",
"only",
"supports",
"git",
".",
"if",
"reading",
"the",
"git",
"user",
".",
"name",
"fall",
"back",
"on",
"whoami"
] |
b21ea876ae2a04e8090206a687436565051f0e08
|
https://github.com/spikegrobstein/capnotify/blob/b21ea876ae2a04e8090206a687436565051f0e08/lib/capnotify/plugin.rb#L33-L46
|
10,051
|
spikegrobstein/capnotify
|
lib/capnotify/plugin.rb
|
Capnotify.Plugin.unload_plugin
|
def unload_plugin(name)
p = get_plugin(name)
p.unload if p.respond_to?(:unload)
Capistrano.remove_plugin(name)
end
|
ruby
|
def unload_plugin(name)
p = get_plugin(name)
p.unload if p.respond_to?(:unload)
Capistrano.remove_plugin(name)
end
|
[
"def",
"unload_plugin",
"(",
"name",
")",
"p",
"=",
"get_plugin",
"(",
"name",
")",
"p",
".",
"unload",
"if",
"p",
".",
"respond_to?",
"(",
":unload",
")",
"Capistrano",
".",
"remove_plugin",
"(",
"name",
")",
"end"
] |
given a plugin name as a symbol, unload the capnotify plugin
this will also unload any kind of capistrano plugin
if the plugin supports the unload method, it will be called.
|
[
"given",
"a",
"plugin",
"name",
"as",
"a",
"symbol",
"unload",
"the",
"capnotify",
"plugin",
"this",
"will",
"also",
"unload",
"any",
"kind",
"of",
"capistrano",
"plugin",
"if",
"the",
"plugin",
"supports",
"the",
"unload",
"method",
"it",
"will",
"be",
"called",
"."
] |
b21ea876ae2a04e8090206a687436565051f0e08
|
https://github.com/spikegrobstein/capnotify/blob/b21ea876ae2a04e8090206a687436565051f0e08/lib/capnotify/plugin.rb#L71-L76
|
10,052
|
spikegrobstein/capnotify
|
lib/capnotify/plugin.rb
|
Capnotify.Plugin.get_plugin
|
def get_plugin(name)
raise "Unknown plugin: #{ name }" unless Capistrano::EXTENSIONS.keys.include?(name)
self.send(name)
end
|
ruby
|
def get_plugin(name)
raise "Unknown plugin: #{ name }" unless Capistrano::EXTENSIONS.keys.include?(name)
self.send(name)
end
|
[
"def",
"get_plugin",
"(",
"name",
")",
"raise",
"\"Unknown plugin: #{ name }\"",
"unless",
"Capistrano",
"::",
"EXTENSIONS",
".",
"keys",
".",
"include?",
"(",
"name",
")",
"self",
".",
"send",
"(",
"name",
")",
"end"
] |
given a plugin name, return the plugin.
|
[
"given",
"a",
"plugin",
"name",
"return",
"the",
"plugin",
"."
] |
b21ea876ae2a04e8090206a687436565051f0e08
|
https://github.com/spikegrobstein/capnotify/blob/b21ea876ae2a04e8090206a687436565051f0e08/lib/capnotify/plugin.rb#L79-L82
|
10,053
|
spikegrobstein/capnotify
|
lib/capnotify/plugin.rb
|
Capnotify.Plugin.build_template
|
def build_template(template_path)
# FIXME: this is called every time build_template is called.
# although this is idepodent, it's got room for optimization
self.build_components!
ERB.new( File.open( template_path ).read, nil, '<>' ).result(self.binding)
end
|
ruby
|
def build_template(template_path)
# FIXME: this is called every time build_template is called.
# although this is idepodent, it's got room for optimization
self.build_components!
ERB.new( File.open( template_path ).read, nil, '<>' ).result(self.binding)
end
|
[
"def",
"build_template",
"(",
"template_path",
")",
"# FIXME: this is called every time build_template is called.",
"# although this is idepodent, it's got room for optimization",
"self",
".",
"build_components!",
"ERB",
".",
"new",
"(",
"File",
".",
"open",
"(",
"template_path",
")",
".",
"read",
",",
"nil",
",",
"'<>'",
")",
".",
"result",
"(",
"self",
".",
"binding",
")",
"end"
] |
given a path to an ERB template, process it with the current binding and return the output.
|
[
"given",
"a",
"path",
"to",
"an",
"ERB",
"template",
"process",
"it",
"with",
"the",
"current",
"binding",
"and",
"return",
"the",
"output",
"."
] |
b21ea876ae2a04e8090206a687436565051f0e08
|
https://github.com/spikegrobstein/capnotify/blob/b21ea876ae2a04e8090206a687436565051f0e08/lib/capnotify/plugin.rb#L93-L99
|
10,054
|
spikegrobstein/capnotify
|
lib/capnotify/plugin.rb
|
Capnotify.Plugin.component
|
def component(name)
components.each { |c| return c if c.name == name.to_sym }
return nil
end
|
ruby
|
def component(name)
components.each { |c| return c if c.name == name.to_sym }
return nil
end
|
[
"def",
"component",
"(",
"name",
")",
"components",
".",
"each",
"{",
"|",
"c",
"|",
"return",
"c",
"if",
"c",
".",
"name",
"==",
"name",
".",
"to_sym",
"}",
"return",
"nil",
"end"
] |
fetch a component given the name
this is most useful for getting a component directly if you want to make modificatins to it
|
[
"fetch",
"a",
"component",
"given",
"the",
"name",
"this",
"is",
"most",
"useful",
"for",
"getting",
"a",
"component",
"directly",
"if",
"you",
"want",
"to",
"make",
"modificatins",
"to",
"it"
] |
b21ea876ae2a04e8090206a687436565051f0e08
|
https://github.com/spikegrobstein/capnotify/blob/b21ea876ae2a04e8090206a687436565051f0e08/lib/capnotify/plugin.rb#L112-L115
|
10,055
|
spikegrobstein/capnotify
|
lib/capnotify/plugin.rb
|
Capnotify.Plugin.insert_component_before
|
def insert_component_before(name, component)
# iterate over all components, find the component with the given name
# once found, insert the given component at that location and return
components.each_with_index do |c, i|
if c.name == name
components.insert(i, component)
return
end
end
components << component
end
|
ruby
|
def insert_component_before(name, component)
# iterate over all components, find the component with the given name
# once found, insert the given component at that location and return
components.each_with_index do |c, i|
if c.name == name
components.insert(i, component)
return
end
end
components << component
end
|
[
"def",
"insert_component_before",
"(",
"name",
",",
"component",
")",
"# iterate over all components, find the component with the given name",
"# once found, insert the given component at that location and return",
"components",
".",
"each_with_index",
"do",
"|",
"c",
",",
"i",
"|",
"if",
"c",
".",
"name",
"==",
"name",
"components",
".",
"insert",
"(",
"i",
",",
"component",
")",
"return",
"end",
"end",
"components",
"<<",
"component",
"end"
] |
insert the given component before the component with `name`
if no component is found with that name, the component will be inserted at the end
|
[
"insert",
"the",
"given",
"component",
"before",
"the",
"component",
"with",
"name",
"if",
"no",
"component",
"is",
"found",
"with",
"that",
"name",
"the",
"component",
"will",
"be",
"inserted",
"at",
"the",
"end"
] |
b21ea876ae2a04e8090206a687436565051f0e08
|
https://github.com/spikegrobstein/capnotify/blob/b21ea876ae2a04e8090206a687436565051f0e08/lib/capnotify/plugin.rb#L119-L130
|
10,056
|
spikegrobstein/capnotify
|
lib/capnotify/plugin.rb
|
Capnotify.Plugin.insert_component_after
|
def insert_component_after(name, component)
# iterate over all components, find the component with the given name
# once found, insert the given component at the following location and return
components.each_with_index do |c, i|
if c.name == name
components.insert(i + 1, component)
return
end
end
components << component
end
|
ruby
|
def insert_component_after(name, component)
# iterate over all components, find the component with the given name
# once found, insert the given component at the following location and return
components.each_with_index do |c, i|
if c.name == name
components.insert(i + 1, component)
return
end
end
components << component
end
|
[
"def",
"insert_component_after",
"(",
"name",
",",
"component",
")",
"# iterate over all components, find the component with the given name",
"# once found, insert the given component at the following location and return",
"components",
".",
"each_with_index",
"do",
"|",
"c",
",",
"i",
"|",
"if",
"c",
".",
"name",
"==",
"name",
"components",
".",
"insert",
"(",
"i",
"+",
"1",
",",
"component",
")",
"return",
"end",
"end",
"components",
"<<",
"component",
"end"
] |
insert the given component after the component with `name`
if no component is found with that name, the component will be inserted at the end
|
[
"insert",
"the",
"given",
"component",
"after",
"the",
"component",
"with",
"name",
"if",
"no",
"component",
"is",
"found",
"with",
"that",
"name",
"the",
"component",
"will",
"be",
"inserted",
"at",
"the",
"end"
] |
b21ea876ae2a04e8090206a687436565051f0e08
|
https://github.com/spikegrobstein/capnotify/blob/b21ea876ae2a04e8090206a687436565051f0e08/lib/capnotify/plugin.rb#L134-L145
|
10,057
|
ykpeng/networkr
|
lib/networkr/graphs/multigraph.rb
|
Networkr.MultiGraph.new_edge_key
|
def new_edge_key(u, v)
if @adj[u] && @adj[u][v]
keys = @adj[u][v]
key = keys.length
while keys.include?(key)
key += 1
end
return key
else
return 0
end
end
|
ruby
|
def new_edge_key(u, v)
if @adj[u] && @adj[u][v]
keys = @adj[u][v]
key = keys.length
while keys.include?(key)
key += 1
end
return key
else
return 0
end
end
|
[
"def",
"new_edge_key",
"(",
"u",
",",
"v",
")",
"if",
"@adj",
"[",
"u",
"]",
"&&",
"@adj",
"[",
"u",
"]",
"[",
"v",
"]",
"keys",
"=",
"@adj",
"[",
"u",
"]",
"[",
"v",
"]",
"key",
"=",
"keys",
".",
"length",
"while",
"keys",
".",
"include?",
"(",
"key",
")",
"key",
"+=",
"1",
"end",
"return",
"key",
"else",
"return",
"0",
"end",
"end"
] |
returns an unused key for edges between nodes 'u' and 'v'.
The nodes 'u' and 'v' do not need to be already in the graph.
Notes
-----
The new key is the number of existing edges between 'u' and 'v', increased if necessary to ensure uniqueness. The first edge will have key 0, the second edge 1, etc. If an edge is removed, new keys may not be in this order.
Parameters
----------
u, v: nodes
Returns
-------
key: int
|
[
"returns",
"an",
"unused",
"key",
"for",
"edges",
"between",
"nodes",
"u",
"and",
"v",
"."
] |
8b3f9495b53a73735c1a73aa98c7327423377eb6
|
https://github.com/ykpeng/networkr/blob/8b3f9495b53a73735c1a73aa98c7327423377eb6/lib/networkr/graphs/multigraph.rb#L28-L39
|
10,058
|
mpapis/gh_contributors
|
lib/gh_contributors/calculator.rb
|
GhContributors.Calculator.calculated_data
|
def calculated_data
@data ||= @raw_data.group_by { |contributor|
contributor['login']
}.map {|login, data|
log "user: #{login}"
[login, user_data(login, data)]
}.sort_by{|login, data|
[1000000/data['contributions'], login]
}
end
|
ruby
|
def calculated_data
@data ||= @raw_data.group_by { |contributor|
contributor['login']
}.map {|login, data|
log "user: #{login}"
[login, user_data(login, data)]
}.sort_by{|login, data|
[1000000/data['contributions'], login]
}
end
|
[
"def",
"calculated_data",
"@data",
"||=",
"@raw_data",
".",
"group_by",
"{",
"|",
"contributor",
"|",
"contributor",
"[",
"'login'",
"]",
"}",
".",
"map",
"{",
"|",
"login",
",",
"data",
"|",
"log",
"\"user: #{login}\"",
"[",
"login",
",",
"user_data",
"(",
"login",
",",
"data",
")",
"]",
"}",
".",
"sort_by",
"{",
"|",
"login",
",",
"data",
"|",
"[",
"1000000",
"/",
"data",
"[",
"'contributions'",
"]",
",",
"login",
"]",
"}",
"end"
] |
group data, calculate contributions, sort by contributions
|
[
"group",
"data",
"calculate",
"contributions",
"sort",
"by",
"contributions"
] |
3d5c82acf697384a0f965f73b8d5be092022d4a8
|
https://github.com/mpapis/gh_contributors/blob/3d5c82acf697384a0f965f73b8d5be092022d4a8/lib/gh_contributors/calculator.rb#L26-L35
|
10,059
|
caruby/scat
|
lib/scat/cache.rb
|
Scat.Cache.start
|
def start(redis)
logger.debug { "Scat is starting the Redis cache server..." }
unless system(REDIS_SERVER, REDIS_CONF) then
raise ScatError.new("Scat cannot start the Redis cache server.")
end
# Ping the server until loaded.
3.times do |n|
begin
redis.ping
logger.debug { "Scat started the Redis cache server." }
return redis
rescue
n < 2 ? sleep(0.5) : raise
end
end
end
|
ruby
|
def start(redis)
logger.debug { "Scat is starting the Redis cache server..." }
unless system(REDIS_SERVER, REDIS_CONF) then
raise ScatError.new("Scat cannot start the Redis cache server.")
end
# Ping the server until loaded.
3.times do |n|
begin
redis.ping
logger.debug { "Scat started the Redis cache server." }
return redis
rescue
n < 2 ? sleep(0.5) : raise
end
end
end
|
[
"def",
"start",
"(",
"redis",
")",
"logger",
".",
"debug",
"{",
"\"Scat is starting the Redis cache server...\"",
"}",
"unless",
"system",
"(",
"REDIS_SERVER",
",",
"REDIS_CONF",
")",
"then",
"raise",
"ScatError",
".",
"new",
"(",
"\"Scat cannot start the Redis cache server.\"",
")",
"end",
"# Ping the server until loaded. ",
"3",
".",
"times",
"do",
"|",
"n",
"|",
"begin",
"redis",
".",
"ping",
"logger",
".",
"debug",
"{",
"\"Scat started the Redis cache server.\"",
"}",
"return",
"redis",
"rescue",
"n",
"<",
"2",
"?",
"sleep",
"(",
"0.5",
")",
":",
"raise",
"end",
"end",
"end"
] |
Starts the Redis server on the default Redis port.
@param [Redis] the Redis client
@raise [ScatError] if the server command could not be executed
@raise [Exception] if the server is not reachable
|
[
"Starts",
"the",
"Redis",
"server",
"on",
"the",
"default",
"Redis",
"port",
"."
] |
90291b317eb6b8ef8b0a4497622eadc15d3d9028
|
https://github.com/caruby/scat/blob/90291b317eb6b8ef8b0a4497622eadc15d3d9028/lib/scat/cache.rb#L73-L88
|
10,060
|
cordawyn/redlander
|
lib/redlander/model.rb
|
Redlander.Model.query
|
def query(q, options = {}, &block)
query = Query::Results.new(q, options)
query.process(self, &block)
end
|
ruby
|
def query(q, options = {}, &block)
query = Query::Results.new(q, options)
query.process(self, &block)
end
|
[
"def",
"query",
"(",
"q",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"query",
"=",
"Query",
"::",
"Results",
".",
"new",
"(",
"q",
",",
"options",
")",
"query",
".",
"process",
"(",
"self",
",",
"block",
")",
"end"
] |
Query the model RDF graph using a query language
@param [String] q the text of the query
@param [Hash<Symbol => [String, URI]>] options options for the query
@option options [String] :language language of the query, one of:
- "sparql10" SPARQL 1.0 W3C RDF Query Language (default)
- "sparql" SPARQL 1.1 (DRAFT) Query and Update Languages
- "sparql11-query" SPARQL 1.1 (DRAFT) Query Language
- "sparql11-update" SPARQL 1.1 (DRAFT) Update Language
- "laqrs" LAQRS adds to Querying RDF in SPARQL
- "rdql" RDF Data Query Language (RDQL)
@option options [String] :language_uri URI of the query language, if applicable
@option options [String] :base_uri base URI of the query, if applicable
@return [void]
@note
The returned value is determined by the type of the query:
- [Boolean] for SPARQL ASK queries (ignores block, if given)
- [Redlander::Model] for SPARQL CONSTRUCT queries
if given a block, yields the constructed statements to it instead
- [Array<Hash>] for SPARQL SELECT queries
where hash values are Redlander::Node instances;
if given a block, yields each binding hash to it
- nil, if query fails
@raise [RedlandError] if fails to create a query
|
[
"Query",
"the",
"model",
"RDF",
"graph",
"using",
"a",
"query",
"language"
] |
a5c84e15a7602c674606e531bda6a616b1237c44
|
https://github.com/cordawyn/redlander/blob/a5c84e15a7602c674606e531bda6a616b1237c44/lib/redlander/model.rb#L116-L119
|
10,061
|
octoai/gem-octocore-cassandra
|
lib/octocore-cassandra/models/enterprise/funnels.rb
|
Octo.Funnel.populate_with_fake_data
|
def populate_with_fake_data(interval_days = 7)
if self.enterprise.fakedata?
today = Time.now.beginning_of_day
(today - interval_days.days).to(today, 24.hour).each do |ts|
Octo::FunnelData.new(
enterprise_id: self.enterprise_id,
funnel_slug: self.name_slug,
ts: ts,
value: fake_data(self.funnel.count)
).save!
end
end
end
|
ruby
|
def populate_with_fake_data(interval_days = 7)
if self.enterprise.fakedata?
today = Time.now.beginning_of_day
(today - interval_days.days).to(today, 24.hour).each do |ts|
Octo::FunnelData.new(
enterprise_id: self.enterprise_id,
funnel_slug: self.name_slug,
ts: ts,
value: fake_data(self.funnel.count)
).save!
end
end
end
|
[
"def",
"populate_with_fake_data",
"(",
"interval_days",
"=",
"7",
")",
"if",
"self",
".",
"enterprise",
".",
"fakedata?",
"today",
"=",
"Time",
".",
"now",
".",
"beginning_of_day",
"(",
"today",
"-",
"interval_days",
".",
"days",
")",
".",
"to",
"(",
"today",
",",
"24",
".",
"hour",
")",
".",
"each",
"do",
"|",
"ts",
"|",
"Octo",
"::",
"FunnelData",
".",
"new",
"(",
"enterprise_id",
":",
"self",
".",
"enterprise_id",
",",
"funnel_slug",
":",
"self",
".",
"name_slug",
",",
"ts",
":",
"ts",
",",
"value",
":",
"fake_data",
"(",
"self",
".",
"funnel",
".",
"count",
")",
")",
".",
"save!",
"end",
"end",
"end"
] |
Populates a newly created funnel with some fake data
@param [Fixnum] days The number of days for which data to be faked
|
[
"Populates",
"a",
"newly",
"created",
"funnel",
"with",
"some",
"fake",
"data"
] |
c0977dce5ba0eb174ff810f161aba151069935df
|
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/models/enterprise/funnels.rb#L75-L87
|
10,062
|
octoai/gem-octocore-cassandra
|
lib/octocore-cassandra/models/enterprise/funnels.rb
|
Octo.Funnel.data
|
def data(ts = Time.now.floor)
args = {
enterprise_id: self.enterprise.id,
funnel_slug: self.name_slug,
ts: ts
}
res = Octo::FunnelData.where(args)
if res.count > 0
res.first
elsif self.enterprise.fakedata?
args.merge!({ value: fake_data(self.funnel.count) })
Octo::FunnelData.new(args).save!
end
end
|
ruby
|
def data(ts = Time.now.floor)
args = {
enterprise_id: self.enterprise.id,
funnel_slug: self.name_slug,
ts: ts
}
res = Octo::FunnelData.where(args)
if res.count > 0
res.first
elsif self.enterprise.fakedata?
args.merge!({ value: fake_data(self.funnel.count) })
Octo::FunnelData.new(args).save!
end
end
|
[
"def",
"data",
"(",
"ts",
"=",
"Time",
".",
"now",
".",
"floor",
")",
"args",
"=",
"{",
"enterprise_id",
":",
"self",
".",
"enterprise",
".",
"id",
",",
"funnel_slug",
":",
"self",
".",
"name_slug",
",",
"ts",
":",
"ts",
"}",
"res",
"=",
"Octo",
"::",
"FunnelData",
".",
"where",
"(",
"args",
")",
"if",
"res",
".",
"count",
">",
"0",
"res",
".",
"first",
"elsif",
"self",
".",
"enterprise",
".",
"fakedata?",
"args",
".",
"merge!",
"(",
"{",
"value",
":",
"fake_data",
"(",
"self",
".",
"funnel",
".",
"count",
")",
"}",
")",
"Octo",
"::",
"FunnelData",
".",
"new",
"(",
"args",
")",
".",
"save!",
"end",
"end"
] |
Returns data for a funnel
@return [Octo::FunnelData] The Octo funnel data
|
[
"Returns",
"data",
"for",
"a",
"funnel"
] |
c0977dce5ba0eb174ff810f161aba151069935df
|
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/models/enterprise/funnels.rb#L91-L104
|
10,063
|
octoai/gem-octocore-cassandra
|
lib/octocore-cassandra/models/enterprise/funnels.rb
|
Octo.Funnel.fake_data
|
def fake_data(n)
fun = Array.new(n)
max_dropoff = 100/n
n.times do |i|
if i == 0
fun[i] = 100.0
else
fun[i] = fun[i-1] - rand(1..max_dropoff)
if fun[i] < 0
fun[i] = rand(0...fun[i].abs)
end
end
end
fun
end
|
ruby
|
def fake_data(n)
fun = Array.new(n)
max_dropoff = 100/n
n.times do |i|
if i == 0
fun[i] = 100.0
else
fun[i] = fun[i-1] - rand(1..max_dropoff)
if fun[i] < 0
fun[i] = rand(0...fun[i].abs)
end
end
end
fun
end
|
[
"def",
"fake_data",
"(",
"n",
")",
"fun",
"=",
"Array",
".",
"new",
"(",
"n",
")",
"max_dropoff",
"=",
"100",
"/",
"n",
"n",
".",
"times",
"do",
"|",
"i",
"|",
"if",
"i",
"==",
"0",
"fun",
"[",
"i",
"]",
"=",
"100.0",
"else",
"fun",
"[",
"i",
"]",
"=",
"fun",
"[",
"i",
"-",
"1",
"]",
"-",
"rand",
"(",
"1",
"..",
"max_dropoff",
")",
"if",
"fun",
"[",
"i",
"]",
"<",
"0",
"fun",
"[",
"i",
"]",
"=",
"rand",
"(",
"0",
"...",
"fun",
"[",
"i",
"]",
".",
"abs",
")",
"end",
"end",
"end",
"fun",
"end"
] |
Generates fake data for funnel
@param [Fixnum] n The length of funnel
@return [Array] An array containing the funnel value
|
[
"Generates",
"fake",
"data",
"for",
"funnel"
] |
c0977dce5ba0eb174ff810f161aba151069935df
|
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/models/enterprise/funnels.rb#L111-L125
|
10,064
|
betaworks/slack-bot-manager
|
lib/slack-bot-manager/client/base.rb
|
SlackBotManager.Client.handle_error
|
def handle_error(err, data = nil)
case determine_error_type(err)
when :token_revoked
on_revoke(data)
when :rate_limited
on_rate_limit(data)
when :closed
on_close(data)
else
on_error(err, data)
end
end
|
ruby
|
def handle_error(err, data = nil)
case determine_error_type(err)
when :token_revoked
on_revoke(data)
when :rate_limited
on_rate_limit(data)
when :closed
on_close(data)
else
on_error(err, data)
end
end
|
[
"def",
"handle_error",
"(",
"err",
",",
"data",
"=",
"nil",
")",
"case",
"determine_error_type",
"(",
"err",
")",
"when",
":token_revoked",
"on_revoke",
"(",
"data",
")",
"when",
":rate_limited",
"on_rate_limit",
"(",
"data",
")",
"when",
":closed",
"on_close",
"(",
"data",
")",
"else",
"on_error",
"(",
"err",
",",
"data",
")",
"end",
"end"
] |
Handle different error cases
|
[
"Handle",
"different",
"error",
"cases"
] |
cb59bd1c80abd3ede0520017708891486f733e40
|
https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/client/base.rb#L118-L129
|
10,065
|
fotonauts/activr
|
lib/activr/storage.rb
|
Activr.Storage.find_activity
|
def find_activity(activity_id)
activity_hash = self.driver.find_activity(activity_id)
if activity_hash
# run hook
self.run_hook(:did_find_activity, activity_hash)
# unserialize
Activr::Activity.from_hash(activity_hash)
else
nil
end
end
|
ruby
|
def find_activity(activity_id)
activity_hash = self.driver.find_activity(activity_id)
if activity_hash
# run hook
self.run_hook(:did_find_activity, activity_hash)
# unserialize
Activr::Activity.from_hash(activity_hash)
else
nil
end
end
|
[
"def",
"find_activity",
"(",
"activity_id",
")",
"activity_hash",
"=",
"self",
".",
"driver",
".",
"find_activity",
"(",
"activity_id",
")",
"if",
"activity_hash",
"# run hook",
"self",
".",
"run_hook",
"(",
":did_find_activity",
",",
"activity_hash",
")",
"# unserialize",
"Activr",
"::",
"Activity",
".",
"from_hash",
"(",
"activity_hash",
")",
"else",
"nil",
"end",
"end"
] |
Find an activity
@param activity_id [Object] Activity id to find
@return [Activity, Nil] An activity instance or `nil` if not found
|
[
"Find",
"an",
"activity"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L76-L87
|
10,066
|
fotonauts/activr
|
lib/activr/storage.rb
|
Activr.Storage.find_activities
|
def find_activities(limit, options = { })
# default options
options = {
:skip => 0,
:before => nil,
:after => nil,
:entities => { },
:only => [ ],
:except => [ ],
}.merge(options)
options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array))
# find
result = self.driver.find_activities(limit, options).map do |activity_hash|
# run hook
self.run_hook(:did_find_activity, activity_hash)
# unserialize
Activr::Activity.from_hash(activity_hash)
end
result
end
|
ruby
|
def find_activities(limit, options = { })
# default options
options = {
:skip => 0,
:before => nil,
:after => nil,
:entities => { },
:only => [ ],
:except => [ ],
}.merge(options)
options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array))
# find
result = self.driver.find_activities(limit, options).map do |activity_hash|
# run hook
self.run_hook(:did_find_activity, activity_hash)
# unserialize
Activr::Activity.from_hash(activity_hash)
end
result
end
|
[
"def",
"find_activities",
"(",
"limit",
",",
"options",
"=",
"{",
"}",
")",
"# default options",
"options",
"=",
"{",
":skip",
"=>",
"0",
",",
":before",
"=>",
"nil",
",",
":after",
"=>",
"nil",
",",
":entities",
"=>",
"{",
"}",
",",
":only",
"=>",
"[",
"]",
",",
":except",
"=>",
"[",
"]",
",",
"}",
".",
"merge",
"(",
"options",
")",
"options",
"[",
":only",
"]",
"=",
"[",
"options",
"[",
":only",
"]",
"]",
"if",
"(",
"options",
"[",
":only",
"]",
"&&",
"!",
"options",
"[",
":only",
"]",
".",
"is_a?",
"(",
"Array",
")",
")",
"# find",
"result",
"=",
"self",
".",
"driver",
".",
"find_activities",
"(",
"limit",
",",
"options",
")",
".",
"map",
"do",
"|",
"activity_hash",
"|",
"# run hook",
"self",
".",
"run_hook",
"(",
":did_find_activity",
",",
"activity_hash",
")",
"# unserialize",
"Activr",
"::",
"Activity",
".",
"from_hash",
"(",
"activity_hash",
")",
"end",
"result",
"end"
] |
Find latest activities
@note If you use others selectors then 'limit' argument and 'skip' option then you have to setup corresponding indexes in database.
@param limit [Integer] Max number of activities to find
@param options [Hash] Options hash
@option options [Integer] :skip Number of activities to skip (default: 0)
@option options [Time] :before Find activities generated before that datetime (excluding)
@option options [Time] :after Find activities generated after that datetime (excluding)
@option options [Hash{Sym=>String}] :entities Filter by entities values (empty means 'all values')
@option options [Array<Class>] :only Find only these activities
@option options [Array<Class>] :except Skip these activities
@return [Array<Activity>] An array of activities
|
[
"Find",
"latest",
"activities"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L102-L125
|
10,067
|
fotonauts/activr
|
lib/activr/storage.rb
|
Activr.Storage.count_activities
|
def count_activities(options = { })
# default options
options = {
:before => nil,
:after => nil,
:entities => { },
:only => [ ],
:except => [ ],
}.merge(options)
options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array))
# count
self.driver.count_activities(options)
end
|
ruby
|
def count_activities(options = { })
# default options
options = {
:before => nil,
:after => nil,
:entities => { },
:only => [ ],
:except => [ ],
}.merge(options)
options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array))
# count
self.driver.count_activities(options)
end
|
[
"def",
"count_activities",
"(",
"options",
"=",
"{",
"}",
")",
"# default options",
"options",
"=",
"{",
":before",
"=>",
"nil",
",",
":after",
"=>",
"nil",
",",
":entities",
"=>",
"{",
"}",
",",
":only",
"=>",
"[",
"]",
",",
":except",
"=>",
"[",
"]",
",",
"}",
".",
"merge",
"(",
"options",
")",
"options",
"[",
":only",
"]",
"=",
"[",
"options",
"[",
":only",
"]",
"]",
"if",
"(",
"options",
"[",
":only",
"]",
"&&",
"!",
"options",
"[",
":only",
"]",
".",
"is_a?",
"(",
"Array",
")",
")",
"# count",
"self",
".",
"driver",
".",
"count_activities",
"(",
"options",
")",
"end"
] |
Count number of activities
@note If you use one of options selectors then you have to setup corresponding indexes in database.
@param options [Hash] Options hash
@option options [Time] :before Find activities generated before that datetime (excluding)
@option options [Time] :after Find activities generated after that datetime (excluding)
@option options [Hash{Sym=>String}] :entities Filter by entities values (empty means 'all values')
@option options [Array<Class>] :only Find only these activities
@option options [Array<Class>] :except Skip these activities
@return [Integer] Number of activities
|
[
"Count",
"number",
"of",
"activities"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L138-L152
|
10,068
|
fotonauts/activr
|
lib/activr/storage.rb
|
Activr.Storage.count_duplicate_activities
|
def count_duplicate_activities(activity, after)
entities = { }
activity.entities.each do |entity_name, entity|
entities[entity_name.to_sym] = entity.model_id
end
self.count_activities({
:only => activity.class,
:entities => entities,
:after => after,
})
end
|
ruby
|
def count_duplicate_activities(activity, after)
entities = { }
activity.entities.each do |entity_name, entity|
entities[entity_name.to_sym] = entity.model_id
end
self.count_activities({
:only => activity.class,
:entities => entities,
:after => after,
})
end
|
[
"def",
"count_duplicate_activities",
"(",
"activity",
",",
"after",
")",
"entities",
"=",
"{",
"}",
"activity",
".",
"entities",
".",
"each",
"do",
"|",
"entity_name",
",",
"entity",
"|",
"entities",
"[",
"entity_name",
".",
"to_sym",
"]",
"=",
"entity",
".",
"model_id",
"end",
"self",
".",
"count_activities",
"(",
"{",
":only",
"=>",
"activity",
".",
"class",
",",
":entities",
"=>",
"entities",
",",
":after",
"=>",
"after",
",",
"}",
")",
"end"
] |
Find number of duplicate activities
@param activity [Activity] Activity to search
@param after [Time] Search after that datetime
@return [Integer] Number of activity duplicates
|
[
"Find",
"number",
"of",
"duplicate",
"activities"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L159-L171
|
10,069
|
fotonauts/activr
|
lib/activr/storage.rb
|
Activr.Storage.delete_activities_for_entity_model
|
def delete_activities_for_entity_model(model)
Activr.registry.activity_entities_for_model(model.class).each do |entity_name|
self.driver.delete_activities(:entities => { entity_name => model.id })
end
end
|
ruby
|
def delete_activities_for_entity_model(model)
Activr.registry.activity_entities_for_model(model.class).each do |entity_name|
self.driver.delete_activities(:entities => { entity_name => model.id })
end
end
|
[
"def",
"delete_activities_for_entity_model",
"(",
"model",
")",
"Activr",
".",
"registry",
".",
"activity_entities_for_model",
"(",
"model",
".",
"class",
")",
".",
"each",
"do",
"|",
"entity_name",
"|",
"self",
".",
"driver",
".",
"delete_activities",
"(",
":entities",
"=>",
"{",
"entity_name",
"=>",
"model",
".",
"id",
"}",
")",
"end",
"end"
] |
Delete activities referring to given entity model instance
@param model [Object] Model instance
|
[
"Delete",
"activities",
"referring",
"to",
"given",
"entity",
"model",
"instance"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L176-L180
|
10,070
|
fotonauts/activr
|
lib/activr/storage.rb
|
Activr.Storage.find_timeline_entry
|
def find_timeline_entry(timeline, tl_entry_id)
timeline_entry_hash = self.driver.find_timeline_entry(timeline.kind, tl_entry_id)
if timeline_entry_hash
# run hook
self.run_hook(:did_find_timeline_entry, timeline_entry_hash, timeline.class)
# unserialize
Activr::Timeline::Entry.from_hash(timeline_entry_hash, timeline)
else
nil
end
end
|
ruby
|
def find_timeline_entry(timeline, tl_entry_id)
timeline_entry_hash = self.driver.find_timeline_entry(timeline.kind, tl_entry_id)
if timeline_entry_hash
# run hook
self.run_hook(:did_find_timeline_entry, timeline_entry_hash, timeline.class)
# unserialize
Activr::Timeline::Entry.from_hash(timeline_entry_hash, timeline)
else
nil
end
end
|
[
"def",
"find_timeline_entry",
"(",
"timeline",
",",
"tl_entry_id",
")",
"timeline_entry_hash",
"=",
"self",
".",
"driver",
".",
"find_timeline_entry",
"(",
"timeline",
".",
"kind",
",",
"tl_entry_id",
")",
"if",
"timeline_entry_hash",
"# run hook",
"self",
".",
"run_hook",
"(",
":did_find_timeline_entry",
",",
"timeline_entry_hash",
",",
"timeline",
".",
"class",
")",
"# unserialize",
"Activr",
"::",
"Timeline",
"::",
"Entry",
".",
"from_hash",
"(",
"timeline_entry_hash",
",",
"timeline",
")",
"else",
"nil",
"end",
"end"
] |
Find a timeline entry
@param timeline [Timeline] Timeline instance
@param tl_entry_id [Object] Timeline entry id
@return [Timeline::Entry, Nil] Found timeline entry
|
[
"Find",
"a",
"timeline",
"entry"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L207-L218
|
10,071
|
fotonauts/activr
|
lib/activr/storage.rb
|
Activr.Storage.find_timeline
|
def find_timeline(timeline, limit, options = { })
options = {
:skip => 0,
:only => [ ],
}.merge(options)
options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array))
result = self.driver.find_timeline_entries(timeline.kind, timeline.recipient_id, limit, options).map do |timeline_entry_hash|
# run hook
self.run_hook(:did_find_timeline_entry, timeline_entry_hash, timeline.class)
# unserialize
Activr::Timeline::Entry.from_hash(timeline_entry_hash, timeline)
end
result
end
|
ruby
|
def find_timeline(timeline, limit, options = { })
options = {
:skip => 0,
:only => [ ],
}.merge(options)
options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array))
result = self.driver.find_timeline_entries(timeline.kind, timeline.recipient_id, limit, options).map do |timeline_entry_hash|
# run hook
self.run_hook(:did_find_timeline_entry, timeline_entry_hash, timeline.class)
# unserialize
Activr::Timeline::Entry.from_hash(timeline_entry_hash, timeline)
end
result
end
|
[
"def",
"find_timeline",
"(",
"timeline",
",",
"limit",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":skip",
"=>",
"0",
",",
":only",
"=>",
"[",
"]",
",",
"}",
".",
"merge",
"(",
"options",
")",
"options",
"[",
":only",
"]",
"=",
"[",
"options",
"[",
":only",
"]",
"]",
"if",
"(",
"options",
"[",
":only",
"]",
"&&",
"!",
"options",
"[",
":only",
"]",
".",
"is_a?",
"(",
"Array",
")",
")",
"result",
"=",
"self",
".",
"driver",
".",
"find_timeline_entries",
"(",
"timeline",
".",
"kind",
",",
"timeline",
".",
"recipient_id",
",",
"limit",
",",
"options",
")",
".",
"map",
"do",
"|",
"timeline_entry_hash",
"|",
"# run hook",
"self",
".",
"run_hook",
"(",
":did_find_timeline_entry",
",",
"timeline_entry_hash",
",",
"timeline",
".",
"class",
")",
"# unserialize",
"Activr",
"::",
"Timeline",
"::",
"Entry",
".",
"from_hash",
"(",
"timeline_entry_hash",
",",
"timeline",
")",
"end",
"result",
"end"
] |
Find timeline entries by descending timestamp
@param timeline [Timeline] Timeline instance
@param limit [Integer] Max number of entries to find
@param options [Hash] Options hash
@option options [Integer] :skip Number of entries to skip (default: 0)
@option options [Array<Timeline::Route>] :only An array of routes to fetch
@return [Array<Timeline::Entry>] An array of timeline entries
|
[
"Find",
"timeline",
"entries",
"by",
"descending",
"timestamp"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L228-L245
|
10,072
|
fotonauts/activr
|
lib/activr/storage.rb
|
Activr.Storage.count_timeline
|
def count_timeline(timeline, options = { })
options = {
:only => [ ],
}.merge(options)
options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array))
self.driver.count_timeline_entries(timeline.kind, timeline.recipient_id, options)
end
|
ruby
|
def count_timeline(timeline, options = { })
options = {
:only => [ ],
}.merge(options)
options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array))
self.driver.count_timeline_entries(timeline.kind, timeline.recipient_id, options)
end
|
[
"def",
"count_timeline",
"(",
"timeline",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":only",
"=>",
"[",
"]",
",",
"}",
".",
"merge",
"(",
"options",
")",
"options",
"[",
":only",
"]",
"=",
"[",
"options",
"[",
":only",
"]",
"]",
"if",
"(",
"options",
"[",
":only",
"]",
"&&",
"!",
"options",
"[",
":only",
"]",
".",
"is_a?",
"(",
"Array",
")",
")",
"self",
".",
"driver",
".",
"count_timeline_entries",
"(",
"timeline",
".",
"kind",
",",
"timeline",
".",
"recipient_id",
",",
"options",
")",
"end"
] |
Count number of timeline entries
@param timeline [Timeline] Timeline instance
@param options [Hash] Options hash
@option options [Array<Timeline::Route>] :only An array of routes to count
@return [Integer] Number of timeline entries in given timeline
|
[
"Count",
"number",
"of",
"timeline",
"entries"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L253-L261
|
10,073
|
fotonauts/activr
|
lib/activr/storage.rb
|
Activr.Storage.delete_timeline
|
def delete_timeline(timeline, options = { })
# default options
options = {
:before => nil,
:entities => { },
}.merge(options)
self.driver.delete_timeline_entries(timeline.kind, timeline.recipient_id, options)
end
|
ruby
|
def delete_timeline(timeline, options = { })
# default options
options = {
:before => nil,
:entities => { },
}.merge(options)
self.driver.delete_timeline_entries(timeline.kind, timeline.recipient_id, options)
end
|
[
"def",
"delete_timeline",
"(",
"timeline",
",",
"options",
"=",
"{",
"}",
")",
"# default options",
"options",
"=",
"{",
":before",
"=>",
"nil",
",",
":entities",
"=>",
"{",
"}",
",",
"}",
".",
"merge",
"(",
"options",
")",
"self",
".",
"driver",
".",
"delete_timeline_entries",
"(",
"timeline",
".",
"kind",
",",
"timeline",
".",
"recipient_id",
",",
"options",
")",
"end"
] |
Delete timeline entries
@param timeline [Timeline] Timeline instance
@param options [Hash] Options hash
@option options [Time] :before Delete only timeline entries which timestamp is before that datetime (excluding)
@option options [Hash{Sym=>String}] :entity Delete only timeline entries with these entities values
|
[
"Delete",
"timeline",
"entries"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L269-L277
|
10,074
|
fotonauts/activr
|
lib/activr/storage.rb
|
Activr.Storage.delete_timeline_entries_for_entity_model
|
def delete_timeline_entries_for_entity_model(model)
Activr.registry.timeline_entities_for_model(model.class).each do |timeline_class, entities|
entities.each do |entity_name|
self.driver.delete_timeline_entries(timeline_class.kind, nil, :entities => { entity_name => model.id })
end
end
end
|
ruby
|
def delete_timeline_entries_for_entity_model(model)
Activr.registry.timeline_entities_for_model(model.class).each do |timeline_class, entities|
entities.each do |entity_name|
self.driver.delete_timeline_entries(timeline_class.kind, nil, :entities => { entity_name => model.id })
end
end
end
|
[
"def",
"delete_timeline_entries_for_entity_model",
"(",
"model",
")",
"Activr",
".",
"registry",
".",
"timeline_entities_for_model",
"(",
"model",
".",
"class",
")",
".",
"each",
"do",
"|",
"timeline_class",
",",
"entities",
"|",
"entities",
".",
"each",
"do",
"|",
"entity_name",
"|",
"self",
".",
"driver",
".",
"delete_timeline_entries",
"(",
"timeline_class",
".",
"kind",
",",
"nil",
",",
":entities",
"=>",
"{",
"entity_name",
"=>",
"model",
".",
"id",
"}",
")",
"end",
"end",
"end"
] |
Delete timeline entries referring to given entity model instance
@param model [Object] Model instance
|
[
"Delete",
"timeline",
"entries",
"referring",
"to",
"given",
"entity",
"model",
"instance"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L282-L288
|
10,075
|
fotonauts/activr
|
lib/activr/storage.rb
|
Activr.Storage.run_hook
|
def run_hook(name, *args)
return if @hooks[name].blank?
@hooks[name].each do |hook|
args.any? ? hook.call(*args) : hook.call
end
end
|
ruby
|
def run_hook(name, *args)
return if @hooks[name].blank?
@hooks[name].each do |hook|
args.any? ? hook.call(*args) : hook.call
end
end
|
[
"def",
"run_hook",
"(",
"name",
",",
"*",
"args",
")",
"return",
"if",
"@hooks",
"[",
"name",
"]",
".",
"blank?",
"@hooks",
"[",
"name",
"]",
".",
"each",
"do",
"|",
"hook",
"|",
"args",
".",
"any?",
"?",
"hook",
".",
"call",
"(",
"args",
")",
":",
"hook",
".",
"call",
"end",
"end"
] |
Run a hook
@api private
@param name [Symbol] Hook name
@param args [Array] Hook arguments
|
[
"Run",
"a",
"hook"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/storage.rb#L387-L393
|
10,076
|
polypressure/formant
|
lib/formant.rb
|
Formant.FormObject.reformatted!
|
def reformatted!
self.class.format_fields.each do |field_name, format_method, options|
formatted_value = send(format_method, get_field(field_name), options)
set_field(field_name, formatted_value)
end
self
end
|
ruby
|
def reformatted!
self.class.format_fields.each do |field_name, format_method, options|
formatted_value = send(format_method, get_field(field_name), options)
set_field(field_name, formatted_value)
end
self
end
|
[
"def",
"reformatted!",
"self",
".",
"class",
".",
"format_fields",
".",
"each",
"do",
"|",
"field_name",
",",
"format_method",
",",
"options",
"|",
"formatted_value",
"=",
"send",
"(",
"format_method",
",",
"get_field",
"(",
"field_name",
")",
",",
"options",
")",
"set_field",
"(",
"field_name",
",",
"formatted_value",
")",
"end",
"self",
"end"
] |
Triger any formatting rules specified with the reformat directive.
The attributes are reformatted and mutated in place.
Returns an instance of the form object.
|
[
"Triger",
"any",
"formatting",
"rules",
"specified",
"with",
"the",
"reformat",
"directive",
".",
"The",
"attributes",
"are",
"reformatted",
"and",
"mutated",
"in",
"place",
"."
] |
fbfe7095542f92ef3d1e659038c4257aafe417c5
|
https://github.com/polypressure/formant/blob/fbfe7095542f92ef3d1e659038c4257aafe417c5/lib/formant.rb#L101-L107
|
10,077
|
polypressure/formant
|
lib/formant.rb
|
Formant.FormObject.to_params
|
def to_params
attrs = Hash.new
instance_variables.each do |ivar|
name = ivar[1..-1]
attrs[name.to_sym] = instance_variable_get(ivar) if respond_to? "#{name}="
end
attrs
end
|
ruby
|
def to_params
attrs = Hash.new
instance_variables.each do |ivar|
name = ivar[1..-1]
attrs[name.to_sym] = instance_variable_get(ivar) if respond_to? "#{name}="
end
attrs
end
|
[
"def",
"to_params",
"attrs",
"=",
"Hash",
".",
"new",
"instance_variables",
".",
"each",
"do",
"|",
"ivar",
"|",
"name",
"=",
"ivar",
"[",
"1",
"..",
"-",
"1",
"]",
"attrs",
"[",
"name",
".",
"to_sym",
"]",
"=",
"instance_variable_get",
"(",
"ivar",
")",
"if",
"respond_to?",
"\"#{name}=\"",
"end",
"attrs",
"end"
] |
Return all the attributes as a params hash.
|
[
"Return",
"all",
"the",
"attributes",
"as",
"a",
"params",
"hash",
"."
] |
fbfe7095542f92ef3d1e659038c4257aafe417c5
|
https://github.com/polypressure/formant/blob/fbfe7095542f92ef3d1e659038c4257aafe417c5/lib/formant.rb#L112-L119
|
10,078
|
cjbottaro/param_protected
|
lib/param_protected/protector.rb
|
ParamProtected.Protector.merge_protections
|
def merge_protections(protections, protected_params)
protected_params.each do |k,v|
if protections[k].is_a?(Hash)
merge_protections(protections[k], v) if v
else
protections[k] = v
end
end
protections
end
|
ruby
|
def merge_protections(protections, protected_params)
protected_params.each do |k,v|
if protections[k].is_a?(Hash)
merge_protections(protections[k], v) if v
else
protections[k] = v
end
end
protections
end
|
[
"def",
"merge_protections",
"(",
"protections",
",",
"protected_params",
")",
"protected_params",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"if",
"protections",
"[",
"k",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"merge_protections",
"(",
"protections",
"[",
"k",
"]",
",",
"v",
")",
"if",
"v",
"else",
"protections",
"[",
"k",
"]",
"=",
"v",
"end",
"end",
"protections",
"end"
] |
Merge protections for the same params into one so as to allow extension of them
in inheriting controllers.
Mutating the first argument is okay since this method is used within inject only.
Example:
merge_protections({ :foo => { :qux => nil }, :bar => { :baz => nil, :qux => nil } },
{ :foo => { :baz => nil, :qux => { :foo => nil } } })
=>
{ :foo => { :baz => nil, :qux => { :foo => nil } }, :bar => { :baz =>nil, :qux => nil } }
|
[
"Merge",
"protections",
"for",
"the",
"same",
"params",
"into",
"one",
"so",
"as",
"to",
"allow",
"extension",
"of",
"them",
"in",
"inheriting",
"controllers",
"."
] |
24e2d297b0def7498af02758455d89bd87b62dbc
|
https://github.com/cjbottaro/param_protected/blob/24e2d297b0def7498af02758455d89bd87b62dbc/lib/param_protected/protector.rb#L47-L57
|
10,079
|
alexanderbez/sounddrop
|
lib/sounddrop/drop.rb
|
SoundDrop.Drop.media_url
|
def media_url
begin
r = HTTParty.get("https://api.soundcloud.com/i1/tracks/#{id}/streams?client_id=#{@CLIENT.client_id}")
r['http_mp3_128_url']
rescue Exception => ex
raise SoundDrop::Exception::FailedRequest.new(ex)
end
end
|
ruby
|
def media_url
begin
r = HTTParty.get("https://api.soundcloud.com/i1/tracks/#{id}/streams?client_id=#{@CLIENT.client_id}")
r['http_mp3_128_url']
rescue Exception => ex
raise SoundDrop::Exception::FailedRequest.new(ex)
end
end
|
[
"def",
"media_url",
"begin",
"r",
"=",
"HTTParty",
".",
"get",
"(",
"\"https://api.soundcloud.com/i1/tracks/#{id}/streams?client_id=#{@CLIENT.client_id}\"",
")",
"r",
"[",
"'http_mp3_128_url'",
"]",
"rescue",
"Exception",
"=>",
"ex",
"raise",
"SoundDrop",
"::",
"Exception",
"::",
"FailedRequest",
".",
"new",
"(",
"ex",
")",
"end",
"end"
] |
Track media url
|
[
"Track",
"media",
"url"
] |
563903234cb8a86d2fd8c19f2991437a5dc71d7e
|
https://github.com/alexanderbez/sounddrop/blob/563903234cb8a86d2fd8c19f2991437a5dc71d7e/lib/sounddrop/drop.rb#L35-L42
|
10,080
|
kvokka/active_admin_simple_life
|
lib/active_admin_simple_life/simple_menu.rb
|
ActiveAdminSimpleLife.SimpleMenu.for
|
def for(klass, options = {}, &blk)
ActiveAdmin.register klass do
options = {index: {}, form: {}, filter: {}}.merge options
permitted_params = options.delete :permitted_params
permit_params(*(klass.main_fields + (permitted_params || [])))
# menu_options = options.slice(:priority, :parent, :if)
menu options if options.any?
actions :all, except: [:show]
controller.class_variable_set(:@@permitted_params, permitted_params)
controller.class_variable_set(:@@klass, klass)
controller do
def scoped_collection
permitted_params = self.class.class_variable_get :@@permitted_params
self.class.class_variable_get(:@@klass).includes(*permitted_params.map{|symbol| ExtensionedSymbol.new(symbol).cut_id})
end
end if permitted_params
%i[index filter form].each do |action|
send "#{action}_for_main_fields", klass, options[action] unless options[action][:skip] == true
end
instance_exec &blk if block_given?
end
end
|
ruby
|
def for(klass, options = {}, &blk)
ActiveAdmin.register klass do
options = {index: {}, form: {}, filter: {}}.merge options
permitted_params = options.delete :permitted_params
permit_params(*(klass.main_fields + (permitted_params || [])))
# menu_options = options.slice(:priority, :parent, :if)
menu options if options.any?
actions :all, except: [:show]
controller.class_variable_set(:@@permitted_params, permitted_params)
controller.class_variable_set(:@@klass, klass)
controller do
def scoped_collection
permitted_params = self.class.class_variable_get :@@permitted_params
self.class.class_variable_get(:@@klass).includes(*permitted_params.map{|symbol| ExtensionedSymbol.new(symbol).cut_id})
end
end if permitted_params
%i[index filter form].each do |action|
send "#{action}_for_main_fields", klass, options[action] unless options[action][:skip] == true
end
instance_exec &blk if block_given?
end
end
|
[
"def",
"for",
"(",
"klass",
",",
"options",
"=",
"{",
"}",
",",
"&",
"blk",
")",
"ActiveAdmin",
".",
"register",
"klass",
"do",
"options",
"=",
"{",
"index",
":",
"{",
"}",
",",
"form",
":",
"{",
"}",
",",
"filter",
":",
"{",
"}",
"}",
".",
"merge",
"options",
"permitted_params",
"=",
"options",
".",
"delete",
":permitted_params",
"permit_params",
"(",
"(",
"klass",
".",
"main_fields",
"+",
"(",
"permitted_params",
"||",
"[",
"]",
")",
")",
")",
"# menu_options = options.slice(:priority, :parent, :if)",
"menu",
"options",
"if",
"options",
".",
"any?",
"actions",
":all",
",",
"except",
":",
"[",
":show",
"]",
"controller",
".",
"class_variable_set",
"(",
":@@permitted_params",
",",
"permitted_params",
")",
"controller",
".",
"class_variable_set",
"(",
":@@klass",
",",
"klass",
")",
"controller",
"do",
"def",
"scoped_collection",
"permitted_params",
"=",
"self",
".",
"class",
".",
"class_variable_get",
":@@permitted_params",
"self",
".",
"class",
".",
"class_variable_get",
"(",
":@@klass",
")",
".",
"includes",
"(",
"permitted_params",
".",
"map",
"{",
"|",
"symbol",
"|",
"ExtensionedSymbol",
".",
"new",
"(",
"symbol",
")",
".",
"cut_id",
"}",
")",
"end",
"end",
"if",
"permitted_params",
"%i[",
"index",
"filter",
"form",
"]",
".",
"each",
"do",
"|",
"action",
"|",
"send",
"\"#{action}_for_main_fields\"",
",",
"klass",
",",
"options",
"[",
"action",
"]",
"unless",
"options",
"[",
"action",
"]",
"[",
":skip",
"]",
"==",
"true",
"end",
"instance_exec",
"blk",
"if",
"block_given?",
"end",
"end"
] |
for proper work, model must have class method `mail_fields`, which return array of field symbols.
references write as is, like `foo_id`
in options can take:
menu_priority:integer
menu_parent:string
permitted_params:array for some additions to main_fields permitted params
def simple_menu_for(klass, options = {})
|
[
"for",
"proper",
"work",
"model",
"must",
"have",
"class",
"method",
"mail_fields",
"which",
"return",
"array",
"of",
"field",
"symbols",
".",
"references",
"write",
"as",
"is",
"like",
"foo_id"
] |
050ac1a87462c2b57bd42bae43df3cb0c238c42b
|
https://github.com/kvokka/active_admin_simple_life/blob/050ac1a87462c2b57bd42bae43df3cb0c238c42b/lib/active_admin_simple_life/simple_menu.rb#L14-L39
|
10,081
|
ChrisSandison/missing_text
|
lib/missing_text/diff.rb
|
MissingText.Diff.generate_diff_for_language
|
def generate_diff_for_language(current_language, target_language)
current_langmap = langmap[current_language]
target_langmap = langmap[target_language]
diffmap_key = [current_language, target_language]
diffmap[diffmap_key] = current_langmap - target_langmap
end
|
ruby
|
def generate_diff_for_language(current_language, target_language)
current_langmap = langmap[current_language]
target_langmap = langmap[target_language]
diffmap_key = [current_language, target_language]
diffmap[diffmap_key] = current_langmap - target_langmap
end
|
[
"def",
"generate_diff_for_language",
"(",
"current_language",
",",
"target_language",
")",
"current_langmap",
"=",
"langmap",
"[",
"current_language",
"]",
"target_langmap",
"=",
"langmap",
"[",
"target_language",
"]",
"diffmap_key",
"=",
"[",
"current_language",
",",
"target_language",
"]",
"diffmap",
"[",
"diffmap_key",
"]",
"=",
"current_langmap",
"-",
"target_langmap",
"end"
] |
a diffmap shows what is missing between two languages
the key is a two-element array, the first element is the current language
and the second element is the target language
for example
diffmap: {[:en, :fr] => [[:obj3], ...]}
means that fr was examined against en, where en had an entry for obj3 that fr didn't
|
[
"a",
"diffmap",
"shows",
"what",
"is",
"missing",
"between",
"two",
"languages",
"the",
"key",
"is",
"a",
"two",
"-",
"element",
"array",
"the",
"first",
"element",
"is",
"the",
"current",
"language",
"and",
"the",
"second",
"element",
"is",
"the",
"target",
"language"
] |
dd33f0118f0a69798537e0280a6c62dc387f3e81
|
https://github.com/ChrisSandison/missing_text/blob/dd33f0118f0a69798537e0280a6c62dc387f3e81/lib/missing_text/diff.rb#L106-L111
|
10,082
|
ChrisSandison/missing_text
|
lib/missing_text/diff.rb
|
MissingText.Diff.make_keymap
|
def make_keymap(langmap_entry, language)
language.each do |key, value|
if value.is_a? Hash
make_keymap_for(langmap_entry, value, [key.to_sym])
else
langmap_entry << [key.to_sym]
end
end
end
|
ruby
|
def make_keymap(langmap_entry, language)
language.each do |key, value|
if value.is_a? Hash
make_keymap_for(langmap_entry, value, [key.to_sym])
else
langmap_entry << [key.to_sym]
end
end
end
|
[
"def",
"make_keymap",
"(",
"langmap_entry",
",",
"language",
")",
"language",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
".",
"is_a?",
"Hash",
"make_keymap_for",
"(",
"langmap_entry",
",",
"value",
",",
"[",
"key",
".",
"to_sym",
"]",
")",
"else",
"langmap_entry",
"<<",
"[",
"key",
".",
"to_sym",
"]",
"end",
"end",
"end"
] |
outer method for creating keymap on parent hash
|
[
"outer",
"method",
"for",
"creating",
"keymap",
"on",
"parent",
"hash"
] |
dd33f0118f0a69798537e0280a6c62dc387f3e81
|
https://github.com/ChrisSandison/missing_text/blob/dd33f0118f0a69798537e0280a6c62dc387f3e81/lib/missing_text/diff.rb#L133-L141
|
10,083
|
ChrisSandison/missing_text
|
lib/missing_text/diff.rb
|
MissingText.Diff.make_keymap_for
|
def make_keymap_for(langmap_entry, language, key_path)
language.each do |key, value|
# need a new value of this for every value we are looking at because we want all route traces to have single threading for when they are called again
new_path = Array.new key_path
if value.is_a? Hash
make_keymap_for(langmap_entry, value, new_path.push(key.to_s.to_sym))
else
langmap_entry << new_path.push(key.to_s.to_sym)
end
end
end
|
ruby
|
def make_keymap_for(langmap_entry, language, key_path)
language.each do |key, value|
# need a new value of this for every value we are looking at because we want all route traces to have single threading for when they are called again
new_path = Array.new key_path
if value.is_a? Hash
make_keymap_for(langmap_entry, value, new_path.push(key.to_s.to_sym))
else
langmap_entry << new_path.push(key.to_s.to_sym)
end
end
end
|
[
"def",
"make_keymap_for",
"(",
"langmap_entry",
",",
"language",
",",
"key_path",
")",
"language",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"# need a new value of this for every value we are looking at because we want all route traces to have single threading for when they are called again",
"new_path",
"=",
"Array",
".",
"new",
"key_path",
"if",
"value",
".",
"is_a?",
"Hash",
"make_keymap_for",
"(",
"langmap_entry",
",",
"value",
",",
"new_path",
".",
"push",
"(",
"key",
".",
"to_s",
".",
"to_sym",
")",
")",
"else",
"langmap_entry",
"<<",
"new_path",
".",
"push",
"(",
"key",
".",
"to_s",
".",
"to_sym",
")",
"end",
"end",
"end"
] |
recursive helper for creating keymap on children hashes
|
[
"recursive",
"helper",
"for",
"creating",
"keymap",
"on",
"children",
"hashes"
] |
dd33f0118f0a69798537e0280a6c62dc387f3e81
|
https://github.com/ChrisSandison/missing_text/blob/dd33f0118f0a69798537e0280a6c62dc387f3e81/lib/missing_text/diff.rb#L144-L154
|
10,084
|
teodor-pripoae/scalaroid
|
lib/scalaroid/transaction_single_op.rb
|
Scalaroid.TransactionSingleOp.write
|
def write(key, value, binary = false)
value = @conn.class.encode_value(value, binary)
result = @conn.call(:write, [key, value])
@conn.class.check_fail_abort(result)
@conn.class.process_result_commit(result)
end
|
ruby
|
def write(key, value, binary = false)
value = @conn.class.encode_value(value, binary)
result = @conn.call(:write, [key, value])
@conn.class.check_fail_abort(result)
@conn.class.process_result_commit(result)
end
|
[
"def",
"write",
"(",
"key",
",",
"value",
",",
"binary",
"=",
"false",
")",
"value",
"=",
"@conn",
".",
"class",
".",
"encode_value",
"(",
"value",
",",
"binary",
")",
"result",
"=",
"@conn",
".",
"call",
"(",
":write",
",",
"[",
"key",
",",
"value",
"]",
")",
"@conn",
".",
"class",
".",
"check_fail_abort",
"(",
"result",
")",
"@conn",
".",
"class",
".",
"process_result_commit",
"(",
"result",
")",
"end"
] |
Write the value to key.
|
[
"Write",
"the",
"value",
"to",
"key",
"."
] |
4e9e90e71ce3008da79a72eae40fe2f187580be2
|
https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/transaction_single_op.rb#L85-L90
|
10,085
|
teodor-pripoae/scalaroid
|
lib/scalaroid/transaction_single_op.rb
|
Scalaroid.TransactionSingleOp.add_del_on_list
|
def add_del_on_list(key, to_add, to_remove)
result = @conn.call(:add_del_on_list, [key, to_add, to_remove])
@conn.class.check_fail_abort(result)
@conn.class.process_result_add_del_on_list(result)
end
|
ruby
|
def add_del_on_list(key, to_add, to_remove)
result = @conn.call(:add_del_on_list, [key, to_add, to_remove])
@conn.class.check_fail_abort(result)
@conn.class.process_result_add_del_on_list(result)
end
|
[
"def",
"add_del_on_list",
"(",
"key",
",",
"to_add",
",",
"to_remove",
")",
"result",
"=",
"@conn",
".",
"call",
"(",
":add_del_on_list",
",",
"[",
"key",
",",
"to_add",
",",
"to_remove",
"]",
")",
"@conn",
".",
"class",
".",
"check_fail_abort",
"(",
"result",
")",
"@conn",
".",
"class",
".",
"process_result_add_del_on_list",
"(",
"result",
")",
"end"
] |
Changes the list stored at the given key, i.e. first adds all items in
to_add then removes all items in to_remove.
Both, to_add and to_remove, must be lists.
Assumes en empty list if no value exists at key.
|
[
"Changes",
"the",
"list",
"stored",
"at",
"the",
"given",
"key",
"i",
".",
"e",
".",
"first",
"adds",
"all",
"items",
"in",
"to_add",
"then",
"removes",
"all",
"items",
"in",
"to_remove",
".",
"Both",
"to_add",
"and",
"to_remove",
"must",
"be",
"lists",
".",
"Assumes",
"en",
"empty",
"list",
"if",
"no",
"value",
"exists",
"at",
"key",
"."
] |
4e9e90e71ce3008da79a72eae40fe2f187580be2
|
https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/transaction_single_op.rb#L96-L100
|
10,086
|
teodor-pripoae/scalaroid
|
lib/scalaroid/transaction_single_op.rb
|
Scalaroid.TransactionSingleOp.add_on_nr
|
def add_on_nr(key, to_add)
result = @conn.call(:add_on_nr, [key, to_add])
@conn.class.check_fail_abort(result)
@conn.class.process_result_add_on_nr(result)
end
|
ruby
|
def add_on_nr(key, to_add)
result = @conn.call(:add_on_nr, [key, to_add])
@conn.class.check_fail_abort(result)
@conn.class.process_result_add_on_nr(result)
end
|
[
"def",
"add_on_nr",
"(",
"key",
",",
"to_add",
")",
"result",
"=",
"@conn",
".",
"call",
"(",
":add_on_nr",
",",
"[",
"key",
",",
"to_add",
"]",
")",
"@conn",
".",
"class",
".",
"check_fail_abort",
"(",
"result",
")",
"@conn",
".",
"class",
".",
"process_result_add_on_nr",
"(",
"result",
")",
"end"
] |
Changes the number stored at the given key, i.e. adds some value.
Assumes 0 if no value exists at key.
|
[
"Changes",
"the",
"number",
"stored",
"at",
"the",
"given",
"key",
"i",
".",
"e",
".",
"adds",
"some",
"value",
".",
"Assumes",
"0",
"if",
"no",
"value",
"exists",
"at",
"key",
"."
] |
4e9e90e71ce3008da79a72eae40fe2f187580be2
|
https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/transaction_single_op.rb#L104-L108
|
10,087
|
NUBIC/psc.rb
|
lib/psc/connection.rb
|
Psc.Connection.has_superclass?
|
def has_superclass?(child, ancestor)
if child.superclass == ancestor
true
elsif child.superclass.nil?
false
else
has_superclass?(child.superclass, ancestor)
end
end
|
ruby
|
def has_superclass?(child, ancestor)
if child.superclass == ancestor
true
elsif child.superclass.nil?
false
else
has_superclass?(child.superclass, ancestor)
end
end
|
[
"def",
"has_superclass?",
"(",
"child",
",",
"ancestor",
")",
"if",
"child",
".",
"superclass",
"==",
"ancestor",
"true",
"elsif",
"child",
".",
"superclass",
".",
"nil?",
"false",
"else",
"has_superclass?",
"(",
"child",
".",
"superclass",
",",
"ancestor",
")",
"end",
"end"
] |
It seems like there must be a builtin for this, but I'm not
finding it.
|
[
"It",
"seems",
"like",
"there",
"must",
"be",
"a",
"builtin",
"for",
"this",
"but",
"I",
"m",
"not",
"finding",
"it",
"."
] |
4ac9df03fe655094e4889966a9a1e029583a38de
|
https://github.com/NUBIC/psc.rb/blob/4ac9df03fe655094e4889966a9a1e029583a38de/lib/psc/connection.rb#L87-L95
|
10,088
|
jonahoffline/endi_feed
|
lib/endi_feed/news.rb
|
EndiFeed.News.process_news
|
def process_news(total = 25)
items.map.with_index do |item, num|
@headlines << format_headline(item, num) if total_met?(total)
end.compact || nil
end
|
ruby
|
def process_news(total = 25)
items.map.with_index do |item, num|
@headlines << format_headline(item, num) if total_met?(total)
end.compact || nil
end
|
[
"def",
"process_news",
"(",
"total",
"=",
"25",
")",
"items",
".",
"map",
".",
"with_index",
"do",
"|",
"item",
",",
"num",
"|",
"@headlines",
"<<",
"format_headline",
"(",
"item",
",",
"num",
")",
"if",
"total_met?",
"(",
"total",
")",
"end",
".",
"compact",
"||",
"nil",
"end"
] |
Handles iteration of each headline
@return [Array<String>] news headlines
|
[
"Handles",
"iteration",
"of",
"each",
"headline"
] |
d698a7104fb74273098734d62c2291a47f861115
|
https://github.com/jonahoffline/endi_feed/blob/d698a7104fb74273098734d62c2291a47f861115/lib/endi_feed/news.rb#L93-L97
|
10,089
|
cul/cul-ldap
|
lib/cul/ldap.rb
|
Cul.LDAP.find_by_uni
|
def find_by_uni(uni)
entries = search(base: "ou=People,o=Columbia University, c=US", filter: Net::LDAP::Filter.eq("uid", uni))
(entries.count == 1) ? entries.first : nil
end
|
ruby
|
def find_by_uni(uni)
entries = search(base: "ou=People,o=Columbia University, c=US", filter: Net::LDAP::Filter.eq("uid", uni))
(entries.count == 1) ? entries.first : nil
end
|
[
"def",
"find_by_uni",
"(",
"uni",
")",
"entries",
"=",
"search",
"(",
"base",
":",
"\"ou=People,o=Columbia University, c=US\"",
",",
"filter",
":",
"Net",
"::",
"LDAP",
"::",
"Filter",
".",
"eq",
"(",
"\"uid\"",
",",
"uni",
")",
")",
"(",
"entries",
".",
"count",
"==",
"1",
")",
"?",
"entries",
".",
"first",
":",
"nil",
"end"
] |
LDAP lookup based on UNI. If record could not be found returns nil.
@param [String] uni
@return [Cul::LDAP::Entry] containing all the ldap information available for the uni given
@return [nil] if record for uni could not be found, or more than one record was found
|
[
"LDAP",
"lookup",
"based",
"on",
"UNI",
".",
"If",
"record",
"could",
"not",
"be",
"found",
"returns",
"nil",
"."
] |
07c35bbf1c2fdc73719e32c39397c3971c0878bc
|
https://github.com/cul/cul-ldap/blob/07c35bbf1c2fdc73719e32c39397c3971c0878bc/lib/cul/ldap.rb#L28-L31
|
10,090
|
cul/cul-ldap
|
lib/cul/ldap.rb
|
Cul.LDAP.find_by_name
|
def find_by_name(name)
if name.include?(',')
name = name.split(',').map(&:strip).reverse.join(" ")
end
entries = search(base: "ou=People,o=Columbia University, c=US", filter: Net::LDAP::Filter.eq("cn", name))
(entries.count == 1) ? entries.first : nil
end
|
ruby
|
def find_by_name(name)
if name.include?(',')
name = name.split(',').map(&:strip).reverse.join(" ")
end
entries = search(base: "ou=People,o=Columbia University, c=US", filter: Net::LDAP::Filter.eq("cn", name))
(entries.count == 1) ? entries.first : nil
end
|
[
"def",
"find_by_name",
"(",
"name",
")",
"if",
"name",
".",
"include?",
"(",
"','",
")",
"name",
"=",
"name",
".",
"split",
"(",
"','",
")",
".",
"map",
"(",
":strip",
")",
".",
"reverse",
".",
"join",
"(",
"\" \"",
")",
"end",
"entries",
"=",
"search",
"(",
"base",
":",
"\"ou=People,o=Columbia University, c=US\"",
",",
"filter",
":",
"Net",
"::",
"LDAP",
"::",
"Filter",
".",
"eq",
"(",
"\"cn\"",
",",
"name",
")",
")",
"(",
"entries",
".",
"count",
"==",
"1",
")",
"?",
"entries",
".",
"first",
":",
"nil",
"end"
] |
LDAP lookup based on name.
@param [String] name
@return [Cul::LDAP::Entry] containing the entry matching this name, if it is unique
@return [nil] if record could not be found or if there is more than one match
|
[
"LDAP",
"lookup",
"based",
"on",
"name",
"."
] |
07c35bbf1c2fdc73719e32c39397c3971c0878bc
|
https://github.com/cul/cul-ldap/blob/07c35bbf1c2fdc73719e32c39397c3971c0878bc/lib/cul/ldap.rb#L38-L44
|
10,091
|
thirst/glass-rails
|
lib/glass/client.rb
|
Glass.Client.rest_action
|
def rest_action(options, action="insert")
body_object = json_content(options, action)
inserting_content = { api_method: mirror_api.timeline.send(action),
body_object: body_object}
end
|
ruby
|
def rest_action(options, action="insert")
body_object = json_content(options, action)
inserting_content = { api_method: mirror_api.timeline.send(action),
body_object: body_object}
end
|
[
"def",
"rest_action",
"(",
"options",
",",
"action",
"=",
"\"insert\"",
")",
"body_object",
"=",
"json_content",
"(",
"options",
",",
"action",
")",
"inserting_content",
"=",
"{",
"api_method",
":",
"mirror_api",
".",
"timeline",
".",
"send",
"(",
"action",
")",
",",
"body_object",
":",
"body_object",
"}",
"end"
] |
optional parameter is merged into the content hash
before sending. good for specifying more application
specific stuff like speakableText parameters.
|
[
"optional",
"parameter",
"is",
"merged",
"into",
"the",
"content",
"hash",
"before",
"sending",
".",
"good",
"for",
"specifying",
"more",
"application",
"specific",
"stuff",
"like",
"speakableText",
"parameters",
"."
] |
a581281a9c5d09ed21ba7369b5b714f1c95d629d
|
https://github.com/thirst/glass-rails/blob/a581281a9c5d09ed21ba7369b5b714f1c95d629d/lib/glass/client.rb#L88-L92
|
10,092
|
thirst/glass-rails
|
lib/glass/client.rb
|
Glass.Client.list
|
def list(opts={as_hash: true})
page_token = nil
parameters = {}
self.timeline_list = []
begin
parameters = {}
parameters['pageToken'] = page_token if page_token.present?
api_result = google_client.execute(api_method: mirror_api.timeline.list,
parameters: parameters)
if api_result.success?
timeline_items = api_result.data
page_token = nil if timeline_items.items.empty?
if timeline_items.items.any?
@timeline_list.concat(timeline_items.items)
page_token = timeline_items.next_page_token
end
else
puts "An error occurred: #{api_result.data['error']['message']}"
page_token = nil
end
end while page_token.to_s != ''
timeline_list(opts)
end
|
ruby
|
def list(opts={as_hash: true})
page_token = nil
parameters = {}
self.timeline_list = []
begin
parameters = {}
parameters['pageToken'] = page_token if page_token.present?
api_result = google_client.execute(api_method: mirror_api.timeline.list,
parameters: parameters)
if api_result.success?
timeline_items = api_result.data
page_token = nil if timeline_items.items.empty?
if timeline_items.items.any?
@timeline_list.concat(timeline_items.items)
page_token = timeline_items.next_page_token
end
else
puts "An error occurred: #{api_result.data['error']['message']}"
page_token = nil
end
end while page_token.to_s != ''
timeline_list(opts)
end
|
[
"def",
"list",
"(",
"opts",
"=",
"{",
"as_hash",
":",
"true",
"}",
")",
"page_token",
"=",
"nil",
"parameters",
"=",
"{",
"}",
"self",
".",
"timeline_list",
"=",
"[",
"]",
"begin",
"parameters",
"=",
"{",
"}",
"parameters",
"[",
"'pageToken'",
"]",
"=",
"page_token",
"if",
"page_token",
".",
"present?",
"api_result",
"=",
"google_client",
".",
"execute",
"(",
"api_method",
":",
"mirror_api",
".",
"timeline",
".",
"list",
",",
"parameters",
":",
"parameters",
")",
"if",
"api_result",
".",
"success?",
"timeline_items",
"=",
"api_result",
".",
"data",
"page_token",
"=",
"nil",
"if",
"timeline_items",
".",
"items",
".",
"empty?",
"if",
"timeline_items",
".",
"items",
".",
"any?",
"@timeline_list",
".",
"concat",
"(",
"timeline_items",
".",
"items",
")",
"page_token",
"=",
"timeline_items",
".",
"next_page_token",
"end",
"else",
"puts",
"\"An error occurred: #{api_result.data['error']['message']}\"",
"page_token",
"=",
"nil",
"end",
"end",
"while",
"page_token",
".",
"to_s",
"!=",
"''",
"timeline_list",
"(",
"opts",
")",
"end"
] |
this method is pretty much extracted directly from
the mirror API code samples in ruby
https://developers.google.com/glass/v1/reference/timeline/list
|
[
"this",
"method",
"is",
"pretty",
"much",
"extracted",
"directly",
"from",
"the",
"mirror",
"API",
"code",
"samples",
"in",
"ruby"
] |
a581281a9c5d09ed21ba7369b5b714f1c95d629d
|
https://github.com/thirst/glass-rails/blob/a581281a9c5d09ed21ba7369b5b714f1c95d629d/lib/glass/client.rb#L135-L157
|
10,093
|
zohararad/handlebarer
|
lib/handlebarer/serialize.rb
|
Handlebarer.Serialize.to_hbs
|
def to_hbs
h = {:model => self.class.name.downcase}
self.hbs_attributes.each do |attr|
h[attr] = self.send(attr)
ans = h[attr].class.ancestors
if h[attr].class.respond_to?(:hbs_serializable) || ans.include?(Enumerable) || ans.include?(ActiveModel::Validations)
h[attr] = h[attr].to_hbs
else
end
end
h
end
|
ruby
|
def to_hbs
h = {:model => self.class.name.downcase}
self.hbs_attributes.each do |attr|
h[attr] = self.send(attr)
ans = h[attr].class.ancestors
if h[attr].class.respond_to?(:hbs_serializable) || ans.include?(Enumerable) || ans.include?(ActiveModel::Validations)
h[attr] = h[attr].to_hbs
else
end
end
h
end
|
[
"def",
"to_hbs",
"h",
"=",
"{",
":model",
"=>",
"self",
".",
"class",
".",
"name",
".",
"downcase",
"}",
"self",
".",
"hbs_attributes",
".",
"each",
"do",
"|",
"attr",
"|",
"h",
"[",
"attr",
"]",
"=",
"self",
".",
"send",
"(",
"attr",
")",
"ans",
"=",
"h",
"[",
"attr",
"]",
".",
"class",
".",
"ancestors",
"if",
"h",
"[",
"attr",
"]",
".",
"class",
".",
"respond_to?",
"(",
":hbs_serializable",
")",
"||",
"ans",
".",
"include?",
"(",
"Enumerable",
")",
"||",
"ans",
".",
"include?",
"(",
"ActiveModel",
"::",
"Validations",
")",
"h",
"[",
"attr",
"]",
"=",
"h",
"[",
"attr",
"]",
".",
"to_hbs",
"else",
"end",
"end",
"h",
"end"
] |
Serialize instance attributes to a Hash based on serializable attributes defined on Model class.
@return [Hash] hash of model instance attributes
|
[
"Serialize",
"instance",
"attributes",
"to",
"a",
"Hash",
"based",
"on",
"serializable",
"attributes",
"defined",
"on",
"Model",
"class",
"."
] |
f5b2db17cb72fd2874ebe8268cf6f2ae17e74002
|
https://github.com/zohararad/handlebarer/blob/f5b2db17cb72fd2874ebe8268cf6f2ae17e74002/lib/handlebarer/serialize.rb#L40-L52
|
10,094
|
zohararad/handlebarer
|
lib/handlebarer/serialize.rb
|
Handlebarer.Serialize.hbs_attributes
|
def hbs_attributes
s = self.class.class_variable_get(:@@serialize)
if s[:merge]
attrs = s[:attrs] + self.attributes.keys
else
attrs = s[:attrs]
end
attrs.collect{|attr| attr.to_sym}.uniq
end
|
ruby
|
def hbs_attributes
s = self.class.class_variable_get(:@@serialize)
if s[:merge]
attrs = s[:attrs] + self.attributes.keys
else
attrs = s[:attrs]
end
attrs.collect{|attr| attr.to_sym}.uniq
end
|
[
"def",
"hbs_attributes",
"s",
"=",
"self",
".",
"class",
".",
"class_variable_get",
"(",
":@@serialize",
")",
"if",
"s",
"[",
":merge",
"]",
"attrs",
"=",
"s",
"[",
":attrs",
"]",
"+",
"self",
".",
"attributes",
".",
"keys",
"else",
"attrs",
"=",
"s",
"[",
":attrs",
"]",
"end",
"attrs",
".",
"collect",
"{",
"|",
"attr",
"|",
"attr",
".",
"to_sym",
"}",
".",
"uniq",
"end"
] |
List of Model attributes that should be serialized when called `to_hbs` on Model instance
@return [Array] list of serializable attributes
|
[
"List",
"of",
"Model",
"attributes",
"that",
"should",
"be",
"serialized",
"when",
"called",
"to_hbs",
"on",
"Model",
"instance"
] |
f5b2db17cb72fd2874ebe8268cf6f2ae17e74002
|
https://github.com/zohararad/handlebarer/blob/f5b2db17cb72fd2874ebe8268cf6f2ae17e74002/lib/handlebarer/serialize.rb#L56-L64
|
10,095
|
patchapps/hash-that-tree
|
lib/compare.rb
|
HashThatTree.CompareMD5.validate
|
def validate
if(folder1==nil) || (folder1=="") || !Dir.exists?(folder1)
puts "a valid folder path is required as argument 1"
exit
end
if(folder2==nil) || (folder2=="") || !Dir.exists?(folder2)
puts "a valid folder path is required as argument 2"
exit
end
end
|
ruby
|
def validate
if(folder1==nil) || (folder1=="") || !Dir.exists?(folder1)
puts "a valid folder path is required as argument 1"
exit
end
if(folder2==nil) || (folder2=="") || !Dir.exists?(folder2)
puts "a valid folder path is required as argument 2"
exit
end
end
|
[
"def",
"validate",
"if",
"(",
"folder1",
"==",
"nil",
")",
"||",
"(",
"folder1",
"==",
"\"\"",
")",
"||",
"!",
"Dir",
".",
"exists?",
"(",
"folder1",
")",
"puts",
"\"a valid folder path is required as argument 1\"",
"exit",
"end",
"if",
"(",
"folder2",
"==",
"nil",
")",
"||",
"(",
"folder2",
"==",
"\"\"",
")",
"||",
"!",
"Dir",
".",
"exists?",
"(",
"folder2",
")",
"puts",
"\"a valid folder path is required as argument 2\"",
"exit",
"end",
"end"
] |
the format to output the results to. csv, html or json
initialize the class with the folders to be compared
Validates the input ensuring the arguments are both valid folders
|
[
"the",
"format",
"to",
"output",
"the",
"results",
"to",
".",
"csv",
"html",
"or",
"json",
"initialize",
"the",
"class",
"with",
"the",
"folders",
"to",
"be",
"compared",
"Validates",
"the",
"input",
"ensuring",
"the",
"arguments",
"are",
"both",
"valid",
"folders"
] |
05a006389340d96d13613abc60a16f83b2bfd052
|
https://github.com/patchapps/hash-that-tree/blob/05a006389340d96d13613abc60a16f83b2bfd052/lib/compare.rb#L28-L39
|
10,096
|
patchapps/hash-that-tree
|
lib/compare.rb
|
HashThatTree.CompareMD5.display_results_html
|
def display_results_html
output ="<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title></title></head><body>"
output.concat("<table><thead><tr><td>FileName</td></tr><tr><td>#{@folder1}</td></tr><tr><td>#{@folder2}</td></tr><tr><td>Equal</td></tr></thead>")
@filehash.each{ |key, value| output.concat("<tbody><tr><td>#{value.file_name}</td></tr><tr><td>#{value.file_hash1}</td></tr><tr><td>#{value.file_hash2}</td></tr><tr><td>#{value.file_hash1==value.file_hash2}</td></tr>")}
output.concat("</tbody></table></body></html>")
puts output
end
|
ruby
|
def display_results_html
output ="<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title></title></head><body>"
output.concat("<table><thead><tr><td>FileName</td></tr><tr><td>#{@folder1}</td></tr><tr><td>#{@folder2}</td></tr><tr><td>Equal</td></tr></thead>")
@filehash.each{ |key, value| output.concat("<tbody><tr><td>#{value.file_name}</td></tr><tr><td>#{value.file_hash1}</td></tr><tr><td>#{value.file_hash2}</td></tr><tr><td>#{value.file_hash1==value.file_hash2}</td></tr>")}
output.concat("</tbody></table></body></html>")
puts output
end
|
[
"def",
"display_results_html",
"output",
"=",
"\"<!DOCTYPE html><html xmlns=\\\"http://www.w3.org/1999/xhtml\\\"><head><title></title></head><body>\"",
"output",
".",
"concat",
"(",
"\"<table><thead><tr><td>FileName</td></tr><tr><td>#{@folder1}</td></tr><tr><td>#{@folder2}</td></tr><tr><td>Equal</td></tr></thead>\"",
")",
"@filehash",
".",
"each",
"{",
"|",
"key",
",",
"value",
"|",
"output",
".",
"concat",
"(",
"\"<tbody><tr><td>#{value.file_name}</td></tr><tr><td>#{value.file_hash1}</td></tr><tr><td>#{value.file_hash2}</td></tr><tr><td>#{value.file_hash1==value.file_hash2}</td></tr>\"",
")",
"}",
"output",
".",
"concat",
"(",
"\"</tbody></table></body></html>\"",
")",
"puts",
"output",
"end"
] |
Prints the results to standard out in the csv format specified.
|
[
"Prints",
"the",
"results",
"to",
"standard",
"out",
"in",
"the",
"csv",
"format",
"specified",
"."
] |
05a006389340d96d13613abc60a16f83b2bfd052
|
https://github.com/patchapps/hash-that-tree/blob/05a006389340d96d13613abc60a16f83b2bfd052/lib/compare.rb#L96-L102
|
10,097
|
plexus/analects
|
lib/analects/encoding.rb
|
Analects.Encoding.ratings
|
def ratings(str)
all_valid_cjk(str).map do |enc|
[
enc,
recode(enc, str).codepoints.map do |point|
Analects::Models::Zi.codepoint_ranges.map.with_index do |range, idx|
next 6 - idx if range.include?(point)
0
end.inject(:+)
end.inject(:+)
]
end.sort_by(&:last).reverse
end
|
ruby
|
def ratings(str)
all_valid_cjk(str).map do |enc|
[
enc,
recode(enc, str).codepoints.map do |point|
Analects::Models::Zi.codepoint_ranges.map.with_index do |range, idx|
next 6 - idx if range.include?(point)
0
end.inject(:+)
end.inject(:+)
]
end.sort_by(&:last).reverse
end
|
[
"def",
"ratings",
"(",
"str",
")",
"all_valid_cjk",
"(",
"str",
")",
".",
"map",
"do",
"|",
"enc",
"|",
"[",
"enc",
",",
"recode",
"(",
"enc",
",",
"str",
")",
".",
"codepoints",
".",
"map",
"do",
"|",
"point",
"|",
"Analects",
"::",
"Models",
"::",
"Zi",
".",
"codepoint_ranges",
".",
"map",
".",
"with_index",
"do",
"|",
"range",
",",
"idx",
"|",
"next",
"6",
"-",
"idx",
"if",
"range",
".",
"include?",
"(",
"point",
")",
"0",
"end",
".",
"inject",
"(",
":+",
")",
"end",
".",
"inject",
"(",
":+",
")",
"]",
"end",
".",
"sort_by",
"(",
":last",
")",
".",
"reverse",
"end"
] |
Crude way to guess which encoding it is
|
[
"Crude",
"way",
"to",
"guess",
"which",
"encoding",
"it",
"is"
] |
3ef5c9b54b5d31fd1c3b7143f9e5e4ae40185dd9
|
https://github.com/plexus/analects/blob/3ef5c9b54b5d31fd1c3b7143f9e5e4ae40185dd9/lib/analects/encoding.rb#L34-L46
|
10,098
|
ecssiah/project-euler-cli
|
lib/project_euler_cli/concerns/scraper.rb
|
ProjectEulerCli.Scraper.lookup_totals
|
def lookup_totals
begin
Timeout.timeout(4) do
html = open("https://projecteuler.net/recent")
fragment = Nokogiri::HTML(html)
id_col = fragment.css('#problems_table td.id_column')
# The newest problem is the first one listed on the recent page. The ID
# of this problem will always equal the total number of problems.
id_col.first.text.to_i.times { Problem.new }
# There are ten problems on the recent page, so the last archive problem
# can be found by subtracting 10 from the total number of problems.
Page.total = Problem.page(Problem.total - 10)
end
rescue Timeout::Error
puts "Project Euler is not responding."
exit(true)
end
end
|
ruby
|
def lookup_totals
begin
Timeout.timeout(4) do
html = open("https://projecteuler.net/recent")
fragment = Nokogiri::HTML(html)
id_col = fragment.css('#problems_table td.id_column')
# The newest problem is the first one listed on the recent page. The ID
# of this problem will always equal the total number of problems.
id_col.first.text.to_i.times { Problem.new }
# There are ten problems on the recent page, so the last archive problem
# can be found by subtracting 10 from the total number of problems.
Page.total = Problem.page(Problem.total - 10)
end
rescue Timeout::Error
puts "Project Euler is not responding."
exit(true)
end
end
|
[
"def",
"lookup_totals",
"begin",
"Timeout",
".",
"timeout",
"(",
"4",
")",
"do",
"html",
"=",
"open",
"(",
"\"https://projecteuler.net/recent\"",
")",
"fragment",
"=",
"Nokogiri",
"::",
"HTML",
"(",
"html",
")",
"id_col",
"=",
"fragment",
".",
"css",
"(",
"'#problems_table td.id_column'",
")",
"# The newest problem is the first one listed on the recent page. The ID ",
"# of this problem will always equal the total number of problems.",
"id_col",
".",
"first",
".",
"text",
".",
"to_i",
".",
"times",
"{",
"Problem",
".",
"new",
"}",
"# There are ten problems on the recent page, so the last archive problem ",
"# can be found by subtracting 10 from the total number of problems.",
"Page",
".",
"total",
"=",
"Problem",
".",
"page",
"(",
"Problem",
".",
"total",
"-",
"10",
")",
"end",
"rescue",
"Timeout",
"::",
"Error",
"puts",
"\"Project Euler is not responding.\"",
"exit",
"(",
"true",
")",
"end",
"end"
] |
Pulls information from the recent page to determine the total number of
problems and pages.
|
[
"Pulls",
"information",
"from",
"the",
"recent",
"page",
"to",
"determine",
"the",
"total",
"number",
"of",
"problems",
"and",
"pages",
"."
] |
ae6fb1fb516bd9bcf193e3e1f1c82894198fe997
|
https://github.com/ecssiah/project-euler-cli/blob/ae6fb1fb516bd9bcf193e3e1f1c82894198fe997/lib/project_euler_cli/concerns/scraper.rb#L8-L28
|
10,099
|
ecssiah/project-euler-cli
|
lib/project_euler_cli/concerns/scraper.rb
|
ProjectEulerCli.Scraper.load_recent
|
def load_recent
return if Page.visited.include?(0)
html = open("https://projecteuler.net/recent")
fragment = Nokogiri::HTML(html)
problem_links = fragment.css('#problems_table td a')
i = Problem.total
problem_links.each do |link|
Problem[i].title = link.text
i -= 1
end
Page.visited << 0
end
|
ruby
|
def load_recent
return if Page.visited.include?(0)
html = open("https://projecteuler.net/recent")
fragment = Nokogiri::HTML(html)
problem_links = fragment.css('#problems_table td a')
i = Problem.total
problem_links.each do |link|
Problem[i].title = link.text
i -= 1
end
Page.visited << 0
end
|
[
"def",
"load_recent",
"return",
"if",
"Page",
".",
"visited",
".",
"include?",
"(",
"0",
")",
"html",
"=",
"open",
"(",
"\"https://projecteuler.net/recent\"",
")",
"fragment",
"=",
"Nokogiri",
"::",
"HTML",
"(",
"html",
")",
"problem_links",
"=",
"fragment",
".",
"css",
"(",
"'#problems_table td a'",
")",
"i",
"=",
"Problem",
".",
"total",
"problem_links",
".",
"each",
"do",
"|",
"link",
"|",
"Problem",
"[",
"i",
"]",
".",
"title",
"=",
"link",
".",
"text",
"i",
"-=",
"1",
"end",
"Page",
".",
"visited",
"<<",
"0",
"end"
] |
Loads in all of the problem numbers and titles from the recent page.
|
[
"Loads",
"in",
"all",
"of",
"the",
"problem",
"numbers",
"and",
"titles",
"from",
"the",
"recent",
"page",
"."
] |
ae6fb1fb516bd9bcf193e3e1f1c82894198fe997
|
https://github.com/ecssiah/project-euler-cli/blob/ae6fb1fb516bd9bcf193e3e1f1c82894198fe997/lib/project_euler_cli/concerns/scraper.rb#L31-L46
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.