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 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
stevenhaddox/cert_munger | lib/cert_munger/formatter.rb | CertMunger.ClassMethods.multi_line_contents | def multi_line_contents(raw_cert)
cert_contents = raw_cert.split(/[-](.*)[-]/)[2]
cert_contents.lines.map do |line|
line.lstrip.squeeze(' ').split(' ')
end
end | ruby | def multi_line_contents(raw_cert)
cert_contents = raw_cert.split(/[-](.*)[-]/)[2]
cert_contents.lines.map do |line|
line.lstrip.squeeze(' ').split(' ')
end
end | [
"def",
"multi_line_contents",
"(",
"raw_cert",
")",
"cert_contents",
"=",
"raw_cert",
".",
"split",
"(",
"/",
"/",
")",
"[",
"2",
"]",
"cert_contents",
".",
"lines",
".",
"map",
"do",
"|",
"line",
"|",
"line",
".",
"lstrip",
".",
"squeeze",
"(",
"' '",... | Attempts to reformat multi-line certificate bodies
@param raw_cert [String] The string of text you wish to parse into a cert
@return [String] reformatted certificate body | [
"Attempts",
"to",
"reformat",
"multi",
"-",
"line",
"certificate",
"bodies"
] | 48a42f93f964bb47f4311d9e3f7a3ab03c7a5bee | https://github.com/stevenhaddox/cert_munger/blob/48a42f93f964bb47f4311d9e3f7a3ab03c7a5bee/lib/cert_munger/formatter.rb#L96-L101 | train |
wvanbergen/love | lib/love.rb | Love.ResourceURI.append_query | def append_query(base_uri, added_params = {})
base_params = base_uri.query ? CGI.parse(base_uri.query) : {}
get_params = base_params.merge(added_params.stringify_keys)
base_uri.dup.tap do |uri|
assignments = get_params.map do |k, v|
case v
when Array; v.map { |val| "#{::C... | ruby | def append_query(base_uri, added_params = {})
base_params = base_uri.query ? CGI.parse(base_uri.query) : {}
get_params = base_params.merge(added_params.stringify_keys)
base_uri.dup.tap do |uri|
assignments = get_params.map do |k, v|
case v
when Array; v.map { |val| "#{::C... | [
"def",
"append_query",
"(",
"base_uri",
",",
"added_params",
"=",
"{",
"}",
")",
"base_params",
"=",
"base_uri",
".",
"query",
"?",
"CGI",
".",
"parse",
"(",
"base_uri",
".",
"query",
")",
":",
"{",
"}",
"get_params",
"=",
"base_params",
".",
"merge",
... | Appends GET parameters to a URI instance. Duplicate parameters will
be replaced with the new value.
@param [URI] base_uri The original URI to work with (will not be modified)
@param [Hash] added_params To GET params to add.
@return [URI] The URI with appended GET parameters | [
"Appends",
"GET",
"parameters",
"to",
"a",
"URI",
"instance",
".",
"Duplicate",
"parameters",
"will",
"be",
"replaced",
"with",
"the",
"new",
"value",
"."
] | 14ed84c2fcc6b008879dd598328ab56d7dd4a053 | https://github.com/wvanbergen/love/blob/14ed84c2fcc6b008879dd598328ab56d7dd4a053/lib/love.rb#L108-L120 | train |
wvanbergen/love | lib/love.rb | Love.Client.connection | def connection
@connection ||= Net::HTTP.new(TENDER_API_HOST, Net::HTTP.https_default_port).tap do |http|
http.use_ssl = true
# http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.start
end
end | ruby | def connection
@connection ||= Net::HTTP.new(TENDER_API_HOST, Net::HTTP.https_default_port).tap do |http|
http.use_ssl = true
# http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.start
end
end | [
"def",
"connection",
"@connection",
"||=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"TENDER_API_HOST",
",",
"Net",
"::",
"HTTP",
".",
"https_default_port",
")",
".",
"tap",
"do",
"|",
"http",
"|",
"http",
".",
"use_ssl",
"=",
"true",
"# http.verify_mode = OpenS... | Returns a persistent connection to the server, reusing a connection of it was
previously established.
This method is mainly used for internal use but can be used to do advanced
HTTP connectivity with the Tender API server.
@return [Net::HTTP] The net/http connection instance. | [
"Returns",
"a",
"persistent",
"connection",
"to",
"the",
"server",
"reusing",
"a",
"connection",
"of",
"it",
"was",
"previously",
"established",
"."
] | 14ed84c2fcc6b008879dd598328ab56d7dd4a053 | https://github.com/wvanbergen/love/blob/14ed84c2fcc6b008879dd598328ab56d7dd4a053/lib/love.rb#L239-L245 | train |
wvanbergen/love | lib/love.rb | Love.Client.paged_each | def paged_each(uri, list_key, options = {}, &block)
query_params = {}
query_params[:since] = options[:since].to_date.to_s(:db) if options[:since]
query_params[:page] = [options[:start_page].to_i, 1].max rescue 1
results = []
initial_result = get(append_query(uri, query_params))
# D... | ruby | def paged_each(uri, list_key, options = {}, &block)
query_params = {}
query_params[:since] = options[:since].to_date.to_s(:db) if options[:since]
query_params[:page] = [options[:start_page].to_i, 1].max rescue 1
results = []
initial_result = get(append_query(uri, query_params))
# D... | [
"def",
"paged_each",
"(",
"uri",
",",
"list_key",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"query_params",
"=",
"{",
"}",
"query_params",
"[",
":since",
"]",
"=",
"options",
"[",
":since",
"]",
".",
"to_date",
".",
"to_s",
"(",
":db",
... | Iterates over a collection, issuing multiple requests to get all the paged results.
@option options [Date] :since Only include records updated since the provided date.
Caution: not supported by all resources.
@option options [Integer] :start_page The initial page number to request.
@option options [Integer] :end... | [
"Iterates",
"over",
"a",
"collection",
"issuing",
"multiple",
"requests",
"to",
"get",
"all",
"the",
"paged",
"results",
"."
] | 14ed84c2fcc6b008879dd598328ab56d7dd4a053 | https://github.com/wvanbergen/love/blob/14ed84c2fcc6b008879dd598328ab56d7dd4a053/lib/love.rb#L310-L340 | train |
IntegraCore/quick_dry | app/controllers/quick_dry/quick_dry_controller.rb | QuickDry.QuickDryController.serialize | def serialize stuff
if stuff.is_a? Array or stuff.is_a? ActiveRecord::Relation
json = render_to_string json:QuickDryArraySerializer.new(stuff, root:get_model.model_name.route_key )
hash = JSON.parse(json)
temp = []
if hash[get_model.model_name.route_key].first.has_key? get_model.model_name.route_key
... | ruby | def serialize stuff
if stuff.is_a? Array or stuff.is_a? ActiveRecord::Relation
json = render_to_string json:QuickDryArraySerializer.new(stuff, root:get_model.model_name.route_key )
hash = JSON.parse(json)
temp = []
if hash[get_model.model_name.route_key].first.has_key? get_model.model_name.route_key
... | [
"def",
"serialize",
"stuff",
"if",
"stuff",
".",
"is_a?",
"Array",
"or",
"stuff",
".",
"is_a?",
"ActiveRecord",
"::",
"Relation",
"json",
"=",
"render_to_string",
"json",
":",
"QuickDryArraySerializer",
".",
"new",
"(",
"stuff",
",",
"root",
":",
"get_model",
... | nasty hack until I can get an answer on the official way to remove the instance root keys in a list | [
"nasty",
"hack",
"until",
"I",
"can",
"get",
"an",
"answer",
"on",
"the",
"official",
"way",
"to",
"remove",
"the",
"instance",
"root",
"keys",
"in",
"a",
"list"
] | 5a488499497dd453dbd0d29d3a0511f1b99a2fdf | https://github.com/IntegraCore/quick_dry/blob/5a488499497dd453dbd0d29d3a0511f1b99a2fdf/app/controllers/quick_dry/quick_dry_controller.rb#L10-L24 | train |
IntegraCore/quick_dry | app/controllers/quick_dry/quick_dry_controller.rb | QuickDry.QuickDryController.get_paged_search_results | def get_paged_search_results(params,user:nil,model:nil)
params[:per_page] = 10 if params[:per_page].blank?
params[:page] = 1 if params[:page].blank?
# a ghetto user check, but for some reason a devise user is not a devise user...
user = User.new if user.blank? or !user.class.to_s == User.to_s
# get the ... | ruby | def get_paged_search_results(params,user:nil,model:nil)
params[:per_page] = 10 if params[:per_page].blank?
params[:page] = 1 if params[:page].blank?
# a ghetto user check, but for some reason a devise user is not a devise user...
user = User.new if user.blank? or !user.class.to_s == User.to_s
# get the ... | [
"def",
"get_paged_search_results",
"(",
"params",
",",
"user",
":",
"nil",
",",
"model",
":",
"nil",
")",
"params",
"[",
":per_page",
"]",
"=",
"10",
"if",
"params",
"[",
":per_page",
"]",
".",
"blank?",
"params",
"[",
":page",
"]",
"=",
"1",
"if",
"... | Assumes the existance of a User model | [
"Assumes",
"the",
"existance",
"of",
"a",
"User",
"model"
] | 5a488499497dd453dbd0d29d3a0511f1b99a2fdf | https://github.com/IntegraCore/quick_dry/blob/5a488499497dd453dbd0d29d3a0511f1b99a2fdf/app/controllers/quick_dry/quick_dry_controller.rb#L176-L223 | train |
0000marcell/simple_commander | lib/simple_commander/user_interaction.rb | SimpleCommander.UI.converse | def converse(prompt, responses = {})
i, commands = 0, responses.map { |_key, value| value.inspect }.join(',')
statement = responses.inject '' do |inner_statement, (key, value)|
inner_statement <<
(
(i += 1) == 1 ?
%(if response is "#{value}" then\n) :
%(else if ... | ruby | def converse(prompt, responses = {})
i, commands = 0, responses.map { |_key, value| value.inspect }.join(',')
statement = responses.inject '' do |inner_statement, (key, value)|
inner_statement <<
(
(i += 1) == 1 ?
%(if response is "#{value}" then\n) :
%(else if ... | [
"def",
"converse",
"(",
"prompt",
",",
"responses",
"=",
"{",
"}",
")",
"i",
",",
"commands",
"=",
"0",
",",
"responses",
".",
"map",
"{",
"|",
"_key",
",",
"value",
"|",
"value",
".",
"inspect",
"}",
".",
"join",
"(",
"','",
")",
"statement",
"=... | Converse with speech recognition.
Currently a "poorman's" DSL to utilize applescript and
the MacOS speech recognition server.
=== Examples
case converse 'What is the best food?', :cookies => 'Cookies', :unknown => 'Nothing'
when :cookies
speak 'o.m.g. you are awesome!'
else
case converse 'That ... | [
"Converse",
"with",
"speech",
"recognition",
"."
] | 337c2e0d9926c643ce131b1a1ebd3740241e4424 | https://github.com/0000marcell/simple_commander/blob/337c2e0d9926c643ce131b1a1ebd3740241e4424/lib/simple_commander/user_interaction.rb#L166-L186 | train |
davidan1981/rails-identity | app/helpers/rails_identity/application_helper.rb | RailsIdentity.ApplicationHelper.authorized_for? | def authorized_for?(obj)
logger.debug("Checking to see if authorized to access object")
if @auth_user.nil?
# :nocov:
return false
# :nocov:
elsif @auth_user.role >= Roles::ADMIN
return true
elsif obj.is_a? User
return obj == @auth_user
else
r... | ruby | def authorized_for?(obj)
logger.debug("Checking to see if authorized to access object")
if @auth_user.nil?
# :nocov:
return false
# :nocov:
elsif @auth_user.role >= Roles::ADMIN
return true
elsif obj.is_a? User
return obj == @auth_user
else
r... | [
"def",
"authorized_for?",
"(",
"obj",
")",
"logger",
".",
"debug",
"(",
"\"Checking to see if authorized to access object\"",
")",
"if",
"@auth_user",
".",
"nil?",
"# :nocov:",
"return",
"false",
"# :nocov:",
"elsif",
"@auth_user",
".",
"role",
">=",
"Roles",
"::",
... | Determines if the user is authorized for the object. The user must be
either the creator of the object or must be an admin or above. | [
"Determines",
"if",
"the",
"user",
"is",
"authorized",
"for",
"the",
"object",
".",
"The",
"user",
"must",
"be",
"either",
"the",
"creator",
"of",
"the",
"object",
"or",
"must",
"be",
"an",
"admin",
"or",
"above",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L124-L137 | train |
davidan1981/rails-identity | app/helpers/rails_identity/application_helper.rb | RailsIdentity.ApplicationHelper.get_token_payload | def get_token_payload(token)
# Attempt to decode without verifying. May raise DecodeError.
decoded = JWT.decode token, nil, false
payload = decoded[0]
# At this point, we know that the token is not expired and
# well formatted. Find out if the payload is well defined.
i... | ruby | def get_token_payload(token)
# Attempt to decode without verifying. May raise DecodeError.
decoded = JWT.decode token, nil, false
payload = decoded[0]
# At this point, we know that the token is not expired and
# well formatted. Find out if the payload is well defined.
i... | [
"def",
"get_token_payload",
"(",
"token",
")",
"# Attempt to decode without verifying. May raise DecodeError.",
"decoded",
"=",
"JWT",
".",
"decode",
"token",
",",
"nil",
",",
"false",
"payload",
"=",
"decoded",
"[",
"0",
"]",
"# At this point, we know that the token is n... | Attempts to retrieve the payload encoded in the token. It checks if
the token is "valid" according to JWT definition and not expired.
A UNAUTHORIZED_ERROR is raised if token cannot be decoded. | [
"Attempts",
"to",
"retrieve",
"the",
"payload",
"encoded",
"in",
"the",
"token",
".",
"It",
"checks",
"if",
"the",
"token",
"is",
"valid",
"according",
"to",
"JWT",
"definition",
"and",
"not",
"expired",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L169-L189 | train |
davidan1981/rails-identity | app/helpers/rails_identity/application_helper.rb | RailsIdentity.ApplicationHelper.verify_token | def verify_token(token)
logger.debug("Verifying token: #{token}")
# First get the payload of the token. This will also verify whether
# or not the token is welformed.
payload = get_token_payload(token)
# Next, the payload should define user UUID and session UUID.
user_u... | ruby | def verify_token(token)
logger.debug("Verifying token: #{token}")
# First get the payload of the token. This will also verify whether
# or not the token is welformed.
payload = get_token_payload(token)
# Next, the payload should define user UUID and session UUID.
user_u... | [
"def",
"verify_token",
"(",
"token",
")",
"logger",
".",
"debug",
"(",
"\"Verifying token: #{token}\"",
")",
"# First get the payload of the token. This will also verify whether",
"# or not the token is welformed.",
"payload",
"=",
"get_token_payload",
"(",
"token",
")",
"# Nex... | Truly verifies the token and its payload. It ensures the user and
session specified in the token payload are indeed valid. The
required role is also checked.
A UNAUTHORIZED_ERROR is thrown for all cases where token is
invalid. | [
"Truly",
"verifies",
"the",
"token",
"and",
"its",
"payload",
".",
"It",
"ensures",
"the",
"user",
"and",
"session",
"specified",
"in",
"the",
"token",
"payload",
"are",
"indeed",
"valid",
".",
"The",
"required",
"role",
"is",
"also",
"checked",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L199-L242 | train |
davidan1981/rails-identity | app/helpers/rails_identity/application_helper.rb | RailsIdentity.ApplicationHelper.get_token | def get_token(required_role: Roles::PUBLIC)
token = params[:token]
# Look up the cache. If present, use it and skip the verification.
# Use token itself (and not a session UUID) as part of the key so
# it can be considered *verified*.
@auth_session = Cache.get(kind: :session, to... | ruby | def get_token(required_role: Roles::PUBLIC)
token = params[:token]
# Look up the cache. If present, use it and skip the verification.
# Use token itself (and not a session UUID) as part of the key so
# it can be considered *verified*.
@auth_session = Cache.get(kind: :session, to... | [
"def",
"get_token",
"(",
"required_role",
":",
"Roles",
"::",
"PUBLIC",
")",
"token",
"=",
"params",
"[",
":token",
"]",
"# Look up the cache. If present, use it and skip the verification.",
"# Use token itself (and not a session UUID) as part of the key so",
"# it can be considere... | Attempt to get a token for the session. Token must be specified in
query string or part of the JSON object.
Raises a UNAUTHORIZED_ERROR if cached session has less role
than what's required. | [
"Attempt",
"to",
"get",
"a",
"token",
"for",
"the",
"session",
".",
"Token",
"must",
"be",
"specified",
"in",
"query",
"string",
"or",
"part",
"of",
"the",
"JSON",
"object",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L251-L275 | train |
davidan1981/rails-identity | app/helpers/rails_identity/application_helper.rb | RailsIdentity.ApplicationHelper.get_api_key | def get_api_key(required_role: Roles::PUBLIC)
api_key = params[:api_key]
if api_key.nil?
# This case is not likely, but as a safeguard in case migration
# has not gone well.
# :nocov:
raise UNAUTHORIZED_ERROR, "Invalid api key"
# :nocov:
end
... | ruby | def get_api_key(required_role: Roles::PUBLIC)
api_key = params[:api_key]
if api_key.nil?
# This case is not likely, but as a safeguard in case migration
# has not gone well.
# :nocov:
raise UNAUTHORIZED_ERROR, "Invalid api key"
# :nocov:
end
... | [
"def",
"get_api_key",
"(",
"required_role",
":",
"Roles",
"::",
"PUBLIC",
")",
"api_key",
"=",
"params",
"[",
":api_key",
"]",
"if",
"api_key",
".",
"nil?",
"# This case is not likely, but as a safeguard in case migration",
"# has not gone well.",
"# :nocov:",
"raise",
... | Get API key from the request.
Raises a UNAUTHORIZED_ERROR if API key is not valid (or not
provided). | [
"Get",
"API",
"key",
"from",
"the",
"request",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L283-L300 | train |
davidan1981/rails-identity | app/helpers/rails_identity/application_helper.rb | RailsIdentity.ApplicationHelper.get_auth | def get_auth(required_role: Roles::USER)
if params[:token]
get_token(required_role: required_role)
else
get_api_key(required_role: required_role)
end
end | ruby | def get_auth(required_role: Roles::USER)
if params[:token]
get_token(required_role: required_role)
else
get_api_key(required_role: required_role)
end
end | [
"def",
"get_auth",
"(",
"required_role",
":",
"Roles",
"::",
"USER",
")",
"if",
"params",
"[",
":token",
"]",
"get_token",
"(",
"required_role",
":",
"required_role",
")",
"else",
"get_api_key",
"(",
"required_role",
":",
"required_role",
")",
"end",
"end"
] | Get auth data from the request. The token takes the precedence. | [
"Get",
"auth",
"data",
"from",
"the",
"request",
".",
"The",
"token",
"takes",
"the",
"precedence",
"."
] | 12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0 | https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L305-L311 | train |
jeremyvdw/disqussion | lib/disqussion/client/reactions.rb | Disqussion.Reactions.details | def details(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
if args.length == 2
options.merge!(:reaction => args[0])
options.merge!(:forum => args[1])
response = get('reactions/details', options)
else
puts "#{Kernel.caller.first}: Reactions.details expects 2 argu... | ruby | def details(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
if args.length == 2
options.merge!(:reaction => args[0])
options.merge!(:forum => args[1])
response = get('reactions/details', options)
else
puts "#{Kernel.caller.first}: Reactions.details expects 2 argu... | [
"def",
"details",
"(",
"*",
"args",
")",
"options",
"=",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"if",
"args",
".",
"length",
"==",
"2",
"options",
".",
"merge!",
"(",
":reaction",
"=>",
"args"... | Returns reaction details
@accessibility: public key, secret key
@methods: GET
@format: json, jsonp
@authenticated: false
@limited: false
@param reaction [Integer] Looks up a reaction by ID.
@param forum [String] Looks up a forum by ID (aka shortname).
@return [Hashie::Rash] Reaction of the forum.
@example Mess... | [
"Returns",
"reaction",
"details"
] | 5ad1b0325b7630daf41eb59fc8acbcb785cbc387 | https://github.com/jeremyvdw/disqussion/blob/5ad1b0325b7630daf41eb59fc8acbcb785cbc387/lib/disqussion/client/reactions.rb#L16-L25 | train |
biola/biola-logs | lib/biola_logs/controller_extensions.rb | BiolaLogs.ControllerExtensions.append_info_to_payload | def append_info_to_payload(payload)
super
payload[:session_id] = request.session_options[:id]
payload[:uuid] = request.uuid
payload[:host] = request.host
end | ruby | def append_info_to_payload(payload)
super
payload[:session_id] = request.session_options[:id]
payload[:uuid] = request.uuid
payload[:host] = request.host
end | [
"def",
"append_info_to_payload",
"(",
"payload",
")",
"super",
"payload",
"[",
":session_id",
"]",
"=",
"request",
".",
"session_options",
"[",
":id",
"]",
"payload",
"[",
":uuid",
"]",
"=",
"request",
".",
"uuid",
"payload",
"[",
":host",
"]",
"=",
"reque... | Custom attributes for lograge logging | [
"Custom",
"attributes",
"for",
"lograge",
"logging"
] | 614a0b9181c0c647ccf82d4fcb44d07fc2ab1829 | https://github.com/biola/biola-logs/blob/614a0b9181c0c647ccf82d4fcb44d07fc2ab1829/lib/biola_logs/controller_extensions.rb#L14-L19 | train |
irvingwashington/gem_footprint_analyzer | lib/gem_footprint_analyzer/child_context.rb | GemFootprintAnalyzer.ChildContext.start | def start
RequireSpy.spy_require(transport)
error = try_require(require_string)
return transport.done_and_wait_for_ack unless error
transport.exit_with_error(error)
exit(1)
end | ruby | def start
RequireSpy.spy_require(transport)
error = try_require(require_string)
return transport.done_and_wait_for_ack unless error
transport.exit_with_error(error)
exit(1)
end | [
"def",
"start",
"RequireSpy",
".",
"spy_require",
"(",
"transport",
")",
"error",
"=",
"try_require",
"(",
"require_string",
")",
"return",
"transport",
".",
"done_and_wait_for_ack",
"unless",
"error",
"transport",
".",
"exit_with_error",
"(",
"error",
")",
"exit"... | Prints the process pid, so it can be grabbed by the supervisor process, inits tranport fifos
and requires requested libraries.
Installs the require-spying code and starts requiring | [
"Prints",
"the",
"process",
"pid",
"so",
"it",
"can",
"be",
"grabbed",
"by",
"the",
"supervisor",
"process",
"inits",
"tranport",
"fifos",
"and",
"requires",
"requested",
"libraries",
".",
"Installs",
"the",
"require",
"-",
"spying",
"code",
"and",
"starts",
... | 19a8892f6baaeb16b1b166144c4f73852396220c | https://github.com/irvingwashington/gem_footprint_analyzer/blob/19a8892f6baaeb16b1b166144c4f73852396220c/lib/gem_footprint_analyzer/child_context.rb#L22-L29 | train |
mattmccray/gumdrop | lib/gumdrop/content.rb | Gumdrop.SpecialContentList.find | def find(uri)
_try_variations_of(uri) do |path|
content= get path
return [content] unless content.nil?
end unless uri.nil?
[]
end | ruby | def find(uri)
_try_variations_of(uri) do |path|
content= get path
return [content] unless content.nil?
end unless uri.nil?
[]
end | [
"def",
"find",
"(",
"uri",
")",
"_try_variations_of",
"(",
"uri",
")",
"do",
"|",
"path",
"|",
"content",
"=",
"get",
"path",
"return",
"[",
"content",
"]",
"unless",
"content",
".",
"nil?",
"end",
"unless",
"uri",
".",
"nil?",
"[",
"]",
"end"
] | Find isn't fuzzy for Special Content. It looks for full
uri or the uri's basename, optionally tacking on @ext | [
"Find",
"isn",
"t",
"fuzzy",
"for",
"Special",
"Content",
".",
"It",
"looks",
"for",
"full",
"uri",
"or",
"the",
"uri",
"s",
"basename",
"optionally",
"tacking",
"on"
] | 7c0998675dbc65e6c7fa0cd580ea0fc3167394fd | https://github.com/mattmccray/gumdrop/blob/7c0998675dbc65e6c7fa0cd580ea0fc3167394fd/lib/gumdrop/content.rb#L277-L283 | train |
chetan/bixby-common | lib/bixby-common/api/json_request.rb | Bixby.JsonRequest.to_s | def to_s(include_params=true)
s = []
s << "JsonRequest:#{self.object_id}"
s << " operation: #{self.operation}"
s << " params: " + MultiJson.dump(self.params) if include_params
s.join("\n")
end | ruby | def to_s(include_params=true)
s = []
s << "JsonRequest:#{self.object_id}"
s << " operation: #{self.operation}"
s << " params: " + MultiJson.dump(self.params) if include_params
s.join("\n")
end | [
"def",
"to_s",
"(",
"include_params",
"=",
"true",
")",
"s",
"=",
"[",
"]",
"s",
"<<",
"\"JsonRequest:#{self.object_id}\"",
"s",
"<<",
"\" operation: #{self.operation}\"",
"s",
"<<",
"\" params: \"",
"+",
"MultiJson",
".",
"dump",
"(",
"self",
".",
"param... | Create a new JsonRequest
@param [String] operation Name of operation
@param [Array] params Array of parameters; must ve valid JSON types
Stringify, useful for debugging
@param [Boolean] include_params whether or not to include params in the output (default: true)
@return [String] | [
"Create",
"a",
"new",
"JsonRequest"
] | 3fb8829987b115fc53ec820d97a20b4a8c49b4a2 | https://github.com/chetan/bixby-common/blob/3fb8829987b115fc53ec820d97a20b4a8c49b4a2/lib/bixby-common/api/json_request.rb#L29-L35 | train |
zacscodingclub/balancing_act | lib/balancing_act/server.rb | BalancingAct.Server.valid_params? | def valid_params?(name, size)
return raise TypeError.new("A 'name' should be a string") if name.class != String
return raise TypeError.new("A 'size' should be an integer") if size.class != Integer
true
end | ruby | def valid_params?(name, size)
return raise TypeError.new("A 'name' should be a string") if name.class != String
return raise TypeError.new("A 'size' should be an integer") if size.class != Integer
true
end | [
"def",
"valid_params?",
"(",
"name",
",",
"size",
")",
"return",
"raise",
"TypeError",
".",
"new",
"(",
"\"A 'name' should be a string\"",
")",
"if",
"name",
".",
"class",
"!=",
"String",
"return",
"raise",
"TypeError",
".",
"new",
"(",
"\"A 'size' should be an ... | Validates the params by type. Could add in additional validations in
this method depending on requirements. Raises exception with invalid
types with early return or returns true if params are valid | [
"Validates",
"the",
"params",
"by",
"type",
".",
"Could",
"add",
"in",
"additional",
"validations",
"in",
"this",
"method",
"depending",
"on",
"requirements",
".",
"Raises",
"exception",
"with",
"invalid",
"types",
"with",
"early",
"return",
"or",
"returns",
"... | 5a8b86d03b1218192cef23c14533d1dd9264bdc1 | https://github.com/zacscodingclub/balancing_act/blob/5a8b86d03b1218192cef23c14533d1dd9264bdc1/lib/balancing_act/server.rb#L17-L22 | train |
rgeyer/rs_user_policy | lib/rs_user_policy/audit_log.rb | RsUserPolicy.AuditLog.add_entry | def add_entry(email, account, action, changes)
@audit_log[email] = [] unless audit_log[email]
@audit_log[email] << {
:account => account,
:action => action,
:changes => changes
}
end | ruby | def add_entry(email, account, action, changes)
@audit_log[email] = [] unless audit_log[email]
@audit_log[email] << {
:account => account,
:action => action,
:changes => changes
}
end | [
"def",
"add_entry",
"(",
"email",
",",
"account",
",",
"action",
",",
"changes",
")",
"@audit_log",
"[",
"email",
"]",
"=",
"[",
"]",
"unless",
"audit_log",
"[",
"email",
"]",
"@audit_log",
"[",
"email",
"]",
"<<",
"{",
":account",
"=>",
"account",
","... | Initializes a new AuditLog
@param [Hash] options A hash of options that impact the audit log filename.
@option options [String] :timestamp The timestamp to append to the filename
@option options [Bool] :dry_run A boolean indicating if this is a dry run
@option options [String] :audit_dir The directory where the au... | [
"Initializes",
"a",
"new",
"AuditLog"
] | bae3355f1471cc7d28de7992c5d5f4ac39fff68b | https://github.com/rgeyer/rs_user_policy/blob/bae3355f1471cc7d28de7992c5d5f4ac39fff68b/lib/rs_user_policy/audit_log.rb#L57-L64 | train |
mikemackintosh/slackdraft | lib/slackdraft/base.rb | Slackdraft.Base.send! | def send!
# Send the request
request = HTTParty.post(self.target, :body => {
:payload => generate_payload.to_json
})
unless request.code.eql? 200
false
end
true
end | ruby | def send!
# Send the request
request = HTTParty.post(self.target, :body => {
:payload => generate_payload.to_json
})
unless request.code.eql? 200
false
end
true
end | [
"def",
"send!",
"# Send the request",
"request",
"=",
"HTTParty",
".",
"post",
"(",
"self",
".",
"target",
",",
":body",
"=>",
"{",
":payload",
"=>",
"generate_payload",
".",
"to_json",
"}",
")",
"unless",
"request",
".",
"code",
".",
"eql?",
"200",
"false... | Send the message! | [
"Send",
"the",
"message!"
] | 4025fe370f468750fdf5a0dc9741871bca897c0a | https://github.com/mikemackintosh/slackdraft/blob/4025fe370f468750fdf5a0dc9741871bca897c0a/lib/slackdraft/base.rb#L22-L35 | train |
culturecode/templatr | app/models/templatr/template.rb | Templatr.Template.common_fields_attributes= | def common_fields_attributes=(nested_attributes)
nested_attributes.values.each do |attributes|
common_field = common_fields.find {|field| field.id.to_s == attributes[:id] && attributes[:id].present? } || common_fields.build
assign_to_or_mark_for_destruction(common_field, attributes, true, {})
... | ruby | def common_fields_attributes=(nested_attributes)
nested_attributes.values.each do |attributes|
common_field = common_fields.find {|field| field.id.to_s == attributes[:id] && attributes[:id].present? } || common_fields.build
assign_to_or_mark_for_destruction(common_field, attributes, true, {})
... | [
"def",
"common_fields_attributes",
"=",
"(",
"nested_attributes",
")",
"nested_attributes",
".",
"values",
".",
"each",
"do",
"|",
"attributes",
"|",
"common_field",
"=",
"common_fields",
".",
"find",
"{",
"|",
"field",
"|",
"field",
".",
"id",
".",
"to_s",
... | Ensure all nested attributes for common fields get saved as common fields, and not as template fields | [
"Ensure",
"all",
"nested",
"attributes",
"for",
"common",
"fields",
"get",
"saved",
"as",
"common",
"fields",
"and",
"not",
"as",
"template",
"fields"
] | 0bffb930736b4339fb8a9e8adc080404dc6860d8 | https://github.com/culturecode/templatr/blob/0bffb930736b4339fb8a9e8adc080404dc6860d8/app/models/templatr/template.rb#L25-L30 | train |
conversation/chrome_debugger | lib/chrome_debugger/document.rb | ChromeDebugger.Document.start_time | def start_time
@start_time ||= @events.select { |event|
event.is_a?(RequestWillBeSent)
}.select { |event|
event.request['url'] == @url
}.map { |event|
event.timestamp
}.first
end | ruby | def start_time
@start_time ||= @events.select { |event|
event.is_a?(RequestWillBeSent)
}.select { |event|
event.request['url'] == @url
}.map { |event|
event.timestamp
}.first
end | [
"def",
"start_time",
"@start_time",
"||=",
"@events",
".",
"select",
"{",
"|",
"event",
"|",
"event",
".",
"is_a?",
"(",
"RequestWillBeSent",
")",
"}",
".",
"select",
"{",
"|",
"event",
"|",
"event",
".",
"request",
"[",
"'url'",
"]",
"==",
"@url",
"}"... | The seconds since epoch that the request for this document started | [
"The",
"seconds",
"since",
"epoch",
"that",
"the",
"request",
"for",
"this",
"document",
"started"
] | b1b0c6a7bff94e8f4967aefc39c7e043582f549e | https://github.com/conversation/chrome_debugger/blob/b1b0c6a7bff94e8f4967aefc39c7e043582f549e/lib/chrome_debugger/document.rb#L20-L28 | train |
conversation/chrome_debugger | lib/chrome_debugger/document.rb | ChromeDebugger.Document.encoded_bytes | def encoded_bytes(resource_type)
@events.select {|e|
e.is_a?(ResponseReceived) && e.resource_type == resource_type
}.map { |e|
e.request_id
}.map { |request_id|
data_received_for_request(request_id)
}.flatten.inject(0) { |bytes_sum, n| bytes_sum + n.encoded_data_length }
... | ruby | def encoded_bytes(resource_type)
@events.select {|e|
e.is_a?(ResponseReceived) && e.resource_type == resource_type
}.map { |e|
e.request_id
}.map { |request_id|
data_received_for_request(request_id)
}.flatten.inject(0) { |bytes_sum, n| bytes_sum + n.encoded_data_length }
... | [
"def",
"encoded_bytes",
"(",
"resource_type",
")",
"@events",
".",
"select",
"{",
"|",
"e",
"|",
"e",
".",
"is_a?",
"(",
"ResponseReceived",
")",
"&&",
"e",
".",
"resource_type",
"==",
"resource_type",
"}",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"... | The number of bytes downloaded for a particular resource type. If the
resource was gzipped during transfer then the gzipped size is reported.
The HTTP headers for the response are included in the byte count.
Possible resource types: 'Document','Script', 'Image', 'Stylesheet',
'Other'. | [
"The",
"number",
"of",
"bytes",
"downloaded",
"for",
"a",
"particular",
"resource",
"type",
".",
"If",
"the",
"resource",
"was",
"gzipped",
"during",
"transfer",
"then",
"the",
"gzipped",
"size",
"is",
"reported",
"."
] | b1b0c6a7bff94e8f4967aefc39c7e043582f549e | https://github.com/conversation/chrome_debugger/blob/b1b0c6a7bff94e8f4967aefc39c7e043582f549e/lib/chrome_debugger/document.rb#L60-L68 | train |
conversation/chrome_debugger | lib/chrome_debugger/document.rb | ChromeDebugger.Document.bytes | def bytes(resource_type)
@events.select {|e|
e.is_a?(ResponseReceived) && e.resource_type == resource_type
}.map { |e|
e.request_id
}.map { |request_id|
data_received_for_request(request_id)
}.flatten.inject(0) { |bytes_sum, n| bytes_sum + n.data_length }
end | ruby | def bytes(resource_type)
@events.select {|e|
e.is_a?(ResponseReceived) && e.resource_type == resource_type
}.map { |e|
e.request_id
}.map { |request_id|
data_received_for_request(request_id)
}.flatten.inject(0) { |bytes_sum, n| bytes_sum + n.data_length }
end | [
"def",
"bytes",
"(",
"resource_type",
")",
"@events",
".",
"select",
"{",
"|",
"e",
"|",
"e",
".",
"is_a?",
"(",
"ResponseReceived",
")",
"&&",
"e",
".",
"resource_type",
"==",
"resource_type",
"}",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"request_... | The number of bytes downloaded for a particular resource type. If the
resource was gzipped during transfer then the uncompressed size is
reported.
The HTTP headers for the response are NOT included in the byte count.
Possible resource types: 'Document','Script', 'Image', 'Stylesheet',
'Other'. | [
"The",
"number",
"of",
"bytes",
"downloaded",
"for",
"a",
"particular",
"resource",
"type",
".",
"If",
"the",
"resource",
"was",
"gzipped",
"during",
"transfer",
"then",
"the",
"uncompressed",
"size",
"is",
"reported",
"."
] | b1b0c6a7bff94e8f4967aefc39c7e043582f549e | https://github.com/conversation/chrome_debugger/blob/b1b0c6a7bff94e8f4967aefc39c7e043582f549e/lib/chrome_debugger/document.rb#L79-L87 | train |
conversation/chrome_debugger | lib/chrome_debugger/document.rb | ChromeDebugger.Document.request_count_by_resource | def request_count_by_resource(resource_type)
@events.select {|n|
n.is_a?(ResponseReceived) && n.resource_type == resource_type
}.size
end | ruby | def request_count_by_resource(resource_type)
@events.select {|n|
n.is_a?(ResponseReceived) && n.resource_type == resource_type
}.size
end | [
"def",
"request_count_by_resource",
"(",
"resource_type",
")",
"@events",
".",
"select",
"{",
"|",
"n",
"|",
"n",
".",
"is_a?",
"(",
"ResponseReceived",
")",
"&&",
"n",
".",
"resource_type",
"==",
"resource_type",
"}",
".",
"size",
"end"
] | the number of network requests of a particular resource
type that were required to load this document
Possible resource types: 'Document', 'Script', 'Image', 'Stylesheet',
'Other'. | [
"the",
"number",
"of",
"network",
"requests",
"of",
"a",
"particular",
"resource",
"type",
"that",
"were",
"required",
"to",
"load",
"this",
"document"
] | b1b0c6a7bff94e8f4967aefc39c7e043582f549e | https://github.com/conversation/chrome_debugger/blob/b1b0c6a7bff94e8f4967aefc39c7e043582f549e/lib/chrome_debugger/document.rb#L103-L107 | train |
noted/scholar | lib/scholar/search.rb | Scholar.Search.to_hash | def to_hash
hash = {}
instance_variables.each do |v|
hash[v.to_s[1..-1].to_sym] = instance_variable_get(v)
end
hash[:results].each do |c|
hash[:results][hash[:results].index(c)] = c.to_hash
end
hash
end | ruby | def to_hash
hash = {}
instance_variables.each do |v|
hash[v.to_s[1..-1].to_sym] = instance_variable_get(v)
end
hash[:results].each do |c|
hash[:results][hash[:results].index(c)] = c.to_hash
end
hash
end | [
"def",
"to_hash",
"hash",
"=",
"{",
"}",
"instance_variables",
".",
"each",
"do",
"|",
"v",
"|",
"hash",
"[",
"v",
".",
"to_s",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"to_sym",
"]",
"=",
"instance_variable_get",
"(",
"v",
")",
"end",
"hash",
"[",
":... | Searches for sources in Google Books.
==== Attributes
* +query+ - The search term.
Return as hash. | [
"Searches",
"for",
"sources",
"in",
"Google",
"Books",
"."
] | 2bfface9d90307d7d3cecfa756f921087407d394 | https://github.com/noted/scholar/blob/2bfface9d90307d7d3cecfa756f921087407d394/lib/scholar/search.rb#L39-L51 | train |
betaworks/slack-bot-manager | lib/slack-bot-manager/client/commands.rb | SlackBotManager.Commands.on_close | def on_close(data, *args)
options = args.extract_options!
options[:code] ||= (data && data.code) || '1000'
disconnect
fail SlackBotManager::ConnectionRateLimited if %w(1008 429).include?(options[:code].to_s)
end | ruby | def on_close(data, *args)
options = args.extract_options!
options[:code] ||= (data && data.code) || '1000'
disconnect
fail SlackBotManager::ConnectionRateLimited if %w(1008 429).include?(options[:code].to_s)
end | [
"def",
"on_close",
"(",
"data",
",",
"*",
"args",
")",
"options",
"=",
"args",
".",
"extract_options!",
"options",
"[",
":code",
"]",
"||=",
"(",
"data",
"&&",
"data",
".",
"code",
")",
"||",
"'1000'",
"disconnect",
"fail",
"SlackBotManager",
"::",
"Conn... | Handle when connection gets closed | [
"Handle",
"when",
"connection",
"gets",
"closed"
] | cb59bd1c80abd3ede0520017708891486f733e40 | https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/client/commands.rb#L4-L10 | train |
hexorx/oxmlk | lib/oxmlk.rb | OxMlk.ClassMethods.ox_attr | def ox_attr(name,o={},&block)
new_attr = Attr.new(name, o.reverse_merge(:tag_proc => @tag_proc),&block)
@ox_attrs << new_attr
ox_accessor new_attr.accessor
end | ruby | def ox_attr(name,o={},&block)
new_attr = Attr.new(name, o.reverse_merge(:tag_proc => @tag_proc),&block)
@ox_attrs << new_attr
ox_accessor new_attr.accessor
end | [
"def",
"ox_attr",
"(",
"name",
",",
"o",
"=",
"{",
"}",
",",
"&",
"block",
")",
"new_attr",
"=",
"Attr",
".",
"new",
"(",
"name",
",",
"o",
".",
"reverse_merge",
"(",
":tag_proc",
"=>",
"@tag_proc",
")",
",",
"block",
")",
"@ox_attrs",
"<<",
"new_a... | Declares a reference to a certain xml attribute.
== Sym Option
[sym] Symbol representing the name of the accessor
=== Default naming
This is what it will use to lookup the attribute if a name isn't defined in :from. For example:
ox_attr :bob
ox_attr :pony
are equivalent to:
ox_attr :bob, :from => 'bob'
... | [
"Declares",
"a",
"reference",
"to",
"a",
"certain",
"xml",
"attribute",
"."
] | bf4be00ece9b13a3357d8eb324e2a571d2715f79 | https://github.com/hexorx/oxmlk/blob/bf4be00ece9b13a3357d8eb324e2a571d2715f79/lib/oxmlk.rb#L123-L127 | train |
hexorx/oxmlk | lib/oxmlk.rb | OxMlk.ClassMethods.ox_elem | def ox_elem(name,o={},&block)
new_elem = Elem.new(name, o.reverse_merge(:tag_proc => @tag_proc),&block)
@ox_elems << new_elem
ox_accessor new_elem.accessor
end | ruby | def ox_elem(name,o={},&block)
new_elem = Elem.new(name, o.reverse_merge(:tag_proc => @tag_proc),&block)
@ox_elems << new_elem
ox_accessor new_elem.accessor
end | [
"def",
"ox_elem",
"(",
"name",
",",
"o",
"=",
"{",
"}",
",",
"&",
"block",
")",
"new_elem",
"=",
"Elem",
".",
"new",
"(",
"name",
",",
"o",
".",
"reverse_merge",
"(",
":tag_proc",
"=>",
"@tag_proc",
")",
",",
"block",
")",
"@ox_elems",
"<<",
"new_e... | Declares a reference to a certain xml element or a typed collection of elements.
== Sym Option
[sym] Symbol representing the name of the accessor.
=== Default naming
This name will be the default node searched for, if no other is declared. For example:
ox_elem :bob
ox_elem :pony
are equivalent to:
ox_el... | [
"Declares",
"a",
"reference",
"to",
"a",
"certain",
"xml",
"element",
"or",
"a",
"typed",
"collection",
"of",
"elements",
"."
] | bf4be00ece9b13a3357d8eb324e2a571d2715f79 | https://github.com/hexorx/oxmlk/blob/bf4be00ece9b13a3357d8eb324e2a571d2715f79/lib/oxmlk.rb#L335-L339 | train |
hexorx/oxmlk | lib/oxmlk.rb | OxMlk.ClassMethods.ox_tag | def ox_tag(tag=nil,&block)
raise 'you can only set tag or a block, not both.' if tag && block
@base_tag ||= self.to_s.split('::').last
@ox_tag ||= case tag
when String
tag
when Proc, Symbol, nil
@tag_proc = (block || tag || :to_s).to_proc
@tag_proc.call(@base_tag) ... | ruby | def ox_tag(tag=nil,&block)
raise 'you can only set tag or a block, not both.' if tag && block
@base_tag ||= self.to_s.split('::').last
@ox_tag ||= case tag
when String
tag
when Proc, Symbol, nil
@tag_proc = (block || tag || :to_s).to_proc
@tag_proc.call(@base_tag) ... | [
"def",
"ox_tag",
"(",
"tag",
"=",
"nil",
",",
"&",
"block",
")",
"raise",
"'you can only set tag or a block, not both.'",
"if",
"tag",
"&&",
"block",
"@base_tag",
"||=",
"self",
".",
"to_s",
".",
"split",
"(",
"'::'",
")",
".",
"last",
"@ox_tag",
"||=",
"c... | Sets the name of the XML element that represents this class. Use this
to override the default camelcase class name.
Example:
class BookWithPublisher
ox_tag 'book'
end
Without the ox_tag annotation, the XML mapped tag would have been 'BookWithPublisher'.
Most xml documents have a consistent naming conventi... | [
"Sets",
"the",
"name",
"of",
"the",
"XML",
"element",
"that",
"represents",
"this",
"class",
".",
"Use",
"this",
"to",
"override",
"the",
"default",
"camelcase",
"class",
"name",
"."
] | bf4be00ece9b13a3357d8eb324e2a571d2715f79 | https://github.com/hexorx/oxmlk/blob/bf4be00ece9b13a3357d8eb324e2a571d2715f79/lib/oxmlk.rb#L380-L393 | train |
hexorx/oxmlk | lib/oxmlk.rb | OxMlk.ClassMethods.from_xml | def from_xml(data)
xml = XML::Node.from(data)
raise 'invalid XML' unless xml.name == ox_tag
returning new do |ox|
(ox_attrs + ox_elems).each {|e| ox.send(e.setter,e.from_xml(xml))}
ox.send(:after_parse) if ox.respond_to?(:after_parse)
end
end | ruby | def from_xml(data)
xml = XML::Node.from(data)
raise 'invalid XML' unless xml.name == ox_tag
returning new do |ox|
(ox_attrs + ox_elems).each {|e| ox.send(e.setter,e.from_xml(xml))}
ox.send(:after_parse) if ox.respond_to?(:after_parse)
end
end | [
"def",
"from_xml",
"(",
"data",
")",
"xml",
"=",
"XML",
"::",
"Node",
".",
"from",
"(",
"data",
")",
"raise",
"'invalid XML'",
"unless",
"xml",
".",
"name",
"==",
"ox_tag",
"returning",
"new",
"do",
"|",
"ox",
"|",
"(",
"ox_attrs",
"+",
"ox_elems",
"... | Returns a new instance from XML
@param [XML::Document,XML::Node,File,Pathname,URI,String] data
The xml data used to create a new instance.
@return New instance generated from xml data passed in.
Attr and Elem definitions are used to translate the xml to new object. | [
"Returns",
"a",
"new",
"instance",
"from",
"XML"
] | bf4be00ece9b13a3357d8eb324e2a571d2715f79 | https://github.com/hexorx/oxmlk/blob/bf4be00ece9b13a3357d8eb324e2a571d2715f79/lib/oxmlk.rb#L405-L413 | train |
hexorx/oxmlk | lib/oxmlk.rb | OxMlk.ClassMethods.to_xml | def to_xml(data)
ox = XML::Node.new(ox_tag)
wrappers = {}
ox_elems.each do |elem|
if elem.in
wrappers[elem.in] ||= XML::Node.new elem.in
elem.to_xml(data).each {|e| wrappers[elem.in] << e}
else
elem.to_xml(data).each {|e| ox << e}
end
... | ruby | def to_xml(data)
ox = XML::Node.new(ox_tag)
wrappers = {}
ox_elems.each do |elem|
if elem.in
wrappers[elem.in] ||= XML::Node.new elem.in
elem.to_xml(data).each {|e| wrappers[elem.in] << e}
else
elem.to_xml(data).each {|e| ox << e}
end
... | [
"def",
"to_xml",
"(",
"data",
")",
"ox",
"=",
"XML",
"::",
"Node",
".",
"new",
"(",
"ox_tag",
")",
"wrappers",
"=",
"{",
"}",
"ox_elems",
".",
"each",
"do",
"|",
"elem",
"|",
"if",
"elem",
".",
"in",
"wrappers",
"[",
"elem",
".",
"in",
"]",
"||... | Returns XML generated from an instance based on Attr & Elem definitions.
@param [Object] data An instance used to populate XML
@return [XML::Node] Generated XML::Node | [
"Returns",
"XML",
"generated",
"from",
"an",
"instance",
"based",
"on",
"Attr",
"&",
"Elem",
"definitions",
"."
] | bf4be00ece9b13a3357d8eb324e2a571d2715f79 | https://github.com/hexorx/oxmlk/blob/bf4be00ece9b13a3357d8eb324e2a571d2715f79/lib/oxmlk.rb#L429-L450 | train |
urso/rb_prob | lib/prob.rb | Probably.Distribution.pick | def pick
tst = rand
sum = 0
@map.each do |value, prob|
sum += prob
return value,prob if tst < sum
end
return nil
end | ruby | def pick
tst = rand
sum = 0
@map.each do |value, prob|
sum += prob
return value,prob if tst < sum
end
return nil
end | [
"def",
"pick",
"tst",
"=",
"rand",
"sum",
"=",
"0",
"@map",
".",
"each",
"do",
"|",
"value",
",",
"prob",
"|",
"sum",
"+=",
"prob",
"return",
"value",
",",
"prob",
"if",
"tst",
"<",
"sum",
"end",
"return",
"nil",
"end"
] | randomly pick a key-value with respect to its probability
in given distribution | [
"randomly",
"pick",
"a",
"key",
"-",
"value",
"with",
"respect",
"to",
"its",
"probability",
"in",
"given",
"distribution"
] | f7c448a15a40c26ce9a4424151a0f4942e544389 | https://github.com/urso/rb_prob/blob/f7c448a15a40c26ce9a4424151a0f4942e544389/lib/prob.rb#L115-L123 | train |
urso/rb_prob | lib/prob.rb | Probably.Distribution.variance | def variance
expected = self.expectation
@map.reduce(0) {|sum, (value,p)|
tmp = (value.to_f - expectation)
sum + tmp * tmp * p
}
end | ruby | def variance
expected = self.expectation
@map.reduce(0) {|sum, (value,p)|
tmp = (value.to_f - expectation)
sum + tmp * tmp * p
}
end | [
"def",
"variance",
"expected",
"=",
"self",
".",
"expectation",
"@map",
".",
"reduce",
"(",
"0",
")",
"{",
"|",
"sum",
",",
"(",
"value",
",",
"p",
")",
"|",
"tmp",
"=",
"(",
"value",
".",
"to_f",
"-",
"expectation",
")",
"sum",
"+",
"tmp",
"*",
... | computes variance given that keys in distribution
are numeric | [
"computes",
"variance",
"given",
"that",
"keys",
"in",
"distribution",
"are",
"numeric"
] | f7c448a15a40c26ce9a4424151a0f4942e544389 | https://github.com/urso/rb_prob/blob/f7c448a15a40c26ce9a4424151a0f4942e544389/lib/prob.rb#L214-L220 | train |
benschwarz/smoke | lib/smoke/origin.rb | Smoke.Origin.transform | def transform(*keys)
raise ArgumentError, "requires a block" unless block_given?
keys.each do |key|
items.each do |item|
item[key] = yield(item[key]) || item[key]
end
end
end | ruby | def transform(*keys)
raise ArgumentError, "requires a block" unless block_given?
keys.each do |key|
items.each do |item|
item[key] = yield(item[key]) || item[key]
end
end
end | [
"def",
"transform",
"(",
"*",
"keys",
")",
"raise",
"ArgumentError",
",",
"\"requires a block\"",
"unless",
"block_given?",
"keys",
".",
"each",
"do",
"|",
"key",
"|",
"items",
".",
"each",
"do",
"|",
"item",
"|",
"item",
"[",
"key",
"]",
"=",
"yield",
... | Transform must be used inside an `emit` block.
It can be used to alter named keys within the item set
Usage:
emit do
transform :name, :description do |name|
name.gsub(/\302/, "")
end
end
In quasi-english: The result of the block is returned and set to each
of the :name and :descri... | [
"Transform",
"must",
"be",
"used",
"inside",
"an",
"emit",
"block",
".",
"It",
"can",
"be",
"used",
"to",
"alter",
"named",
"keys",
"within",
"the",
"item",
"set"
] | b229e0cc975d6420a3b7505b42f38b8ba1126d54 | https://github.com/benschwarz/smoke/blob/b229e0cc975d6420a3b7505b42f38b8ba1126d54/lib/smoke/origin.rb#L87-L94 | train |
benschwarz/smoke | lib/smoke/origin.rb | Smoke.Origin.method_missing | def method_missing(symbol, *args, &block)
ivar = "@#{symbol}"
if args.empty?
return instance_variable_get(ivar) || super
else
instance_variable_set(ivar, args.pop)
end
return self
end | ruby | def method_missing(symbol, *args, &block)
ivar = "@#{symbol}"
if args.empty?
return instance_variable_get(ivar) || super
else
instance_variable_set(ivar, args.pop)
end
return self
end | [
"def",
"method_missing",
"(",
"symbol",
",",
"*",
"args",
",",
"&",
"block",
")",
"ivar",
"=",
"\"@#{symbol}\"",
"if",
"args",
".",
"empty?",
"return",
"instance_variable_get",
"(",
"ivar",
")",
"||",
"super",
"else",
"instance_variable_set",
"(",
"ivar",
",... | Used to store or retreive variables that are used to query services.
Usage:
Smoke.twitter.username("benschwarz").output
As you can see, the method is chainable, many properties can be
set at once, although it may be cleaner to use the method argument method:
Demo:
Smoke.twitter(:username => "benschwarz").o... | [
"Used",
"to",
"store",
"or",
"retreive",
"variables",
"that",
"are",
"used",
"to",
"query",
"services",
"."
] | b229e0cc975d6420a3b7505b42f38b8ba1126d54 | https://github.com/benschwarz/smoke/blob/b229e0cc975d6420a3b7505b42f38b8ba1126d54/lib/smoke/origin.rb#L145-L155 | train |
benschwarz/smoke | lib/smoke/origin.rb | Smoke.Origin.sort | def sort(key)
@items = @items.sort_by{|i| i[key] }
rescue NoMethodError => e
Smoke.log.info "You're trying to sort by \"#{key}\" but it does not exist in your item set"
end | ruby | def sort(key)
@items = @items.sort_by{|i| i[key] }
rescue NoMethodError => e
Smoke.log.info "You're trying to sort by \"#{key}\" but it does not exist in your item set"
end | [
"def",
"sort",
"(",
"key",
")",
"@items",
"=",
"@items",
".",
"sort_by",
"{",
"|",
"i",
"|",
"i",
"[",
"key",
"]",
"}",
"rescue",
"NoMethodError",
"=>",
"e",
"Smoke",
".",
"log",
".",
"info",
"\"You're trying to sort by \\\"#{key}\\\" but it does not exist in ... | Re-sort items by a particular key
Sort must be used inside an `emit` block. | [
"Re",
"-",
"sort",
"items",
"by",
"a",
"particular",
"key",
"Sort",
"must",
"be",
"used",
"inside",
"an",
"emit",
"block",
"."
] | b229e0cc975d6420a3b7505b42f38b8ba1126d54 | https://github.com/benschwarz/smoke/blob/b229e0cc975d6420a3b7505b42f38b8ba1126d54/lib/smoke/origin.rb#L159-L163 | train |
benschwarz/smoke | lib/smoke/origin.rb | Smoke.Origin.keep | def keep(key, matcher)
@items.reject! {|i| (i[key] =~ matcher) ? false : true }
end | ruby | def keep(key, matcher)
@items.reject! {|i| (i[key] =~ matcher) ? false : true }
end | [
"def",
"keep",
"(",
"key",
",",
"matcher",
")",
"@items",
".",
"reject!",
"{",
"|",
"i",
"|",
"(",
"i",
"[",
"key",
"]",
"=~",
"matcher",
")",
"?",
"false",
":",
"true",
"}",
"end"
] | Keep items that match the regex
Usage (block, during initialization):
Smoke.yql(:ruby) do
...
emit do
keep(:title, /tuesday/i)
end
end
Keep must be used inside an `emit` block. | [
"Keep",
"items",
"that",
"match",
"the",
"regex"
] | b229e0cc975d6420a3b7505b42f38b8ba1126d54 | https://github.com/benschwarz/smoke/blob/b229e0cc975d6420a3b7505b42f38b8ba1126d54/lib/smoke/origin.rb#L192-L194 | train |
benschwarz/smoke | lib/smoke/origin.rb | Smoke.Origin.discard | def discard(key, matcher)
@items.reject! {|i| (i[key] =~ matcher) ? true : false }
end | ruby | def discard(key, matcher)
@items.reject! {|i| (i[key] =~ matcher) ? true : false }
end | [
"def",
"discard",
"(",
"key",
",",
"matcher",
")",
"@items",
".",
"reject!",
"{",
"|",
"i",
"|",
"(",
"i",
"[",
"key",
"]",
"=~",
"matcher",
")",
"?",
"true",
":",
"false",
"}",
"end"
] | Discard items that do not match the regex
Usage (block, during initialization):
Smoke.yql(:ruby) do
...
emit do
discard(:title, /tuesday/i)
end
end
Discard must be used inside an `emit` block. | [
"Discard",
"items",
"that",
"do",
"not",
"match",
"the",
"regex"
] | b229e0cc975d6420a3b7505b42f38b8ba1126d54 | https://github.com/benschwarz/smoke/blob/b229e0cc975d6420a3b7505b42f38b8ba1126d54/lib/smoke/origin.rb#L206-L208 | train |
madx/roy | lib/roy/context.rb | Roy.Context.prepare! | def prepare!(env)
@env = env
@request = Rack::Request.new(env)
@response = Rack::Response.new
@headers = @response.header
@params = @request.GET.merge(@request.POST)
@params.default_proc = proc do |hash, key|
hash[key.to_s] if Symbol === key
end
end | ruby | def prepare!(env)
@env = env
@request = Rack::Request.new(env)
@response = Rack::Response.new
@headers = @response.header
@params = @request.GET.merge(@request.POST)
@params.default_proc = proc do |hash, key|
hash[key.to_s] if Symbol === key
end
end | [
"def",
"prepare!",
"(",
"env",
")",
"@env",
"=",
"env",
"@request",
"=",
"Rack",
"::",
"Request",
".",
"new",
"(",
"env",
")",
"@response",
"=",
"Rack",
"::",
"Response",
".",
"new",
"@headers",
"=",
"@response",
".",
"header",
"@params",
"=",
"@reques... | Creates a new Context object.
@param app the context's application
Initializes the attributes based on an environment.
@param env the environment to use | [
"Creates",
"a",
"new",
"Context",
"object",
"."
] | 7f9d96b146c15c7b2d3f4019a8a2078475983186 | https://github.com/madx/roy/blob/7f9d96b146c15c7b2d3f4019a8a2078475983186/lib/roy/context.rb#L43-L52 | train |
mikemackintosh/slackdraft | lib/slackdraft/attachment.rb | Slackdraft.Attachment.generate_attachment | def generate_attachment
payload = {}
payload[:fallback] = self.fallback unless self.fallback.nil?
payload[:color] = self.color unless self.color.nil?
payload[:pretext] = self.pretext unless self.pretext.nil?
payload[:author_name] = self.author_name unles... | ruby | def generate_attachment
payload = {}
payload[:fallback] = self.fallback unless self.fallback.nil?
payload[:color] = self.color unless self.color.nil?
payload[:pretext] = self.pretext unless self.pretext.nil?
payload[:author_name] = self.author_name unles... | [
"def",
"generate_attachment",
"payload",
"=",
"{",
"}",
"payload",
"[",
":fallback",
"]",
"=",
"self",
".",
"fallback",
"unless",
"self",
".",
"fallback",
".",
"nil?",
"payload",
"[",
":color",
"]",
"=",
"self",
".",
"color",
"unless",
"self",
".",
"colo... | Generate the payload for slack attachments | [
"Generate",
"the",
"payload",
"for",
"slack",
"attachments"
] | 4025fe370f468750fdf5a0dc9741871bca897c0a | https://github.com/mikemackintosh/slackdraft/blob/4025fe370f468750fdf5a0dc9741871bca897c0a/lib/slackdraft/attachment.rb#L34-L53 | train |
Deradon/Rdcpu16 | lib/dcpu16/screen.rb | DCPU16.Screen.frame | def frame
return @frame if @frame
chars = []
# 4 corners
chars << Char.new(0x23, @x_offset - 1, @y_offset - 1) # TopLeft
chars << Char.new(0x23, @x_offset + @width, @y_offset - 1) # TopRight
chars << Char.new(0x23, @x_offset - 1, @y_offset + @height) #... | ruby | def frame
return @frame if @frame
chars = []
# 4 corners
chars << Char.new(0x23, @x_offset - 1, @y_offset - 1) # TopLeft
chars << Char.new(0x23, @x_offset + @width, @y_offset - 1) # TopRight
chars << Char.new(0x23, @x_offset - 1, @y_offset + @height) #... | [
"def",
"frame",
"return",
"@frame",
"if",
"@frame",
"chars",
"=",
"[",
"]",
"# 4 corners",
"chars",
"<<",
"Char",
".",
"new",
"(",
"0x23",
",",
"@x_offset",
"-",
"1",
",",
"@y_offset",
"-",
"1",
")",
"# TopLeft",
"chars",
"<<",
"Char",
".",
"new",
"(... | Use a fancy border around console | [
"Use",
"a",
"fancy",
"border",
"around",
"console"
] | a4460927aa64c2a514c57993e8ea13f5b48377e9 | https://github.com/Deradon/Rdcpu16/blob/a4460927aa64c2a514c57993e8ea13f5b48377e9/lib/dcpu16/screen.rb#L73-L92 | train |
Deradon/Rdcpu16 | lib/dcpu16/screen.rb | DCPU16.Screen.update | def update(offset, value)
return unless (memory_offset..memory_offset_end).include?(offset)
@to_s = nil
diff = offset - @memory_offset
h = diff / @width
w = diff % @width
@chars[diff] = Char.new(value, w + @x_offset, h + @y_offset)
print @chars[diff]
changed
... | ruby | def update(offset, value)
return unless (memory_offset..memory_offset_end).include?(offset)
@to_s = nil
diff = offset - @memory_offset
h = diff / @width
w = diff % @width
@chars[diff] = Char.new(value, w + @x_offset, h + @y_offset)
print @chars[diff]
changed
... | [
"def",
"update",
"(",
"offset",
",",
"value",
")",
"return",
"unless",
"(",
"memory_offset",
"..",
"memory_offset_end",
")",
".",
"include?",
"(",
"offset",
")",
"@to_s",
"=",
"nil",
"diff",
"=",
"offset",
"-",
"@memory_offset",
"h",
"=",
"diff",
"/",
"@... | Callback from observed memory | [
"Callback",
"from",
"observed",
"memory"
] | a4460927aa64c2a514c57993e8ea13f5b48377e9 | https://github.com/Deradon/Rdcpu16/blob/a4460927aa64c2a514c57993e8ea13f5b48377e9/lib/dcpu16/screen.rb#L95-L107 | train |
bumbleworks/bumbleworks | lib/bumbleworks/configuration.rb | Bumbleworks.Configuration.add_storage_adapter | def add_storage_adapter(adapter)
raise ArgumentError, "#{adapter} is not a Bumbleworks storage adapter" unless
[:driver, :use?, :new_storage, :allow_history_storage?, :storage_class, :display_name].all? { |m| adapter.respond_to?(m) }
@storage_adapters << adapter
@storage_adapters
end | ruby | def add_storage_adapter(adapter)
raise ArgumentError, "#{adapter} is not a Bumbleworks storage adapter" unless
[:driver, :use?, :new_storage, :allow_history_storage?, :storage_class, :display_name].all? { |m| adapter.respond_to?(m) }
@storage_adapters << adapter
@storage_adapters
end | [
"def",
"add_storage_adapter",
"(",
"adapter",
")",
"raise",
"ArgumentError",
",",
"\"#{adapter} is not a Bumbleworks storage adapter\"",
"unless",
"[",
":driver",
",",
":use?",
",",
":new_storage",
",",
":allow_history_storage?",
",",
":storage_class",
",",
":display_name",... | Add a storage adapter to the set of possible adapters. Takes an object
that responds to `driver`, `use?`, `storage_class`, and `display_name`. | [
"Add",
"a",
"storage",
"adapter",
"to",
"the",
"set",
"of",
"possible",
"adapters",
".",
"Takes",
"an",
"object",
"that",
"responds",
"to",
"driver",
"use?",
"storage_class",
"and",
"display_name",
"."
] | 6f63992e921dcf8371d4453ef9e7b4e3322cc360 | https://github.com/bumbleworks/bumbleworks/blob/6f63992e921dcf8371d4453ef9e7b4e3322cc360/lib/bumbleworks/configuration.rb#L263-L269 | train |
bumbleworks/bumbleworks | lib/bumbleworks/configuration.rb | Bumbleworks.Configuration.storage_adapter | def storage_adapter
@storage_adapter ||= begin
all_adapters = storage_adapters
raise UndefinedSetting, "No storage adapters configured" if all_adapters.empty?
adapter = all_adapters.detect do |potential_adapter|
potential_adapter.use?(storage)
end
raise UndefinedS... | ruby | def storage_adapter
@storage_adapter ||= begin
all_adapters = storage_adapters
raise UndefinedSetting, "No storage adapters configured" if all_adapters.empty?
adapter = all_adapters.detect do |potential_adapter|
potential_adapter.use?(storage)
end
raise UndefinedS... | [
"def",
"storage_adapter",
"@storage_adapter",
"||=",
"begin",
"all_adapters",
"=",
"storage_adapters",
"raise",
"UndefinedSetting",
",",
"\"No storage adapters configured\"",
"if",
"all_adapters",
".",
"empty?",
"adapter",
"=",
"all_adapters",
".",
"detect",
"do",
"|",
... | If storage_adapter is not explicitly set, find first registered adapter that
can use Bumbleworks.storage. | [
"If",
"storage_adapter",
"is",
"not",
"explicitly",
"set",
"find",
"first",
"registered",
"adapter",
"that",
"can",
"use",
"Bumbleworks",
".",
"storage",
"."
] | 6f63992e921dcf8371d4453ef9e7b4e3322cc360 | https://github.com/bumbleworks/bumbleworks/blob/6f63992e921dcf8371d4453ef9e7b4e3322cc360/lib/bumbleworks/configuration.rb#L274-L284 | train |
bumbleworks/bumbleworks | lib/bumbleworks/configuration.rb | Bumbleworks.Configuration.look_up_configured_path | def look_up_configured_path(path_type, options = {})
return @cached_paths[path_type] if @cached_paths.has_key?(path_type)
if user_defined_path = user_configured_path(path_type)
if path_resolves?(user_defined_path, :file => options[:file])
return user_defined_path
else
rai... | ruby | def look_up_configured_path(path_type, options = {})
return @cached_paths[path_type] if @cached_paths.has_key?(path_type)
if user_defined_path = user_configured_path(path_type)
if path_resolves?(user_defined_path, :file => options[:file])
return user_defined_path
else
rai... | [
"def",
"look_up_configured_path",
"(",
"path_type",
",",
"options",
"=",
"{",
"}",
")",
"return",
"@cached_paths",
"[",
"path_type",
"]",
"if",
"@cached_paths",
".",
"has_key?",
"(",
"path_type",
")",
"if",
"user_defined_path",
"=",
"user_configured_path",
"(",
... | If the user explicitly declared a path, raises an exception if the
path was not found. Missing default paths do not raise an exception
since no paths are required. | [
"If",
"the",
"user",
"explicitly",
"declared",
"a",
"path",
"raises",
"an",
"exception",
"if",
"the",
"path",
"was",
"not",
"found",
".",
"Missing",
"default",
"paths",
"do",
"not",
"raise",
"an",
"exception",
"since",
"no",
"paths",
"are",
"required",
"."... | 6f63992e921dcf8371d4453ef9e7b4e3322cc360 | https://github.com/bumbleworks/bumbleworks/blob/6f63992e921dcf8371d4453ef9e7b4e3322cc360/lib/bumbleworks/configuration.rb#L350-L361 | train |
ronen/hash_keyword_args | lib/hash_keyword_args/hash.rb | HashKeywordArgs.Hash.keyword_args | def keyword_args(*args)
argshash = args[-1].is_a?(Hash) ? args.pop : {}
argshash = args.hashify(:optional).merge(argshash)
others_OK = argshash.delete(:OTHERS)
ret = {}
# defaults, required, and checked
required = []
check = {}
argshash.each do |key, val|
# const... | ruby | def keyword_args(*args)
argshash = args[-1].is_a?(Hash) ? args.pop : {}
argshash = args.hashify(:optional).merge(argshash)
others_OK = argshash.delete(:OTHERS)
ret = {}
# defaults, required, and checked
required = []
check = {}
argshash.each do |key, val|
# const... | [
"def",
"keyword_args",
"(",
"*",
"args",
")",
"argshash",
"=",
"args",
"[",
"-",
"1",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"argshash",
"=",
"args",
".",
"hashify",
"(",
":optional",
")",
".",
"merge",
"(",
... | given an argument hash and a description of acceptable keyword args and
their default values, checks validity of the arguments and raises any
errors, otherwise returns a new hash containing all arg values with
defaults filled in as needed.
args = hash.keyword_args(:a, :b, :c, # these are all optional args
... | [
"given",
"an",
"argument",
"hash",
"and",
"a",
"description",
"of",
"acceptable",
"keyword",
"args",
"and",
"their",
"default",
"values",
"checks",
"validity",
"of",
"the",
"arguments",
"and",
"raises",
"any",
"errors",
"otherwise",
"returns",
"a",
"new",
"has... | 10b0b5d46b32afc0cf6129aa84b49b54ec44474a | https://github.com/ronen/hash_keyword_args/blob/10b0b5d46b32afc0cf6129aa84b49b54ec44474a/lib/hash_keyword_args/hash.rb#L27-L111 | train |
ryohashimoto/actionpager | lib/action_pager/pager.rb | ActionPager.Pager.near_pages | def near_pages
@near_pages ||= begin
if current_page <= near + 1
upper_page = shown_page_count >= last_page ? last_page : shown_page_count
1..upper_page
elsif current_page >= last_page - near - 1
bottom_page = last_page - shown_page_count + 1
(bottom_page > ... | ruby | def near_pages
@near_pages ||= begin
if current_page <= near + 1
upper_page = shown_page_count >= last_page ? last_page : shown_page_count
1..upper_page
elsif current_page >= last_page - near - 1
bottom_page = last_page - shown_page_count + 1
(bottom_page > ... | [
"def",
"near_pages",
"@near_pages",
"||=",
"begin",
"if",
"current_page",
"<=",
"near",
"+",
"1",
"upper_page",
"=",
"shown_page_count",
">=",
"last_page",
"?",
"last_page",
":",
"shown_page_count",
"1",
"..",
"upper_page",
"elsif",
"current_page",
">=",
"last_pag... | pages that numbers are displayed | [
"pages",
"that",
"numbers",
"are",
"displayed"
] | 4ef4e3005748fae2d10a23a5ac5a191ca7a3f65f | https://github.com/ryohashimoto/actionpager/blob/4ef4e3005748fae2d10a23a5ac5a191ca7a3f65f/lib/action_pager/pager.rb#L112-L126 | train |
dmmalam/wall-leecher | lib/leecher.rb | WallLeecher.Leecher.prep_file | def prep_file(url, dir)
parts = url.split('/')
File.join(dir, parts[-1])
end | ruby | def prep_file(url, dir)
parts = url.split('/')
File.join(dir, parts[-1])
end | [
"def",
"prep_file",
"(",
"url",
",",
"dir",
")",
"parts",
"=",
"url",
".",
"split",
"(",
"'/'",
")",
"File",
".",
"join",
"(",
"dir",
",",
"parts",
"[",
"-",
"1",
"]",
")",
"end"
] | Pure function to create correct filename | [
"Pure",
"function",
"to",
"create",
"correct",
"filename"
] | c744ec6886db0dfd5f316ff59f410e10866e2e15 | https://github.com/dmmalam/wall-leecher/blob/c744ec6886db0dfd5f316ff59f410e10866e2e15/lib/leecher.rb#L38-L41 | train |
dmmalam/wall-leecher | lib/leecher.rb | WallLeecher.Fetcher.get | def get
schedule do
inc_io
@@log.info("Requesting: #{@url}")
http = EM::HttpRequest.new(@url).get :redirects => 5
http.callback do |h|
succeed http.response
dec_io
end
http.headers do |headers|
... | ruby | def get
schedule do
inc_io
@@log.info("Requesting: #{@url}")
http = EM::HttpRequest.new(@url).get :redirects => 5
http.callback do |h|
succeed http.response
dec_io
end
http.headers do |headers|
... | [
"def",
"get",
"schedule",
"do",
"inc_io",
"@@log",
".",
"info",
"(",
"\"Requesting: #{@url}\"",
")",
"http",
"=",
"EM",
"::",
"HttpRequest",
".",
"new",
"(",
"@url",
")",
".",
"get",
":redirects",
"=>",
"5",
"http",
".",
"callback",
"do",
"|",
"h",
"|"... | Non blocking get url | [
"Non",
"blocking",
"get",
"url"
] | c744ec6886db0dfd5f316ff59f410e10866e2e15 | https://github.com/dmmalam/wall-leecher/blob/c744ec6886db0dfd5f316ff59f410e10866e2e15/lib/leecher.rb#L120-L144 | train |
npolar/npolar-api-client-ruby | lib/npolar/api/client/json_api_client.rb | Npolar::Api::Client.JsonApiClient.valid | def valid(condition=true)
all.select {|d| condition == valid?(d) }.map {|d| model.class.new(d)}
end | ruby | def valid(condition=true)
all.select {|d| condition == valid?(d) }.map {|d| model.class.new(d)}
end | [
"def",
"valid",
"(",
"condition",
"=",
"true",
")",
"all",
".",
"select",
"{",
"|",
"d",
"|",
"condition",
"==",
"valid?",
"(",
"d",
")",
"}",
".",
"map",
"{",
"|",
"d",
"|",
"model",
".",
"class",
".",
"new",
"(",
"d",
")",
"}",
"end"
] | All valid documents | [
"All",
"valid",
"documents"
] | e28ff77dad15bb1bcfcb750f5d1fd4679aa8b7fb | https://github.com/npolar/npolar-api-client-ruby/blob/e28ff77dad15bb1bcfcb750f5d1fd4679aa8b7fb/lib/npolar/api/client/json_api_client.rb#L286-L288 | train |
npolar/npolar-api-client-ruby | lib/npolar/api/client/json_api_client.rb | Npolar::Api::Client.JsonApiClient.multi_request | def multi_request(method, paths, body=nil, param=nil, header=nil)
@multi = true
# Response storage, if not already set
if @responses.nil?
@responses = []
end
# Handle one or many paths
if paths.is_a? String or paths.is_a? URI
paths = [paths]
end
# Handl... | ruby | def multi_request(method, paths, body=nil, param=nil, header=nil)
@multi = true
# Response storage, if not already set
if @responses.nil?
@responses = []
end
# Handle one or many paths
if paths.is_a? String or paths.is_a? URI
paths = [paths]
end
# Handl... | [
"def",
"multi_request",
"(",
"method",
",",
"paths",
",",
"body",
"=",
"nil",
",",
"param",
"=",
"nil",
",",
"header",
"=",
"nil",
")",
"@multi",
"=",
"true",
"# Response storage, if not already set",
"if",
"@responses",
".",
"nil?",
"@responses",
"=",
"[",
... | Prepare and queue a multi request
@return [#run] | [
"Prepare",
"and",
"queue",
"a",
"multi",
"request"
] | e28ff77dad15bb1bcfcb750f5d1fd4679aa8b7fb | https://github.com/npolar/npolar-api-client-ruby/blob/e28ff77dad15bb1bcfcb750f5d1fd4679aa8b7fb/lib/npolar/api/client/json_api_client.rb#L496-L524 | train |
elifoster/fishbans-rb | lib/block_engine.rb | Fishbans.BlockEngine.get_block | def get_block(id, metadata = nil, size = 42)
url = "http://blocks.fishbans.com/#{id}"
url += "-#{metadata}" unless metadata.nil?
url += "/#{size}" if size != 42
response = get(url, false)
ChunkyPNG::Image.from_blob(response.body)
end | ruby | def get_block(id, metadata = nil, size = 42)
url = "http://blocks.fishbans.com/#{id}"
url += "-#{metadata}" unless metadata.nil?
url += "/#{size}" if size != 42
response = get(url, false)
ChunkyPNG::Image.from_blob(response.body)
end | [
"def",
"get_block",
"(",
"id",
",",
"metadata",
"=",
"nil",
",",
"size",
"=",
"42",
")",
"url",
"=",
"\"http://blocks.fishbans.com/#{id}\"",
"url",
"+=",
"\"-#{metadata}\"",
"unless",
"metadata",
".",
"nil?",
"url",
"+=",
"\"/#{size}\"",
"if",
"size",
"!=",
... | Gets a block image by its ID and Metadata. Unfortunately it uses the old
block IDs rather than the new ones, so you have to memorize those
pesky integers.
@param id [Integer] The (outdated) block ID number.
@param metadata [Integer] The metadata, if any, for the block.
@param size [Fixnum] The size of the imag... | [
"Gets",
"a",
"block",
"image",
"by",
"its",
"ID",
"and",
"Metadata",
".",
"Unfortunately",
"it",
"uses",
"the",
"old",
"block",
"IDs",
"rather",
"than",
"the",
"new",
"ones",
"so",
"you",
"have",
"to",
"memorize",
"those",
"pesky",
"integers",
"."
] | 652016694176ade8767ac6a3b4dea2dc631be747 | https://github.com/elifoster/fishbans-rb/blob/652016694176ade8767ac6a3b4dea2dc631be747/lib/block_engine.rb#L14-L20 | train |
elifoster/fishbans-rb | lib/block_engine.rb | Fishbans.BlockEngine.get_monster | def get_monster(id, three = false, size = 42)
id = id.to_s
url = 'http://blocks.fishbans.com'
url += "/#{id}" if id =~ /^m/
url += "/m#{id}" if id !~ /^m/
url += '-3d' if three
url += "/#{size}" if size != 42
response = get(url, false)
ChunkyPNG::Image.from_blob(response.... | ruby | def get_monster(id, three = false, size = 42)
id = id.to_s
url = 'http://blocks.fishbans.com'
url += "/#{id}" if id =~ /^m/
url += "/m#{id}" if id !~ /^m/
url += '-3d' if three
url += "/#{size}" if size != 42
response = get(url, false)
ChunkyPNG::Image.from_blob(response.... | [
"def",
"get_monster",
"(",
"id",
",",
"three",
"=",
"false",
",",
"size",
"=",
"42",
")",
"id",
"=",
"id",
".",
"to_s",
"url",
"=",
"'http://blocks.fishbans.com'",
"url",
"+=",
"\"/#{id}\"",
"if",
"id",
"=~",
"/",
"/",
"url",
"+=",
"\"/m#{id}\"",
"if",... | Gets the monster image by its ID.
@param id [Any] The string ID. It will automatically prefix it with "m" if
that is omitted. It doesn't matter what type it is: String or Fixnum,
because it will automatically convert it to a String.
@param three [Boolean] Whether to get a three-dimensional monster image.
The... | [
"Gets",
"the",
"monster",
"image",
"by",
"its",
"ID",
"."
] | 652016694176ade8767ac6a3b4dea2dc631be747 | https://github.com/elifoster/fishbans-rb/blob/652016694176ade8767ac6a3b4dea2dc631be747/lib/block_engine.rb#L33-L42 | train |
wparad/Osiris | lib/osiris/zip_file_generator.rb | Osiris.ZipFileGenerator.write | def write(inputDir, outputFile)
entries = Dir.entries(inputDir); entries.delete("."); entries.delete("..")
io = Zip::File.open(outputFile, Zip::File::CREATE);
writeEntries(entries, "", io, inputDir)
io.close();
end | ruby | def write(inputDir, outputFile)
entries = Dir.entries(inputDir); entries.delete("."); entries.delete("..")
io = Zip::File.open(outputFile, Zip::File::CREATE);
writeEntries(entries, "", io, inputDir)
io.close();
end | [
"def",
"write",
"(",
"inputDir",
",",
"outputFile",
")",
"entries",
"=",
"Dir",
".",
"entries",
"(",
"inputDir",
")",
";",
"entries",
".",
"delete",
"(",
"\".\"",
")",
";",
"entries",
".",
"delete",
"(",
"\"..\"",
")",
"io",
"=",
"Zip",
"::",
"File",... | Initialize with the directory to zip and the location of the output archive.
Zip the input directory. | [
"Initialize",
"with",
"the",
"directory",
"to",
"zip",
"and",
"the",
"location",
"of",
"the",
"output",
"archive",
".",
"Zip",
"the",
"input",
"directory",
"."
] | efa61f3353674a01e813d9557016bd610277f7de | https://github.com/wparad/Osiris/blob/efa61f3353674a01e813d9557016bd610277f7de/lib/osiris/zip_file_generator.rb#L20-L26 | train |
pwnall/file_blobs_rails | lib/file_blobs_rails/active_record_fixture_set_extensions.rb | FileBlobs.ActiveRecordFixtureSetExtensions.file_blob_id | def file_blob_id(path)
file_path = Rails.root.join('test/fixtures'.freeze).join(path)
blob_contents = File.binread file_path
# This needs to be kept in sync with blob_model.rb.
Base64.urlsafe_encode64(Digest::SHA256.digest(blob_contents)).inspect
end | ruby | def file_blob_id(path)
file_path = Rails.root.join('test/fixtures'.freeze).join(path)
blob_contents = File.binread file_path
# This needs to be kept in sync with blob_model.rb.
Base64.urlsafe_encode64(Digest::SHA256.digest(blob_contents)).inspect
end | [
"def",
"file_blob_id",
"(",
"path",
")",
"file_path",
"=",
"Rails",
".",
"root",
".",
"join",
"(",
"'test/fixtures'",
".",
"freeze",
")",
".",
"join",
"(",
"path",
")",
"blob_contents",
"=",
"File",
".",
"binread",
"file_path",
"# This needs to be kept in sync... | Computes the ID assigned to a blob.
@param [String] path the path of the file whose contents is used in the
fixture, relative to the Rails application's test/fixtures directory
@return [String] the ID used to represent the blob contents | [
"Computes",
"the",
"ID",
"assigned",
"to",
"a",
"blob",
"."
] | 688d43ec8547856f3572b0e6716e6faeff56345b | https://github.com/pwnall/file_blobs_rails/blob/688d43ec8547856f3572b0e6716e6faeff56345b/lib/file_blobs_rails/active_record_fixture_set_extensions.rb#L14-L20 | train |
pwnall/file_blobs_rails | lib/file_blobs_rails/active_record_fixture_set_extensions.rb | FileBlobs.ActiveRecordFixtureSetExtensions.file_blob_data | def file_blob_data(path, options = {})
# The line with base64 data must be indented further than the current line.
indent = ' ' * ((options[:indent] || 2) + 2)
file_path = Rails.root.join('test/fixtures'.freeze).join(path)
blob_contents = File.binread file_path
base64_data = Base64.encode64 blob_co... | ruby | def file_blob_data(path, options = {})
# The line with base64 data must be indented further than the current line.
indent = ' ' * ((options[:indent] || 2) + 2)
file_path = Rails.root.join('test/fixtures'.freeze).join(path)
blob_contents = File.binread file_path
base64_data = Base64.encode64 blob_co... | [
"def",
"file_blob_data",
"(",
"path",
",",
"options",
"=",
"{",
"}",
")",
"# The line with base64 data must be indented further than the current line.",
"indent",
"=",
"' '",
"*",
"(",
"(",
"options",
"[",
":indent",
"]",
"||",
"2",
")",
"+",
"2",
")",
"file_pat... | The contents of a blob, in a YAML-friendly format.
@param [String] path the path of the file whose contents is used in the
fixture, relative to the Rails application's test/fixtures directory
@param [Hash] options optionally specify the current indentation level
@option options [Integer] indent the number of spa... | [
"The",
"contents",
"of",
"a",
"blob",
"in",
"a",
"YAML",
"-",
"friendly",
"format",
"."
] | 688d43ec8547856f3572b0e6716e6faeff56345b | https://github.com/pwnall/file_blobs_rails/blob/688d43ec8547856f3572b0e6716e6faeff56345b/lib/file_blobs_rails/active_record_fixture_set_extensions.rb#L30-L41 | train |
pwnall/file_blobs_rails | lib/file_blobs_rails/active_record_fixture_set_extensions.rb | FileBlobs.ActiveRecordFixtureSetExtensions.file_blob_size | def file_blob_size(path)
file_path = Rails.root.join('test/fixtures'.freeze).join(path)
File.stat(file_path).size
end | ruby | def file_blob_size(path)
file_path = Rails.root.join('test/fixtures'.freeze).join(path)
File.stat(file_path).size
end | [
"def",
"file_blob_size",
"(",
"path",
")",
"file_path",
"=",
"Rails",
".",
"root",
".",
"join",
"(",
"'test/fixtures'",
".",
"freeze",
")",
".",
"join",
"(",
"path",
")",
"File",
".",
"stat",
"(",
"file_path",
")",
".",
"size",
"end"
] | The number of bytes in a file.
@param [String] path the path of the file whose contents is used in the
fixture, relative to the Rails application's test/fixtures directory
@return [Integer] the nubmer of bytes in the file | [
"The",
"number",
"of",
"bytes",
"in",
"a",
"file",
"."
] | 688d43ec8547856f3572b0e6716e6faeff56345b | https://github.com/pwnall/file_blobs_rails/blob/688d43ec8547856f3572b0e6716e6faeff56345b/lib/file_blobs_rails/active_record_fixture_set_extensions.rb#L48-L51 | train |
thriventures/storage_room_gem | lib/storage_room/embeddeds/file.rb | StorageRoom.File.set_with_filename | def set_with_filename(path)
return if path.blank?
self.filename = ::File.basename(path)
self.content_type = ::MIME::Types.type_for(path).first.content_type
self.data = ::Base64.encode64(::File.read(path))
end | ruby | def set_with_filename(path)
return if path.blank?
self.filename = ::File.basename(path)
self.content_type = ::MIME::Types.type_for(path).first.content_type
self.data = ::Base64.encode64(::File.read(path))
end | [
"def",
"set_with_filename",
"(",
"path",
")",
"return",
"if",
"path",
".",
"blank?",
"self",
".",
"filename",
"=",
"::",
"File",
".",
"basename",
"(",
"path",
")",
"self",
".",
"content_type",
"=",
"::",
"MIME",
"::",
"Types",
".",
"type_for",
"(",
"pa... | Sets the filename, content_type and data attributes from a local filename so that a File can be uploaded through the API | [
"Sets",
"the",
"filename",
"content_type",
"and",
"data",
"attributes",
"from",
"a",
"local",
"filename",
"so",
"that",
"a",
"File",
"can",
"be",
"uploaded",
"through",
"the",
"API"
] | cadf132b865ff82f7b09fadfec1d294a714c6728 | https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/embeddeds/file.rb#L20-L26 | train |
thriventures/storage_room_gem | lib/storage_room/embeddeds/file.rb | StorageRoom.File.download_to_directory | def download_to_directory(path)
Dir.mkdir(path) unless ::File.directory?(path)
download_file(self[:@url], ::File.join(path, local_filename))
true
end | ruby | def download_to_directory(path)
Dir.mkdir(path) unless ::File.directory?(path)
download_file(self[:@url], ::File.join(path, local_filename))
true
end | [
"def",
"download_to_directory",
"(",
"path",
")",
"Dir",
".",
"mkdir",
"(",
"path",
")",
"unless",
"::",
"File",
".",
"directory?",
"(",
"path",
")",
"download_file",
"(",
"self",
"[",
":@url",
"]",
",",
"::",
"File",
".",
"join",
"(",
"path",
",",
"... | Download the file to the local disk | [
"Download",
"the",
"file",
"to",
"the",
"local",
"disk"
] | cadf132b865ff82f7b09fadfec1d294a714c6728 | https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/embeddeds/file.rb#L34-L38 | train |
sanichi/icu_tournament | lib/icu_tournament/tournament_spx.rb | ICU.Player.to_sp_text | def to_sp_text(rounds, columns, formats)
values = columns.inject([]) do |vals,col|
val = send(col).to_s
val.sub!(/\.0/, '') if col == :points
vals << val
end
(1..rounds).each do |r|
result = find_result(r)
values << (result ? result.to_sp_text : " : ")
end... | ruby | def to_sp_text(rounds, columns, formats)
values = columns.inject([]) do |vals,col|
val = send(col).to_s
val.sub!(/\.0/, '') if col == :points
vals << val
end
(1..rounds).each do |r|
result = find_result(r)
values << (result ? result.to_sp_text : " : ")
end... | [
"def",
"to_sp_text",
"(",
"rounds",
",",
"columns",
",",
"formats",
")",
"values",
"=",
"columns",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"vals",
",",
"col",
"|",
"val",
"=",
"send",
"(",
"col",
")",
".",
"to_s",
"val",
".",
"sub!",
"(",
... | Format a player's record as it would appear in an SP export file. | [
"Format",
"a",
"player",
"s",
"record",
"as",
"it",
"would",
"appear",
"in",
"an",
"SP",
"export",
"file",
"."
] | badd2940189feaeb9f0edb4b4e07ff6b2548bd3d | https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament_spx.rb#L364-L375 | train |
evansagge/numeric_array | lib/numeric_array.rb | NumericArray.InstanceMethods.variance | def variance(sample = false)
a = numerify
avg = a.average
sum = a.inject(0) { |sum, value| sum + (value - avg) ** 2}
(1 / (a.length.to_f - (sample ? 1 : 0)) * sum)
end | ruby | def variance(sample = false)
a = numerify
avg = a.average
sum = a.inject(0) { |sum, value| sum + (value - avg) ** 2}
(1 / (a.length.to_f - (sample ? 1 : 0)) * sum)
end | [
"def",
"variance",
"(",
"sample",
"=",
"false",
")",
"a",
"=",
"numerify",
"avg",
"=",
"a",
".",
"average",
"sum",
"=",
"a",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"sum",
",",
"value",
"|",
"sum",
"+",
"(",
"value",
"-",
"avg",
")",
"**",
"2... | variance of an array of numbers | [
"variance",
"of",
"an",
"array",
"of",
"numbers"
] | f5cbdd0c658631d42540f9251480e0d38ebb493a | https://github.com/evansagge/numeric_array/blob/f5cbdd0c658631d42540f9251480e0d38ebb493a/lib/numeric_array.rb#L25-L30 | train |
irvingwashington/gem_footprint_analyzer | lib/gem_footprint_analyzer/cli.rb | GemFootprintAnalyzer.CLI.run | def run(args = ARGV)
opts.parse!(args)
if !analyze_gemfile? && args.empty?
puts opts.parser
exit 1
end
print_requires(options, args)
end | ruby | def run(args = ARGV)
opts.parse!(args)
if !analyze_gemfile? && args.empty?
puts opts.parser
exit 1
end
print_requires(options, args)
end | [
"def",
"run",
"(",
"args",
"=",
"ARGV",
")",
"opts",
".",
"parse!",
"(",
"args",
")",
"if",
"!",
"analyze_gemfile?",
"&&",
"args",
".",
"empty?",
"puts",
"opts",
".",
"parser",
"exit",
"1",
"end",
"print_requires",
"(",
"options",
",",
"args",
")",
"... | Sets default options, to be overwritten by option parser down the road
@param args [Array<String>] runs the analyzer with parsed args taken as options
@return [void] | [
"Sets",
"default",
"options",
"to",
"be",
"overwritten",
"by",
"option",
"parser",
"down",
"the",
"road"
] | 19a8892f6baaeb16b1b166144c4f73852396220c | https://github.com/irvingwashington/gem_footprint_analyzer/blob/19a8892f6baaeb16b1b166144c4f73852396220c/lib/gem_footprint_analyzer/cli.rb#L19-L28 | train |
gr4y/streambot | lib/streambot/tracker.rb | StreamBot.Tracker.start | def start
keywords = self.params["keywords"]
@thread = Thread.new do
@client.filter_by_keywords(keywords) do |status|
if retweet?(status)
before_retweet.trigger(status)
@retweet.retweet(status["id"])
after_retweet.trigger(status)
end
e... | ruby | def start
keywords = self.params["keywords"]
@thread = Thread.new do
@client.filter_by_keywords(keywords) do |status|
if retweet?(status)
before_retweet.trigger(status)
@retweet.retweet(status["id"])
after_retweet.trigger(status)
end
e... | [
"def",
"start",
"keywords",
"=",
"self",
".",
"params",
"[",
"\"keywords\"",
"]",
"@thread",
"=",
"Thread",
".",
"new",
"do",
"@client",
".",
"filter_by_keywords",
"(",
"keywords",
")",
"do",
"|",
"status",
"|",
"if",
"retweet?",
"(",
"status",
")",
"bef... | initializes the tracker
start the tracker | [
"initializes",
"the",
"tracker",
"start",
"the",
"tracker"
] | 3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375 | https://github.com/gr4y/streambot/blob/3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375/lib/streambot/tracker.rb#L22-L34 | train |
gr4y/streambot | lib/streambot/tracker.rb | StreamBot.Tracker.load_filters | def load_filters
filters_config = self.params["filters_config" ]
if !filters_config.nil? && File.exists?(filters_config)
begin
YAML::load_file(filters_config)
rescue
on_error.trigger($!, $@)
end
end
end | ruby | def load_filters
filters_config = self.params["filters_config" ]
if !filters_config.nil? && File.exists?(filters_config)
begin
YAML::load_file(filters_config)
rescue
on_error.trigger($!, $@)
end
end
end | [
"def",
"load_filters",
"filters_config",
"=",
"self",
".",
"params",
"[",
"\"filters_config\"",
"]",
"if",
"!",
"filters_config",
".",
"nil?",
"&&",
"File",
".",
"exists?",
"(",
"filters_config",
")",
"begin",
"YAML",
"::",
"load_file",
"(",
"filters_config",
... | load the YAML file that is specified in the params | [
"load",
"the",
"YAML",
"file",
"that",
"is",
"specified",
"in",
"the",
"params"
] | 3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375 | https://github.com/gr4y/streambot/blob/3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375/lib/streambot/tracker.rb#L49-L58 | train |
gr4y/streambot | lib/streambot/tracker.rb | StreamBot.Tracker.retweet? | def retweet?(status)
filters = load_filters
retweet = true
if !filters.nil?
filters.each_pair do |path, value|
array = []
array << value
array.flatten.each do |filter_value|
path_value = StreamBot::ArrayPath.get_path(status, path)
if path_v... | ruby | def retweet?(status)
filters = load_filters
retweet = true
if !filters.nil?
filters.each_pair do |path, value|
array = []
array << value
array.flatten.each do |filter_value|
path_value = StreamBot::ArrayPath.get_path(status, path)
if path_v... | [
"def",
"retweet?",
"(",
"status",
")",
"filters",
"=",
"load_filters",
"retweet",
"=",
"true",
"if",
"!",
"filters",
".",
"nil?",
"filters",
".",
"each_pair",
"do",
"|",
"path",
",",
"value",
"|",
"array",
"=",
"[",
"]",
"array",
"<<",
"value",
"array"... | decide if the status is retweetable | [
"decide",
"if",
"the",
"status",
"is",
"retweetable"
] | 3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375 | https://github.com/gr4y/streambot/blob/3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375/lib/streambot/tracker.rb#L61-L78 | train |
jeffa/html-autotag-ruby | lib/HTML/AutoTag.rb | HTML.AutoTag.tag | def tag( params )
# TODO: make these method args if possible
tag = params['tag']
attr = params['attr']
cdata = params['cdata']
unless attr.kind_of?( HTML::AutoAttr )
attr = HTML::AutoAttr.new( attr, @sorted )
end
#... | ruby | def tag( params )
# TODO: make these method args if possible
tag = params['tag']
attr = params['attr']
cdata = params['cdata']
unless attr.kind_of?( HTML::AutoAttr )
attr = HTML::AutoAttr.new( attr, @sorted )
end
#... | [
"def",
"tag",
"(",
"params",
")",
"# TODO: make these method args if possible",
"tag",
"=",
"params",
"[",
"'tag'",
"]",
"attr",
"=",
"params",
"[",
"'attr'",
"]",
"cdata",
"=",
"params",
"[",
"'cdata'",
"]",
"unless",
"attr",
".",
"kind_of?",
"(",
"HTML",
... | Defaults to empty string which produces no encoding. | [
"Defaults",
"to",
"empty",
"string",
"which",
"produces",
"no",
"encoding",
"."
] | 994103cb2c73e0477077fc041e12c81b7ed6326c | https://github.com/jeffa/html-autotag-ruby/blob/994103cb2c73e0477077fc041e12c81b7ed6326c/lib/HTML/AutoTag.rb#L23-L75 | train |
ashrafuzzaman/chartify | lib/chartify/chart_base.rb | Chartify.ChartBase.darken_color | def darken_color(hex_color, amount=0.4)
hex_color = hex_color.gsub('#', '')
rgb = hex_color.scan(/../).map { |color| color.hex }
rgb[0] = (rgb[0].to_i * amount).round
rgb[1] = (rgb[1].to_i * amount).round
rgb[2] = (rgb[2].to_i * amount).round
"#%02x%02x%02x" % rgb
end | ruby | def darken_color(hex_color, amount=0.4)
hex_color = hex_color.gsub('#', '')
rgb = hex_color.scan(/../).map { |color| color.hex }
rgb[0] = (rgb[0].to_i * amount).round
rgb[1] = (rgb[1].to_i * amount).round
rgb[2] = (rgb[2].to_i * amount).round
"#%02x%02x%02x" % rgb
end | [
"def",
"darken_color",
"(",
"hex_color",
",",
"amount",
"=",
"0.4",
")",
"hex_color",
"=",
"hex_color",
".",
"gsub",
"(",
"'#'",
",",
"''",
")",
"rgb",
"=",
"hex_color",
".",
"scan",
"(",
"/",
"/",
")",
".",
"map",
"{",
"|",
"color",
"|",
"color",
... | Amount should be a decimal between 0 and 1. Lower means darker | [
"Amount",
"should",
"be",
"a",
"decimal",
"between",
"0",
"and",
"1",
".",
"Lower",
"means",
"darker"
] | f791ffb20c10417619bec0afa7a355d9e5e499b6 | https://github.com/ashrafuzzaman/chartify/blob/f791ffb20c10417619bec0afa7a355d9e5e499b6/lib/chartify/chart_base.rb#L99-L106 | train |
ashrafuzzaman/chartify | lib/chartify/chart_base.rb | Chartify.ChartBase.lighten_color | def lighten_color(hex_color, amount=0.6)
hex_color = hex_color.gsub('#', '')
rgb = hex_color.scan(/../).map { |color| color.hex }
rgb[0] = [(rgb[0].to_i + 255 * amount).round, 255].min
rgb[1] = [(rgb[1].to_i + 255 * amount).round, 255].min
rgb[2] = [(rgb[2].to_i + 255 * amount).round, 255]... | ruby | def lighten_color(hex_color, amount=0.6)
hex_color = hex_color.gsub('#', '')
rgb = hex_color.scan(/../).map { |color| color.hex }
rgb[0] = [(rgb[0].to_i + 255 * amount).round, 255].min
rgb[1] = [(rgb[1].to_i + 255 * amount).round, 255].min
rgb[2] = [(rgb[2].to_i + 255 * amount).round, 255]... | [
"def",
"lighten_color",
"(",
"hex_color",
",",
"amount",
"=",
"0.6",
")",
"hex_color",
"=",
"hex_color",
".",
"gsub",
"(",
"'#'",
",",
"''",
")",
"rgb",
"=",
"hex_color",
".",
"scan",
"(",
"/",
"/",
")",
".",
"map",
"{",
"|",
"color",
"|",
"color",... | Amount should be a decimal between 0 and 1. Higher means lighter | [
"Amount",
"should",
"be",
"a",
"decimal",
"between",
"0",
"and",
"1",
".",
"Higher",
"means",
"lighter"
] | f791ffb20c10417619bec0afa7a355d9e5e499b6 | https://github.com/ashrafuzzaman/chartify/blob/f791ffb20c10417619bec0afa7a355d9e5e499b6/lib/chartify/chart_base.rb#L109-L116 | train |
jasonayre/trax_model | lib/trax/model.rb | Trax.Model.reverse_assign_attributes | def reverse_assign_attributes(attributes_hash)
attributes_to_assign = attributes_hash.keys.reject{|_attribute_name| attribute_present?(_attribute_name) }
assign_attributes(attributes_hash.slice(attributes_to_assign))
end | ruby | def reverse_assign_attributes(attributes_hash)
attributes_to_assign = attributes_hash.keys.reject{|_attribute_name| attribute_present?(_attribute_name) }
assign_attributes(attributes_hash.slice(attributes_to_assign))
end | [
"def",
"reverse_assign_attributes",
"(",
"attributes_hash",
")",
"attributes_to_assign",
"=",
"attributes_hash",
".",
"keys",
".",
"reject",
"{",
"|",
"_attribute_name",
"|",
"attribute_present?",
"(",
"_attribute_name",
")",
"}",
"assign_attributes",
"(",
"attributes_h... | like reverse merge, only assigns attributes which have not yet been assigned | [
"like",
"reverse",
"merge",
"only",
"assigns",
"attributes",
"which",
"have",
"not",
"yet",
"been",
"assigned"
] | 5e9b7b12f575a06306882440c147b70cca263d5c | https://github.com/jasonayre/trax_model/blob/5e9b7b12f575a06306882440c147b70cca263d5c/lib/trax/model.rb#L50-L54 | train |
mkulumadzi/mediawiki-keiki | lib/mediawiki-keiki/query.rb | MediaWiki.Query.pages | def pages
result_map = map_query_to_results
query_result["query"]["pages"].each do |key, value|
page_title = value["title"]
original_query = find_result_map_match_for_title(result_map, page_title)
@page_hash[original_query] = MediaWiki::Page.new(value)
end
@page_hash
end | ruby | def pages
result_map = map_query_to_results
query_result["query"]["pages"].each do |key, value|
page_title = value["title"]
original_query = find_result_map_match_for_title(result_map, page_title)
@page_hash[original_query] = MediaWiki::Page.new(value)
end
@page_hash
end | [
"def",
"pages",
"result_map",
"=",
"map_query_to_results",
"query_result",
"[",
"\"query\"",
"]",
"[",
"\"pages\"",
"]",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"page_title",
"=",
"value",
"[",
"\"title\"",
"]",
"original_query",
"=",
"find_result_ma... | Returns a hash filled with Pages | [
"Returns",
"a",
"hash",
"filled",
"with",
"Pages"
] | 849338f643543f3a432d209f0413346d513c1e81 | https://github.com/mkulumadzi/mediawiki-keiki/blob/849338f643543f3a432d209f0413346d513c1e81/lib/mediawiki-keiki/query.rb#L32-L45 | train |
mkulumadzi/mediawiki-keiki | lib/mediawiki-keiki/query.rb | MediaWiki.Query.map_query_to_results | def map_query_to_results
#Initalize map
result_map = initialize_map
# Apply the normalization to the result map
normalized = get_query_map("normalized")
if normalized
result_map = get_normalizations_for(result_map, normalized)
end
# Apply the redirects to the result map
redirects = get_qu... | ruby | def map_query_to_results
#Initalize map
result_map = initialize_map
# Apply the normalization to the result map
normalized = get_query_map("normalized")
if normalized
result_map = get_normalizations_for(result_map, normalized)
end
# Apply the redirects to the result map
redirects = get_qu... | [
"def",
"map_query_to_results",
"#Initalize map",
"result_map",
"=",
"initialize_map",
"# Apply the normalization to the result map",
"normalized",
"=",
"get_query_map",
"(",
"\"normalized\"",
")",
"if",
"normalized",
"result_map",
"=",
"get_normalizations_for",
"(",
"result_map... | Maps original query to results | [
"Maps",
"original",
"query",
"to",
"results"
] | 849338f643543f3a432d209f0413346d513c1e81 | https://github.com/mkulumadzi/mediawiki-keiki/blob/849338f643543f3a432d209f0413346d513c1e81/lib/mediawiki-keiki/query.rb#L70-L89 | train |
alexdean/where_was_i | lib/where_was_i/track.rb | WhereWasI.Track.add_point | def add_point(lat:, lon:, elevation:, time:)
time = Time.parse(time) if ! time.is_a?(Time)
current = [lat, lon, elevation]
if @start_time.nil? || time < @start_time
@start_time = time
@start_location = current
end
if @end_time.nil? || time > @end_time
@end_... | ruby | def add_point(lat:, lon:, elevation:, time:)
time = Time.parse(time) if ! time.is_a?(Time)
current = [lat, lon, elevation]
if @start_time.nil? || time < @start_time
@start_time = time
@start_location = current
end
if @end_time.nil? || time > @end_time
@end_... | [
"def",
"add_point",
"(",
"lat",
":",
",",
"lon",
":",
",",
"elevation",
":",
",",
"time",
":",
")",
"time",
"=",
"Time",
".",
"parse",
"(",
"time",
")",
"if",
"!",
"time",
".",
"is_a?",
"(",
"Time",
")",
"current",
"=",
"[",
"lat",
",",
"lon",
... | add a point to the track
@param [Float] lat latitude
@param [Float] lon longitude
@param [Float] elevation elevation
@param [Time] time time at the given location | [
"add",
"a",
"point",
"to",
"the",
"track"
] | 10d1381d6e0b1a85de65678a540d4dbc6041321d | https://github.com/alexdean/where_was_i/blob/10d1381d6e0b1a85de65678a540d4dbc6041321d/lib/where_was_i/track.rb#L34-L52 | train |
alexdean/where_was_i | lib/where_was_i/track.rb | WhereWasI.Track.in_time_range? | def in_time_range?(time)
time = Time.parse(time) if ! time.is_a?(Time)
time_range.cover?(time)
end | ruby | def in_time_range?(time)
time = Time.parse(time) if ! time.is_a?(Time)
time_range.cover?(time)
end | [
"def",
"in_time_range?",
"(",
"time",
")",
"time",
"=",
"Time",
".",
"parse",
"(",
"time",
")",
"if",
"!",
"time",
".",
"is_a?",
"(",
"Time",
")",
"time_range",
".",
"cover?",
"(",
"time",
")",
"end"
] | is the supplied time covered by this track?
@param time [Time]
@return Boolean | [
"is",
"the",
"supplied",
"time",
"covered",
"by",
"this",
"track?"
] | 10d1381d6e0b1a85de65678a540d4dbc6041321d | https://github.com/alexdean/where_was_i/blob/10d1381d6e0b1a85de65678a540d4dbc6041321d/lib/where_was_i/track.rb#L65-L68 | train |
alexdean/where_was_i | lib/where_was_i/track.rb | WhereWasI.Track.at | def at(time)
if time.is_a?(String)
time = Time.parse(time)
end
if time.is_a?(Integer)
time = Time.at(time)
end
raise ArgumentError, "time must be a Time,String, or Fixnum" if ! time.is_a?(Time)
return nil if ! in_time_range?(time)
@interp ||= Interpolate::Poin... | ruby | def at(time)
if time.is_a?(String)
time = Time.parse(time)
end
if time.is_a?(Integer)
time = Time.at(time)
end
raise ArgumentError, "time must be a Time,String, or Fixnum" if ! time.is_a?(Time)
return nil if ! in_time_range?(time)
@interp ||= Interpolate::Poin... | [
"def",
"at",
"(",
"time",
")",
"if",
"time",
".",
"is_a?",
"(",
"String",
")",
"time",
"=",
"Time",
".",
"parse",
"(",
"time",
")",
"end",
"if",
"time",
".",
"is_a?",
"(",
"Integer",
")",
"time",
"=",
"Time",
".",
"at",
"(",
"time",
")",
"end",... | return the interpolated location for the given time
or nil if time is outside the track's start..end
@example
track.at(time) => {lat:48, lon:98, elevation: 2100}
@param time [String,Time,Fixnum]
@return [Hash,nil] | [
"return",
"the",
"interpolated",
"location",
"for",
"the",
"given",
"time",
"or",
"nil",
"if",
"time",
"is",
"outside",
"the",
"track",
"s",
"start",
"..",
"end"
] | 10d1381d6e0b1a85de65678a540d4dbc6041321d | https://github.com/alexdean/where_was_i/blob/10d1381d6e0b1a85de65678a540d4dbc6041321d/lib/where_was_i/track.rb#L77-L92 | train |
rike422/loose-leaf | rakelib/task_helpers.rb | LooseLeaf.TaskHelpers.sh_in_dir | def sh_in_dir(dir, shell_commands)
shell_commands = [shell_commands] if shell_commands.is_a?(String)
shell_commands.each { |shell_command| sh %(cd #{dir} && #{shell_command.strip}) }
end | ruby | def sh_in_dir(dir, shell_commands)
shell_commands = [shell_commands] if shell_commands.is_a?(String)
shell_commands.each { |shell_command| sh %(cd #{dir} && #{shell_command.strip}) }
end | [
"def",
"sh_in_dir",
"(",
"dir",
",",
"shell_commands",
")",
"shell_commands",
"=",
"[",
"shell_commands",
"]",
"if",
"shell_commands",
".",
"is_a?",
"(",
"String",
")",
"shell_commands",
".",
"each",
"{",
"|",
"shell_command",
"|",
"sh",
"%(cd #{dir} && #{shell_... | Executes a string or an array of strings in a shell in the given directory | [
"Executes",
"a",
"string",
"or",
"an",
"array",
"of",
"strings",
"in",
"a",
"shell",
"in",
"the",
"given",
"directory"
] | ea3cb93667f83e5f4abb3c7879fc0220157aeb81 | https://github.com/rike422/loose-leaf/blob/ea3cb93667f83e5f4abb3c7879fc0220157aeb81/rakelib/task_helpers.rb#L22-L25 | train |
zdavatz/odba | lib/odba/cache.rb | ODBA.Cache.create_deferred_indices | def create_deferred_indices(drop_existing = false)
@deferred_indices.each { |definition|
name = definition.index_name
if(drop_existing && self.indices.include?(name))
drop_index(name)
end
unless(self.indices.include?(name))
index = create_index(definition)
... | ruby | def create_deferred_indices(drop_existing = false)
@deferred_indices.each { |definition|
name = definition.index_name
if(drop_existing && self.indices.include?(name))
drop_index(name)
end
unless(self.indices.include?(name))
index = create_index(definition)
... | [
"def",
"create_deferred_indices",
"(",
"drop_existing",
"=",
"false",
")",
"@deferred_indices",
".",
"each",
"{",
"|",
"definition",
"|",
"name",
"=",
"definition",
".",
"index_name",
"if",
"(",
"drop_existing",
"&&",
"self",
".",
"indices",
".",
"include?",
"... | Creates or recreates automatically defined indices | [
"Creates",
"or",
"recreates",
"automatically",
"defined",
"indices"
] | 40a4f3a07abdc6d41d627338848ca8cb1dd52294 | https://github.com/zdavatz/odba/blob/40a4f3a07abdc6d41d627338848ca8cb1dd52294/lib/odba/cache.rb#L130-L143 | train |
zdavatz/odba | lib/odba/cache.rb | ODBA.Cache.create_index | def create_index(index_definition, origin_module=Object)
transaction {
klass = if(index_definition.fulltext)
FulltextIndex
elsif(index_definition.resolve_search_term.is_a?(Hash))
ConditionIndex
else
Index
end
index = klass.new(index_definition, origin_module... | ruby | def create_index(index_definition, origin_module=Object)
transaction {
klass = if(index_definition.fulltext)
FulltextIndex
elsif(index_definition.resolve_search_term.is_a?(Hash))
ConditionIndex
else
Index
end
index = klass.new(index_definition, origin_module... | [
"def",
"create_index",
"(",
"index_definition",
",",
"origin_module",
"=",
"Object",
")",
"transaction",
"{",
"klass",
"=",
"if",
"(",
"index_definition",
".",
"fulltext",
")",
"FulltextIndex",
"elsif",
"(",
"index_definition",
".",
"resolve_search_term",
".",
"is... | Creates a new index according to IndexDefinition | [
"Creates",
"a",
"new",
"index",
"according",
"to",
"IndexDefinition"
] | 40a4f3a07abdc6d41d627338848ca8cb1dd52294 | https://github.com/zdavatz/odba/blob/40a4f3a07abdc6d41d627338848ca8cb1dd52294/lib/odba/cache.rb#L145-L159 | train |
zdavatz/odba | lib/odba/cache.rb | ODBA.Cache.delete | def delete(odba_object)
odba_id = odba_object.odba_id
name = odba_object.odba_name
odba_object.odba_notify_observers(:delete, odba_id, odba_object.object_id)
rows = ODBA.storage.retrieve_connected_objects(odba_id)
rows.each { |row|
id = row.first
# Self-Referencing objects don't have to be ... | ruby | def delete(odba_object)
odba_id = odba_object.odba_id
name = odba_object.odba_name
odba_object.odba_notify_observers(:delete, odba_id, odba_object.object_id)
rows = ODBA.storage.retrieve_connected_objects(odba_id)
rows.each { |row|
id = row.first
# Self-Referencing objects don't have to be ... | [
"def",
"delete",
"(",
"odba_object",
")",
"odba_id",
"=",
"odba_object",
".",
"odba_id",
"name",
"=",
"odba_object",
".",
"odba_name",
"odba_object",
".",
"odba_notify_observers",
"(",
":delete",
",",
"odba_id",
",",
"odba_object",
".",
"object_id",
")",
"rows",... | Permanently deletes _object_ from the database and deconnects all connected
Persistables | [
"Permanently",
"deletes",
"_object_",
"from",
"the",
"database",
"and",
"deconnects",
"all",
"connected",
"Persistables"
] | 40a4f3a07abdc6d41d627338848ca8cb1dd52294 | https://github.com/zdavatz/odba/blob/40a4f3a07abdc6d41d627338848ca8cb1dd52294/lib/odba/cache.rb#L162-L185 | train |
zdavatz/odba | lib/odba/cache.rb | ODBA.Cache.drop_index | def drop_index(index_name)
transaction {
ODBA.storage.drop_index(index_name)
self.delete(self.indices[index_name])
}
end | ruby | def drop_index(index_name)
transaction {
ODBA.storage.drop_index(index_name)
self.delete(self.indices[index_name])
}
end | [
"def",
"drop_index",
"(",
"index_name",
")",
"transaction",
"{",
"ODBA",
".",
"storage",
".",
"drop_index",
"(",
"index_name",
")",
"self",
".",
"delete",
"(",
"self",
".",
"indices",
"[",
"index_name",
"]",
")",
"}",
"end"
] | Permanently deletes the index named _index_name_ | [
"Permanently",
"deletes",
"the",
"index",
"named",
"_index_name_"
] | 40a4f3a07abdc6d41d627338848ca8cb1dd52294 | https://github.com/zdavatz/odba/blob/40a4f3a07abdc6d41d627338848ca8cb1dd52294/lib/odba/cache.rb#L199-L204 | train |
zdavatz/odba | lib/odba/cache.rb | ODBA.Cache.next_id | def next_id
if @file_lock
dbname = ODBA.storage.instance_variable_get('@dbi').dbi_args.first.split(/:/).last
id = new_id(dbname, ODBA.storage)
else
id = ODBA.storage.next_id
end
@peers.each do |peer|
peer.reserve_next_id id rescue DRb::DRbError
end
id
... | ruby | def next_id
if @file_lock
dbname = ODBA.storage.instance_variable_get('@dbi').dbi_args.first.split(/:/).last
id = new_id(dbname, ODBA.storage)
else
id = ODBA.storage.next_id
end
@peers.each do |peer|
peer.reserve_next_id id rescue DRb::DRbError
end
id
... | [
"def",
"next_id",
"if",
"@file_lock",
"dbname",
"=",
"ODBA",
".",
"storage",
".",
"instance_variable_get",
"(",
"'@dbi'",
")",
".",
"dbi_args",
".",
"first",
".",
"split",
"(",
"/",
"/",
")",
".",
"last",
"id",
"=",
"new_id",
"(",
"dbname",
",",
"ODBA"... | Returns the next valid odba_id | [
"Returns",
"the",
"next",
"valid",
"odba_id"
] | 40a4f3a07abdc6d41d627338848ca8cb1dd52294 | https://github.com/zdavatz/odba/blob/40a4f3a07abdc6d41d627338848ca8cb1dd52294/lib/odba/cache.rb#L401-L414 | train |
zdavatz/odba | lib/odba/cache.rb | ODBA.Cache.retrieve_from_index | def retrieve_from_index(index_name, search_term, meta=nil)
index = indices.fetch(index_name)
ids = index.fetch_ids(search_term, meta)
if meta.respond_to?(:error_limit) && (limit = meta.error_limit) \
&& (size = ids.size) > limit.to_i
error = OdbaResultLimitError.new
error.limit = lim... | ruby | def retrieve_from_index(index_name, search_term, meta=nil)
index = indices.fetch(index_name)
ids = index.fetch_ids(search_term, meta)
if meta.respond_to?(:error_limit) && (limit = meta.error_limit) \
&& (size = ids.size) > limit.to_i
error = OdbaResultLimitError.new
error.limit = lim... | [
"def",
"retrieve_from_index",
"(",
"index_name",
",",
"search_term",
",",
"meta",
"=",
"nil",
")",
"index",
"=",
"indices",
".",
"fetch",
"(",
"index_name",
")",
"ids",
"=",
"index",
".",
"fetch_ids",
"(",
"search_term",
",",
"meta",
")",
"if",
"meta",
"... | Find objects in an index | [
"Find",
"objects",
"in",
"an",
"index"
] | 40a4f3a07abdc6d41d627338848ca8cb1dd52294 | https://github.com/zdavatz/odba/blob/40a4f3a07abdc6d41d627338848ca8cb1dd52294/lib/odba/cache.rb#L457-L471 | train |
zdavatz/odba | lib/odba/cache.rb | ODBA.Cache.store | def store(object)
odba_id = object.odba_id
name = object.odba_name
object.odba_notify_observers(:store, odba_id, object.object_id)
if(ids = Thread.current[:txids])
ids.unshift([odba_id,name])
end
## get target_ids before anything else
target_ids = object.odba_target_ids
changes = st... | ruby | def store(object)
odba_id = object.odba_id
name = object.odba_name
object.odba_notify_observers(:store, odba_id, object.object_id)
if(ids = Thread.current[:txids])
ids.unshift([odba_id,name])
end
## get target_ids before anything else
target_ids = object.odba_target_ids
changes = st... | [
"def",
"store",
"(",
"object",
")",
"odba_id",
"=",
"object",
".",
"odba_id",
"name",
"=",
"object",
".",
"odba_name",
"object",
".",
"odba_notify_observers",
"(",
":store",
",",
"odba_id",
",",
"object",
".",
"object_id",
")",
"if",
"(",
"ids",
"=",
"Th... | Store a Persistable _object_ in the database | [
"Store",
"a",
"Persistable",
"_object_",
"in",
"the",
"database"
] | 40a4f3a07abdc6d41d627338848ca8cb1dd52294 | https://github.com/zdavatz/odba/blob/40a4f3a07abdc6d41d627338848ca8cb1dd52294/lib/odba/cache.rb#L500-L521 | train |
timotheeguerin/i18n_admin_utils | app/helpers/i18n_admin_utils/application_helper.rb | I18nAdminUtils.ApplicationHelper.translation_missing_icon | def translation_missing_icon(translation)
missing_translations = translation.missing_translations
color_id = (missing_translations.size.to_f/translation.translations.size.to_f*5).ceil-1
if missing_translations.size == 0
content_tag 'span', '', :class => 'glyphicon glyphicon-ok greentext',
... | ruby | def translation_missing_icon(translation)
missing_translations = translation.missing_translations
color_id = (missing_translations.size.to_f/translation.translations.size.to_f*5).ceil-1
if missing_translations.size == 0
content_tag 'span', '', :class => 'glyphicon glyphicon-ok greentext',
... | [
"def",
"translation_missing_icon",
"(",
"translation",
")",
"missing_translations",
"=",
"translation",
".",
"missing_translations",
"color_id",
"=",
"(",
"missing_translations",
".",
"size",
".",
"to_f",
"/",
"translation",
".",
"translations",
".",
"size",
".",
"t... | Show the number of translation missing with colorization | [
"Show",
"the",
"number",
"of",
"translation",
"missing",
"with",
"colorization"
] | c45c10e9707f3b876b8b37d120d77e46b25e1783 | https://github.com/timotheeguerin/i18n_admin_utils/blob/c45c10e9707f3b876b8b37d120d77e46b25e1783/app/helpers/i18n_admin_utils/application_helper.rb#L5-L15 | train |
cbrumelle/blueprintr | lib/blueprint-css/lib/blueprint/namespace.rb | Blueprint.Namespace.add_namespace | def add_namespace(html, namespace)
html.gsub!(/(class=")([a-zA-Z0-9\-_ ]*)(")/) do |m|
classes = m.to_s.split('"')[1].split(' ')
classes.map! { |c| c = namespace + c }
'class="' + classes.join(' ') + '"'
end
html
end | ruby | def add_namespace(html, namespace)
html.gsub!(/(class=")([a-zA-Z0-9\-_ ]*)(")/) do |m|
classes = m.to_s.split('"')[1].split(' ')
classes.map! { |c| c = namespace + c }
'class="' + classes.join(' ') + '"'
end
html
end | [
"def",
"add_namespace",
"(",
"html",
",",
"namespace",
")",
"html",
".",
"gsub!",
"(",
"/",
"\\-",
"/",
")",
"do",
"|",
"m",
"|",
"classes",
"=",
"m",
".",
"to_s",
".",
"split",
"(",
"'\"'",
")",
"[",
"1",
"]",
".",
"split",
"(",
"' '",
")",
... | Read html to string, remove namespace if any,
set the new namespace, and update the test file.
adds namespace to BP classes in a html file | [
"Read",
"html",
"to",
"string",
"remove",
"namespace",
"if",
"any",
"set",
"the",
"new",
"namespace",
"and",
"update",
"the",
"test",
"file",
".",
"adds",
"namespace",
"to",
"BP",
"classes",
"in",
"a",
"html",
"file"
] | b414436f614a8d97d77b47b588ddcf3f5e61b6bd | https://github.com/cbrumelle/blueprintr/blob/b414436f614a8d97d77b47b588ddcf3f5e61b6bd/lib/blueprint-css/lib/blueprint/namespace.rb#L14-L21 | train |
johnwunder/stix_schema_spy | lib/stix_schema_spy/models/simple_type.rb | StixSchemaSpy.SimpleType.enumeration_values | def enumeration_values
enumeration = @xml.xpath('./xs:restriction/xs:enumeration', {'xs' => 'http://www.w3.org/2001/XMLSchema'})
if enumeration.length > 0
return enumeration.map {|elem| [elem.attributes['value'].value, elem.xpath('./xs:annotation/xs:documentation', {'xs' => 'http://www.w3.org/2001/X... | ruby | def enumeration_values
enumeration = @xml.xpath('./xs:restriction/xs:enumeration', {'xs' => 'http://www.w3.org/2001/XMLSchema'})
if enumeration.length > 0
return enumeration.map {|elem| [elem.attributes['value'].value, elem.xpath('./xs:annotation/xs:documentation', {'xs' => 'http://www.w3.org/2001/X... | [
"def",
"enumeration_values",
"enumeration",
"=",
"@xml",
".",
"xpath",
"(",
"'./xs:restriction/xs:enumeration'",
",",
"{",
"'xs'",
"=>",
"'http://www.w3.org/2001/XMLSchema'",
"}",
")",
"if",
"enumeration",
".",
"length",
">",
"0",
"return",
"enumeration",
".",
"map"... | Returns the list of values for this enumeration | [
"Returns",
"the",
"list",
"of",
"values",
"for",
"this",
"enumeration"
] | 2d551c6854d749eb330340e69f73baee1c4b52d3 | https://github.com/johnwunder/stix_schema_spy/blob/2d551c6854d749eb330340e69f73baee1c4b52d3/lib/stix_schema_spy/models/simple_type.rb#L16-L23 | train |
ideonetwork/lato-blog | lib/lato_blog/interfaces/categories.rb | LatoBlog.Interface::Categories.blog__create_default_category | def blog__create_default_category
category_parent = LatoBlog::CategoryParent.find_by(meta_default: true)
return if category_parent
category_parent = LatoBlog::CategoryParent.new(meta_default: true)
throw 'Impossible to create default category parent' unless category_parent.save
languages... | ruby | def blog__create_default_category
category_parent = LatoBlog::CategoryParent.find_by(meta_default: true)
return if category_parent
category_parent = LatoBlog::CategoryParent.new(meta_default: true)
throw 'Impossible to create default category parent' unless category_parent.save
languages... | [
"def",
"blog__create_default_category",
"category_parent",
"=",
"LatoBlog",
"::",
"CategoryParent",
".",
"find_by",
"(",
"meta_default",
":",
"true",
")",
"return",
"if",
"category_parent",
"category_parent",
"=",
"LatoBlog",
"::",
"CategoryParent",
".",
"new",
"(",
... | This function create the default category if it not exists. | [
"This",
"function",
"create",
"the",
"default",
"category",
"if",
"it",
"not",
"exists",
"."
] | a0d92de299a0e285851743b9d4a902f611187cba | https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/categories.rb#L7-L25 | train |
ideonetwork/lato-blog | lib/lato_blog/interfaces/categories.rb | LatoBlog.Interface::Categories.blog__clean_category_parents | def blog__clean_category_parents
category_parents = LatoBlog::CategoryParent.all
category_parents.map { |cp| cp.destroy if cp.categories.empty? }
end | ruby | def blog__clean_category_parents
category_parents = LatoBlog::CategoryParent.all
category_parents.map { |cp| cp.destroy if cp.categories.empty? }
end | [
"def",
"blog__clean_category_parents",
"category_parents",
"=",
"LatoBlog",
"::",
"CategoryParent",
".",
"all",
"category_parents",
".",
"map",
"{",
"|",
"cp",
"|",
"cp",
".",
"destroy",
"if",
"cp",
".",
"categories",
".",
"empty?",
"}",
"end"
] | This function cleans all old category parents without any child. | [
"This",
"function",
"cleans",
"all",
"old",
"category",
"parents",
"without",
"any",
"child",
"."
] | a0d92de299a0e285851743b9d4a902f611187cba | https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/categories.rb#L28-L31 | train |
ideonetwork/lato-blog | lib/lato_blog/interfaces/categories.rb | LatoBlog.Interface::Categories.blog__get_categories | def blog__get_categories(
order: nil,
language: nil,
search: nil,
page: nil,
per_page: nil
)
categories = LatoBlog::Category.all
# apply filters
order = order && order == 'ASC' ? 'ASC' : 'DESC'
categories = _categories_filter_by_order(categories, order)
c... | ruby | def blog__get_categories(
order: nil,
language: nil,
search: nil,
page: nil,
per_page: nil
)
categories = LatoBlog::Category.all
# apply filters
order = order && order == 'ASC' ? 'ASC' : 'DESC'
categories = _categories_filter_by_order(categories, order)
c... | [
"def",
"blog__get_categories",
"(",
"order",
":",
"nil",
",",
"language",
":",
"nil",
",",
"search",
":",
"nil",
",",
"page",
":",
"nil",
",",
"per_page",
":",
"nil",
")",
"categories",
"=",
"LatoBlog",
"::",
"Category",
".",
"all",
"# apply filters",
"o... | This function returns an object with the list of categories with some filters. | [
"This",
"function",
"returns",
"an",
"object",
"with",
"the",
"list",
"of",
"categories",
"with",
"some",
"filters",
"."
] | a0d92de299a0e285851743b9d4a902f611187cba | https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/categories.rb#L34-L68 | train |
davidbarral/sugarfree-config | lib/sugarfree-config/config.rb | SugarfreeConfig.Config.fetch_config | def fetch_config
Rails.logger.debug "Loading #{@file}::#{@env}" if Object.const_defined?('Rails') && Rails.logger.present?
YAML::load_file(@file)[@env.to_s]
end | ruby | def fetch_config
Rails.logger.debug "Loading #{@file}::#{@env}" if Object.const_defined?('Rails') && Rails.logger.present?
YAML::load_file(@file)[@env.to_s]
end | [
"def",
"fetch_config",
"Rails",
".",
"logger",
".",
"debug",
"\"Loading #{@file}::#{@env}\"",
"if",
"Object",
".",
"const_defined?",
"(",
"'Rails'",
")",
"&&",
"Rails",
".",
"logger",
".",
"present?",
"YAML",
"::",
"load_file",
"(",
"@file",
")",
"[",
"@env",
... | Fetch the config from the file | [
"Fetch",
"the",
"config",
"from",
"the",
"file"
] | 76b590627d50cd50b237c21fdf8ea3022ebbdf42 | https://github.com/davidbarral/sugarfree-config/blob/76b590627d50cd50b237c21fdf8ea3022ebbdf42/lib/sugarfree-config/config.rb#L47-L50 | train |
davidbarral/sugarfree-config | lib/sugarfree-config/config.rb | SugarfreeConfig.Config.default_options | def default_options
if Object.const_defined?('Rails')
{
:file => Rails.root.join('config', 'config.yml'),
:reload => Rails.env.development?,
:env => Rails.env
}
else
{
:file => File.expand_path("config.yml"),
... | ruby | def default_options
if Object.const_defined?('Rails')
{
:file => Rails.root.join('config', 'config.yml'),
:reload => Rails.env.development?,
:env => Rails.env
}
else
{
:file => File.expand_path("config.yml"),
... | [
"def",
"default_options",
"if",
"Object",
".",
"const_defined?",
"(",
"'Rails'",
")",
"{",
":file",
"=>",
"Rails",
".",
"root",
".",
"join",
"(",
"'config'",
",",
"'config.yml'",
")",
",",
":reload",
"=>",
"Rails",
".",
"env",
".",
"development?",
",",
"... | Default configuration options for Rails and non Rails applications | [
"Default",
"configuration",
"options",
"for",
"Rails",
"and",
"non",
"Rails",
"applications"
] | 76b590627d50cd50b237c21fdf8ea3022ebbdf42 | https://github.com/davidbarral/sugarfree-config/blob/76b590627d50cd50b237c21fdf8ea3022ebbdf42/lib/sugarfree-config/config.rb#L55-L69 | train |
davidbarral/sugarfree-config | lib/sugarfree-config/config.rb | SugarfreeConfig.ConfigIterator.next | def next
if (value = @scoped_config[@path_elements.last]).nil?
raise ConfigKeyException.new(@path_elements)
elsif value.is_a?(Hash)
@scoped_config = value
self
else
value
end
end | ruby | def next
if (value = @scoped_config[@path_elements.last]).nil?
raise ConfigKeyException.new(@path_elements)
elsif value.is_a?(Hash)
@scoped_config = value
self
else
value
end
end | [
"def",
"next",
"if",
"(",
"value",
"=",
"@scoped_config",
"[",
"@path_elements",
".",
"last",
"]",
")",
".",
"nil?",
"raise",
"ConfigKeyException",
".",
"new",
"(",
"@path_elements",
")",
"elsif",
"value",
".",
"is_a?",
"(",
"Hash",
")",
"@scoped_config",
... | Iterate to the next element in the path
Algorithm:
1. Get the last element of the key path
2. Try to find it in the scoped config
3. If not present raise an error
4. If present and is a hash we are not in a config leaf, so the scoped
config is reset to this new value and self is returned
5. If present and is... | [
"Iterate",
"to",
"the",
"next",
"element",
"in",
"the",
"path"
] | 76b590627d50cd50b237c21fdf8ea3022ebbdf42 | https://github.com/davidbarral/sugarfree-config/blob/76b590627d50cd50b237c21fdf8ea3022ebbdf42/lib/sugarfree-config/config.rb#L117-L126 | train |
heelhook/class-proxy | lib/classproxy/classproxy.rb | ClassProxy.ClassMethods.proxy_methods | def proxy_methods(*methods)
@_methods ||= {}
methods.each do |method|
if method.is_a? Symbol
# If given a symbol, store as a method to overwrite and use the default loader
proxy_method method
elsif method.is_a? Hash
# If its a hash it will include methods to ov... | ruby | def proxy_methods(*methods)
@_methods ||= {}
methods.each do |method|
if method.is_a? Symbol
# If given a symbol, store as a method to overwrite and use the default loader
proxy_method method
elsif method.is_a? Hash
# If its a hash it will include methods to ov... | [
"def",
"proxy_methods",
"(",
"*",
"methods",
")",
"@_methods",
"||=",
"{",
"}",
"methods",
".",
"each",
"do",
"|",
"method",
"|",
"if",
"method",
".",
"is_a?",
"Symbol",
"# If given a symbol, store as a method to overwrite and use the default loader",
"proxy_method",
... | Establish attributes to proxy along with an alternative proc of how
the attribute should be loaded
@example Load method using uppercase
class GithubUser
include ClassProxy
fallback_fetch { |args| Octokit.user(args[:login]) }
after_fallback_fetch { |obj| self.name = obj.name; self.login = obj.login... | [
"Establish",
"attributes",
"to",
"proxy",
"along",
"with",
"an",
"alternative",
"proc",
"of",
"how",
"the",
"attribute",
"should",
"be",
"loaded"
] | df69405274133a359aa65e393205c61d47dd5362 | https://github.com/heelhook/class-proxy/blob/df69405274133a359aa65e393205c61d47dd5362/lib/classproxy/classproxy.rb#L63-L75 | train |
heelhook/class-proxy | lib/classproxy/classproxy.rb | ClassProxy.ClassMethods.fetch | def fetch(args, options={})
@primary_fetch.is_a?(Proc) ? @primary_fetch[args] : (raise NotFound)
rescue NotFound
return nil if options[:skip_fallback]
run_fallback(args)
end | ruby | def fetch(args, options={})
@primary_fetch.is_a?(Proc) ? @primary_fetch[args] : (raise NotFound)
rescue NotFound
return nil if options[:skip_fallback]
run_fallback(args)
end | [
"def",
"fetch",
"(",
"args",
",",
"options",
"=",
"{",
"}",
")",
"@primary_fetch",
".",
"is_a?",
"(",
"Proc",
")",
"?",
"@primary_fetch",
"[",
"args",
"]",
":",
"(",
"raise",
"NotFound",
")",
"rescue",
"NotFound",
"return",
"nil",
"if",
"options",
"[",... | Method to find a record using a hash as the criteria
@example
class GithubUser
include MongoMapper::Document
include ClassProxy
primary_fetch { |args| where(args).first or (raise NotFound) }
fallback_fetch { |args| Octokit.user(args[:login]) }
end
GithubUser.fetch(login: 'heelhook') # ... | [
"Method",
"to",
"find",
"a",
"record",
"using",
"a",
"hash",
"as",
"the",
"criteria"
] | df69405274133a359aa65e393205c61d47dd5362 | https://github.com/heelhook/class-proxy/blob/df69405274133a359aa65e393205c61d47dd5362/lib/classproxy/classproxy.rb#L93-L99 | train |
dominikh/weechat-ruby | lib/weechat/plugin.rb | Weechat.Plugin.unload | def unload(force = false)
if name == "ruby" and !force
Weechat.puts "Won't unload the ruby plugin unless you force it."
false
else
Weechat.exec("/plugin unload #{name}")
true
end
end | ruby | def unload(force = false)
if name == "ruby" and !force
Weechat.puts "Won't unload the ruby plugin unless you force it."
false
else
Weechat.exec("/plugin unload #{name}")
true
end
end | [
"def",
"unload",
"(",
"force",
"=",
"false",
")",
"if",
"name",
"==",
"\"ruby\"",
"and",
"!",
"force",
"Weechat",
".",
"puts",
"\"Won't unload the ruby plugin unless you force it.\"",
"false",
"else",
"Weechat",
".",
"exec",
"(",
"\"/plugin unload #{name}\"",
")",
... | Unloads the plugin.
@param [Boolean] force If the plugin to be unloaded is "ruby",
+force+ has to be true.
@return [Boolean] true if we attempted to unload the plugin | [
"Unloads",
"the",
"plugin",
"."
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat/plugin.rb#L70-L78 | train |
dominikh/weechat-ruby | lib/weechat/plugin.rb | Weechat.Plugin.scripts | def scripts
scripts = []
Infolist.parse("#{name}_script").each do |script|
scripts << Script.new(script[:pointer], self)
end
scripts
end | ruby | def scripts
scripts = []
Infolist.parse("#{name}_script").each do |script|
scripts << Script.new(script[:pointer], self)
end
scripts
end | [
"def",
"scripts",
"scripts",
"=",
"[",
"]",
"Infolist",
".",
"parse",
"(",
"\"#{name}_script\"",
")",
".",
"each",
"do",
"|",
"script",
"|",
"scripts",
"<<",
"Script",
".",
"new",
"(",
"script",
"[",
":pointer",
"]",
",",
"self",
")",
"end",
"scripts",... | Returns an array of all scripts loaded by this plugin.
@return [Array<Script>] | [
"Returns",
"an",
"array",
"of",
"all",
"scripts",
"loaded",
"by",
"this",
"plugin",
"."
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat/plugin.rb#L95-L101 | train |
whyarkadas/http_ping | lib/HttpPing/wmi.rb | HttpPing.HttpPing::WMI.ping | def ping(host = @host, options = {})
super(host)
lhost = Socket.gethostname
cs = "winmgmts:{impersonationLevel=impersonate}!//#{lhost}/root/cimv2"
wmi = WIN32OLE.connect(cs)
query = "select * from win32_pingstatus where address = '#{host}'"
unless options.empty?
options.e... | ruby | def ping(host = @host, options = {})
super(host)
lhost = Socket.gethostname
cs = "winmgmts:{impersonationLevel=impersonate}!//#{lhost}/root/cimv2"
wmi = WIN32OLE.connect(cs)
query = "select * from win32_pingstatus where address = '#{host}'"
unless options.empty?
options.e... | [
"def",
"ping",
"(",
"host",
"=",
"@host",
",",
"options",
"=",
"{",
"}",
")",
"super",
"(",
"host",
")",
"lhost",
"=",
"Socket",
".",
"gethostname",
"cs",
"=",
"\"winmgmts:{impersonationLevel=impersonate}!//#{lhost}/root/cimv2\"",
"wmi",
"=",
"WIN32OLE",
".",
... | Unlike the ping method for other Ping subclasses, this version returns
a PingStatus struct which contains various bits of information about
the results of the ping itself, such as response time.
In addition, this version allows you to pass certain options that are
then passed on to the underlying WQL query. See th... | [
"Unlike",
"the",
"ping",
"method",
"for",
"other",
"Ping",
"subclasses",
"this",
"version",
"returns",
"a",
"PingStatus",
"struct",
"which",
"contains",
"various",
"bits",
"of",
"information",
"about",
"the",
"results",
"of",
"the",
"ping",
"itself",
"such",
"... | 0a30dc5e10c56494d10ab270c64d76e085770bf8 | https://github.com/whyarkadas/http_ping/blob/0a30dc5e10c56494d10ab270c64d76e085770bf8/lib/HttpPing/wmi.rb#L60-L110 | train |
caruby/core | lib/caruby/database/sql_executor.rb | CaRuby.SQLExecutor.query | def query(sql, *args, &block)
fetched = nil
execute do |dbh|
result = dbh.execute(sql, *args)
if block_given? then
result.each(&block)
else
fetched = result.fetch(:all)
end
result.finish
end
fetched
end | ruby | def query(sql, *args, &block)
fetched = nil
execute do |dbh|
result = dbh.execute(sql, *args)
if block_given? then
result.each(&block)
else
fetched = result.fetch(:all)
end
result.finish
end
fetched
end | [
"def",
"query",
"(",
"sql",
",",
"*",
"args",
",",
"&",
"block",
")",
"fetched",
"=",
"nil",
"execute",
"do",
"|",
"dbh",
"|",
"result",
"=",
"dbh",
".",
"execute",
"(",
"sql",
",",
"args",
")",
"if",
"block_given?",
"then",
"result",
".",
"each",
... | Runs the given query.
@param [String] sql the SQL to execute
@param [Array] args the SQL bindings
@yield [row] operate on the result
@yield [Array] the result row
@return [Array] the query result | [
"Runs",
"the",
"given",
"query",
"."
] | a682dc57c6fa31aef765cdd206ed3d4b4c289c60 | https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/sql_executor.rb#L100-L112 | train |
caruby/core | lib/caruby/database/sql_executor.rb | CaRuby.SQLExecutor.transact | def transact(sql=nil, *args)
# Work-around for rcbi nil substitution.
if sql then
sql, *args = replace_nil_binds(sql, args)
transact { |dbh| dbh.execute(sql, *args) }
elsif block_given? then
execute { |dbh| dbh.transaction { yield dbh } }
else
raise ArgumentError.... | ruby | def transact(sql=nil, *args)
# Work-around for rcbi nil substitution.
if sql then
sql, *args = replace_nil_binds(sql, args)
transact { |dbh| dbh.execute(sql, *args) }
elsif block_given? then
execute { |dbh| dbh.transaction { yield dbh } }
else
raise ArgumentError.... | [
"def",
"transact",
"(",
"sql",
"=",
"nil",
",",
"*",
"args",
")",
"# Work-around for rcbi nil substitution.",
"if",
"sql",
"then",
"sql",
",",
"*",
"args",
"=",
"replace_nil_binds",
"(",
"sql",
",",
"args",
")",
"transact",
"{",
"|",
"dbh",
"|",
"dbh",
"... | Runs the given SQL or block in a transaction. If SQL is provided, then that
SQL is executed. Otherwise, the block is called.
@quirk RDBI RDBI converts nil args to 12. Work-around this bug by embedding
+NULL+ in the SQL instead.
@param [String] sql the SQL to execute
@param [Array] args the SQL bindings
@yield... | [
"Runs",
"the",
"given",
"SQL",
"or",
"block",
"in",
"a",
"transaction",
".",
"If",
"SQL",
"is",
"provided",
"then",
"that",
"SQL",
"is",
"executed",
".",
"Otherwise",
"the",
"block",
"is",
"called",
"."
] | a682dc57c6fa31aef765cdd206ed3d4b4c289c60 | https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/sql_executor.rb#L124-L134 | train |
Subsets and Splits
SQL Console for semeru/code-text-ruby
Retrieves 20,000 non-null code samples labeled as Ruby, providing a basic overview of the dataset but without deeper analysis.