repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
healthfinch/allscripts-unity-client | lib/allscripts_unity_client/client.rb | AllscriptsUnityClient.Client.get_task_list | def get_task_list(userid = nil, since = nil, delegated = nil, task_types = nil, task_statuses = nil)
magic_parameters = {
action: 'GetTaskList',
userid: userid,
parameter1: since,
parameter2: task_types,
parameter3: task_statuses,
parameter4: delegated
}
response = magic(magic_parameters)
unless response.is_a?(Array)
response = [ response ]
end
response
end | ruby | def get_task_list(userid = nil, since = nil, delegated = nil, task_types = nil, task_statuses = nil)
magic_parameters = {
action: 'GetTaskList',
userid: userid,
parameter1: since,
parameter2: task_types,
parameter3: task_statuses,
parameter4: delegated
}
response = magic(magic_parameters)
unless response.is_a?(Array)
response = [ response ]
end
response
end | [
"def",
"get_task_list",
"(",
"userid",
"=",
"nil",
",",
"since",
"=",
"nil",
",",
"delegated",
"=",
"nil",
",",
"task_types",
"=",
"nil",
",",
"task_statuses",
"=",
"nil",
")",
"magic_parameters",
"=",
"{",
"action",
":",
"'GetTaskList'",
",",
"userid",
":",
"userid",
",",
"parameter1",
":",
"since",
",",
"parameter2",
":",
"task_types",
",",
"parameter3",
":",
"task_statuses",
",",
"parameter4",
":",
"delegated",
"}",
"response",
"=",
"magic",
"(",
"magic_parameters",
")",
"unless",
"response",
".",
"is_a?",
"(",
"Array",
")",
"response",
"=",
"[",
"response",
"]",
"end",
"response",
"end"
] | delegated is an undocumented parameter | [
"delegated",
"is",
"an",
"undocumented",
"parameter"
] | fd9b7148cb6fe806a3f9dba70c138ba8c5e75985 | https://github.com/healthfinch/allscripts-unity-client/blob/fd9b7148cb6fe806a3f9dba70c138ba8c5e75985/lib/allscripts_unity_client/client.rb#L536-L552 | train |
pcorliss/ruby_route_53 | lib/route53/zone.rb | Route53.Zone.perform_actions | def perform_actions(change_list,comment=nil)
xml_str = gen_change_xml(change_list,comment)
@conn.request(@conn.base_url + @host_url+"/rrset","POST",xml_str)
end | ruby | def perform_actions(change_list,comment=nil)
xml_str = gen_change_xml(change_list,comment)
@conn.request(@conn.base_url + @host_url+"/rrset","POST",xml_str)
end | [
"def",
"perform_actions",
"(",
"change_list",
",",
"comment",
"=",
"nil",
")",
"xml_str",
"=",
"gen_change_xml",
"(",
"change_list",
",",
"comment",
")",
"@conn",
".",
"request",
"(",
"@conn",
".",
"base_url",
"+",
"@host_url",
"+",
"\"/rrset\"",
",",
"\"POST\"",
",",
"xml_str",
")",
"end"
] | For modifying multiple or single records within a single transaction | [
"For",
"modifying",
"multiple",
"or",
"single",
"records",
"within",
"a",
"single",
"transaction"
] | f96fab52931f069ba4b5fddb291aa53c7412aa52 | https://github.com/pcorliss/ruby_route_53/blob/f96fab52931f069ba4b5fddb291aa53c7412aa52/lib/route53/zone.rb#L124-L127 | train |
pcorliss/ruby_route_53 | lib/route53/cli.rb | Route53.CLI.process_options | def process_options
@options.verbose = false if @options.quiet
@options.file = (user_home+"/.route53") if @options.file.nil?
#setup file
if @options.setup
setup
end
load_config
@config['access_key'] = @options.access unless @options.access.nil?
@config['secret_key'] = @options.secret unless @options.secret.nil?
required_options("",["--access-key"]) if @config['access_key'].nil? || @config['access_key'] == ""
required_options("",["--secret_key"]) if @config['secret_key'].nil? || @config['secret_key'] == ""
end | ruby | def process_options
@options.verbose = false if @options.quiet
@options.file = (user_home+"/.route53") if @options.file.nil?
#setup file
if @options.setup
setup
end
load_config
@config['access_key'] = @options.access unless @options.access.nil?
@config['secret_key'] = @options.secret unless @options.secret.nil?
required_options("",["--access-key"]) if @config['access_key'].nil? || @config['access_key'] == ""
required_options("",["--secret_key"]) if @config['secret_key'].nil? || @config['secret_key'] == ""
end | [
"def",
"process_options",
"@options",
".",
"verbose",
"=",
"false",
"if",
"@options",
".",
"quiet",
"@options",
".",
"file",
"=",
"(",
"user_home",
"+",
"\"/.route53\"",
")",
"if",
"@options",
".",
"file",
".",
"nil?",
"if",
"@options",
".",
"setup",
"setup",
"end",
"load_config",
"@config",
"[",
"'access_key'",
"]",
"=",
"@options",
".",
"access",
"unless",
"@options",
".",
"access",
".",
"nil?",
"@config",
"[",
"'secret_key'",
"]",
"=",
"@options",
".",
"secret",
"unless",
"@options",
".",
"secret",
".",
"nil?",
"required_options",
"(",
"\"\"",
",",
"[",
"\"--access-key\"",
"]",
")",
"if",
"@config",
"[",
"'access_key'",
"]",
".",
"nil?",
"||",
"@config",
"[",
"'access_key'",
"]",
"==",
"\"\"",
"required_options",
"(",
"\"\"",
",",
"[",
"\"--secret_key\"",
"]",
")",
"if",
"@config",
"[",
"'secret_key'",
"]",
".",
"nil?",
"||",
"@config",
"[",
"'secret_key'",
"]",
"==",
"\"\"",
"end"
] | Performs post-parse processing on options | [
"Performs",
"post",
"-",
"parse",
"processing",
"on",
"options"
] | f96fab52931f069ba4b5fddb291aa53c7412aa52 | https://github.com/pcorliss/ruby_route_53/blob/f96fab52931f069ba4b5fddb291aa53c7412aa52/lib/route53/cli.rb#L92-L107 | train |
pcorliss/ruby_route_53 | lib/route53/cli.rb | Route53.CLI.process_arguments | def process_arguments
if @options.new_zone
new_zone
elsif @options.delete_zone
delete_zone
elsif @options.create_record
create_record
elsif @options.remove_record
remove_record
elsif @options.change_record
change_record
else
list
end
end | ruby | def process_arguments
if @options.new_zone
new_zone
elsif @options.delete_zone
delete_zone
elsif @options.create_record
create_record
elsif @options.remove_record
remove_record
elsif @options.change_record
change_record
else
list
end
end | [
"def",
"process_arguments",
"if",
"@options",
".",
"new_zone",
"new_zone",
"elsif",
"@options",
".",
"delete_zone",
"delete_zone",
"elsif",
"@options",
".",
"create_record",
"create_record",
"elsif",
"@options",
".",
"remove_record",
"remove_record",
"elsif",
"@options",
".",
"change_record",
"change_record",
"else",
"list",
"end",
"end"
] | Setup the arguments | [
"Setup",
"the",
"arguments"
] | f96fab52931f069ba4b5fddb291aa53c7412aa52 | https://github.com/pcorliss/ruby_route_53/blob/f96fab52931f069ba4b5fddb291aa53c7412aa52/lib/route53/cli.rb#L128-L142 | train |
mongoid/mongoid-cached-json | lib/mongoid-cached-json/cached_json.rb | Mongoid.CachedJson.as_json_partial | def as_json_partial(options = {})
options ||= {}
if options[:properties] && !all_json_properties.member?(options[:properties])
fail ArgumentError.new("Unknown properties option: #{options[:properties]}")
end
# partial, unmaterialized JSON
keys, partial_json = self.class.materialize_json({
properties: :short, is_top_level_json: true, version: Mongoid::CachedJson.config.default_version
}.merge(options), object: self)
[keys, partial_json]
end | ruby | def as_json_partial(options = {})
options ||= {}
if options[:properties] && !all_json_properties.member?(options[:properties])
fail ArgumentError.new("Unknown properties option: #{options[:properties]}")
end
# partial, unmaterialized JSON
keys, partial_json = self.class.materialize_json({
properties: :short, is_top_level_json: true, version: Mongoid::CachedJson.config.default_version
}.merge(options), object: self)
[keys, partial_json]
end | [
"def",
"as_json_partial",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"||=",
"{",
"}",
"if",
"options",
"[",
":properties",
"]",
"&&",
"!",
"all_json_properties",
".",
"member?",
"(",
"options",
"[",
":properties",
"]",
")",
"fail",
"ArgumentError",
".",
"new",
"(",
"\"Unknown properties option: #{options[:properties]}\"",
")",
"end",
"keys",
",",
"partial_json",
"=",
"self",
".",
"class",
".",
"materialize_json",
"(",
"{",
"properties",
":",
":short",
",",
"is_top_level_json",
":",
"true",
",",
"version",
":",
"Mongoid",
"::",
"CachedJson",
".",
"config",
".",
"default_version",
"}",
".",
"merge",
"(",
"options",
")",
",",
"object",
":",
"self",
")",
"[",
"keys",
",",
"partial_json",
"]",
"end"
] | Return a partial JSON without resolved references and all the keys. | [
"Return",
"a",
"partial",
"JSON",
"without",
"resolved",
"references",
"and",
"all",
"the",
"keys",
"."
] | d430e313d4259b13c4d75ed1782caad1609b5250 | https://github.com/mongoid/mongoid-cached-json/blob/d430e313d4259b13c4d75ed1782caad1609b5250/lib/mongoid-cached-json/cached_json.rb#L200-L210 | train |
mongoid/mongoid-cached-json | lib/mongoid-cached-json/cached_json.rb | Mongoid.CachedJson.as_json_cached | def as_json_cached(options = {})
keys, json = as_json_partial(options)
Mongoid::CachedJson.materialize_json_references_with_read_multi(keys, json)
end | ruby | def as_json_cached(options = {})
keys, json = as_json_partial(options)
Mongoid::CachedJson.materialize_json_references_with_read_multi(keys, json)
end | [
"def",
"as_json_cached",
"(",
"options",
"=",
"{",
"}",
")",
"keys",
",",
"json",
"=",
"as_json_partial",
"(",
"options",
")",
"Mongoid",
"::",
"CachedJson",
".",
"materialize_json_references_with_read_multi",
"(",
"keys",
",",
"json",
")",
"end"
] | Fetch the partial JSON and materialize all JSON references. | [
"Fetch",
"the",
"partial",
"JSON",
"and",
"materialize",
"all",
"JSON",
"references",
"."
] | d430e313d4259b13c4d75ed1782caad1609b5250 | https://github.com/mongoid/mongoid-cached-json/blob/d430e313d4259b13c4d75ed1782caad1609b5250/lib/mongoid-cached-json/cached_json.rb#L213-L216 | train |
mongoid/mongoid-cached-json | lib/mongoid-cached-json/cached_json.rb | Mongoid.CachedJson.expire_cached_json | def expire_cached_json
all_json_properties.each do |properties|
[true, false].each do |is_top_level_json|
all_json_versions.each do |version|
Mongoid::CachedJson.config.cache.delete(self.class.cached_json_key({
properties: properties,
is_top_level_json: is_top_level_json,
version: version
}, self.class, id))
end
end
end
end | ruby | def expire_cached_json
all_json_properties.each do |properties|
[true, false].each do |is_top_level_json|
all_json_versions.each do |version|
Mongoid::CachedJson.config.cache.delete(self.class.cached_json_key({
properties: properties,
is_top_level_json: is_top_level_json,
version: version
}, self.class, id))
end
end
end
end | [
"def",
"expire_cached_json",
"all_json_properties",
".",
"each",
"do",
"|",
"properties",
"|",
"[",
"true",
",",
"false",
"]",
".",
"each",
"do",
"|",
"is_top_level_json",
"|",
"all_json_versions",
".",
"each",
"do",
"|",
"version",
"|",
"Mongoid",
"::",
"CachedJson",
".",
"config",
".",
"cache",
".",
"delete",
"(",
"self",
".",
"class",
".",
"cached_json_key",
"(",
"{",
"properties",
":",
"properties",
",",
"is_top_level_json",
":",
"is_top_level_json",
",",
"version",
":",
"version",
"}",
",",
"self",
".",
"class",
",",
"id",
")",
")",
"end",
"end",
"end",
"end"
] | Expire all JSON entries for this class. | [
"Expire",
"all",
"JSON",
"entries",
"for",
"this",
"class",
"."
] | d430e313d4259b13c4d75ed1782caad1609b5250 | https://github.com/mongoid/mongoid-cached-json/blob/d430e313d4259b13c4d75ed1782caad1609b5250/lib/mongoid-cached-json/cached_json.rb#L224-L236 | train |
danieldreier/autosign | lib/autosign/journal.rb | Autosign.Journal.setup | def setup
@log.debug "using journalfile: " + self.settings['journalfile']
journalfile = self.settings['journalfile']
store = YAML::Store.new(journalfile, true)
store.ultra_safe = true
return store
end | ruby | def setup
@log.debug "using journalfile: " + self.settings['journalfile']
journalfile = self.settings['journalfile']
store = YAML::Store.new(journalfile, true)
store.ultra_safe = true
return store
end | [
"def",
"setup",
"@log",
".",
"debug",
"\"using journalfile: \"",
"+",
"self",
".",
"settings",
"[",
"'journalfile'",
"]",
"journalfile",
"=",
"self",
".",
"settings",
"[",
"'journalfile'",
"]",
"store",
"=",
"YAML",
"::",
"Store",
".",
"new",
"(",
"journalfile",
",",
"true",
")",
"store",
".",
"ultra_safe",
"=",
"true",
"return",
"store",
"end"
] | Create a new journal file, or load an existing one if it already exists.
@return [YAML::Store] instance of YAML::Store using the configured journal file. | [
"Create",
"a",
"new",
"journal",
"file",
"or",
"load",
"an",
"existing",
"one",
"if",
"it",
"already",
"exists",
"."
] | d457eeec5b2084ff63ee4555f7de97cf87be1aca | https://github.com/danieldreier/autosign/blob/d457eeec5b2084ff63ee4555f7de97cf87be1aca/lib/autosign/journal.rb#L65-L71 | train |
danieldreier/autosign | lib/autosign/journal.rb | Autosign.Journal.validate_uuid | def validate_uuid(uuid)
unless uuid.is_a?(String)
@log.error "UUID is not a string"
return false
end
unless !!/^\S{8}-\S{4}-4\S{3}-[89abAB]\S{3}-\S{12}$/.match(uuid.to_s)
@log.error "UUID is not a valid V4 UUID"
return false
end
return true
end | ruby | def validate_uuid(uuid)
unless uuid.is_a?(String)
@log.error "UUID is not a string"
return false
end
unless !!/^\S{8}-\S{4}-4\S{3}-[89abAB]\S{3}-\S{12}$/.match(uuid.to_s)
@log.error "UUID is not a valid V4 UUID"
return false
end
return true
end | [
"def",
"validate_uuid",
"(",
"uuid",
")",
"unless",
"uuid",
".",
"is_a?",
"(",
"String",
")",
"@log",
".",
"error",
"\"UUID is not a string\"",
"return",
"false",
"end",
"unless",
"!",
"!",
"/",
"\\S",
"\\S",
"\\S",
"\\S",
"\\S",
"/",
".",
"match",
"(",
"uuid",
".",
"to_s",
")",
"@log",
".",
"error",
"\"UUID is not a valid V4 UUID\"",
"return",
"false",
"end",
"return",
"true",
"end"
] | Verify that a string is a V4 UUID
@param uuid [String] RFC4122 v4 UUID
@return [Boolean] true if the uuid string is a valid UUID, false if not a valid UUID | [
"Verify",
"that",
"a",
"string",
"is",
"a",
"V4",
"UUID"
] | d457eeec5b2084ff63ee4555f7de97cf87be1aca | https://github.com/danieldreier/autosign/blob/d457eeec5b2084ff63ee4555f7de97cf87be1aca/lib/autosign/journal.rb#L77-L88 | train |
koraktor/metior | lib/metior/collections/commit_collection.rb | Metior.CommitCollection.<< | def <<(commit)
return self if key? commit.id
if @additions.nil? && empty? && commit.line_stats?
@additions = commit.additions
@deletions = commit.deletions
elsif [email protected]?
@additions += commit.additions
@deletions += commit.deletions
end
super
end | ruby | def <<(commit)
return self if key? commit.id
if @additions.nil? && empty? && commit.line_stats?
@additions = commit.additions
@deletions = commit.deletions
elsif [email protected]?
@additions += commit.additions
@deletions += commit.deletions
end
super
end | [
"def",
"<<",
"(",
"commit",
")",
"return",
"self",
"if",
"key?",
"commit",
".",
"id",
"if",
"@additions",
".",
"nil?",
"&&",
"empty?",
"&&",
"commit",
".",
"line_stats?",
"@additions",
"=",
"commit",
".",
"additions",
"@deletions",
"=",
"commit",
".",
"deletions",
"elsif",
"!",
"@additions",
".",
"nil?",
"@additions",
"+=",
"commit",
".",
"additions",
"@deletions",
"+=",
"commit",
".",
"deletions",
"end",
"super",
"end"
] | Creates a new collection with the given commits
@param [Array<Commit>] commits The commits that should be initially
inserted into the collection
Adds a commit to this collection
@param [Commit] commit The commit to add to this collection
@return [CommitCollection] The collection itself | [
"Creates",
"a",
"new",
"collection",
"with",
"the",
"given",
"commits"
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L47-L59 | train |
koraktor/metior | lib/metior/collections/commit_collection.rb | Metior.CommitCollection.activity | def activity
activity = {}
return activity if empty?
commit_count = values.size
active_days = {}
each do |commit|
date = commit.committed_date.utc
day = Time.utc(date.year, date.month, date.day).send :to_date
if active_days.key? day
active_days[day] += 1
else
active_days[day] = 1
end
end
most_active_day = active_days.sort_by { |day, count| count }.last.first
activity[:first_commit_date] = last.committed_date
activity[:last_commit_date] = first.committed_date
age_in_days = (Time.now - activity[:first_commit_date]) / 86400.0
activity[:active_days] = active_days
activity[:most_active_day] = most_active_day
activity[:commits_per_day] = commit_count / age_in_days
activity[:commits_per_active_day] = commit_count.to_f / active_days.size
activity
end | ruby | def activity
activity = {}
return activity if empty?
commit_count = values.size
active_days = {}
each do |commit|
date = commit.committed_date.utc
day = Time.utc(date.year, date.month, date.day).send :to_date
if active_days.key? day
active_days[day] += 1
else
active_days[day] = 1
end
end
most_active_day = active_days.sort_by { |day, count| count }.last.first
activity[:first_commit_date] = last.committed_date
activity[:last_commit_date] = first.committed_date
age_in_days = (Time.now - activity[:first_commit_date]) / 86400.0
activity[:active_days] = active_days
activity[:most_active_day] = most_active_day
activity[:commits_per_day] = commit_count / age_in_days
activity[:commits_per_active_day] = commit_count.to_f / active_days.size
activity
end | [
"def",
"activity",
"activity",
"=",
"{",
"}",
"return",
"activity",
"if",
"empty?",
"commit_count",
"=",
"values",
".",
"size",
"active_days",
"=",
"{",
"}",
"each",
"do",
"|",
"commit",
"|",
"date",
"=",
"commit",
".",
"committed_date",
".",
"utc",
"day",
"=",
"Time",
".",
"utc",
"(",
"date",
".",
"year",
",",
"date",
".",
"month",
",",
"date",
".",
"day",
")",
".",
"send",
":to_date",
"if",
"active_days",
".",
"key?",
"day",
"active_days",
"[",
"day",
"]",
"+=",
"1",
"else",
"active_days",
"[",
"day",
"]",
"=",
"1",
"end",
"end",
"most_active_day",
"=",
"active_days",
".",
"sort_by",
"{",
"|",
"day",
",",
"count",
"|",
"count",
"}",
".",
"last",
".",
"first",
"activity",
"[",
":first_commit_date",
"]",
"=",
"last",
".",
"committed_date",
"activity",
"[",
":last_commit_date",
"]",
"=",
"first",
".",
"committed_date",
"age_in_days",
"=",
"(",
"Time",
".",
"now",
"-",
"activity",
"[",
":first_commit_date",
"]",
")",
"/",
"86400.0",
"activity",
"[",
":active_days",
"]",
"=",
"active_days",
"activity",
"[",
":most_active_day",
"]",
"=",
"most_active_day",
"activity",
"[",
":commits_per_day",
"]",
"=",
"commit_count",
"/",
"age_in_days",
"activity",
"[",
":commits_per_active_day",
"]",
"=",
"commit_count",
".",
"to_f",
"/",
"active_days",
".",
"size",
"activity",
"end"
] | Calculate some predefined activity statistics for the commits in this
collection
@return [Hash<Symbol, Object>] The calculated statistics for the commits
in this collection
@see Commit#committed_date | [
"Calculate",
"some",
"predefined",
"activity",
"statistics",
"for",
"the",
"commits",
"in",
"this",
"collection"
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L67-L97 | train |
koraktor/metior | lib/metior/collections/commit_collection.rb | Metior.CommitCollection.authors | def authors(commit_id = nil)
authors = ActorCollection.new
if commit_id.nil?
each { |commit| authors << commit.author }
elsif key? commit_id
authors << self[commit_id].author
end
authors
end | ruby | def authors(commit_id = nil)
authors = ActorCollection.new
if commit_id.nil?
each { |commit| authors << commit.author }
elsif key? commit_id
authors << self[commit_id].author
end
authors
end | [
"def",
"authors",
"(",
"commit_id",
"=",
"nil",
")",
"authors",
"=",
"ActorCollection",
".",
"new",
"if",
"commit_id",
".",
"nil?",
"each",
"{",
"|",
"commit",
"|",
"authors",
"<<",
"commit",
".",
"author",
"}",
"elsif",
"key?",
"commit_id",
"authors",
"<<",
"self",
"[",
"commit_id",
"]",
".",
"author",
"end",
"authors",
"end"
] | Returns the authors of all or a specific commit in this collection
@param [Object] commit_id The ID of the commit, if only the author of a
specific commit should be returned
@return [ActorCollection] All authors of the commits in this collection
or the author of a specific commit
@see Commit#author | [
"Returns",
"the",
"authors",
"of",
"all",
"or",
"a",
"specific",
"commit",
"in",
"this",
"collection"
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L139-L147 | train |
koraktor/metior | lib/metior/collections/commit_collection.rb | Metior.CommitCollection.before | def before(date)
date = Time.parse date if date.is_a? String
commits = CommitCollection.new
each do |commit|
commits << commit if commit.committed_date < date
end
commits
end | ruby | def before(date)
date = Time.parse date if date.is_a? String
commits = CommitCollection.new
each do |commit|
commits << commit if commit.committed_date < date
end
commits
end | [
"def",
"before",
"(",
"date",
")",
"date",
"=",
"Time",
".",
"parse",
"date",
"if",
"date",
".",
"is_a?",
"String",
"commits",
"=",
"CommitCollection",
".",
"new",
"each",
"do",
"|",
"commit",
"|",
"commits",
"<<",
"commit",
"if",
"commit",
".",
"committed_date",
"<",
"date",
"end",
"commits",
"end"
] | Returns the commits in this collection that have been committed before
the given time
@param [Time, Date, DateTime, String] date The time to use as the upper
limit to filter the commits
@return [CommitCollection] The commits that have been committed after the
given date
@see Commit#committed_date
@see Time.parse | [
"Returns",
"the",
"commits",
"in",
"this",
"collection",
"that",
"have",
"been",
"committed",
"before",
"the",
"given",
"time"
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L158-L165 | train |
koraktor/metior | lib/metior/collections/commit_collection.rb | Metior.CommitCollection.by | def by(*author_ids)
author_ids = author_ids.flatten.map do |author_id|
author_id.is_a?(Actor) ? author_id.id : author_id
end
commits = CommitCollection.new
each do |commit|
commits << commit if author_ids.include? commit.author.id
end
commits
end | ruby | def by(*author_ids)
author_ids = author_ids.flatten.map do |author_id|
author_id.is_a?(Actor) ? author_id.id : author_id
end
commits = CommitCollection.new
each do |commit|
commits << commit if author_ids.include? commit.author.id
end
commits
end | [
"def",
"by",
"(",
"*",
"author_ids",
")",
"author_ids",
"=",
"author_ids",
".",
"flatten",
".",
"map",
"do",
"|",
"author_id",
"|",
"author_id",
".",
"is_a?",
"(",
"Actor",
")",
"?",
"author_id",
".",
"id",
":",
"author_id",
"end",
"commits",
"=",
"CommitCollection",
".",
"new",
"each",
"do",
"|",
"commit",
"|",
"commits",
"<<",
"commit",
"if",
"author_ids",
".",
"include?",
"commit",
".",
"author",
".",
"id",
"end",
"commits",
"end"
] | Returns the list of commits that have been authored by the given authors
@param [Array<Actor, Object>] author_ids One or more actual `Actor`
instances or IDs of the authors that the commits should be
filtered by
@return [CommitCollection] The commits that have been authored by the
given authors
@see Commit#author | [
"Returns",
"the",
"list",
"of",
"commits",
"that",
"have",
"been",
"authored",
"by",
"the",
"given",
"authors"
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L176-L185 | train |
koraktor/metior | lib/metior/collections/commit_collection.rb | Metior.CommitCollection.changing | def changing(*files)
support! :file_stats
commits = CommitCollection.new
each do |commit|
commit_files = commit.added_files + commit.deleted_files + commit.modified_files
commits << commit unless (commit_files & files).empty?
end
commits
end | ruby | def changing(*files)
support! :file_stats
commits = CommitCollection.new
each do |commit|
commit_files = commit.added_files + commit.deleted_files + commit.modified_files
commits << commit unless (commit_files & files).empty?
end
commits
end | [
"def",
"changing",
"(",
"*",
"files",
")",
"support!",
":file_stats",
"commits",
"=",
"CommitCollection",
".",
"new",
"each",
"do",
"|",
"commit",
"|",
"commit_files",
"=",
"commit",
".",
"added_files",
"+",
"commit",
".",
"deleted_files",
"+",
"commit",
".",
"modified_files",
"commits",
"<<",
"commit",
"unless",
"(",
"commit_files",
"&",
"files",
")",
".",
"empty?",
"end",
"commits",
"end"
] | Returns the commits in this collection that change any of the given files
@param [Array<String>] files The path of the files to filter commits by
@return [CommitCollection] The commits that contain changes to the given
files
@see Commit#added_files
@see Commit#deleted_files
@see Commit#modified_files | [
"Returns",
"the",
"commits",
"in",
"this",
"collection",
"that",
"change",
"any",
"of",
"the",
"given",
"files"
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L195-L204 | train |
koraktor/metior | lib/metior/collections/commit_collection.rb | Metior.CommitCollection.committers | def committers(commit_id = nil)
committers = ActorCollection.new
if commit_id.nil?
each { |commit| committers << commit.committer }
elsif key? commit_id
committers << self[commit_id].committer
end
committers
end | ruby | def committers(commit_id = nil)
committers = ActorCollection.new
if commit_id.nil?
each { |commit| committers << commit.committer }
elsif key? commit_id
committers << self[commit_id].committer
end
committers
end | [
"def",
"committers",
"(",
"commit_id",
"=",
"nil",
")",
"committers",
"=",
"ActorCollection",
".",
"new",
"if",
"commit_id",
".",
"nil?",
"each",
"{",
"|",
"commit",
"|",
"committers",
"<<",
"commit",
".",
"committer",
"}",
"elsif",
"key?",
"commit_id",
"committers",
"<<",
"self",
"[",
"commit_id",
"]",
".",
"committer",
"end",
"committers",
"end"
] | Returns the committers of all or a specific commit in this collection
@param [Object] commit_id The ID of the commit, if only the committer of
a specific commit should be returned
@return [ActorCollection] All committers of the commits in this
collection or the committer of a specific commit
@see Commit#committer | [
"Returns",
"the",
"committers",
"of",
"all",
"or",
"a",
"specific",
"commit",
"in",
"this",
"collection"
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L214-L222 | train |
koraktor/metior | lib/metior/collections/commit_collection.rb | Metior.CommitCollection.line_history | def line_history
support! :line_stats
history = { :additions => [], :deletions => [] }
values.reverse.each do |commit|
history[:additions] << commit.additions
history[:deletions] << -commit.deletions
end
history
end | ruby | def line_history
support! :line_stats
history = { :additions => [], :deletions => [] }
values.reverse.each do |commit|
history[:additions] << commit.additions
history[:deletions] << -commit.deletions
end
history
end | [
"def",
"line_history",
"support!",
":line_stats",
"history",
"=",
"{",
":additions",
"=>",
"[",
"]",
",",
":deletions",
"=>",
"[",
"]",
"}",
"values",
".",
"reverse",
".",
"each",
"do",
"|",
"commit",
"|",
"history",
"[",
":additions",
"]",
"<<",
"commit",
".",
"additions",
"history",
"[",
":deletions",
"]",
"<<",
"-",
"commit",
".",
"deletions",
"end",
"history",
"end"
] | This evaluates the changed lines in each commit of this collection
For easier use, the values are stored in separate arrays where each
number represents the number of changed (i.e. added or deleted) lines in
one commit.
@example
commits.line_history
=> { :additions => [10, 5, 0], :deletions => [0, -2, -1] }
@return [Hash<Symbol, Array>] Added lines are returned in an `Array`
assigned to key `:additions`, deleted lines are assigned to
`:deletions`
@see Commit#additions
@see Commit#deletions | [
"This",
"evaluates",
"the",
"changed",
"lines",
"in",
"each",
"commit",
"of",
"this",
"collection"
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L252-L262 | train |
koraktor/metior | lib/metior/collections/commit_collection.rb | Metior.CommitCollection.most_significant | def most_significant(count = 10)
support! :line_stats
commits = CommitCollection.new
sort_by { |commit| -commit.modifications }.each do |commit|
commits << commit
break if commits.size == count
end
commits
end | ruby | def most_significant(count = 10)
support! :line_stats
commits = CommitCollection.new
sort_by { |commit| -commit.modifications }.each do |commit|
commits << commit
break if commits.size == count
end
commits
end | [
"def",
"most_significant",
"(",
"count",
"=",
"10",
")",
"support!",
":line_stats",
"commits",
"=",
"CommitCollection",
".",
"new",
"sort_by",
"{",
"|",
"commit",
"|",
"-",
"commit",
".",
"modifications",
"}",
".",
"each",
"do",
"|",
"commit",
"|",
"commits",
"<<",
"commit",
"break",
"if",
"commits",
".",
"size",
"==",
"count",
"end",
"commits",
"end"
] | Returns the given number of commits with most line changes on the
repository
@param [Numeric] count The number of commits to return
@return [CommitCollection] The given number of commits ordered by impact
@see Commit#modifications | [
"Returns",
"the",
"given",
"number",
"of",
"commits",
"with",
"most",
"line",
"changes",
"on",
"the",
"repository"
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L279-L288 | train |
koraktor/metior | lib/metior/collections/commit_collection.rb | Metior.CommitCollection.with_impact | def with_impact(line_count)
support! :line_stats
commits = CommitCollection.new
each do |commit|
commits << commit if commit.modifications >= line_count
end
commits
end | ruby | def with_impact(line_count)
support! :line_stats
commits = CommitCollection.new
each do |commit|
commits << commit if commit.modifications >= line_count
end
commits
end | [
"def",
"with_impact",
"(",
"line_count",
")",
"support!",
":line_stats",
"commits",
"=",
"CommitCollection",
".",
"new",
"each",
"do",
"|",
"commit",
"|",
"commits",
"<<",
"commit",
"if",
"commit",
".",
"modifications",
">=",
"line_count",
"end",
"commits",
"end"
] | Returns the commits in this collection that change at least the given
number of lines
@param [Numeric] line_count The number of lines that should be
changed at least by the commits
@return [CommitCollection] The commits that change at least the given
number of lines
@see Commit#modifications | [
"Returns",
"the",
"commits",
"in",
"this",
"collection",
"that",
"change",
"at",
"least",
"the",
"given",
"number",
"of",
"lines"
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L299-L307 | train |
koraktor/metior | lib/metior/collections/commit_collection.rb | Metior.CommitCollection.load_line_stats | def load_line_stats
@additions = 0
@deletions = 0
return if empty?
line_stats = nil
if @range.nil?
ids = values.reject { |c| c.line_stats? }.map { |c| c.id }
line_stats = first.repo.load_line_stats ids unless ids.empty?
else
line_stats = first.repo.load_line_stats @range
end
unless line_stats.nil?
line_stats.each do |id, stats|
commit = self[id]
commit.line_stats = stats
end
end
each do |commit|
@additions += commit.additions
@deletions += commit.deletions
end
end | ruby | def load_line_stats
@additions = 0
@deletions = 0
return if empty?
line_stats = nil
if @range.nil?
ids = values.reject { |c| c.line_stats? }.map { |c| c.id }
line_stats = first.repo.load_line_stats ids unless ids.empty?
else
line_stats = first.repo.load_line_stats @range
end
unless line_stats.nil?
line_stats.each do |id, stats|
commit = self[id]
commit.line_stats = stats
end
end
each do |commit|
@additions += commit.additions
@deletions += commit.deletions
end
end | [
"def",
"load_line_stats",
"@additions",
"=",
"0",
"@deletions",
"=",
"0",
"return",
"if",
"empty?",
"line_stats",
"=",
"nil",
"if",
"@range",
".",
"nil?",
"ids",
"=",
"values",
".",
"reject",
"{",
"|",
"c",
"|",
"c",
".",
"line_stats?",
"}",
".",
"map",
"{",
"|",
"c",
"|",
"c",
".",
"id",
"}",
"line_stats",
"=",
"first",
".",
"repo",
".",
"load_line_stats",
"ids",
"unless",
"ids",
".",
"empty?",
"else",
"line_stats",
"=",
"first",
".",
"repo",
".",
"load_line_stats",
"@range",
"end",
"unless",
"line_stats",
".",
"nil?",
"line_stats",
".",
"each",
"do",
"|",
"id",
",",
"stats",
"|",
"commit",
"=",
"self",
"[",
"id",
"]",
"commit",
".",
"line_stats",
"=",
"stats",
"end",
"end",
"each",
"do",
"|",
"commit",
"|",
"@additions",
"+=",
"commit",
".",
"additions",
"@deletions",
"+=",
"commit",
".",
"deletions",
"end",
"end"
] | Loads the line stats for the commits in this collection
For collections holding a specific range of commits, this always gets the
line stats for all commits. For other, lets say fragmented, collections
this loads the line stats for all commits that are missing their stats.
@see Commit#additions
@see Commit#deletions
@see Commit#line_stats?
@see Repository#line_stats | [
"Loads",
"the",
"line",
"stats",
"for",
"the",
"commits",
"in",
"this",
"collection"
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L321-L345 | train |
koraktor/metior | lib/metior/report/view.rb | Metior::Report.View.render | def render(*args)
begin
features = self.class.send :class_variable_get, :@@required_features
super if features.all? { |feature| repository.supports? feature }
rescue Metior::UnsupportedError
end
end | ruby | def render(*args)
begin
features = self.class.send :class_variable_get, :@@required_features
super if features.all? { |feature| repository.supports? feature }
rescue Metior::UnsupportedError
end
end | [
"def",
"render",
"(",
"*",
"args",
")",
"begin",
"features",
"=",
"self",
".",
"class",
".",
"send",
":class_variable_get",
",",
":@@required_features",
"super",
"if",
"features",
".",
"all?",
"{",
"|",
"feature",
"|",
"repository",
".",
"supports?",
"feature",
"}",
"rescue",
"Metior",
"::",
"UnsupportedError",
"end",
"end"
] | This checks if all required VCS features of this view are available for
this report's repository
@param [Object, ...] args The arguments expected by {Mustache#render}
@see .requires
@see http://rubydoc.info/gems/mustache/Mustache#render-instance_method
Mustache#render | [
"This",
"checks",
"if",
"all",
"required",
"VCS",
"features",
"of",
"this",
"view",
"are",
"available",
"for",
"this",
"report",
"s",
"repository"
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/report/view.rb#L105-L111 | train |
jrochkind/bento_search | app/controllers/bento_search/search_controller.rb | BentoSearch.SearchController.search | def search
engine = BentoSearch.get_engine(params[:engine_id])
# put it in an iVar mainly for testing purposes.
@engine = engine
unless engine.configuration.allow_routable_results == true
raise AccessDenied.new("engine needs to be registered with :allow_routable_results => true")
end
@results = engine.search safe_search_args(engine, params)
# template name of a partial with 'yield' to use to wrap the results
@partial_wrapper = @results.display_configuration.lookup!("ajax.wrapper_template")
# partial HTML results
render "bento_search/search/search", :layout => false
end | ruby | def search
engine = BentoSearch.get_engine(params[:engine_id])
# put it in an iVar mainly for testing purposes.
@engine = engine
unless engine.configuration.allow_routable_results == true
raise AccessDenied.new("engine needs to be registered with :allow_routable_results => true")
end
@results = engine.search safe_search_args(engine, params)
# template name of a partial with 'yield' to use to wrap the results
@partial_wrapper = @results.display_configuration.lookup!("ajax.wrapper_template")
# partial HTML results
render "bento_search/search/search", :layout => false
end | [
"def",
"search",
"engine",
"=",
"BentoSearch",
".",
"get_engine",
"(",
"params",
"[",
":engine_id",
"]",
")",
"@engine",
"=",
"engine",
"unless",
"engine",
".",
"configuration",
".",
"allow_routable_results",
"==",
"true",
"raise",
"AccessDenied",
".",
"new",
"(",
"\"engine needs to be registered with :allow_routable_results => true\"",
")",
"end",
"@results",
"=",
"engine",
".",
"search",
"safe_search_args",
"(",
"engine",
",",
"params",
")",
"@partial_wrapper",
"=",
"@results",
".",
"display_configuration",
".",
"lookup!",
"(",
"\"ajax.wrapper_template\"",
")",
"render",
"\"bento_search/search/search\"",
",",
":layout",
"=>",
"false",
"end"
] | returns partial HTML results, suitable for
AJAX to insert into DOM.
arguments for engine.search are taken from URI request params, whitelisted | [
"returns",
"partial",
"HTML",
"results",
"suitable",
"for",
"AJAX",
"to",
"insert",
"into",
"DOM",
".",
"arguments",
"for",
"engine",
".",
"search",
"are",
"taken",
"from",
"URI",
"request",
"params",
"whitelisted"
] | f567ead386d4a2e283c03b787e7c0d620567c9de | https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/controllers/bento_search/search_controller.rb#L44-L61 | train |
koraktor/metior | lib/metior/adapter/grit/repository.rb | Metior::Adapter::Grit.Repository.current_branch | def current_branch
branch = @grit_repo.head
return branch.name unless branch.nil?
commit = @grit_repo.commit('HEAD')
commit.id unless commit.nil?
end | ruby | def current_branch
branch = @grit_repo.head
return branch.name unless branch.nil?
commit = @grit_repo.commit('HEAD')
commit.id unless commit.nil?
end | [
"def",
"current_branch",
"branch",
"=",
"@grit_repo",
".",
"head",
"return",
"branch",
".",
"name",
"unless",
"branch",
".",
"nil?",
"commit",
"=",
"@grit_repo",
".",
"commit",
"(",
"'HEAD'",
")",
"commit",
".",
"id",
"unless",
"commit",
".",
"nil?",
"end"
] | Creates a new Git repository based on the given path
This creates a new `Grit::Repo` instance to interface with the
repository.
@param [String] path The file system path of the repository
Returns the current branch of the repository
This is the target ref of Git's HEAD, i.e. the currently checked out
branch. For a detached HEAD this may also be the commit ID of the checked
out commit.
@see Grit::Repo#head | [
"Creates",
"a",
"new",
"Git",
"repository",
"based",
"on",
"the",
"given",
"path"
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter/grit/repository.rb#L36-L41 | train |
koraktor/metior | lib/metior/adapter/grit/repository.rb | Metior::Adapter::Grit.Repository.load_line_stats | def load_line_stats(ids)
if ids.is_a? Range
if ids.first == ''
range = ids.last
else
range = '%s..%s' % [ids.first, ids.last]
end
options = { :numstat => true, :timeout => false }
output = @grit_repo.git.native :log, options, range
commit_stats = ::Grit::CommitStats.list_from_string @grit_repo, output
else
commit_stats = []
ids.each_slice(500) do |id_slice|
options = { :numstat => true, :timeout => false }
output = @grit_repo.git.native :log, options, *id_slice
commit_stats += ::Grit::CommitStats.list_from_string @grit_repo, output
end
end
Hash[commit_stats.map do |stats|
[stats.first, [stats.last.additions, stats.last.deletions]]
end]
end | ruby | def load_line_stats(ids)
if ids.is_a? Range
if ids.first == ''
range = ids.last
else
range = '%s..%s' % [ids.first, ids.last]
end
options = { :numstat => true, :timeout => false }
output = @grit_repo.git.native :log, options, range
commit_stats = ::Grit::CommitStats.list_from_string @grit_repo, output
else
commit_stats = []
ids.each_slice(500) do |id_slice|
options = { :numstat => true, :timeout => false }
output = @grit_repo.git.native :log, options, *id_slice
commit_stats += ::Grit::CommitStats.list_from_string @grit_repo, output
end
end
Hash[commit_stats.map do |stats|
[stats.first, [stats.last.additions, stats.last.deletions]]
end]
end | [
"def",
"load_line_stats",
"(",
"ids",
")",
"if",
"ids",
".",
"is_a?",
"Range",
"if",
"ids",
".",
"first",
"==",
"''",
"range",
"=",
"ids",
".",
"last",
"else",
"range",
"=",
"'%s..%s'",
"%",
"[",
"ids",
".",
"first",
",",
"ids",
".",
"last",
"]",
"end",
"options",
"=",
"{",
":numstat",
"=>",
"true",
",",
":timeout",
"=>",
"false",
"}",
"output",
"=",
"@grit_repo",
".",
"git",
".",
"native",
":log",
",",
"options",
",",
"range",
"commit_stats",
"=",
"::",
"Grit",
"::",
"CommitStats",
".",
"list_from_string",
"@grit_repo",
",",
"output",
"else",
"commit_stats",
"=",
"[",
"]",
"ids",
".",
"each_slice",
"(",
"500",
")",
"do",
"|",
"id_slice",
"|",
"options",
"=",
"{",
":numstat",
"=>",
"true",
",",
":timeout",
"=>",
"false",
"}",
"output",
"=",
"@grit_repo",
".",
"git",
".",
"native",
":log",
",",
"options",
",",
"*",
"id_slice",
"commit_stats",
"+=",
"::",
"Grit",
"::",
"CommitStats",
".",
"list_from_string",
"@grit_repo",
",",
"output",
"end",
"end",
"Hash",
"[",
"commit_stats",
".",
"map",
"do",
"|",
"stats",
"|",
"[",
"stats",
".",
"first",
",",
"[",
"stats",
".",
"last",
".",
"additions",
",",
"stats",
".",
"last",
".",
"deletions",
"]",
"]",
"end",
"]",
"end"
] | Loads the line stats for the commits given by a set of commit IDs
@param [Array<String>] ids The IDs of the commits to load line stats for
@return [Hash<String, Array<Fixnum>] An array of two number (line
additions and deletions) for each of the given commit IDs | [
"Loads",
"the",
"line",
"stats",
"for",
"the",
"commits",
"given",
"by",
"a",
"set",
"of",
"commit",
"IDs"
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter/grit/repository.rb#L65-L88 | train |
koraktor/metior | lib/metior/adapter/grit/repository.rb | Metior::Adapter::Grit.Repository.load_branches | def load_branches
Hash[@grit_repo.branches.map { |b| [b.name, b.commit.id] }]
end | ruby | def load_branches
Hash[@grit_repo.branches.map { |b| [b.name, b.commit.id] }]
end | [
"def",
"load_branches",
"Hash",
"[",
"@grit_repo",
".",
"branches",
".",
"map",
"{",
"|",
"b",
"|",
"[",
"b",
".",
"name",
",",
"b",
".",
"commit",
".",
"id",
"]",
"}",
"]",
"end"
] | Loads all branches and the corresponding commit IDs of this repository
@return [Hash<String, String>] The names of all branches and the
corresponding commit IDs
@see Grit::Repo#branches | [
"Loads",
"all",
"branches",
"and",
"the",
"corresponding",
"commit",
"IDs",
"of",
"this",
"repository"
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter/grit/repository.rb#L106-L108 | train |
koraktor/metior | lib/metior/adapter/grit/repository.rb | Metior::Adapter::Grit.Repository.load_commits | def load_commits(range)
if range.first == ''
base_commit = nil
range = range.last
else
base_commit = @grit_repo.commit(range.first)
range = '%s..%s' % [range.first, range.last]
end
options = { :pretty => 'raw', :timeout => false }
output = @grit_repo.git.native :rev_list, options, range
commits = ::Grit::Commit.list_from_string @grit_repo, output
[base_commit, commits]
end | ruby | def load_commits(range)
if range.first == ''
base_commit = nil
range = range.last
else
base_commit = @grit_repo.commit(range.first)
range = '%s..%s' % [range.first, range.last]
end
options = { :pretty => 'raw', :timeout => false }
output = @grit_repo.git.native :rev_list, options, range
commits = ::Grit::Commit.list_from_string @grit_repo, output
[base_commit, commits]
end | [
"def",
"load_commits",
"(",
"range",
")",
"if",
"range",
".",
"first",
"==",
"''",
"base_commit",
"=",
"nil",
"range",
"=",
"range",
".",
"last",
"else",
"base_commit",
"=",
"@grit_repo",
".",
"commit",
"(",
"range",
".",
"first",
")",
"range",
"=",
"'%s..%s'",
"%",
"[",
"range",
".",
"first",
",",
"range",
".",
"last",
"]",
"end",
"options",
"=",
"{",
":pretty",
"=>",
"'raw'",
",",
":timeout",
"=>",
"false",
"}",
"output",
"=",
"@grit_repo",
".",
"git",
".",
"native",
":rev_list",
",",
"options",
",",
"range",
"commits",
"=",
"::",
"Grit",
"::",
"Commit",
".",
"list_from_string",
"@grit_repo",
",",
"output",
"[",
"base_commit",
",",
"commits",
"]",
"end"
] | This method uses Grit to load all commits from the given commit range
Because of some Grit internal limitations, the commits have to be loaded
in batches of up to 300 commits.
@note Grit will choke on huge repositories, like Homebrew or the Linux
kernel. You will have to raise the timeout limit using
`Grit.git_timeout=`.
@param [String, Range] range The range of commits for which the commits
should be loaded. This may be given as a string
(`'master..development'`), a range (`'master'..'development'`)
or as a single ref (`'master'`). A single ref name means all
commits reachable from that ref.
@return [Grit::Commit, nil] The base commit of the requested range or
`nil` if the the range starts at the beginning of the history
@return [Array<Grit::Commit>] All commits in the given commit range
@see Grit::Repo#commits | [
"This",
"method",
"uses",
"Grit",
"to",
"load",
"all",
"commits",
"from",
"the",
"given",
"commit",
"range"
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter/grit/repository.rb#L127-L141 | train |
koraktor/metior | lib/metior/adapter/grit/repository.rb | Metior::Adapter::Grit.Repository.load_name_and_description | def load_name_and_description
description = @grit_repo.description
if description.start_with? 'Unnamed repository'
@name = ''
@description = ''
else
description = description.lines.to_a
@name = description.shift.strip
@description = description.join("\n").strip
end
end | ruby | def load_name_and_description
description = @grit_repo.description
if description.start_with? 'Unnamed repository'
@name = ''
@description = ''
else
description = description.lines.to_a
@name = description.shift.strip
@description = description.join("\n").strip
end
end | [
"def",
"load_name_and_description",
"description",
"=",
"@grit_repo",
".",
"description",
"if",
"description",
".",
"start_with?",
"'Unnamed repository'",
"@name",
"=",
"''",
"@description",
"=",
"''",
"else",
"description",
"=",
"description",
".",
"lines",
".",
"to_a",
"@name",
"=",
"description",
".",
"shift",
".",
"strip",
"@description",
"=",
"description",
".",
"join",
"(",
"\"\\n\"",
")",
".",
"strip",
"end",
"end"
] | Loads both the name and description of the project contained in the
repository from the description file in `GIT_DIR`. The first line of that
file is used as the project's name, the remaining text is used as a
description of the project.
@see #description
@see #name
@see Grit::Repo#name | [
"Loads",
"both",
"the",
"name",
"and",
"description",
"of",
"the",
"project",
"contained",
"in",
"the",
"repository",
"from",
"the",
"description",
"file",
"in",
"GIT_DIR",
".",
"The",
"first",
"line",
"of",
"that",
"file",
"is",
"used",
"as",
"the",
"project",
"s",
"name",
"the",
"remaining",
"text",
"is",
"used",
"as",
"a",
"description",
"of",
"the",
"project",
"."
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter/grit/repository.rb#L151-L161 | train |
koraktor/metior | lib/metior/adapter/grit/repository.rb | Metior::Adapter::Grit.Repository.load_tags | def load_tags
Hash[@grit_repo.tags.map { |b| [b.name, b.commit.id] }]
end | ruby | def load_tags
Hash[@grit_repo.tags.map { |b| [b.name, b.commit.id] }]
end | [
"def",
"load_tags",
"Hash",
"[",
"@grit_repo",
".",
"tags",
".",
"map",
"{",
"|",
"b",
"|",
"[",
"b",
".",
"name",
",",
"b",
".",
"commit",
".",
"id",
"]",
"}",
"]",
"end"
] | Loads all tags and the corresponding commit IDs of this repository
@return [Hash<String, String>] The names of all tags and the
corresponding commit IDs
@see Grit::Repo#tags | [
"Loads",
"all",
"tags",
"and",
"the",
"corresponding",
"commit",
"IDs",
"of",
"this",
"repository"
] | 02da0f330774c91e1a7325a5a7edbe696f389f95 | https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter/grit/repository.rb#L170-L172 | train |
rwz/nestive | lib/nestive/layout_helper.rb | Nestive.LayoutHelper.area | def area(name, content=nil, &block)
content = capture(&block) if block_given?
append name, content
render_area name
end | ruby | def area(name, content=nil, &block)
content = capture(&block) if block_given?
append name, content
render_area name
end | [
"def",
"area",
"(",
"name",
",",
"content",
"=",
"nil",
",",
"&",
"block",
")",
"content",
"=",
"capture",
"(",
"&",
"block",
")",
"if",
"block_given?",
"append",
"name",
",",
"content",
"render_area",
"name",
"end"
] | Defines an area of content in your layout that can be modified or replaced by child layouts
that extend it. You can optionally add content to an area using either a String, or a block.
Areas are declared in a parent layout and modified by a child layout, but since Nestive
allows for multiple levels of inheritance, a child layout can also declare an area for it's
children to modify.
@example Define an area without adding content to it:
<%= area :sidebar %>
@example Define an area and add a String of content to it:
<%= area :sidebar, "Some content." %>
@example Define an area and add content to it with a block:
<%= area :sidebar do %>
Some content.
<% end %>
@example Define an area in a child layout:
<%= extends :global do %>
<%= area :sidebar do %>
Some content.
<% end %>
<% end %>
@param [Symbol] name
A unique name to identify this area of content.
@param [String] content
An optional String of content to add to the area as you declare it. | [
"Defines",
"an",
"area",
"of",
"content",
"in",
"your",
"layout",
"that",
"can",
"be",
"modified",
"or",
"replaced",
"by",
"child",
"layouts",
"that",
"extend",
"it",
".",
"You",
"can",
"optionally",
"add",
"content",
"to",
"an",
"area",
"using",
"either",
"a",
"String",
"or",
"a",
"block",
"."
] | 3f9cc1282c0059c4a3d8665507c14c2a6f0a986a | https://github.com/rwz/nestive/blob/3f9cc1282c0059c4a3d8665507c14c2a6f0a986a/lib/nestive/layout_helper.rb#L127-L131 | train |
rwz/nestive | lib/nestive/layout_helper.rb | Nestive.LayoutHelper.render_area | def render_area(name)
[].tap do |output|
@_area_for.fetch(name, []).reverse_each do |method_name, content|
output.public_send method_name, content
end
end.join.html_safe
end | ruby | def render_area(name)
[].tap do |output|
@_area_for.fetch(name, []).reverse_each do |method_name, content|
output.public_send method_name, content
end
end.join.html_safe
end | [
"def",
"render_area",
"(",
"name",
")",
"[",
"]",
".",
"tap",
"do",
"|",
"output",
"|",
"@_area_for",
".",
"fetch",
"(",
"name",
",",
"[",
"]",
")",
".",
"reverse_each",
"do",
"|",
"method_name",
",",
"content",
"|",
"output",
".",
"public_send",
"method_name",
",",
"content",
"end",
"end",
".",
"join",
".",
"html_safe",
"end"
] | Take the instructions we've gathered for the area and replay them one after the other on
an empty array. These instructions will push, unshift or replace items into our output array,
which we then join and mark as html_safe.
These instructions are reversed and replayed when we render the block (rather than as they
happen) due to the way they are gathered by the layout extension process (in reverse). | [
"Take",
"the",
"instructions",
"we",
"ve",
"gathered",
"for",
"the",
"area",
"and",
"replay",
"them",
"one",
"after",
"the",
"other",
"on",
"an",
"empty",
"array",
".",
"These",
"instructions",
"will",
"push",
"unshift",
"or",
"replace",
"items",
"into",
"our",
"output",
"array",
"which",
"we",
"then",
"join",
"and",
"mark",
"as",
"html_safe",
"."
] | 3f9cc1282c0059c4a3d8665507c14c2a6f0a986a | https://github.com/rwz/nestive/blob/3f9cc1282c0059c4a3d8665507c14c2a6f0a986a/lib/nestive/layout_helper.rb#L236-L242 | train |
jrochkind/bento_search | app/search_engines/bento_search/google_books_engine.rb | BentoSearch.GoogleBooksEngine.hash_to_item | def hash_to_item(item_response)
v_info = item_response["volumeInfo"] || {}
item = ResultItem.new
item.unique_id = item_response["id"]
item.title = format_title(v_info)
item.publisher = v_info["publisher"]
# previewLink gives you your search results highlighted, preferable
# if it exists.
item.link = v_info["previewLink"] || v_info["canonicalVolumeLink"]
item.abstract = sanitize v_info["description"]
item.year = get_year v_info["publishedDate"]
# sometimes we have yyyy-mm, but we need a date to make a ruby Date,
# we'll just say the 1st.
item.publication_date = case v_info["publishedDate"]
when /(\d\d\d\d)-(\d\d)/ then Date.parse "#{$1}-#{$2}-01"
when /(\d\d\d\d)-(\d\d)-(\d\d)/ then Date.parse v_info["published_date"]
else nil
end
item.format = if v_info["printType"] == "MAGAZINE"
:serial
else
"Book"
end
item.language_code = v_info["language"]
(v_info["authors"] || []).each do |author_name|
item.authors << Author.new(:display => author_name)
end
# Find ISBN's, prefer ISBN-13
item.isbn = (v_info["industryIdentifiers"] || []).find {|node| node["type"] == "ISBN_13"}.try {|node| node["identifier"]}
unless item.isbn
# Look for ISBN-10 okay
item.isbn = (v_info["industryIdentifiers"] || []).find {|node| node["type"] == "ISBN_10"}.try {|node| node["identifier"]}
end
# only VERY occasionally does a GBS hit have an OCLC number, but let's look
# just in case.
item.oclcnum = (v_info["industryIdentifiers"] || []).
find {|node| node["type"] == "OTHER" && node["identifier"].starts_with?("OCLC:") }.
try do |node|
node =~ /OCLC:(.*)/ ? $1 : nil
end
# save viewability status in custom_data. PARTIAL, ALL_PAGES, NO_PAGES or UNKNOWN.
# https://developers.google.com/books/docs/v1/reference/volumes#resource
item.custom_data[:viewability] = item_response["accessInfo"].try {|h| h["viewability"]}
item.link_is_fulltext = (item.custom_data[:viewability] == "ALL_PAGES") if item.custom_data[:viewability]
return item
end | ruby | def hash_to_item(item_response)
v_info = item_response["volumeInfo"] || {}
item = ResultItem.new
item.unique_id = item_response["id"]
item.title = format_title(v_info)
item.publisher = v_info["publisher"]
# previewLink gives you your search results highlighted, preferable
# if it exists.
item.link = v_info["previewLink"] || v_info["canonicalVolumeLink"]
item.abstract = sanitize v_info["description"]
item.year = get_year v_info["publishedDate"]
# sometimes we have yyyy-mm, but we need a date to make a ruby Date,
# we'll just say the 1st.
item.publication_date = case v_info["publishedDate"]
when /(\d\d\d\d)-(\d\d)/ then Date.parse "#{$1}-#{$2}-01"
when /(\d\d\d\d)-(\d\d)-(\d\d)/ then Date.parse v_info["published_date"]
else nil
end
item.format = if v_info["printType"] == "MAGAZINE"
:serial
else
"Book"
end
item.language_code = v_info["language"]
(v_info["authors"] || []).each do |author_name|
item.authors << Author.new(:display => author_name)
end
# Find ISBN's, prefer ISBN-13
item.isbn = (v_info["industryIdentifiers"] || []).find {|node| node["type"] == "ISBN_13"}.try {|node| node["identifier"]}
unless item.isbn
# Look for ISBN-10 okay
item.isbn = (v_info["industryIdentifiers"] || []).find {|node| node["type"] == "ISBN_10"}.try {|node| node["identifier"]}
end
# only VERY occasionally does a GBS hit have an OCLC number, but let's look
# just in case.
item.oclcnum = (v_info["industryIdentifiers"] || []).
find {|node| node["type"] == "OTHER" && node["identifier"].starts_with?("OCLC:") }.
try do |node|
node =~ /OCLC:(.*)/ ? $1 : nil
end
# save viewability status in custom_data. PARTIAL, ALL_PAGES, NO_PAGES or UNKNOWN.
# https://developers.google.com/books/docs/v1/reference/volumes#resource
item.custom_data[:viewability] = item_response["accessInfo"].try {|h| h["viewability"]}
item.link_is_fulltext = (item.custom_data[:viewability] == "ALL_PAGES") if item.custom_data[:viewability]
return item
end | [
"def",
"hash_to_item",
"(",
"item_response",
")",
"v_info",
"=",
"item_response",
"[",
"\"volumeInfo\"",
"]",
"||",
"{",
"}",
"item",
"=",
"ResultItem",
".",
"new",
"item",
".",
"unique_id",
"=",
"item_response",
"[",
"\"id\"",
"]",
"item",
".",
"title",
"=",
"format_title",
"(",
"v_info",
")",
"item",
".",
"publisher",
"=",
"v_info",
"[",
"\"publisher\"",
"]",
"item",
".",
"link",
"=",
"v_info",
"[",
"\"previewLink\"",
"]",
"||",
"v_info",
"[",
"\"canonicalVolumeLink\"",
"]",
"item",
".",
"abstract",
"=",
"sanitize",
"v_info",
"[",
"\"description\"",
"]",
"item",
".",
"year",
"=",
"get_year",
"v_info",
"[",
"\"publishedDate\"",
"]",
"item",
".",
"publication_date",
"=",
"case",
"v_info",
"[",
"\"publishedDate\"",
"]",
"when",
"/",
"\\d",
"\\d",
"\\d",
"\\d",
"\\d",
"\\d",
"/",
"then",
"Date",
".",
"parse",
"\"#{$1}-#{$2}-01\"",
"when",
"/",
"\\d",
"\\d",
"\\d",
"\\d",
"\\d",
"\\d",
"\\d",
"\\d",
"/",
"then",
"Date",
".",
"parse",
"v_info",
"[",
"\"published_date\"",
"]",
"else",
"nil",
"end",
"item",
".",
"format",
"=",
"if",
"v_info",
"[",
"\"printType\"",
"]",
"==",
"\"MAGAZINE\"",
":serial",
"else",
"\"Book\"",
"end",
"item",
".",
"language_code",
"=",
"v_info",
"[",
"\"language\"",
"]",
"(",
"v_info",
"[",
"\"authors\"",
"]",
"||",
"[",
"]",
")",
".",
"each",
"do",
"|",
"author_name",
"|",
"item",
".",
"authors",
"<<",
"Author",
".",
"new",
"(",
":display",
"=>",
"author_name",
")",
"end",
"item",
".",
"isbn",
"=",
"(",
"v_info",
"[",
"\"industryIdentifiers\"",
"]",
"||",
"[",
"]",
")",
".",
"find",
"{",
"|",
"node",
"|",
"node",
"[",
"\"type\"",
"]",
"==",
"\"ISBN_13\"",
"}",
".",
"try",
"{",
"|",
"node",
"|",
"node",
"[",
"\"identifier\"",
"]",
"}",
"unless",
"item",
".",
"isbn",
"item",
".",
"isbn",
"=",
"(",
"v_info",
"[",
"\"industryIdentifiers\"",
"]",
"||",
"[",
"]",
")",
".",
"find",
"{",
"|",
"node",
"|",
"node",
"[",
"\"type\"",
"]",
"==",
"\"ISBN_10\"",
"}",
".",
"try",
"{",
"|",
"node",
"|",
"node",
"[",
"\"identifier\"",
"]",
"}",
"end",
"item",
".",
"oclcnum",
"=",
"(",
"v_info",
"[",
"\"industryIdentifiers\"",
"]",
"||",
"[",
"]",
")",
".",
"find",
"{",
"|",
"node",
"|",
"node",
"[",
"\"type\"",
"]",
"==",
"\"OTHER\"",
"&&",
"node",
"[",
"\"identifier\"",
"]",
".",
"starts_with?",
"(",
"\"OCLC:\"",
")",
"}",
".",
"try",
"do",
"|",
"node",
"|",
"node",
"=~",
"/",
"/",
"?",
"$1",
":",
"nil",
"end",
"item",
".",
"custom_data",
"[",
":viewability",
"]",
"=",
"item_response",
"[",
"\"accessInfo\"",
"]",
".",
"try",
"{",
"|",
"h",
"|",
"h",
"[",
"\"viewability\"",
"]",
"}",
"item",
".",
"link_is_fulltext",
"=",
"(",
"item",
".",
"custom_data",
"[",
":viewability",
"]",
"==",
"\"ALL_PAGES\"",
")",
"if",
"item",
".",
"custom_data",
"[",
":viewability",
"]",
"return",
"item",
"end"
] | take a hash from Google json response, representing a single
item, return a ResultItem obj. Used internally. | [
"take",
"a",
"hash",
"from",
"Google",
"json",
"response",
"representing",
"a",
"single",
"item",
"return",
"a",
"ResultItem",
"obj",
".",
"Used",
"internally",
"."
] | f567ead386d4a2e283c03b787e7c0d620567c9de | https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/search_engines/bento_search/google_books_engine.rb#L119-L178 | train |
jrochkind/bento_search | app/search_engines/bento_search/google_books_engine.rb | BentoSearch.GoogleBooksEngine.args_to_search_url | def args_to_search_url(arguments)
query = if arguments[:query].kind_of? Hash
#multi-field
arguments[:query].collect {|field, query_value| fielded_query(query_value, field)}.join(" ")
elsif arguments[:search_field]
fielded_query(arguments[:query], arguments[:search_field])
else
arguments[:query]
end
query_url = base_url + "volumes?q=#{CGI.escape query}"
if configuration.api_key
query_url += "&key=#{configuration.api_key}"
end
if arguments[:per_page]
query_url += "&maxResults=#{arguments[:per_page]}"
end
if arguments[:start]
query_url += "&startIndex=#{arguments[:start]}"
end
if arguments[:sort] &&
(defn = sort_definitions[arguments[:sort]]) &&
(value = defn[:implementation])
query_url += "&orderBy=#{CGI.escape(value)}"
end
return query_url
end | ruby | def args_to_search_url(arguments)
query = if arguments[:query].kind_of? Hash
#multi-field
arguments[:query].collect {|field, query_value| fielded_query(query_value, field)}.join(" ")
elsif arguments[:search_field]
fielded_query(arguments[:query], arguments[:search_field])
else
arguments[:query]
end
query_url = base_url + "volumes?q=#{CGI.escape query}"
if configuration.api_key
query_url += "&key=#{configuration.api_key}"
end
if arguments[:per_page]
query_url += "&maxResults=#{arguments[:per_page]}"
end
if arguments[:start]
query_url += "&startIndex=#{arguments[:start]}"
end
if arguments[:sort] &&
(defn = sort_definitions[arguments[:sort]]) &&
(value = defn[:implementation])
query_url += "&orderBy=#{CGI.escape(value)}"
end
return query_url
end | [
"def",
"args_to_search_url",
"(",
"arguments",
")",
"query",
"=",
"if",
"arguments",
"[",
":query",
"]",
".",
"kind_of?",
"Hash",
"arguments",
"[",
":query",
"]",
".",
"collect",
"{",
"|",
"field",
",",
"query_value",
"|",
"fielded_query",
"(",
"query_value",
",",
"field",
")",
"}",
".",
"join",
"(",
"\" \"",
")",
"elsif",
"arguments",
"[",
":search_field",
"]",
"fielded_query",
"(",
"arguments",
"[",
":query",
"]",
",",
"arguments",
"[",
":search_field",
"]",
")",
"else",
"arguments",
"[",
":query",
"]",
"end",
"query_url",
"=",
"base_url",
"+",
"\"volumes?q=#{CGI.escape query}\"",
"if",
"configuration",
".",
"api_key",
"query_url",
"+=",
"\"&key=#{configuration.api_key}\"",
"end",
"if",
"arguments",
"[",
":per_page",
"]",
"query_url",
"+=",
"\"&maxResults=#{arguments[:per_page]}\"",
"end",
"if",
"arguments",
"[",
":start",
"]",
"query_url",
"+=",
"\"&startIndex=#{arguments[:start]}\"",
"end",
"if",
"arguments",
"[",
":sort",
"]",
"&&",
"(",
"defn",
"=",
"sort_definitions",
"[",
"arguments",
"[",
":sort",
"]",
"]",
")",
"&&",
"(",
"value",
"=",
"defn",
"[",
":implementation",
"]",
")",
"query_url",
"+=",
"\"&orderBy=#{CGI.escape(value)}\"",
"end",
"return",
"query_url",
"end"
] | Our own implementation code
takes a normalized #search arguments hash from SearchEngine
turns it into a URL for Google API. Factored out to make testing
possible. | [
"Our",
"own",
"implementation",
"code"
] | f567ead386d4a2e283c03b787e7c0d620567c9de | https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/search_engines/bento_search/google_books_engine.rb#L223-L253 | train |
jrochkind/bento_search | app/item_decorators/bento_search/standard_decorator.rb | BentoSearch.StandardDecorator.render_authors_list | def render_authors_list
parts = []
first_three = self.authors.slice(0,3)
first_three.each_with_index do |author, index|
parts << _h.content_tag("span", :class => "author") do
self.author_display(author)
end
if (index + 1) < first_three.length
parts << "; "
end
end
if self.authors.length > 3
parts << I18n.t("bento_search.authors_et_al")
end
return _h.safe_join(parts, "")
end | ruby | def render_authors_list
parts = []
first_three = self.authors.slice(0,3)
first_three.each_with_index do |author, index|
parts << _h.content_tag("span", :class => "author") do
self.author_display(author)
end
if (index + 1) < first_three.length
parts << "; "
end
end
if self.authors.length > 3
parts << I18n.t("bento_search.authors_et_al")
end
return _h.safe_join(parts, "")
end | [
"def",
"render_authors_list",
"parts",
"=",
"[",
"]",
"first_three",
"=",
"self",
".",
"authors",
".",
"slice",
"(",
"0",
",",
"3",
")",
"first_three",
".",
"each_with_index",
"do",
"|",
"author",
",",
"index",
"|",
"parts",
"<<",
"_h",
".",
"content_tag",
"(",
"\"span\"",
",",
":class",
"=>",
"\"author\"",
")",
"do",
"self",
".",
"author_display",
"(",
"author",
")",
"end",
"if",
"(",
"index",
"+",
"1",
")",
"<",
"first_three",
".",
"length",
"parts",
"<<",
"\"; \"",
"end",
"end",
"if",
"self",
".",
"authors",
".",
"length",
">",
"3",
"parts",
"<<",
"I18n",
".",
"t",
"(",
"\"bento_search.authors_et_al\"",
")",
"end",
"return",
"_h",
".",
"safe_join",
"(",
"parts",
",",
"\"\"",
")",
"end"
] | display multiple authors, with HTML markup, returns html_safe string.
experimentally trying this as a decorator helper method rather
than a view partial, not sure which is best.
Will limit to first three authors, with elipsis if there are more.
Over-ride if you want to format authors names differently, or
show more or less than first 3, etc. | [
"display",
"multiple",
"authors",
"with",
"HTML",
"markup",
"returns",
"html_safe",
"string",
".",
"experimentally",
"trying",
"this",
"as",
"a",
"decorator",
"helper",
"method",
"rather",
"than",
"a",
"view",
"partial",
"not",
"sure",
"which",
"is",
"best",
"."
] | f567ead386d4a2e283c03b787e7c0d620567c9de | https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/item_decorators/bento_search/standard_decorator.rb#L38-L57 | train |
jrochkind/bento_search | app/item_decorators/bento_search/standard_decorator.rb | BentoSearch.StandardDecorator.render_citation_details | def render_citation_details
# \u00A0 is unicode non-breaking space to keep labels and values from
# getting separated.
result_elements = []
result_elements.push("#{I18n.t('bento_search.volume')}\u00A0#{volume}") if volume.present?
result_elements.push("#{I18n.t('bento_search.issue')}\u00A0#{issue}") if issue.present?
if (! start_page.blank?) && (! end_page.blank?)
result_elements.push html_escape "#{I18n.t('bento_search.pages')}\u00A0#{start_page}-#{end_page}"
elsif ! start_page.blank?
result_elements.push html_escape "#{I18n.t('bento_search.page')}\u00A0#{start_page}"
end
return nil if result_elements.empty?
return result_elements.join(", ").html_safe
end | ruby | def render_citation_details
# \u00A0 is unicode non-breaking space to keep labels and values from
# getting separated.
result_elements = []
result_elements.push("#{I18n.t('bento_search.volume')}\u00A0#{volume}") if volume.present?
result_elements.push("#{I18n.t('bento_search.issue')}\u00A0#{issue}") if issue.present?
if (! start_page.blank?) && (! end_page.blank?)
result_elements.push html_escape "#{I18n.t('bento_search.pages')}\u00A0#{start_page}-#{end_page}"
elsif ! start_page.blank?
result_elements.push html_escape "#{I18n.t('bento_search.page')}\u00A0#{start_page}"
end
return nil if result_elements.empty?
return result_elements.join(", ").html_safe
end | [
"def",
"render_citation_details",
"result_elements",
"=",
"[",
"]",
"result_elements",
".",
"push",
"(",
"\"#{I18n.t('bento_search.volume')}\\u00A0#{volume}\"",
")",
"if",
"volume",
".",
"present?",
"result_elements",
".",
"push",
"(",
"\"#{I18n.t('bento_search.issue')}\\u00A0#{issue}\"",
")",
"if",
"issue",
".",
"present?",
"if",
"(",
"!",
"start_page",
".",
"blank?",
")",
"&&",
"(",
"!",
"end_page",
".",
"blank?",
")",
"result_elements",
".",
"push",
"html_escape",
"\"#{I18n.t('bento_search.pages')}\\u00A0#{start_page}-#{end_page}\"",
"elsif",
"!",
"start_page",
".",
"blank?",
"result_elements",
".",
"push",
"html_escape",
"\"#{I18n.t('bento_search.page')}\\u00A0#{start_page}\"",
"end",
"return",
"nil",
"if",
"result_elements",
".",
"empty?",
"return",
"result_elements",
".",
"join",
"(",
"\", \"",
")",
".",
"html_safe",
"end"
] | volume, issue, and page numbers. With prefixed labels from I18n.
That's it. | [
"volume",
"issue",
"and",
"page",
"numbers",
".",
"With",
"prefixed",
"labels",
"from",
"I18n",
".",
"That",
"s",
"it",
"."
] | f567ead386d4a2e283c03b787e7c0d620567c9de | https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/item_decorators/bento_search/standard_decorator.rb#L104-L122 | train |
jrochkind/bento_search | app/item_decorators/bento_search/standard_decorator.rb | BentoSearch.StandardDecorator.render_summary | def render_summary
summary = nil
max_chars = (self.display_configuration.try {|h| h["summary_max_chars"]}) || 280
if self.snippets.length > 0 && !(self.display_configuration.try {|h| h["prefer_abstract_as_summary"]} && self.abstract)
summary = self.snippets.first
self.snippets.slice(1, self.snippets.length).each do |snippet|
summary += ' '.html_safe + snippet if (summary.length + snippet.length) <= max_chars
end
else
summary = _h.bento_truncate( self.abstract, :length => max_chars )
end
summary
end | ruby | def render_summary
summary = nil
max_chars = (self.display_configuration.try {|h| h["summary_max_chars"]}) || 280
if self.snippets.length > 0 && !(self.display_configuration.try {|h| h["prefer_abstract_as_summary"]} && self.abstract)
summary = self.snippets.first
self.snippets.slice(1, self.snippets.length).each do |snippet|
summary += ' '.html_safe + snippet if (summary.length + snippet.length) <= max_chars
end
else
summary = _h.bento_truncate( self.abstract, :length => max_chars )
end
summary
end | [
"def",
"render_summary",
"summary",
"=",
"nil",
"max_chars",
"=",
"(",
"self",
".",
"display_configuration",
".",
"try",
"{",
"|",
"h",
"|",
"h",
"[",
"\"summary_max_chars\"",
"]",
"}",
")",
"||",
"280",
"if",
"self",
".",
"snippets",
".",
"length",
">",
"0",
"&&",
"!",
"(",
"self",
".",
"display_configuration",
".",
"try",
"{",
"|",
"h",
"|",
"h",
"[",
"\"prefer_abstract_as_summary\"",
"]",
"}",
"&&",
"self",
".",
"abstract",
")",
"summary",
"=",
"self",
".",
"snippets",
".",
"first",
"self",
".",
"snippets",
".",
"slice",
"(",
"1",
",",
"self",
".",
"snippets",
".",
"length",
")",
".",
"each",
"do",
"|",
"snippet",
"|",
"summary",
"+=",
"' '",
".",
"html_safe",
"+",
"snippet",
"if",
"(",
"summary",
".",
"length",
"+",
"snippet",
".",
"length",
")",
"<=",
"max_chars",
"end",
"else",
"summary",
"=",
"_h",
".",
"bento_truncate",
"(",
"self",
".",
"abstract",
",",
":length",
"=>",
"max_chars",
")",
"end",
"summary",
"end"
] | A summary. If config.for_dispaly.prefer_snippets_as_summary is set to true
then prefers that, otherwise abstract.
Truncates for display. | [
"A",
"summary",
".",
"If",
"config",
".",
"for_dispaly",
".",
"prefer_snippets_as_summary",
"is",
"set",
"to",
"true",
"then",
"prefers",
"that",
"otherwise",
"abstract",
"."
] | f567ead386d4a2e283c03b787e7c0d620567c9de | https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/item_decorators/bento_search/standard_decorator.rb#L128-L144 | train |
danieldreier/autosign | lib/autosign/config.rb | Autosign.Config.configfile | def configfile
@log.debug "Finding config file"
@config_file_paths.each { |file|
@log.debug "Checking if file '#{file}' exists"
if File.file?(file)
@log.debug "Reading config file from: " + file
config_file = File.read(file)
parsed_config_file = YAML.load(config_file)
#parsed_config_file = IniParse.parse(config_file).to_hash
@log.debug "configuration read from config file: " + parsed_config_file.to_s
return parsed_config_file if parsed_config_file.is_a?(Hash)
else
@log.debug "Configuration file '#{file}' not found"
end
}
return {}
end | ruby | def configfile
@log.debug "Finding config file"
@config_file_paths.each { |file|
@log.debug "Checking if file '#{file}' exists"
if File.file?(file)
@log.debug "Reading config file from: " + file
config_file = File.read(file)
parsed_config_file = YAML.load(config_file)
#parsed_config_file = IniParse.parse(config_file).to_hash
@log.debug "configuration read from config file: " + parsed_config_file.to_s
return parsed_config_file if parsed_config_file.is_a?(Hash)
else
@log.debug "Configuration file '#{file}' not found"
end
}
return {}
end | [
"def",
"configfile",
"@log",
".",
"debug",
"\"Finding config file\"",
"@config_file_paths",
".",
"each",
"{",
"|",
"file",
"|",
"@log",
".",
"debug",
"\"Checking if file '#{file}' exists\"",
"if",
"File",
".",
"file?",
"(",
"file",
")",
"@log",
".",
"debug",
"\"Reading config file from: \"",
"+",
"file",
"config_file",
"=",
"File",
".",
"read",
"(",
"file",
")",
"parsed_config_file",
"=",
"YAML",
".",
"load",
"(",
"config_file",
")",
"@log",
".",
"debug",
"\"configuration read from config file: \"",
"+",
"parsed_config_file",
".",
"to_s",
"return",
"parsed_config_file",
"if",
"parsed_config_file",
".",
"is_a?",
"(",
"Hash",
")",
"else",
"@log",
".",
"debug",
"\"Configuration file '#{file}' not found\"",
"end",
"}",
"return",
"{",
"}",
"end"
] | Locate the configuration file, parse it from INI-format, and return
the results as a hash. Returns an empty hash if no config file is found.
@return [Hash] configuration settings loaded from INI file | [
"Locate",
"the",
"configuration",
"file",
"parse",
"it",
"from",
"INI",
"-",
"format",
"and",
"return",
"the",
"results",
"as",
"a",
"hash",
".",
"Returns",
"an",
"empty",
"hash",
"if",
"no",
"config",
"file",
"is",
"found",
"."
] | d457eeec5b2084ff63ee4555f7de97cf87be1aca | https://github.com/danieldreier/autosign/blob/d457eeec5b2084ff63ee4555f7de97cf87be1aca/lib/autosign/config.rb#L93-L109 | train |
danieldreier/autosign | lib/autosign/config.rb | Autosign.Config.validate_config_file | def validate_config_file(configfile = location)
@log.debug "validating config file"
unless File.file?(configfile)
@log.error "configuration file not found at: #{configfile}"
raise Autosign::Exceptions::NotFound
end
# check if file is world-readable
if File.world_readable?(configfile) or File.world_writable?(configfile)
@log.error "configuration file #{configfile} is world-readable or world-writable, which is a security risk"
raise Autosign::Exceptions::Permissions
end
configfile
end | ruby | def validate_config_file(configfile = location)
@log.debug "validating config file"
unless File.file?(configfile)
@log.error "configuration file not found at: #{configfile}"
raise Autosign::Exceptions::NotFound
end
# check if file is world-readable
if File.world_readable?(configfile) or File.world_writable?(configfile)
@log.error "configuration file #{configfile} is world-readable or world-writable, which is a security risk"
raise Autosign::Exceptions::Permissions
end
configfile
end | [
"def",
"validate_config_file",
"(",
"configfile",
"=",
"location",
")",
"@log",
".",
"debug",
"\"validating config file\"",
"unless",
"File",
".",
"file?",
"(",
"configfile",
")",
"@log",
".",
"error",
"\"configuration file not found at: #{configfile}\"",
"raise",
"Autosign",
"::",
"Exceptions",
"::",
"NotFound",
"end",
"if",
"File",
".",
"world_readable?",
"(",
"configfile",
")",
"or",
"File",
".",
"world_writable?",
"(",
"configfile",
")",
"@log",
".",
"error",
"\"configuration file #{configfile} is world-readable or world-writable, which is a security risk\"",
"raise",
"Autosign",
"::",
"Exceptions",
"::",
"Permissions",
"end",
"configfile",
"end"
] | Validate configuration file
Raises an exception if the config file cannot be validated
@param configfile [String] the absolute path of the config file to validate
@return [String] the absolute path of the config file | [
"Validate",
"configuration",
"file",
"Raises",
"an",
"exception",
"if",
"the",
"config",
"file",
"cannot",
"be",
"validated"
] | d457eeec5b2084ff63ee4555f7de97cf87be1aca | https://github.com/danieldreier/autosign/blob/d457eeec5b2084ff63ee4555f7de97cf87be1aca/lib/autosign/config.rb#L116-L130 | train |
jrochkind/bento_search | app/models/bento_search/ris_creator.rb | BentoSearch.RISCreator.format_author_name | def format_author_name(author)
if author.last.present? && author.first.present?
str = "#{author.last}, #{author.first}"
if author.middle.present?
middle = author.middle
middle += "." if middle.length == 1
str += " #{middle}"
end
return str
elsif author.display.present?
return author.display
elsif author.last.present?
return author.last?
else
return nil
end
end | ruby | def format_author_name(author)
if author.last.present? && author.first.present?
str = "#{author.last}, #{author.first}"
if author.middle.present?
middle = author.middle
middle += "." if middle.length == 1
str += " #{middle}"
end
return str
elsif author.display.present?
return author.display
elsif author.last.present?
return author.last?
else
return nil
end
end | [
"def",
"format_author_name",
"(",
"author",
")",
"if",
"author",
".",
"last",
".",
"present?",
"&&",
"author",
".",
"first",
".",
"present?",
"str",
"=",
"\"#{author.last}, #{author.first}\"",
"if",
"author",
".",
"middle",
".",
"present?",
"middle",
"=",
"author",
".",
"middle",
"middle",
"+=",
"\".\"",
"if",
"middle",
".",
"length",
"==",
"1",
"str",
"+=",
"\" #{middle}\"",
"end",
"return",
"str",
"elsif",
"author",
".",
"display",
".",
"present?",
"return",
"author",
".",
"display",
"elsif",
"author",
".",
"last",
".",
"present?",
"return",
"author",
".",
"last?",
"else",
"return",
"nil",
"end",
"end"
] | RIS wants `Last, First M.`, we'll do what we can. | [
"RIS",
"wants",
"Last",
"First",
"M",
".",
"we",
"ll",
"do",
"what",
"we",
"can",
"."
] | f567ead386d4a2e283c03b787e7c0d620567c9de | https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/models/bento_search/ris_creator.rb#L147-L163 | train |
sendwithus/sendwithus_ruby | lib/send_with_us/api.rb | SendWithUs.Api.send_email | def send_email(email_id, to, options = {})
if email_id.nil?
raise SendWithUs::ApiNilEmailId, 'email_id cannot be nil'
end
payload = {
email_id: email_id,
recipient: to
}
if options[:data] && options[:data].any?
payload[:email_data] = options[:data]
end
if options[:from] && options[:from].any?
payload[:sender] = options[:from]
end
if options[:cc] && options[:cc].any?
payload[:cc] = options[:cc]
end
if options[:bcc] && options[:bcc].any?
payload[:bcc] = options[:bcc]
end
if options[:esp_account]
payload[:esp_account] = options[:esp_account]
end
if options[:version_name]
payload[:version_name] = options[:version_name]
end
if options[:headers] && options[:headers].any?
payload[:headers] = options[:headers]
end
if options[:tags] && options[:tags].any?
payload[:tags] = options[:tags]
end
if options[:locale]
payload[:locale] = options[:locale]
end
if options[:files] && options[:files].any?
payload[:files] = options[:files].map do |file_data|
SendWithUs::File.new(file_data).to_h
end
end
SendWithUs::ApiRequest.new(@configuration).post(:send, payload.to_json)
end | ruby | def send_email(email_id, to, options = {})
if email_id.nil?
raise SendWithUs::ApiNilEmailId, 'email_id cannot be nil'
end
payload = {
email_id: email_id,
recipient: to
}
if options[:data] && options[:data].any?
payload[:email_data] = options[:data]
end
if options[:from] && options[:from].any?
payload[:sender] = options[:from]
end
if options[:cc] && options[:cc].any?
payload[:cc] = options[:cc]
end
if options[:bcc] && options[:bcc].any?
payload[:bcc] = options[:bcc]
end
if options[:esp_account]
payload[:esp_account] = options[:esp_account]
end
if options[:version_name]
payload[:version_name] = options[:version_name]
end
if options[:headers] && options[:headers].any?
payload[:headers] = options[:headers]
end
if options[:tags] && options[:tags].any?
payload[:tags] = options[:tags]
end
if options[:locale]
payload[:locale] = options[:locale]
end
if options[:files] && options[:files].any?
payload[:files] = options[:files].map do |file_data|
SendWithUs::File.new(file_data).to_h
end
end
SendWithUs::ApiRequest.new(@configuration).post(:send, payload.to_json)
end | [
"def",
"send_email",
"(",
"email_id",
",",
"to",
",",
"options",
"=",
"{",
"}",
")",
"if",
"email_id",
".",
"nil?",
"raise",
"SendWithUs",
"::",
"ApiNilEmailId",
",",
"'email_id cannot be nil'",
"end",
"payload",
"=",
"{",
"email_id",
":",
"email_id",
",",
"recipient",
":",
"to",
"}",
"if",
"options",
"[",
":data",
"]",
"&&",
"options",
"[",
":data",
"]",
".",
"any?",
"payload",
"[",
":email_data",
"]",
"=",
"options",
"[",
":data",
"]",
"end",
"if",
"options",
"[",
":from",
"]",
"&&",
"options",
"[",
":from",
"]",
".",
"any?",
"payload",
"[",
":sender",
"]",
"=",
"options",
"[",
":from",
"]",
"end",
"if",
"options",
"[",
":cc",
"]",
"&&",
"options",
"[",
":cc",
"]",
".",
"any?",
"payload",
"[",
":cc",
"]",
"=",
"options",
"[",
":cc",
"]",
"end",
"if",
"options",
"[",
":bcc",
"]",
"&&",
"options",
"[",
":bcc",
"]",
".",
"any?",
"payload",
"[",
":bcc",
"]",
"=",
"options",
"[",
":bcc",
"]",
"end",
"if",
"options",
"[",
":esp_account",
"]",
"payload",
"[",
":esp_account",
"]",
"=",
"options",
"[",
":esp_account",
"]",
"end",
"if",
"options",
"[",
":version_name",
"]",
"payload",
"[",
":version_name",
"]",
"=",
"options",
"[",
":version_name",
"]",
"end",
"if",
"options",
"[",
":headers",
"]",
"&&",
"options",
"[",
":headers",
"]",
".",
"any?",
"payload",
"[",
":headers",
"]",
"=",
"options",
"[",
":headers",
"]",
"end",
"if",
"options",
"[",
":tags",
"]",
"&&",
"options",
"[",
":tags",
"]",
".",
"any?",
"payload",
"[",
":tags",
"]",
"=",
"options",
"[",
":tags",
"]",
"end",
"if",
"options",
"[",
":locale",
"]",
"payload",
"[",
":locale",
"]",
"=",
"options",
"[",
":locale",
"]",
"end",
"if",
"options",
"[",
":files",
"]",
"&&",
"options",
"[",
":files",
"]",
".",
"any?",
"payload",
"[",
":files",
"]",
"=",
"options",
"[",
":files",
"]",
".",
"map",
"do",
"|",
"file_data",
"|",
"SendWithUs",
"::",
"File",
".",
"new",
"(",
"file_data",
")",
".",
"to_h",
"end",
"end",
"SendWithUs",
"::",
"ApiRequest",
".",
"new",
"(",
"@configuration",
")",
".",
"post",
"(",
":send",
",",
"payload",
".",
"to_json",
")",
"end"
] | Sends the specified email with any optional arguments
* *Args* :
- +email_id+ -> ID of the email to send
- +to+ -> Hash of recipient details
* *Options* :
- +:data+ -> Hash of email data
- +:from+ -> Hash of sender details
- +:cc+ -> Array of CC recipients
- +:bcc+ -> Array of BCC recipients
- +:files+ -> Array of attachments
- +:esp_account+ -> The ESP account to use
- +:version_name+ -> The specific email version to use
- +:headers+ -> Hash of headers
- +:tags+ -> Array of tags
- +:locale+ -> Localization string
* *Notes* :
- "send" is already a ruby-defined method on all classes | [
"Sends",
"the",
"specified",
"email",
"with",
"any",
"optional",
"arguments"
] | e1d54e00e20da17cd032fb8e5b602ef99c7f984a | https://github.com/sendwithus/sendwithus_ruby/blob/e1d54e00e20da17cd032fb8e5b602ef99c7f984a/lib/send_with_us/api.rb#L83-L128 | train |
zorab47/active_admin-duplicatable | lib/active_admin/duplicatable.rb | ActiveAdmin.Duplicatable.enable_resource_duplication_via_form | def enable_resource_duplication_via_form
action_item(*compatible_action_item_parameters) do
if controller.action_methods.include?('new') && authorized?(ActiveAdmin::Auth::CREATE, active_admin_config.resource_class)
link_to(I18n.t(:duplicate_model, default: "Duplicate %{model}", scope: [:active_admin], model: active_admin_config.resource_label), action: :new, _source_id: resource.id)
end
end
controller do
before_action only: :new do
if !params[:_source_id].blank?
source = resource_class.find(params[:_source_id])
@resource ||= source.amoeba_dup if source
end
end
end
end | ruby | def enable_resource_duplication_via_form
action_item(*compatible_action_item_parameters) do
if controller.action_methods.include?('new') && authorized?(ActiveAdmin::Auth::CREATE, active_admin_config.resource_class)
link_to(I18n.t(:duplicate_model, default: "Duplicate %{model}", scope: [:active_admin], model: active_admin_config.resource_label), action: :new, _source_id: resource.id)
end
end
controller do
before_action only: :new do
if !params[:_source_id].blank?
source = resource_class.find(params[:_source_id])
@resource ||= source.amoeba_dup if source
end
end
end
end | [
"def",
"enable_resource_duplication_via_form",
"action_item",
"(",
"*",
"compatible_action_item_parameters",
")",
"do",
"if",
"controller",
".",
"action_methods",
".",
"include?",
"(",
"'new'",
")",
"&&",
"authorized?",
"(",
"ActiveAdmin",
"::",
"Auth",
"::",
"CREATE",
",",
"active_admin_config",
".",
"resource_class",
")",
"link_to",
"(",
"I18n",
".",
"t",
"(",
":duplicate_model",
",",
"default",
":",
"\"Duplicate %{model}\"",
",",
"scope",
":",
"[",
":active_admin",
"]",
",",
"model",
":",
"active_admin_config",
".",
"resource_label",
")",
",",
"action",
":",
":new",
",",
"_source_id",
":",
"resource",
".",
"id",
")",
"end",
"end",
"controller",
"do",
"before_action",
"only",
":",
":new",
"do",
"if",
"!",
"params",
"[",
":_source_id",
"]",
".",
"blank?",
"source",
"=",
"resource_class",
".",
"find",
"(",
"params",
"[",
":_source_id",
"]",
")",
"@resource",
"||=",
"source",
".",
"amoeba_dup",
"if",
"source",
"end",
"end",
"end",
"end"
] | Enables resource duplication via new form.
- Adds a duplicate action button.
- Preloads a duplicated resource on `:new` to pre-fill the form fields.
No return. | [
"Enables",
"resource",
"duplication",
"via",
"new",
"form",
"."
] | 135c1712befcfe3a8af4bdc5c5e1f0f8a2652500 | https://github.com/zorab47/active_admin-duplicatable/blob/135c1712befcfe3a8af4bdc5c5e1f0f8a2652500/lib/active_admin/duplicatable.rb#L41-L56 | train |
zorab47/active_admin-duplicatable | lib/active_admin/duplicatable.rb | ActiveAdmin.Duplicatable.enable_resource_duplication_via_save | def enable_resource_duplication_via_save
action_item(*compatible_action_item_parameters) do
if controller.action_methods.include?('new') && authorized?(ActiveAdmin::Auth::CREATE, active_admin_config.resource_class)
link_to(I18n.t(:duplicate_model, default: "Duplicate %{model}", scope: [:active_admin], model: active_admin_config.resource_label), action: :duplicate)
end
end
member_action :duplicate do
resource = resource_class.find(params[:id])
authorize! ActiveAdmin::Auth::CREATE, resource
duplicate = resource.amoeba_dup
if duplicate.save
redirect_to({ action: :edit, id: duplicate.id }, flash: { notice: "#{active_admin_config.resource_label} was successfully duplicated." })
else
redirect_to({ action: :show }, flash: { error: "#{active_admin_config.resource_label} could not be duplicated." })
end
end
end | ruby | def enable_resource_duplication_via_save
action_item(*compatible_action_item_parameters) do
if controller.action_methods.include?('new') && authorized?(ActiveAdmin::Auth::CREATE, active_admin_config.resource_class)
link_to(I18n.t(:duplicate_model, default: "Duplicate %{model}", scope: [:active_admin], model: active_admin_config.resource_label), action: :duplicate)
end
end
member_action :duplicate do
resource = resource_class.find(params[:id])
authorize! ActiveAdmin::Auth::CREATE, resource
duplicate = resource.amoeba_dup
if duplicate.save
redirect_to({ action: :edit, id: duplicate.id }, flash: { notice: "#{active_admin_config.resource_label} was successfully duplicated." })
else
redirect_to({ action: :show }, flash: { error: "#{active_admin_config.resource_label} could not be duplicated." })
end
end
end | [
"def",
"enable_resource_duplication_via_save",
"action_item",
"(",
"*",
"compatible_action_item_parameters",
")",
"do",
"if",
"controller",
".",
"action_methods",
".",
"include?",
"(",
"'new'",
")",
"&&",
"authorized?",
"(",
"ActiveAdmin",
"::",
"Auth",
"::",
"CREATE",
",",
"active_admin_config",
".",
"resource_class",
")",
"link_to",
"(",
"I18n",
".",
"t",
"(",
":duplicate_model",
",",
"default",
":",
"\"Duplicate %{model}\"",
",",
"scope",
":",
"[",
":active_admin",
"]",
",",
"model",
":",
"active_admin_config",
".",
"resource_label",
")",
",",
"action",
":",
":duplicate",
")",
"end",
"end",
"member_action",
":duplicate",
"do",
"resource",
"=",
"resource_class",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"authorize!",
"ActiveAdmin",
"::",
"Auth",
"::",
"CREATE",
",",
"resource",
"duplicate",
"=",
"resource",
".",
"amoeba_dup",
"if",
"duplicate",
".",
"save",
"redirect_to",
"(",
"{",
"action",
":",
":edit",
",",
"id",
":",
"duplicate",
".",
"id",
"}",
",",
"flash",
":",
"{",
"notice",
":",
"\"#{active_admin_config.resource_label} was successfully duplicated.\"",
"}",
")",
"else",
"redirect_to",
"(",
"{",
"action",
":",
":show",
"}",
",",
"flash",
":",
"{",
"error",
":",
"\"#{active_admin_config.resource_label} could not be duplicated.\"",
"}",
")",
"end",
"end",
"end"
] | Enables resource duplication via save.
- Adds a duplicate action button.
- Duplicates a resource, persists it, and redirects the user to edit
the newly duplicated resource.
No return. | [
"Enables",
"resource",
"duplication",
"via",
"save",
"."
] | 135c1712befcfe3a8af4bdc5c5e1f0f8a2652500 | https://github.com/zorab47/active_admin-duplicatable/blob/135c1712befcfe3a8af4bdc5c5e1f0f8a2652500/lib/active_admin/duplicatable.rb#L65-L84 | train |
zorab47/active_admin-duplicatable | lib/active_admin/duplicatable.rb | ActiveAdmin.Duplicatable.enable_resource_duplication_via_custom_method | def enable_resource_duplication_via_custom_method(method)
action_item(*compatible_action_item_parameters) do
if controller.action_methods.include?('new') && authorized?(ActiveAdmin::Auth::CREATE, active_admin_config.resource_class)
link_to(I18n.t(:duplicate_model, default: "Duplicate %{model}", scope: [:active_admin], model: active_admin_config.resource_label), action: :duplicate)
end
end
member_action :duplicate do
resource = resource_class.find(params[:id])
authorize! ActiveAdmin::Auth::CREATE, resource
begin
duplicate = resource.send method
redirect_to({ action: :edit, id: duplicate.id }, flash: { notice: "#{active_admin_config.resource_label} was successfully duplicated." })
rescue => e
Rails.logger.warn(e)
redirect_to({ action: :show }, flash: { error: "#{active_admin_config.resource_label} could not be duplicated." })
end
end
end | ruby | def enable_resource_duplication_via_custom_method(method)
action_item(*compatible_action_item_parameters) do
if controller.action_methods.include?('new') && authorized?(ActiveAdmin::Auth::CREATE, active_admin_config.resource_class)
link_to(I18n.t(:duplicate_model, default: "Duplicate %{model}", scope: [:active_admin], model: active_admin_config.resource_label), action: :duplicate)
end
end
member_action :duplicate do
resource = resource_class.find(params[:id])
authorize! ActiveAdmin::Auth::CREATE, resource
begin
duplicate = resource.send method
redirect_to({ action: :edit, id: duplicate.id }, flash: { notice: "#{active_admin_config.resource_label} was successfully duplicated." })
rescue => e
Rails.logger.warn(e)
redirect_to({ action: :show }, flash: { error: "#{active_admin_config.resource_label} could not be duplicated." })
end
end
end | [
"def",
"enable_resource_duplication_via_custom_method",
"(",
"method",
")",
"action_item",
"(",
"*",
"compatible_action_item_parameters",
")",
"do",
"if",
"controller",
".",
"action_methods",
".",
"include?",
"(",
"'new'",
")",
"&&",
"authorized?",
"(",
"ActiveAdmin",
"::",
"Auth",
"::",
"CREATE",
",",
"active_admin_config",
".",
"resource_class",
")",
"link_to",
"(",
"I18n",
".",
"t",
"(",
":duplicate_model",
",",
"default",
":",
"\"Duplicate %{model}\"",
",",
"scope",
":",
"[",
":active_admin",
"]",
",",
"model",
":",
"active_admin_config",
".",
"resource_label",
")",
",",
"action",
":",
":duplicate",
")",
"end",
"end",
"member_action",
":duplicate",
"do",
"resource",
"=",
"resource_class",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"authorize!",
"ActiveAdmin",
"::",
"Auth",
"::",
"CREATE",
",",
"resource",
"begin",
"duplicate",
"=",
"resource",
".",
"send",
"method",
"redirect_to",
"(",
"{",
"action",
":",
":edit",
",",
"id",
":",
"duplicate",
".",
"id",
"}",
",",
"flash",
":",
"{",
"notice",
":",
"\"#{active_admin_config.resource_label} was successfully duplicated.\"",
"}",
")",
"rescue",
"=>",
"e",
"Rails",
".",
"logger",
".",
"warn",
"(",
"e",
")",
"redirect_to",
"(",
"{",
"action",
":",
":show",
"}",
",",
"flash",
":",
"{",
"error",
":",
"\"#{active_admin_config.resource_label} could not be duplicated.\"",
"}",
")",
"end",
"end",
"end"
] | Enables resource duplication via a custom method
- Adds a duplicate action button.
- Calls a custom duplication method on the model. The method should
handle any copying of data and persistence of the new record.
- Redirects the user to edit the newly duplicated resource.
No return. | [
"Enables",
"resource",
"duplication",
"via",
"a",
"custom",
"method"
] | 135c1712befcfe3a8af4bdc5c5e1f0f8a2652500 | https://github.com/zorab47/active_admin-duplicatable/blob/135c1712befcfe3a8af4bdc5c5e1f0f8a2652500/lib/active_admin/duplicatable.rb#L94-L114 | train |
dilcom/gnuplotrb | lib/gnuplotrb/mixins/error_handling.rb | GnuplotRB.ErrorHandling.check_errors | def check_errors(raw: false)
return if @err_array.empty?
command = ''
rest = ''
@semaphore.synchronize do
command = @err_array.first
rest = @err_array[1..-1].join('; ')
@err_array.clear
end
message = if raw
"#{command};#{rest}}"
else
"Error in previous command (\"#{command}\"): \"#{rest}\""
end
fail GnuplotError, message
end | ruby | def check_errors(raw: false)
return if @err_array.empty?
command = ''
rest = ''
@semaphore.synchronize do
command = @err_array.first
rest = @err_array[1..-1].join('; ')
@err_array.clear
end
message = if raw
"#{command};#{rest}}"
else
"Error in previous command (\"#{command}\"): \"#{rest}\""
end
fail GnuplotError, message
end | [
"def",
"check_errors",
"(",
"raw",
":",
"false",
")",
"return",
"if",
"@err_array",
".",
"empty?",
"command",
"=",
"''",
"rest",
"=",
"''",
"@semaphore",
".",
"synchronize",
"do",
"command",
"=",
"@err_array",
".",
"first",
"rest",
"=",
"@err_array",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"join",
"(",
"'; '",
")",
"@err_array",
".",
"clear",
"end",
"message",
"=",
"if",
"raw",
"\"#{command};#{rest}}\"",
"else",
"\"Error in previous command (\\\"#{command}\\\"): \\\"#{rest}\\\"\"",
"end",
"fail",
"GnuplotError",
",",
"message",
"end"
] | Check if there were errors in previous commands.
Throws GnuplotError in case of any errors. | [
"Check",
"if",
"there",
"were",
"errors",
"in",
"previous",
"commands",
".",
"Throws",
"GnuplotError",
"in",
"case",
"of",
"any",
"errors",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/mixins/error_handling.rb#L14-L29 | train |
dilcom/gnuplotrb | lib/gnuplotrb/mixins/error_handling.rb | GnuplotRB.ErrorHandling.handle_stderr | def handle_stderr(stream)
@err_array = []
# synchronize access to @err_array
@semaphore = Mutex.new
Thread.new do
until (line = stream.gets).nil?
line.strip!
@semaphore.synchronize { @err_array << line if line.size > 3 }
end
end
end | ruby | def handle_stderr(stream)
@err_array = []
# synchronize access to @err_array
@semaphore = Mutex.new
Thread.new do
until (line = stream.gets).nil?
line.strip!
@semaphore.synchronize { @err_array << line if line.size > 3 }
end
end
end | [
"def",
"handle_stderr",
"(",
"stream",
")",
"@err_array",
"=",
"[",
"]",
"@semaphore",
"=",
"Mutex",
".",
"new",
"Thread",
".",
"new",
"do",
"until",
"(",
"line",
"=",
"stream",
".",
"gets",
")",
".",
"nil?",
"line",
".",
"strip!",
"@semaphore",
".",
"synchronize",
"{",
"@err_array",
"<<",
"line",
"if",
"line",
".",
"size",
">",
"3",
"}",
"end",
"end",
"end"
] | Start new thread that will read stderr given as stream
and add errors into @err_array. | [
"Start",
"new",
"thread",
"that",
"will",
"read",
"stderr",
"given",
"as",
"stream",
"and",
"add",
"errors",
"into"
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/mixins/error_handling.rb#L36-L46 | train |
dilcom/gnuplotrb | lib/gnuplotrb/mixins/option_handling.rb | GnuplotRB.OptionHandling.option | def option(key, *value)
if value.empty?
value = options[key]
value = value[0] if value && value.size == 1
value
else
options(key => value)
end
end | ruby | def option(key, *value)
if value.empty?
value = options[key]
value = value[0] if value && value.size == 1
value
else
options(key => value)
end
end | [
"def",
"option",
"(",
"key",
",",
"*",
"value",
")",
"if",
"value",
".",
"empty?",
"value",
"=",
"options",
"[",
"key",
"]",
"value",
"=",
"value",
"[",
"0",
"]",
"if",
"value",
"&&",
"value",
".",
"size",
"==",
"1",
"value",
"else",
"options",
"(",
"key",
"=>",
"value",
")",
"end",
"end"
] | Return current option value if no value given. Create new
object with given option set if value given. | [
"Return",
"current",
"option",
"value",
"if",
"no",
"value",
"given",
".",
"Create",
"new",
"object",
"with",
"given",
"option",
"set",
"if",
"value",
"given",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/mixins/option_handling.rb#L174-L182 | train |
mezis/blurrily | lib/blurrily/client.rb | Blurrily.Client.put | def put(needle, ref, weight = 0)
check_valid_needle(needle)
check_valid_ref(ref)
raise(ArgumentError, "WEIGHT value must be in #{WEIGHT_RANGE}") unless WEIGHT_RANGE.include?(weight)
cmd = ["PUT", @db_name, needle, ref, weight]
send_cmd_and_get_results(cmd)
return
end | ruby | def put(needle, ref, weight = 0)
check_valid_needle(needle)
check_valid_ref(ref)
raise(ArgumentError, "WEIGHT value must be in #{WEIGHT_RANGE}") unless WEIGHT_RANGE.include?(weight)
cmd = ["PUT", @db_name, needle, ref, weight]
send_cmd_and_get_results(cmd)
return
end | [
"def",
"put",
"(",
"needle",
",",
"ref",
",",
"weight",
"=",
"0",
")",
"check_valid_needle",
"(",
"needle",
")",
"check_valid_ref",
"(",
"ref",
")",
"raise",
"(",
"ArgumentError",
",",
"\"WEIGHT value must be in #{WEIGHT_RANGE}\"",
")",
"unless",
"WEIGHT_RANGE",
".",
"include?",
"(",
"weight",
")",
"cmd",
"=",
"[",
"\"PUT\"",
",",
"@db_name",
",",
"needle",
",",
"ref",
",",
"weight",
"]",
"send_cmd_and_get_results",
"(",
"cmd",
")",
"return",
"end"
] | Index a given record.
@param db_name The name of the data store being targeted. Required
@param needle The string you wish to index. Must not contain tabs. Required
@param ref The indentifying value of the record being indexed. Must be numeric. Required
@param weight Weight of this particular reference. Default 0. Don't change unless you know what you're doing. Optional.
Examples
```
@client.put('location_en', 'London', 123, 0)
# => OK
```
@returns something to let you know that all is well. | [
"Index",
"a",
"given",
"record",
"."
] | 496deee64a7e1c04b1241968dab46250e7b36569 | https://github.com/mezis/blurrily/blob/496deee64a7e1c04b1241968dab46250e7b36569/lib/blurrily/client.rb#L76-L84 | train |
sparkleformation/sfn-parameters | lib/sfn-parameters/utils.rb | SfnParameters.Utils.lock_content | def lock_content(content)
content = content.to_smash
content.merge!(:sfn_lock_enabled => true)
safe = SfnParameters::Safe.build(
config.fetch(:sfn_parameters, :safe, Smash.new)
)
safe.lock(dump_json(content))
end | ruby | def lock_content(content)
content = content.to_smash
content.merge!(:sfn_lock_enabled => true)
safe = SfnParameters::Safe.build(
config.fetch(:sfn_parameters, :safe, Smash.new)
)
safe.lock(dump_json(content))
end | [
"def",
"lock_content",
"(",
"content",
")",
"content",
"=",
"content",
".",
"to_smash",
"content",
".",
"merge!",
"(",
":sfn_lock_enabled",
"=>",
"true",
")",
"safe",
"=",
"SfnParameters",
"::",
"Safe",
".",
"build",
"(",
"config",
".",
"fetch",
"(",
":sfn_parameters",
",",
":safe",
",",
"Smash",
".",
"new",
")",
")",
"safe",
".",
"lock",
"(",
"dump_json",
"(",
"content",
")",
")",
"end"
] | Lock the given content
@param content [Hash] content to lock
@return [Hash] locked content | [
"Lock",
"the",
"given",
"content"
] | 9699a61327f1ef0603d967d0b597824290aa9001 | https://github.com/sparkleformation/sfn-parameters/blob/9699a61327f1ef0603d967d0b597824290aa9001/lib/sfn-parameters/utils.rb#L11-L18 | train |
sparkleformation/sfn-parameters | lib/sfn-parameters/utils.rb | SfnParameters.Utils.unlock_content | def unlock_content(content)
content = content.to_smash
if content[:sfn_parameters_lock]
safe = SfnParameters::Safe.build(
config.fetch(:sfn_parameters, :safe, Smash.new)
)
load_json(safe.unlock(content)).to_smash.merge(:sfn_lock_enabled => true)
else
content
end
end | ruby | def unlock_content(content)
content = content.to_smash
if content[:sfn_parameters_lock]
safe = SfnParameters::Safe.build(
config.fetch(:sfn_parameters, :safe, Smash.new)
)
load_json(safe.unlock(content)).to_smash.merge(:sfn_lock_enabled => true)
else
content
end
end | [
"def",
"unlock_content",
"(",
"content",
")",
"content",
"=",
"content",
".",
"to_smash",
"if",
"content",
"[",
":sfn_parameters_lock",
"]",
"safe",
"=",
"SfnParameters",
"::",
"Safe",
".",
"build",
"(",
"config",
".",
"fetch",
"(",
":sfn_parameters",
",",
":safe",
",",
"Smash",
".",
"new",
")",
")",
"load_json",
"(",
"safe",
".",
"unlock",
"(",
"content",
")",
")",
".",
"to_smash",
".",
"merge",
"(",
":sfn_lock_enabled",
"=>",
"true",
")",
"else",
"content",
"end",
"end"
] | Unlock given content
@param content [Hash] content to unlock
@return [Hash] unlocked content | [
"Unlock",
"given",
"content"
] | 9699a61327f1ef0603d967d0b597824290aa9001 | https://github.com/sparkleformation/sfn-parameters/blob/9699a61327f1ef0603d967d0b597824290aa9001/lib/sfn-parameters/utils.rb#L24-L34 | train |
mediaburst/clockwork-ruby | lib/clockwork/api.rb | Clockwork.API.balance | def balance
xml = Clockwork::XML::Balance.build( self )
response = Clockwork::HTTP.post( Clockwork::API::BALANCE_URL, xml, @use_ssl )
balance = Clockwork::XML::Balance.parse( response )
end | ruby | def balance
xml = Clockwork::XML::Balance.build( self )
response = Clockwork::HTTP.post( Clockwork::API::BALANCE_URL, xml, @use_ssl )
balance = Clockwork::XML::Balance.parse( response )
end | [
"def",
"balance",
"xml",
"=",
"Clockwork",
"::",
"XML",
"::",
"Balance",
".",
"build",
"(",
"self",
")",
"response",
"=",
"Clockwork",
"::",
"HTTP",
".",
"post",
"(",
"Clockwork",
"::",
"API",
"::",
"BALANCE_URL",
",",
"xml",
",",
"@use_ssl",
")",
"balance",
"=",
"Clockwork",
"::",
"XML",
"::",
"Balance",
".",
"parse",
"(",
"response",
")",
"end"
] | Check the remaining credit for this account.
@raise Clockwork::Error::Authentication - if API login details are incorrect
@return [integer] Number of messages remaining | [
"Check",
"the",
"remaining",
"credit",
"for",
"this",
"account",
"."
] | 1c2a00ea56f68e9e8144601862b82e65ce77df85 | https://github.com/mediaburst/clockwork-ruby/blob/1c2a00ea56f68e9e8144601862b82e65ce77df85/lib/clockwork/api.rb#L131-L135 | train |
dilcom/gnuplotrb | lib/gnuplotrb/multiplot.rb | GnuplotRB.Multiplot.mix_options | def mix_options(options)
all_options = @options.merge(options)
specific_options, plot_options = all_options.partition { |key, _value| specific_option?(key) }
yield(plot_options, default_options.merge(specific_options))
end | ruby | def mix_options(options)
all_options = @options.merge(options)
specific_options, plot_options = all_options.partition { |key, _value| specific_option?(key) }
yield(plot_options, default_options.merge(specific_options))
end | [
"def",
"mix_options",
"(",
"options",
")",
"all_options",
"=",
"@options",
".",
"merge",
"(",
"options",
")",
"specific_options",
",",
"plot_options",
"=",
"all_options",
".",
"partition",
"{",
"|",
"key",
",",
"_value",
"|",
"specific_option?",
"(",
"key",
")",
"}",
"yield",
"(",
"plot_options",
",",
"default_options",
".",
"merge",
"(",
"specific_options",
")",
")",
"end"
] | Takes all options and splits them into specific and
others. Requires a block where this two classes should
be mixed. | [
"Takes",
"all",
"options",
"and",
"splits",
"them",
"into",
"specific",
"and",
"others",
".",
"Requires",
"a",
"block",
"where",
"this",
"two",
"classes",
"should",
"be",
"mixed",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/multiplot.rb#L255-L259 | train |
flamontagne/rrschedule | lib/rrschedule.rb | RRSchedule.Schedule.generate | def generate(params={})
raise "You need to specify at least 1 team" if @teams.nil? || @teams.empty?
raise "You need to specify at least 1 rule" if @rules.nil? || @rules.empty?
arrange_flights
init_stats
@gamedays = []; @rounds = []
@flights.each_with_index do |teams,flight_id|
current_cycle = current_round = 0
teams = teams.sort_by{rand} if @shuffle
#loop to generate the whole round-robin(s) for the current flight
begin
t = teams.clone
games = []
#process one round
while !t.empty? do
team_a = t.shift
team_b = t.reverse!.shift
t.reverse!
x = (current_cycle % 2) == 0 ? [team_a,team_b] : [team_b,team_a]
matchup = {:team_a => x[0], :team_b => x[1]}
games << matchup
end
#done processing round
current_round += 1
#Team rotation (the first team is fixed)
teams = teams.insert(1,teams.delete_at(teams.size-1))
#add the round in memory
@rounds ||= []
@rounds[flight_id] ||= []
@rounds[flight_id] << Round.new(
:round => current_round,
:cycle => current_cycle + 1,
:round_with_cycle => current_cycle * (teams.size-1) + current_round,
:flight => flight_id,
:games => games.collect { |g|
Game.new(
:team_a => g[:team_a],
:team_b => g[:team_b]
)
}
)
#done adding round
#have we completed a full round-robin for the current flight?
if current_round == teams.size-1
current_cycle += 1
current_round = 0 if current_cycle < self.cycles
end
end until current_round == teams.size-1 && current_cycle==self.cycles
end
dispatch_games(@rounds)
self
end | ruby | def generate(params={})
raise "You need to specify at least 1 team" if @teams.nil? || @teams.empty?
raise "You need to specify at least 1 rule" if @rules.nil? || @rules.empty?
arrange_flights
init_stats
@gamedays = []; @rounds = []
@flights.each_with_index do |teams,flight_id|
current_cycle = current_round = 0
teams = teams.sort_by{rand} if @shuffle
#loop to generate the whole round-robin(s) for the current flight
begin
t = teams.clone
games = []
#process one round
while !t.empty? do
team_a = t.shift
team_b = t.reverse!.shift
t.reverse!
x = (current_cycle % 2) == 0 ? [team_a,team_b] : [team_b,team_a]
matchup = {:team_a => x[0], :team_b => x[1]}
games << matchup
end
#done processing round
current_round += 1
#Team rotation (the first team is fixed)
teams = teams.insert(1,teams.delete_at(teams.size-1))
#add the round in memory
@rounds ||= []
@rounds[flight_id] ||= []
@rounds[flight_id] << Round.new(
:round => current_round,
:cycle => current_cycle + 1,
:round_with_cycle => current_cycle * (teams.size-1) + current_round,
:flight => flight_id,
:games => games.collect { |g|
Game.new(
:team_a => g[:team_a],
:team_b => g[:team_b]
)
}
)
#done adding round
#have we completed a full round-robin for the current flight?
if current_round == teams.size-1
current_cycle += 1
current_round = 0 if current_cycle < self.cycles
end
end until current_round == teams.size-1 && current_cycle==self.cycles
end
dispatch_games(@rounds)
self
end | [
"def",
"generate",
"(",
"params",
"=",
"{",
"}",
")",
"raise",
"\"You need to specify at least 1 team\"",
"if",
"@teams",
".",
"nil?",
"||",
"@teams",
".",
"empty?",
"raise",
"\"You need to specify at least 1 rule\"",
"if",
"@rules",
".",
"nil?",
"||",
"@rules",
".",
"empty?",
"arrange_flights",
"init_stats",
"@gamedays",
"=",
"[",
"]",
";",
"@rounds",
"=",
"[",
"]",
"@flights",
".",
"each_with_index",
"do",
"|",
"teams",
",",
"flight_id",
"|",
"current_cycle",
"=",
"current_round",
"=",
"0",
"teams",
"=",
"teams",
".",
"sort_by",
"{",
"rand",
"}",
"if",
"@shuffle",
"begin",
"t",
"=",
"teams",
".",
"clone",
"games",
"=",
"[",
"]",
"while",
"!",
"t",
".",
"empty?",
"do",
"team_a",
"=",
"t",
".",
"shift",
"team_b",
"=",
"t",
".",
"reverse!",
".",
"shift",
"t",
".",
"reverse!",
"x",
"=",
"(",
"current_cycle",
"%",
"2",
")",
"==",
"0",
"?",
"[",
"team_a",
",",
"team_b",
"]",
":",
"[",
"team_b",
",",
"team_a",
"]",
"matchup",
"=",
"{",
":team_a",
"=>",
"x",
"[",
"0",
"]",
",",
":team_b",
"=>",
"x",
"[",
"1",
"]",
"}",
"games",
"<<",
"matchup",
"end",
"current_round",
"+=",
"1",
"teams",
"=",
"teams",
".",
"insert",
"(",
"1",
",",
"teams",
".",
"delete_at",
"(",
"teams",
".",
"size",
"-",
"1",
")",
")",
"@rounds",
"||=",
"[",
"]",
"@rounds",
"[",
"flight_id",
"]",
"||=",
"[",
"]",
"@rounds",
"[",
"flight_id",
"]",
"<<",
"Round",
".",
"new",
"(",
":round",
"=>",
"current_round",
",",
":cycle",
"=>",
"current_cycle",
"+",
"1",
",",
":round_with_cycle",
"=>",
"current_cycle",
"*",
"(",
"teams",
".",
"size",
"-",
"1",
")",
"+",
"current_round",
",",
":flight",
"=>",
"flight_id",
",",
":games",
"=>",
"games",
".",
"collect",
"{",
"|",
"g",
"|",
"Game",
".",
"new",
"(",
":team_a",
"=>",
"g",
"[",
":team_a",
"]",
",",
":team_b",
"=>",
"g",
"[",
":team_b",
"]",
")",
"}",
")",
"if",
"current_round",
"==",
"teams",
".",
"size",
"-",
"1",
"current_cycle",
"+=",
"1",
"current_round",
"=",
"0",
"if",
"current_cycle",
"<",
"self",
".",
"cycles",
"end",
"end",
"until",
"current_round",
"==",
"teams",
".",
"size",
"-",
"1",
"&&",
"current_cycle",
"==",
"self",
".",
"cycles",
"end",
"dispatch_games",
"(",
"@rounds",
")",
"self",
"end"
] | This will generate the schedule based on the various parameters | [
"This",
"will",
"generate",
"the",
"schedule",
"based",
"on",
"the",
"various",
"parameters"
] | 7b334205e38901786a7569a6e96e49c24f9b425e | https://github.com/flamontagne/rrschedule/blob/7b334205e38901786a7569a6e96e49c24f9b425e/lib/rrschedule.rb#L24-L89 | train |
flamontagne/rrschedule | lib/rrschedule.rb | RRSchedule.Schedule.to_s | def to_s
res = ""
res << "#{self.gamedays.size.to_s} gamedays\n"
self.gamedays.each do |gd|
res << gd.date.strftime("%Y-%m-%d") + "\n"
res << "==========\n"
gd.games.sort{|g1,g2| g1.gt == g2.gt ? g1.ps <=> g2.ps : g1.gt <=> g2.gt}.each do |g|
res << "#{g.ta.to_s} VS #{g.tb.to_s} on playing surface #{g.ps} at #{g.gt.strftime("%I:%M %p")}\n"
end
res << "\n"
end
res
end | ruby | def to_s
res = ""
res << "#{self.gamedays.size.to_s} gamedays\n"
self.gamedays.each do |gd|
res << gd.date.strftime("%Y-%m-%d") + "\n"
res << "==========\n"
gd.games.sort{|g1,g2| g1.gt == g2.gt ? g1.ps <=> g2.ps : g1.gt <=> g2.gt}.each do |g|
res << "#{g.ta.to_s} VS #{g.tb.to_s} on playing surface #{g.ps} at #{g.gt.strftime("%I:%M %p")}\n"
end
res << "\n"
end
res
end | [
"def",
"to_s",
"res",
"=",
"\"\"",
"res",
"<<",
"\"#{self.gamedays.size.to_s} gamedays\\n\"",
"self",
".",
"gamedays",
".",
"each",
"do",
"|",
"gd",
"|",
"res",
"<<",
"gd",
".",
"date",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"+",
"\"\\n\"",
"res",
"<<",
"\"==========\\n\"",
"gd",
".",
"games",
".",
"sort",
"{",
"|",
"g1",
",",
"g2",
"|",
"g1",
".",
"gt",
"==",
"g2",
".",
"gt",
"?",
"g1",
".",
"ps",
"<=>",
"g2",
".",
"ps",
":",
"g1",
".",
"gt",
"<=>",
"g2",
".",
"gt",
"}",
".",
"each",
"do",
"|",
"g",
"|",
"res",
"<<",
"\"#{g.ta.to_s} VS #{g.tb.to_s} on playing surface #{g.ps} at #{g.gt.strftime(\"%I:%M %p\")}\\n\"",
"end",
"res",
"<<",
"\"\\n\"",
"end",
"res",
"end"
] | human readable schedule | [
"human",
"readable",
"schedule"
] | 7b334205e38901786a7569a6e96e49c24f9b425e | https://github.com/flamontagne/rrschedule/blob/7b334205e38901786a7569a6e96e49c24f9b425e/lib/rrschedule.rb#L101-L113 | train |
flamontagne/rrschedule | lib/rrschedule.rb | RRSchedule.Schedule.next_game_date | def next_game_date(dt,wday)
dt += 1 until wday == dt.wday && !self.exclude_dates.include?(dt)
dt
end | ruby | def next_game_date(dt,wday)
dt += 1 until wday == dt.wday && !self.exclude_dates.include?(dt)
dt
end | [
"def",
"next_game_date",
"(",
"dt",
",",
"wday",
")",
"dt",
"+=",
"1",
"until",
"wday",
"==",
"dt",
".",
"wday",
"&&",
"!",
"self",
".",
"exclude_dates",
".",
"include?",
"(",
"dt",
")",
"dt",
"end"
] | get the next gameday | [
"get",
"the",
"next",
"gameday"
] | 7b334205e38901786a7569a6e96e49c24f9b425e | https://github.com/flamontagne/rrschedule/blob/7b334205e38901786a7569a6e96e49c24f9b425e/lib/rrschedule.rb#L258-L261 | train |
flamontagne/rrschedule | lib/rrschedule.rb | RRSchedule.Schedule.face_to_face | def face_to_face(team_a,team_b)
res=[]
self.gamedays.each do |gd|
res << gd.games.select {|g| (g.team_a == team_a && g.team_b == team_b) || (g.team_a == team_b && g.team_b == team_a)}
end
res.flatten
end | ruby | def face_to_face(team_a,team_b)
res=[]
self.gamedays.each do |gd|
res << gd.games.select {|g| (g.team_a == team_a && g.team_b == team_b) || (g.team_a == team_b && g.team_b == team_a)}
end
res.flatten
end | [
"def",
"face_to_face",
"(",
"team_a",
",",
"team_b",
")",
"res",
"=",
"[",
"]",
"self",
".",
"gamedays",
".",
"each",
"do",
"|",
"gd",
"|",
"res",
"<<",
"gd",
".",
"games",
".",
"select",
"{",
"|",
"g",
"|",
"(",
"g",
".",
"team_a",
"==",
"team_a",
"&&",
"g",
".",
"team_b",
"==",
"team_b",
")",
"||",
"(",
"g",
".",
"team_a",
"==",
"team_b",
"&&",
"g",
".",
"team_b",
"==",
"team_a",
")",
"}",
"end",
"res",
".",
"flatten",
"end"
] | return matchups between two teams | [
"return",
"matchups",
"between",
"two",
"teams"
] | 7b334205e38901786a7569a6e96e49c24f9b425e | https://github.com/flamontagne/rrschedule/blob/7b334205e38901786a7569a6e96e49c24f9b425e/lib/rrschedule.rb#L316-L322 | train |
flamontagne/rrschedule | lib/rrschedule.rb | RRSchedule.Rule.gt= | def gt=(gt)
@gt = Array(gt).empty? ? ["7:00 PM"] : Array(gt)
@gt.collect! do |gt|
begin
DateTime.parse(gt)
rescue
raise "game times must be valid time representations in the string form (e.g. 3:00 PM, 11:00 AM, 18:20, etc)"
end
end
end | ruby | def gt=(gt)
@gt = Array(gt).empty? ? ["7:00 PM"] : Array(gt)
@gt.collect! do |gt|
begin
DateTime.parse(gt)
rescue
raise "game times must be valid time representations in the string form (e.g. 3:00 PM, 11:00 AM, 18:20, etc)"
end
end
end | [
"def",
"gt",
"=",
"(",
"gt",
")",
"@gt",
"=",
"Array",
"(",
"gt",
")",
".",
"empty?",
"?",
"[",
"\"7:00 PM\"",
"]",
":",
"Array",
"(",
"gt",
")",
"@gt",
".",
"collect!",
"do",
"|",
"gt",
"|",
"begin",
"DateTime",
".",
"parse",
"(",
"gt",
")",
"rescue",
"raise",
"\"game times must be valid time representations in the string form (e.g. 3:00 PM, 11:00 AM, 18:20, etc)\"",
"end",
"end",
"end"
] | Array of game times where games are played. Must be valid DateTime objects in the string form | [
"Array",
"of",
"game",
"times",
"where",
"games",
"are",
"played",
".",
"Must",
"be",
"valid",
"DateTime",
"objects",
"in",
"the",
"string",
"form"
] | 7b334205e38901786a7569a6e96e49c24f9b425e | https://github.com/flamontagne/rrschedule/blob/7b334205e38901786a7569a6e96e49c24f9b425e/lib/rrschedule.rb#L369-L378 | train |
dilcom/gnuplotrb | lib/gnuplotrb/staff/terminal.rb | GnuplotRB.Terminal.options_hash_to_string | def options_hash_to_string(options)
result = ''
options.sort_by { |key, _| OPTION_ORDER.find_index(key) || -1 }.each do |key, value|
if value
result += "set #{OptionHandling.option_to_string(key, value)}\n"
else
result += "unset #{key}\n"
end
end
result
end | ruby | def options_hash_to_string(options)
result = ''
options.sort_by { |key, _| OPTION_ORDER.find_index(key) || -1 }.each do |key, value|
if value
result += "set #{OptionHandling.option_to_string(key, value)}\n"
else
result += "unset #{key}\n"
end
end
result
end | [
"def",
"options_hash_to_string",
"(",
"options",
")",
"result",
"=",
"''",
"options",
".",
"sort_by",
"{",
"|",
"key",
",",
"_",
"|",
"OPTION_ORDER",
".",
"find_index",
"(",
"key",
")",
"||",
"-",
"1",
"}",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
"result",
"+=",
"\"set #{OptionHandling.option_to_string(key, value)}\\n\"",
"else",
"result",
"+=",
"\"unset #{key}\\n\"",
"end",
"end",
"result",
"end"
] | Convert given options to gnuplot format.
For "{ opt1: val1, .. , optN: valN }" it returns
set opt1 val1
..
set optN valN
@param ptions [Hash] options to convert
@return [String] options in Gnuplot format | [
"Convert",
"given",
"options",
"to",
"gnuplot",
"format",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/staff/terminal.rb#L91-L101 | train |
cfis/proj4rb | lib/proj4.rb | Proj4.Projection.forwardDeg! | def forwardDeg!(point)
point.x *= Proj4::DEG_TO_RAD
point.y *= Proj4::DEG_TO_RAD
forward!(point)
end | ruby | def forwardDeg!(point)
point.x *= Proj4::DEG_TO_RAD
point.y *= Proj4::DEG_TO_RAD
forward!(point)
end | [
"def",
"forwardDeg!",
"(",
"point",
")",
"point",
".",
"x",
"*=",
"Proj4",
"::",
"DEG_TO_RAD",
"point",
".",
"y",
"*=",
"Proj4",
"::",
"DEG_TO_RAD",
"forward!",
"(",
"point",
")",
"end"
] | Convenience function for calculating a forward projection with degrees instead of radians.
This version works in-place, i.e. the point objects content is overwritten.
call-seq: forwardDeg!(point) -> point | [
"Convenience",
"function",
"for",
"calculating",
"a",
"forward",
"projection",
"with",
"degrees",
"instead",
"of",
"radians",
".",
"This",
"version",
"works",
"in",
"-",
"place",
"i",
".",
"e",
".",
"the",
"point",
"objects",
"content",
"is",
"overwritten",
"."
] | 97a14b5d6884506795953f7c69b8ede73bb84e0f | https://github.com/cfis/proj4rb/blob/97a14b5d6884506795953f7c69b8ede73bb84e0f/lib/proj4.rb#L196-L200 | train |
cfis/proj4rb | lib/proj4.rb | Proj4.Projection.inverseDeg! | def inverseDeg!(point)
inverse!(point)
point.x *= Proj4::RAD_TO_DEG
point.y *= Proj4::RAD_TO_DEG
point
end | ruby | def inverseDeg!(point)
inverse!(point)
point.x *= Proj4::RAD_TO_DEG
point.y *= Proj4::RAD_TO_DEG
point
end | [
"def",
"inverseDeg!",
"(",
"point",
")",
"inverse!",
"(",
"point",
")",
"point",
".",
"x",
"*=",
"Proj4",
"::",
"RAD_TO_DEG",
"point",
".",
"y",
"*=",
"Proj4",
"::",
"RAD_TO_DEG",
"point",
"end"
] | Convenience function for calculating an inverse projection with the result in degrees instead of radians.
This version works in-place, i.e. the point objects content is overwritten.
call-seq: inverseDeg!(point) -> point | [
"Convenience",
"function",
"for",
"calculating",
"an",
"inverse",
"projection",
"with",
"the",
"result",
"in",
"degrees",
"instead",
"of",
"radians",
".",
"This",
"version",
"works",
"in",
"-",
"place",
"i",
".",
"e",
".",
"the",
"point",
"objects",
"content",
"is",
"overwritten",
"."
] | 97a14b5d6884506795953f7c69b8ede73bb84e0f | https://github.com/cfis/proj4rb/blob/97a14b5d6884506795953f7c69b8ede73bb84e0f/lib/proj4.rb#L250-L255 | train |
cfis/proj4rb | lib/proj4.rb | Proj4.Projection.transform_all! | def transform_all!(otherProjection, collection)
collection.each do |point|
transform!(otherProjection, point)
end
collection
end | ruby | def transform_all!(otherProjection, collection)
collection.each do |point|
transform!(otherProjection, point)
end
collection
end | [
"def",
"transform_all!",
"(",
"otherProjection",
",",
"collection",
")",
"collection",
".",
"each",
"do",
"|",
"point",
"|",
"transform!",
"(",
"otherProjection",
",",
"point",
")",
"end",
"collection",
"end"
] | Transforms all points in a collection 'in place' from one projection
to another. The +collection+ object must implement the +each+
method for this to work.
call-seq: transform_all!(destinationProjection, collection) -> collection | [
"Transforms",
"all",
"points",
"in",
"a",
"collection",
"in",
"place",
"from",
"one",
"projection",
"to",
"another",
".",
"The",
"+",
"collection",
"+",
"object",
"must",
"implement",
"the",
"+",
"each",
"+",
"method",
"for",
"this",
"to",
"work",
"."
] | 97a14b5d6884506795953f7c69b8ede73bb84e0f | https://github.com/cfis/proj4rb/blob/97a14b5d6884506795953f7c69b8ede73bb84e0f/lib/proj4.rb#L298-L303 | train |
wework/faraday-sunset | lib/faraday/sunset.rb | Faraday.Sunset.call | def call(env)
@app.call(env).on_complete do |response_env|
datetime = sunset_header(response_env.response_headers)
report_deprecated_usage(env, datetime) unless datetime.nil?
end
end | ruby | def call(env)
@app.call(env).on_complete do |response_env|
datetime = sunset_header(response_env.response_headers)
report_deprecated_usage(env, datetime) unless datetime.nil?
end
end | [
"def",
"call",
"(",
"env",
")",
"@app",
".",
"call",
"(",
"env",
")",
".",
"on_complete",
"do",
"|",
"response_env",
"|",
"datetime",
"=",
"sunset_header",
"(",
"response_env",
".",
"response_headers",
")",
"report_deprecated_usage",
"(",
"env",
",",
"datetime",
")",
"unless",
"datetime",
".",
"nil?",
"end",
"end"
] | Initialize the middleware
@param [Type] app describe app
@param [Hash] options = {}
@return void
@param [Faraday::Env] no idea what this does
@return [Faraday::Response] response from the middleware | [
"Initialize",
"the",
"middleware"
] | aac1e1ac5828ae7d2bed173e5d03fd2c63b5ce6a | https://github.com/wework/faraday-sunset/blob/aac1e1ac5828ae7d2bed173e5d03fd2c63b5ce6a/lib/faraday/sunset.rb#L21-L26 | train |
dilcom/gnuplotrb | lib/gnuplotrb/staff/dataset.rb | GnuplotRB.Dataset.update | def update(data = nil, **options)
if data && @type == :datablock
new_datablock = @data.update(data)
if new_datablock == @data
update_options(options)
else
self.class.new(new_datablock, options)
end
else
update_options(options)
end
end | ruby | def update(data = nil, **options)
if data && @type == :datablock
new_datablock = @data.update(data)
if new_datablock == @data
update_options(options)
else
self.class.new(new_datablock, options)
end
else
update_options(options)
end
end | [
"def",
"update",
"(",
"data",
"=",
"nil",
",",
"**",
"options",
")",
"if",
"data",
"&&",
"@type",
"==",
":datablock",
"new_datablock",
"=",
"@data",
".",
"update",
"(",
"data",
")",
"if",
"new_datablock",
"==",
"@data",
"update_options",
"(",
"options",
")",
"else",
"self",
".",
"class",
".",
"new",
"(",
"new_datablock",
",",
"options",
")",
"end",
"else",
"update_options",
"(",
"options",
")",
"end",
"end"
] | Create new dataset with updated data and merged options.
Given data is appended to existing.
Data is updated only if Dataset stores it in Datablock.
Method does nothing if no options given and data isn't stored
in in-memory Datablock.
@param data [#to_gnuplot_points] data to append to existing
@param options [Hash] new options to merge with existing options
@return self if dataset corresponds to math formula or file
(filename or temporary file if datablock)
@return [Dataset] new dataset if data is stored in 'in-memory' Datablock
@example Updating dataset with Math formula or filename given:
dataset = Dataset.new('file.data')
dataset.update(data: 'asd')
#=> nothing updated
dataset.update(data: 'asd', title: 'File')
#=> Dataset.new('file.data', title: 'File')
@example Updating dataset with data stored in Datablock (in-memory):
in_memory_points = Dataset.new(points, title: 'Old one')
in_memory_points.update(data: some_update, title: 'Updated')
#=> Dataset.new(points + some_update, title: 'Updated')
@example Updating dataset with data stored in Datablock (in-file):
temp_file_points = Dataset.new(points, title: 'Old one', file: true)
temp_file_points.update(data: some_update)
#=> data updated but no new dataset created
temp_file_points.update(data: some_update, title: 'Updated')
#=> data updated and new dataset with title 'Updated' returned | [
"Create",
"new",
"dataset",
"with",
"updated",
"data",
"and",
"merged",
"options",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/staff/dataset.rb#L119-L130 | train |
dilcom/gnuplotrb | lib/gnuplotrb/staff/dataset.rb | GnuplotRB.Dataset.options_to_string | def options_to_string
options.sort_by { |key, _| OPTION_ORDER.find_index(key.to_s) || 999 }
.map { |key, value| OptionHandling.option_to_string(key, value) }
.join(' ')
end | ruby | def options_to_string
options.sort_by { |key, _| OPTION_ORDER.find_index(key.to_s) || 999 }
.map { |key, value| OptionHandling.option_to_string(key, value) }
.join(' ')
end | [
"def",
"options_to_string",
"options",
".",
"sort_by",
"{",
"|",
"key",
",",
"_",
"|",
"OPTION_ORDER",
".",
"find_index",
"(",
"key",
".",
"to_s",
")",
"||",
"999",
"}",
".",
"map",
"{",
"|",
"key",
",",
"value",
"|",
"OptionHandling",
".",
"option_to_string",
"(",
"key",
",",
"value",
")",
"}",
".",
"join",
"(",
"' '",
")",
"end"
] | Create string from own options
@return [String] options converted to Gnuplot format | [
"Create",
"string",
"from",
"own",
"options"
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/staff/dataset.rb#L221-L225 | train |
dilcom/gnuplotrb | lib/gnuplotrb/staff/dataset.rb | GnuplotRB.Dataset.init_string | def init_string(data, options)
@type, @data = File.exist?(data) ? [:datafile, "'#{data}'"] : [:math_function, data.clone]
@options = Hamster.hash(options)
end | ruby | def init_string(data, options)
@type, @data = File.exist?(data) ? [:datafile, "'#{data}'"] : [:math_function, data.clone]
@options = Hamster.hash(options)
end | [
"def",
"init_string",
"(",
"data",
",",
"options",
")",
"@type",
",",
"@data",
"=",
"File",
".",
"exist?",
"(",
"data",
")",
"?",
"[",
":datafile",
",",
"\"'#{data}'\"",
"]",
":",
"[",
":math_function",
",",
"data",
".",
"clone",
"]",
"@options",
"=",
"Hamster",
".",
"hash",
"(",
"options",
")",
"end"
] | Initialize Dataset from given String | [
"Initialize",
"Dataset",
"from",
"given",
"String"
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/staff/dataset.rb#L235-L238 | train |
dilcom/gnuplotrb | lib/gnuplotrb/staff/dataset.rb | GnuplotRB.Dataset.get_daru_columns | def get_daru_columns(data, cnt)
new_opt = (2..cnt).to_a.join(':')
if data.index[0].is_a?(DateTime) || data.index[0].is_a?(Numeric)
"1:#{new_opt}"
else
"#{new_opt}:xtic(1)"
end
end | ruby | def get_daru_columns(data, cnt)
new_opt = (2..cnt).to_a.join(':')
if data.index[0].is_a?(DateTime) || data.index[0].is_a?(Numeric)
"1:#{new_opt}"
else
"#{new_opt}:xtic(1)"
end
end | [
"def",
"get_daru_columns",
"(",
"data",
",",
"cnt",
")",
"new_opt",
"=",
"(",
"2",
"..",
"cnt",
")",
".",
"to_a",
".",
"join",
"(",
"':'",
")",
"if",
"data",
".",
"index",
"[",
"0",
"]",
".",
"is_a?",
"(",
"DateTime",
")",
"||",
"data",
".",
"index",
"[",
"0",
"]",
".",
"is_a?",
"(",
"Numeric",
")",
"\"1:#{new_opt}\"",
"else",
"\"#{new_opt}:xtic(1)\"",
"end",
"end"
] | Create new value for 'using' option based on column count | [
"Create",
"new",
"value",
"for",
"using",
"option",
"based",
"on",
"column",
"count"
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/staff/dataset.rb#L250-L257 | train |
dilcom/gnuplotrb | lib/gnuplotrb/plot.rb | GnuplotRB.Plot.provide_with_datetime_format | def provide_with_datetime_format(data, using)
return unless defined?(Daru)
return unless data.is_a?(Daru::DataFrame) || data.is_a?(Daru::Vector)
return unless data.index.first.is_a?(DateTime)
return if using[0..1] != '1:'
@options = Hamster::Hash.new(
xdata: 'time',
timefmt: '%Y-%m-%dT%H:%M:%S',
format_x: '%d\n%b\n%Y'
).merge(@options)
end | ruby | def provide_with_datetime_format(data, using)
return unless defined?(Daru)
return unless data.is_a?(Daru::DataFrame) || data.is_a?(Daru::Vector)
return unless data.index.first.is_a?(DateTime)
return if using[0..1] != '1:'
@options = Hamster::Hash.new(
xdata: 'time',
timefmt: '%Y-%m-%dT%H:%M:%S',
format_x: '%d\n%b\n%Y'
).merge(@options)
end | [
"def",
"provide_with_datetime_format",
"(",
"data",
",",
"using",
")",
"return",
"unless",
"defined?",
"(",
"Daru",
")",
"return",
"unless",
"data",
".",
"is_a?",
"(",
"Daru",
"::",
"DataFrame",
")",
"||",
"data",
".",
"is_a?",
"(",
"Daru",
"::",
"Vector",
")",
"return",
"unless",
"data",
".",
"index",
".",
"first",
".",
"is_a?",
"(",
"DateTime",
")",
"return",
"if",
"using",
"[",
"0",
"..",
"1",
"]",
"!=",
"'1:'",
"@options",
"=",
"Hamster",
"::",
"Hash",
".",
"new",
"(",
"xdata",
":",
"'time'",
",",
"timefmt",
":",
"'%Y-%m-%dT%H:%M:%S'",
",",
"format_x",
":",
"'%d\\n%b\\n%Y'",
")",
".",
"merge",
"(",
"@options",
")",
"end"
] | Checks several conditions and set options needed
to handle DateTime indexes properly. | [
"Checks",
"several",
"conditions",
"and",
"set",
"options",
"needed",
"to",
"handle",
"DateTime",
"indexes",
"properly",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/plot.rb#L250-L260 | train |
dilcom/gnuplotrb | lib/gnuplotrb/plot.rb | GnuplotRB.Plot.dataset_from_any | def dataset_from_any(source)
ds = case source
# when initialized with dataframe (it passes here several vectors)
when (defined?(Daru) ? Daru::Vector : nil)
Dataset.new(source)
when Dataset
source.clone
else
Dataset.new(*source)
end
data = source.is_a?(Array) ? source[0] : source
provide_with_datetime_format(data, ds.using)
ds
end | ruby | def dataset_from_any(source)
ds = case source
# when initialized with dataframe (it passes here several vectors)
when (defined?(Daru) ? Daru::Vector : nil)
Dataset.new(source)
when Dataset
source.clone
else
Dataset.new(*source)
end
data = source.is_a?(Array) ? source[0] : source
provide_with_datetime_format(data, ds.using)
ds
end | [
"def",
"dataset_from_any",
"(",
"source",
")",
"ds",
"=",
"case",
"source",
"when",
"(",
"defined?",
"(",
"Daru",
")",
"?",
"Daru",
"::",
"Vector",
":",
"nil",
")",
"Dataset",
".",
"new",
"(",
"source",
")",
"when",
"Dataset",
"source",
".",
"clone",
"else",
"Dataset",
".",
"new",
"(",
"*",
"source",
")",
"end",
"data",
"=",
"source",
".",
"is_a?",
"(",
"Array",
")",
"?",
"source",
"[",
"0",
"]",
":",
"source",
"provide_with_datetime_format",
"(",
"data",
",",
"ds",
".",
"using",
")",
"ds",
"end"
] | Check if given args is a dataset and returns it. Creates
new dataset from given args otherwise. | [
"Check",
"if",
"given",
"args",
"is",
"a",
"dataset",
"and",
"returns",
"it",
".",
"Creates",
"new",
"dataset",
"from",
"given",
"args",
"otherwise",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/plot.rb#L265-L278 | train |
alor/em-http-server | lib/em-http-server/response.rb | EventMachine.HttpResponse.send_headers | def send_headers
raise "sent headers already" if @sent_headers
@sent_headers = true
fixup_headers
ary = []
ary << "HTTP/1.1 #{@status || 200} #{@status_string || '...'}\r\n"
ary += generate_header_lines(@headers)
ary << "\r\n"
send_data ary.join
end | ruby | def send_headers
raise "sent headers already" if @sent_headers
@sent_headers = true
fixup_headers
ary = []
ary << "HTTP/1.1 #{@status || 200} #{@status_string || '...'}\r\n"
ary += generate_header_lines(@headers)
ary << "\r\n"
send_data ary.join
end | [
"def",
"send_headers",
"raise",
"\"sent headers already\"",
"if",
"@sent_headers",
"@sent_headers",
"=",
"true",
"fixup_headers",
"ary",
"=",
"[",
"]",
"ary",
"<<",
"\"HTTP/1.1 #{@status || 200} #{@status_string || '...'}\\r\\n\"",
"ary",
"+=",
"generate_header_lines",
"(",
"@headers",
")",
"ary",
"<<",
"\"\\r\\n\"",
"send_data",
"ary",
".",
"join",
"end"
] | Send the headers out in alpha-sorted order. This will degrade performance to some
degree, and is intended only to simplify the construction of unit tests. | [
"Send",
"the",
"headers",
"out",
"in",
"alpha",
"-",
"sorted",
"order",
".",
"This",
"will",
"degrade",
"performance",
"to",
"some",
"degree",
"and",
"is",
"intended",
"only",
"to",
"simplify",
"the",
"construction",
"of",
"unit",
"tests",
"."
] | 4c5050b376e5765572e074db7a92f65f882b24a2 | https://github.com/alor/em-http-server/blob/4c5050b376e5765572e074db7a92f65f882b24a2/lib/em-http-server/response.rb#L108-L120 | train |
iron-io/rest | lib/rest/wrappers/base_wrapper.rb | Rest.BaseResponseWrapper.headers | def headers
new_h = {}
headers_orig.each_pair do |k, v|
if v.is_a?(Array) && v.size == 1
v = v[0]
end
new_h[k.downcase] = v
end
new_h
end | ruby | def headers
new_h = {}
headers_orig.each_pair do |k, v|
if v.is_a?(Array) && v.size == 1
v = v[0]
end
new_h[k.downcase] = v
end
new_h
end | [
"def",
"headers",
"new_h",
"=",
"{",
"}",
"headers_orig",
".",
"each_pair",
"do",
"|",
"k",
",",
"v",
"|",
"if",
"v",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"v",
".",
"size",
"==",
"1",
"v",
"=",
"v",
"[",
"0",
"]",
"end",
"new_h",
"[",
"k",
".",
"downcase",
"]",
"=",
"v",
"end",
"new_h",
"end"
] | Provide a headers_orig method in your wrapper to allow this to work | [
"Provide",
"a",
"headers_orig",
"method",
"in",
"your",
"wrapper",
"to",
"allow",
"this",
"to",
"work"
] | 7775483f775a4b0560a1687fee48149b52fa5c51 | https://github.com/iron-io/rest/blob/7775483f775a4b0560a1687fee48149b52fa5c51/lib/rest/wrappers/base_wrapper.rb#L42-L51 | train |
dilcom/gnuplotrb | lib/gnuplotrb/animation.rb | GnuplotRB.Animation.plot | def plot(path = nil, **options)
options[:output] ||= path
plot_options = mix_options(options) do |plot_opts, anim_opts|
plot_opts.merge(term: ['gif', anim_opts])
end.to_h
need_output = plot_options[:output].nil?
plot_options[:output] = Dir::Tmpname.make_tmpname('anim', 0) if need_output
terminal = Terminal.new
multiplot(terminal, plot_options)
# guaranteed wait for plotting to finish
terminal.close
if need_output
result = File.binread(plot_options[:output])
File.delete(plot_options[:output])
else
result = nil
end
result
end | ruby | def plot(path = nil, **options)
options[:output] ||= path
plot_options = mix_options(options) do |plot_opts, anim_opts|
plot_opts.merge(term: ['gif', anim_opts])
end.to_h
need_output = plot_options[:output].nil?
plot_options[:output] = Dir::Tmpname.make_tmpname('anim', 0) if need_output
terminal = Terminal.new
multiplot(terminal, plot_options)
# guaranteed wait for plotting to finish
terminal.close
if need_output
result = File.binread(plot_options[:output])
File.delete(plot_options[:output])
else
result = nil
end
result
end | [
"def",
"plot",
"(",
"path",
"=",
"nil",
",",
"**",
"options",
")",
"options",
"[",
":output",
"]",
"||=",
"path",
"plot_options",
"=",
"mix_options",
"(",
"options",
")",
"do",
"|",
"plot_opts",
",",
"anim_opts",
"|",
"plot_opts",
".",
"merge",
"(",
"term",
":",
"[",
"'gif'",
",",
"anim_opts",
"]",
")",
"end",
".",
"to_h",
"need_output",
"=",
"plot_options",
"[",
":output",
"]",
".",
"nil?",
"plot_options",
"[",
":output",
"]",
"=",
"Dir",
"::",
"Tmpname",
".",
"make_tmpname",
"(",
"'anim'",
",",
"0",
")",
"if",
"need_output",
"terminal",
"=",
"Terminal",
".",
"new",
"multiplot",
"(",
"terminal",
",",
"plot_options",
")",
"terminal",
".",
"close",
"if",
"need_output",
"result",
"=",
"File",
".",
"binread",
"(",
"plot_options",
"[",
":output",
"]",
")",
"File",
".",
"delete",
"(",
"plot_options",
"[",
":output",
"]",
")",
"else",
"result",
"=",
"nil",
"end",
"result",
"end"
] | This method creates a gif animation where frames are plots
already contained by Animation object.
Options passed in #plot have priority over those which were set before.
Inner options of Plots have the highest priority (except
:term and :output which are ignored).
@param path [String] path to new gif file that will be created as a result
@param options [Hash] see note about available options in top class documentation
@return [nil] if path to output file given
@return [String] gif file contents if no path to output file given | [
"This",
"method",
"creates",
"a",
"gif",
"animation",
"where",
"frames",
"are",
"plots",
"already",
"contained",
"by",
"Animation",
"object",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/animation.rb#L55-L73 | train |
dilcom/gnuplotrb | lib/gnuplotrb/animation.rb | GnuplotRB.Animation.specific_keys | def specific_keys
%w(
animate
size
background
transparent
enhanced
rounded
butt
linewidth
dashlength
tiny
small
medium
large
giant
font
fontscale
crop
)
end | ruby | def specific_keys
%w(
animate
size
background
transparent
enhanced
rounded
butt
linewidth
dashlength
tiny
small
medium
large
giant
font
fontscale
crop
)
end | [
"def",
"specific_keys",
"%w(",
"animate",
"size",
"background",
"transparent",
"enhanced",
"rounded",
"butt",
"linewidth",
"dashlength",
"tiny",
"small",
"medium",
"large",
"giant",
"font",
"fontscale",
"crop",
")",
"end"
] | This plot have some specific options which
should be handled different way than others.
Here are keys of this options. | [
"This",
"plot",
"have",
"some",
"specific",
"options",
"which",
"should",
"be",
"handled",
"different",
"way",
"than",
"others",
".",
"Here",
"are",
"keys",
"of",
"this",
"options",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/animation.rb#L107-L127 | train |
dilcom/gnuplotrb | lib/gnuplotrb/fit.rb | GnuplotRB.Fit.fit | def fit(data, function: 'a2*x*x+a1*x+a0', initials: { a2: 1, a1: 1, a0: 1 }, term_options: {}, **options)
dataset = data.is_a?(Dataset) ? Dataset.new(data.data) : Dataset.new(data)
opts_str = OptionHandling.ruby_class_to_gnuplot(options)
output = gnuplot_fit(function, dataset, opts_str, initials, term_options)
res = parse_output(initials.keys, function, output)
{
formula_ds: Dataset.new(res[2], title: 'Fit formula'),
coefficients: res[0],
deltas: res[1],
data: dataset
}
end | ruby | def fit(data, function: 'a2*x*x+a1*x+a0', initials: { a2: 1, a1: 1, a0: 1 }, term_options: {}, **options)
dataset = data.is_a?(Dataset) ? Dataset.new(data.data) : Dataset.new(data)
opts_str = OptionHandling.ruby_class_to_gnuplot(options)
output = gnuplot_fit(function, dataset, opts_str, initials, term_options)
res = parse_output(initials.keys, function, output)
{
formula_ds: Dataset.new(res[2], title: 'Fit formula'),
coefficients: res[0],
deltas: res[1],
data: dataset
}
end | [
"def",
"fit",
"(",
"data",
",",
"function",
":",
"'a2*x*x+a1*x+a0'",
",",
"initials",
":",
"{",
"a2",
":",
"1",
",",
"a1",
":",
"1",
",",
"a0",
":",
"1",
"}",
",",
"term_options",
":",
"{",
"}",
",",
"**",
"options",
")",
"dataset",
"=",
"data",
".",
"is_a?",
"(",
"Dataset",
")",
"?",
"Dataset",
".",
"new",
"(",
"data",
".",
"data",
")",
":",
"Dataset",
".",
"new",
"(",
"data",
")",
"opts_str",
"=",
"OptionHandling",
".",
"ruby_class_to_gnuplot",
"(",
"options",
")",
"output",
"=",
"gnuplot_fit",
"(",
"function",
",",
"dataset",
",",
"opts_str",
",",
"initials",
",",
"term_options",
")",
"res",
"=",
"parse_output",
"(",
"initials",
".",
"keys",
",",
"function",
",",
"output",
")",
"{",
"formula_ds",
":",
"Dataset",
".",
"new",
"(",
"res",
"[",
"2",
"]",
",",
"title",
":",
"'Fit formula'",
")",
",",
"coefficients",
":",
"res",
"[",
"0",
"]",
",",
"deltas",
":",
"res",
"[",
"1",
"]",
",",
"data",
":",
"dataset",
"}",
"end"
] | Fit given data with function.
Fit waits for output from gnuplot Settings.max_fit_delay and throw exception if gets nothing.
One can change this value in order to wait longer (if huge datasets is fitted).
@param data [#to_gnuplot_points] method accepts the same sources as Dataset.new
and Dataset object
@param :function [String] function to fit data with
@param :initials [Hash] initial values for coefficients used in fitting
@param :term_options [Hash] terminal options that should be setted to terminal before fit.
You can see them in Plot's documentation (or even better in gnuplot doc)
Most useful here are ranges (xrange, yrange etc) and fit option which tunes fit parameters
(see {gnuplot doc}[http://www.gnuplot.info/docs_5.0/gnuplot.pdf] p. 122)
@param options [Hash] options passed to Gnuplot's fit such as *using*. They are covered in
{gnuplot doc}[http://www.gnuplot.info/docs_5.0/gnuplot.pdf] (pp. 69-74)
@return [Hash] hash with four elements:
- :formula_ds - dataset with best fit curve as data
- :coefficients - hash of calculated coefficients. So if you gave
``{ initials: {a: 1, b: 1, c: 1} }`` it will return hash with keys :a, :b, :c and its values
- :deltas - Gnuplot calculates possible deltas for coefficients during fitting and
deltas hash contains this deltas
- :data - pointer to Datablock with given data
@example
fit(some_data, function: 'exp(a/x)', initials: {a: 10}, term_option: { xrange: 1..100 })
fit(some_dataset, using: '1:2:3') | [
"Fit",
"given",
"data",
"with",
"function",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/fit.rb#L36-L47 | train |
dilcom/gnuplotrb | lib/gnuplotrb/fit.rb | GnuplotRB.Fit.wait_for_output | def wait_for_output(term, variables)
# now we should catch 'error' from terminal: it will contain approximation data
# but we can get a real error instead of output, so lets wait for limited time
start = Time.now
output = ''
until output_ready?(output, variables)
begin
term.check_errors(raw: true)
rescue GnuplotRB::GnuplotError => e
output += e.message
end
if Time.now - start > Settings.max_fit_delay
fail GnuplotError, "Seems like there is an error in gnuplotrb: #{output}"
end
end
output
end | ruby | def wait_for_output(term, variables)
# now we should catch 'error' from terminal: it will contain approximation data
# but we can get a real error instead of output, so lets wait for limited time
start = Time.now
output = ''
until output_ready?(output, variables)
begin
term.check_errors(raw: true)
rescue GnuplotRB::GnuplotError => e
output += e.message
end
if Time.now - start > Settings.max_fit_delay
fail GnuplotError, "Seems like there is an error in gnuplotrb: #{output}"
end
end
output
end | [
"def",
"wait_for_output",
"(",
"term",
",",
"variables",
")",
"start",
"=",
"Time",
".",
"now",
"output",
"=",
"''",
"until",
"output_ready?",
"(",
"output",
",",
"variables",
")",
"begin",
"term",
".",
"check_errors",
"(",
"raw",
":",
"true",
")",
"rescue",
"GnuplotRB",
"::",
"GnuplotError",
"=>",
"e",
"output",
"+=",
"e",
".",
"message",
"end",
"if",
"Time",
".",
"now",
"-",
"start",
">",
"Settings",
".",
"max_fit_delay",
"fail",
"GnuplotError",
",",
"\"Seems like there is an error in gnuplotrb: #{output}\"",
"end",
"end",
"output",
"end"
] | It takes some time to produce output so here we need
to wait for it.
Max time to wait is stored in Settings.max_fit_delay, so one
can change it in order to wait longer. | [
"It",
"takes",
"some",
"time",
"to",
"produce",
"output",
"so",
"here",
"we",
"need",
"to",
"wait",
"for",
"it",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/fit.rb#L140-L156 | train |
dilcom/gnuplotrb | lib/gnuplotrb/fit.rb | GnuplotRB.Fit.gnuplot_fit | def gnuplot_fit(function, data, options, initials, term_options)
variables = initials.keys
term = Terminal.new
term.set(term_options)
initials.each { |var_name, value| term.stream_puts "#{var_name} = #{value}" }
command = "fit #{function} #{data.to_s(term, without_options: true)} " \
"#{options} via #{variables.join(',')}"
term.stream_puts(command)
output = wait_for_output(term, variables)
begin
term.close
rescue GnuplotError
# Nothing interesting here.
# If we had an error, we never reach this line.
# Error here may be only additional information
# such as correlation matrix.
end
output
end | ruby | def gnuplot_fit(function, data, options, initials, term_options)
variables = initials.keys
term = Terminal.new
term.set(term_options)
initials.each { |var_name, value| term.stream_puts "#{var_name} = #{value}" }
command = "fit #{function} #{data.to_s(term, without_options: true)} " \
"#{options} via #{variables.join(',')}"
term.stream_puts(command)
output = wait_for_output(term, variables)
begin
term.close
rescue GnuplotError
# Nothing interesting here.
# If we had an error, we never reach this line.
# Error here may be only additional information
# such as correlation matrix.
end
output
end | [
"def",
"gnuplot_fit",
"(",
"function",
",",
"data",
",",
"options",
",",
"initials",
",",
"term_options",
")",
"variables",
"=",
"initials",
".",
"keys",
"term",
"=",
"Terminal",
".",
"new",
"term",
".",
"set",
"(",
"term_options",
")",
"initials",
".",
"each",
"{",
"|",
"var_name",
",",
"value",
"|",
"term",
".",
"stream_puts",
"\"#{var_name} = #{value}\"",
"}",
"command",
"=",
"\"fit #{function} #{data.to_s(term, without_options: true)} \"",
"\"#{options} via #{variables.join(',')}\"",
"term",
".",
"stream_puts",
"(",
"command",
")",
"output",
"=",
"wait_for_output",
"(",
"term",
",",
"variables",
")",
"begin",
"term",
".",
"close",
"rescue",
"GnuplotError",
"end",
"output",
"end"
] | Make fit command and send it to gnuplot | [
"Make",
"fit",
"command",
"and",
"send",
"it",
"to",
"gnuplot"
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/fit.rb#L184-L202 | train |
namick/scatter_swap | lib/scatter_swap/hasher.rb | ScatterSwap.Hasher.swapper_map | def swapper_map(index)
array = (0..9).to_a
10.times.collect.with_index do |i|
array.rotate!(index + i ^ spin).pop
end
end | ruby | def swapper_map(index)
array = (0..9).to_a
10.times.collect.with_index do |i|
array.rotate!(index + i ^ spin).pop
end
end | [
"def",
"swapper_map",
"(",
"index",
")",
"array",
"=",
"(",
"0",
"..",
"9",
")",
".",
"to_a",
"10",
".",
"times",
".",
"collect",
".",
"with_index",
"do",
"|",
"i",
"|",
"array",
".",
"rotate!",
"(",
"index",
"+",
"i",
"^",
"spin",
")",
".",
"pop",
"end",
"end"
] | We want a unique map for each place in the original number | [
"We",
"want",
"a",
"unique",
"map",
"for",
"each",
"place",
"in",
"the",
"original",
"number"
] | 0ae5a936482752e4f2220f0e54d7647b5953d80e | https://github.com/namick/scatter_swap/blob/0ae5a936482752e4f2220f0e54d7647b5953d80e/lib/scatter_swap/hasher.rb#L31-L36 | train |
namick/scatter_swap | lib/scatter_swap/hasher.rb | ScatterSwap.Hasher.unscatter | def unscatter
scattered_array = @working_array
sum_of_digits = scattered_array.inject(:+).to_i
@working_array = []
@working_array.tap do |unscatter|
10.times do
unscatter.push scattered_array.pop
unscatter.rotate! (sum_of_digits ^ spin) * -1
end
end
end | ruby | def unscatter
scattered_array = @working_array
sum_of_digits = scattered_array.inject(:+).to_i
@working_array = []
@working_array.tap do |unscatter|
10.times do
unscatter.push scattered_array.pop
unscatter.rotate! (sum_of_digits ^ spin) * -1
end
end
end | [
"def",
"unscatter",
"scattered_array",
"=",
"@working_array",
"sum_of_digits",
"=",
"scattered_array",
".",
"inject",
"(",
":+",
")",
".",
"to_i",
"@working_array",
"=",
"[",
"]",
"@working_array",
".",
"tap",
"do",
"|",
"unscatter",
"|",
"10",
".",
"times",
"do",
"unscatter",
".",
"push",
"scattered_array",
".",
"pop",
"unscatter",
".",
"rotate!",
"(",
"sum_of_digits",
"^",
"spin",
")",
"*",
"-",
"1",
"end",
"end",
"end"
] | Reverse the scatter | [
"Reverse",
"the",
"scatter"
] | 0ae5a936482752e4f2220f0e54d7647b5953d80e | https://github.com/namick/scatter_swap/blob/0ae5a936482752e4f2220f0e54d7647b5953d80e/lib/scatter_swap/hasher.rb#L64-L74 | train |
futurechimp/awrence | lib/awrence/methods.rb | Awrence.Methods.to_camelback_keys | def to_camelback_keys(value = self)
case value
when Array
value.map { |v| to_camelback_keys(v) }
when Hash
Hash[value.map { |k, v| [camelize_key(k, false), to_camelback_keys(v)] }]
else
value
end
end | ruby | def to_camelback_keys(value = self)
case value
when Array
value.map { |v| to_camelback_keys(v) }
when Hash
Hash[value.map { |k, v| [camelize_key(k, false), to_camelback_keys(v)] }]
else
value
end
end | [
"def",
"to_camelback_keys",
"(",
"value",
"=",
"self",
")",
"case",
"value",
"when",
"Array",
"value",
".",
"map",
"{",
"|",
"v",
"|",
"to_camelback_keys",
"(",
"v",
")",
"}",
"when",
"Hash",
"Hash",
"[",
"value",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"camelize_key",
"(",
"k",
",",
"false",
")",
",",
"to_camelback_keys",
"(",
"v",
")",
"]",
"}",
"]",
"else",
"value",
"end",
"end"
] | Recursively converts Rubyish snake_case hash keys to camelBack JSON-style
hash keys suitable for use with a JSON API. | [
"Recursively",
"converts",
"Rubyish",
"snake_case",
"hash",
"keys",
"to",
"camelBack",
"JSON",
"-",
"style",
"hash",
"keys",
"suitable",
"for",
"use",
"with",
"a",
"JSON",
"API",
"."
] | f040f70b82828a6d803f3552b267eb9aec194c57 | https://github.com/futurechimp/awrence/blob/f040f70b82828a6d803f3552b267eb9aec194c57/lib/awrence/methods.rb#L8-L17 | train |
futurechimp/awrence | lib/awrence/methods.rb | Awrence.Methods.to_camel_keys | def to_camel_keys(value = self)
case value
when Array
value.map { |v| to_camel_keys(v) }
when Hash
Hash[value.map { |k, v| [camelize_key(k), to_camel_keys(v)] }]
else
value
end
end | ruby | def to_camel_keys(value = self)
case value
when Array
value.map { |v| to_camel_keys(v) }
when Hash
Hash[value.map { |k, v| [camelize_key(k), to_camel_keys(v)] }]
else
value
end
end | [
"def",
"to_camel_keys",
"(",
"value",
"=",
"self",
")",
"case",
"value",
"when",
"Array",
"value",
".",
"map",
"{",
"|",
"v",
"|",
"to_camel_keys",
"(",
"v",
")",
"}",
"when",
"Hash",
"Hash",
"[",
"value",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"camelize_key",
"(",
"k",
")",
",",
"to_camel_keys",
"(",
"v",
")",
"]",
"}",
"]",
"else",
"value",
"end",
"end"
] | Recursively converts Rubyish snake_case hash keys to CamelCase JSON-style
hash keys suitable for use with a JSON API. | [
"Recursively",
"converts",
"Rubyish",
"snake_case",
"hash",
"keys",
"to",
"CamelCase",
"JSON",
"-",
"style",
"hash",
"keys",
"suitable",
"for",
"use",
"with",
"a",
"JSON",
"API",
"."
] | f040f70b82828a6d803f3552b267eb9aec194c57 | https://github.com/futurechimp/awrence/blob/f040f70b82828a6d803f3552b267eb9aec194c57/lib/awrence/methods.rb#L22-L31 | train |
mdh/ssm | lib/simple_state_machine/state_machine.rb | SimpleStateMachine.StateMachine.next_state | def next_state(event_name)
transition = transitions.select{|t| t.is_transition_for?(event_name, @subject.send(state_method))}.first
transition ? transition.to : nil
end | ruby | def next_state(event_name)
transition = transitions.select{|t| t.is_transition_for?(event_name, @subject.send(state_method))}.first
transition ? transition.to : nil
end | [
"def",
"next_state",
"(",
"event_name",
")",
"transition",
"=",
"transitions",
".",
"select",
"{",
"|",
"t",
"|",
"t",
".",
"is_transition_for?",
"(",
"event_name",
",",
"@subject",
".",
"send",
"(",
"state_method",
")",
")",
"}",
".",
"first",
"transition",
"?",
"transition",
".",
"to",
":",
"nil",
"end"
] | Returns the next state for the subject for event_name | [
"Returns",
"the",
"next",
"state",
"for",
"the",
"subject",
"for",
"event_name"
] | 81f82c44cf75f444ee720f83fb3a5d3e570247f9 | https://github.com/mdh/ssm/blob/81f82c44cf75f444ee720f83fb3a5d3e570247f9/lib/simple_state_machine/state_machine.rb#L15-L18 | train |
mdh/ssm | lib/simple_state_machine/state_machine.rb | SimpleStateMachine.StateMachine.error_state | def error_state(event_name, error)
transition = transitions.select{|t| t.is_error_transition_for?(event_name, error) }.first
transition ? transition.to : nil
end | ruby | def error_state(event_name, error)
transition = transitions.select{|t| t.is_error_transition_for?(event_name, error) }.first
transition ? transition.to : nil
end | [
"def",
"error_state",
"(",
"event_name",
",",
"error",
")",
"transition",
"=",
"transitions",
".",
"select",
"{",
"|",
"t",
"|",
"t",
".",
"is_error_transition_for?",
"(",
"event_name",
",",
"error",
")",
"}",
".",
"first",
"transition",
"?",
"transition",
".",
"to",
":",
"nil",
"end"
] | Returns the error state for the subject for event_name and error | [
"Returns",
"the",
"error",
"state",
"for",
"the",
"subject",
"for",
"event_name",
"and",
"error"
] | 81f82c44cf75f444ee720f83fb3a5d3e570247f9 | https://github.com/mdh/ssm/blob/81f82c44cf75f444ee720f83fb3a5d3e570247f9/lib/simple_state_machine/state_machine.rb#L21-L24 | train |
mdh/ssm | lib/simple_state_machine/state_machine.rb | SimpleStateMachine.StateMachine.transition | def transition(event_name)
clear_raised_error
if to = next_state(event_name)
begin
result = yield
rescue => e
error_state = error_state(event_name, e) ||
state_machine_definition.default_error_state
if error_state
@raised_error = e
@subject.send("#{state_method}=", error_state)
return result
else
raise
end
end
# TODO refactor out to AR module
if defined?(::ActiveRecord) && @subject.is_a?(::ActiveRecord::Base)
if @subject.errors.entries.empty?
@subject.send("#{state_method}=", to)
return true
else
return false
end
else
@subject.send("#{state_method}=", to)
return result
end
else
illegal_event_callback event_name
end
end | ruby | def transition(event_name)
clear_raised_error
if to = next_state(event_name)
begin
result = yield
rescue => e
error_state = error_state(event_name, e) ||
state_machine_definition.default_error_state
if error_state
@raised_error = e
@subject.send("#{state_method}=", error_state)
return result
else
raise
end
end
# TODO refactor out to AR module
if defined?(::ActiveRecord) && @subject.is_a?(::ActiveRecord::Base)
if @subject.errors.entries.empty?
@subject.send("#{state_method}=", to)
return true
else
return false
end
else
@subject.send("#{state_method}=", to)
return result
end
else
illegal_event_callback event_name
end
end | [
"def",
"transition",
"(",
"event_name",
")",
"clear_raised_error",
"if",
"to",
"=",
"next_state",
"(",
"event_name",
")",
"begin",
"result",
"=",
"yield",
"rescue",
"=>",
"e",
"error_state",
"=",
"error_state",
"(",
"event_name",
",",
"e",
")",
"||",
"state_machine_definition",
".",
"default_error_state",
"if",
"error_state",
"@raised_error",
"=",
"e",
"@subject",
".",
"send",
"(",
"\"#{state_method}=\"",
",",
"error_state",
")",
"return",
"result",
"else",
"raise",
"end",
"end",
"if",
"defined?",
"(",
"::",
"ActiveRecord",
")",
"&&",
"@subject",
".",
"is_a?",
"(",
"::",
"ActiveRecord",
"::",
"Base",
")",
"if",
"@subject",
".",
"errors",
".",
"entries",
".",
"empty?",
"@subject",
".",
"send",
"(",
"\"#{state_method}=\"",
",",
"to",
")",
"return",
"true",
"else",
"return",
"false",
"end",
"else",
"@subject",
".",
"send",
"(",
"\"#{state_method}=\"",
",",
"to",
")",
"return",
"result",
"end",
"else",
"illegal_event_callback",
"event_name",
"end",
"end"
] | Transitions to the next state if next_state exists.
When an error occurs, it uses the error to determine next state.
If no next state can be determined it transitions to the default error
state if defined, otherwise the error is re-raised.
Calls illegal_event_callback event_name if no next_state is found | [
"Transitions",
"to",
"the",
"next",
"state",
"if",
"next_state",
"exists",
".",
"When",
"an",
"error",
"occurs",
"it",
"uses",
"the",
"error",
"to",
"determine",
"next",
"state",
".",
"If",
"no",
"next",
"state",
"can",
"be",
"determined",
"it",
"transitions",
"to",
"the",
"default",
"error",
"state",
"if",
"defined",
"otherwise",
"the",
"error",
"is",
"re",
"-",
"raised",
".",
"Calls",
"illegal_event_callback",
"event_name",
"if",
"no",
"next_state",
"is",
"found"
] | 81f82c44cf75f444ee720f83fb3a5d3e570247f9 | https://github.com/mdh/ssm/blob/81f82c44cf75f444ee720f83fb3a5d3e570247f9/lib/simple_state_machine/state_machine.rb#L31-L62 | train |
alfa-jpn/inum | lib/inum/active_record_mixin.rb | Inum.ActiveRecordMixin.bind_inum | def bind_inum(column, enum_class, options = {})
options = { prefix: column }.merge(options)
options[:prefix] = options[:prefix] ? "#{options[:prefix]}_" : ''
self.class_eval do
define_method(column) do
enum_class.parse(read_attribute(column))
end
define_method("#{column}=") do |value|
enum_class.parse(value).tap do |enum|
if enum
write_attribute(column, enum.to_i)
else
write_attribute(column, nil)
end
end
end
enum_class.each do |enum|
define_method("#{options[:prefix]}#{enum.to_s.underscore}?") do
enum.eql?(read_attribute(column))
end
end
end
end | ruby | def bind_inum(column, enum_class, options = {})
options = { prefix: column }.merge(options)
options[:prefix] = options[:prefix] ? "#{options[:prefix]}_" : ''
self.class_eval do
define_method(column) do
enum_class.parse(read_attribute(column))
end
define_method("#{column}=") do |value|
enum_class.parse(value).tap do |enum|
if enum
write_attribute(column, enum.to_i)
else
write_attribute(column, nil)
end
end
end
enum_class.each do |enum|
define_method("#{options[:prefix]}#{enum.to_s.underscore}?") do
enum.eql?(read_attribute(column))
end
end
end
end | [
"def",
"bind_inum",
"(",
"column",
",",
"enum_class",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"prefix",
":",
"column",
"}",
".",
"merge",
"(",
"options",
")",
"options",
"[",
":prefix",
"]",
"=",
"options",
"[",
":prefix",
"]",
"?",
"\"#{options[:prefix]}_\"",
":",
"''",
"self",
".",
"class_eval",
"do",
"define_method",
"(",
"column",
")",
"do",
"enum_class",
".",
"parse",
"(",
"read_attribute",
"(",
"column",
")",
")",
"end",
"define_method",
"(",
"\"#{column}=\"",
")",
"do",
"|",
"value",
"|",
"enum_class",
".",
"parse",
"(",
"value",
")",
".",
"tap",
"do",
"|",
"enum",
"|",
"if",
"enum",
"write_attribute",
"(",
"column",
",",
"enum",
".",
"to_i",
")",
"else",
"write_attribute",
"(",
"column",
",",
"nil",
")",
"end",
"end",
"end",
"enum_class",
".",
"each",
"do",
"|",
"enum",
"|",
"define_method",
"(",
"\"#{options[:prefix]}#{enum.to_s.underscore}?\"",
")",
"do",
"enum",
".",
"eql?",
"(",
"read_attribute",
"(",
"column",
")",
")",
"end",
"end",
"end",
"end"
] | Define compare method in class.
@param column [Symbol] Binding column name.
@param enum_class [Inum::Base] Binding Enum.
@param options [Hash] option
@option options [Symbol] :prefix Prefix. (default: column) | [
"Define",
"compare",
"method",
"in",
"class",
"."
] | 41a504aaebaf5523a9d895b1173bdbd6f02ac86d | https://github.com/alfa-jpn/inum/blob/41a504aaebaf5523a9d895b1173bdbd6f02ac86d/lib/inum/active_record_mixin.rb#L16-L41 | train |
veelenga/i3ipc-ruby | lib/i3ipc/protocol.rb | I3Ipc.Protocol.receive | def receive(type = nil)
check_connected
# length of "i3-ipc" + 4 bytes length + 4 bytes type
data = @socket.read 14
magic, len, recv_type = unpack_header(data)
raise WrongMagicString.new(magic) unless MAGIC_STRING.eql? magic
type && (raise WrongType.new(type, recv_type) unless type == recv_type)
@socket.read(len)
end | ruby | def receive(type = nil)
check_connected
# length of "i3-ipc" + 4 bytes length + 4 bytes type
data = @socket.read 14
magic, len, recv_type = unpack_header(data)
raise WrongMagicString.new(magic) unless MAGIC_STRING.eql? magic
type && (raise WrongType.new(type, recv_type) unless type == recv_type)
@socket.read(len)
end | [
"def",
"receive",
"(",
"type",
"=",
"nil",
")",
"check_connected",
"data",
"=",
"@socket",
".",
"read",
"14",
"magic",
",",
"len",
",",
"recv_type",
"=",
"unpack_header",
"(",
"data",
")",
"raise",
"WrongMagicString",
".",
"new",
"(",
"magic",
")",
"unless",
"MAGIC_STRING",
".",
"eql?",
"magic",
"type",
"&&",
"(",
"raise",
"WrongType",
".",
"new",
"(",
"type",
",",
"recv_type",
")",
"unless",
"type",
"==",
"recv_type",
")",
"@socket",
".",
"read",
"(",
"len",
")",
"end"
] | Receives message from i3-ipc server socket.
@param [Integer] type expected type of the message.
@return [String] unpacked response from i3 server.
@raise [NotConnected] if protocol is not connected.
@raise [WrongMagicString] if got message with wrong magic string.
@raise [WrongType] if got message with not expected type. | [
"Receives",
"message",
"from",
"i3",
"-",
"ipc",
"server",
"socket",
"."
] | 0c3a2a76d3c264c634a0d94cc31b8be2639d9ec6 | https://github.com/veelenga/i3ipc-ruby/blob/0c3a2a76d3c264c634a0d94cc31b8be2639d9ec6/lib/i3ipc/protocol.rb#L84-L94 | train |
mdh/ssm | lib/simple_state_machine/transition.rb | SimpleStateMachine.Transition.is_error_transition_for? | def is_error_transition_for?(event_name, error)
is_same_event?(event_name) && from.is_a?(Class) && error.is_a?(from)
end | ruby | def is_error_transition_for?(event_name, error)
is_same_event?(event_name) && from.is_a?(Class) && error.is_a?(from)
end | [
"def",
"is_error_transition_for?",
"(",
"event_name",
",",
"error",
")",
"is_same_event?",
"(",
"event_name",
")",
"&&",
"from",
".",
"is_a?",
"(",
"Class",
")",
"&&",
"error",
".",
"is_a?",
"(",
"from",
")",
"end"
] | returns true if it's a error transition for event_name and error | [
"returns",
"true",
"if",
"it",
"s",
"a",
"error",
"transition",
"for",
"event_name",
"and",
"error"
] | 81f82c44cf75f444ee720f83fb3a5d3e570247f9 | https://github.com/mdh/ssm/blob/81f82c44cf75f444ee720f83fb3a5d3e570247f9/lib/simple_state_machine/transition.rb#L17-L19 | train |
fantasticfears/ffi-icu | lib/ffi-icu/normalizer.rb | ICU.Normalizer.normalize | def normalize(input)
input_length = input.jlength
in_ptr = UCharPointer.from_string(input)
needed_length = capacity = 0
out_ptr = UCharPointer.new(needed_length)
retried = false
begin
Lib.check_error do |error|
needed_length = Lib.unorm2_normalize(@instance, in_ptr, input_length, out_ptr, capacity, error)
end
rescue BufferOverflowError
raise BufferOverflowError, "needed: #{needed_length}" if retried
capacity = needed_length
out_ptr = out_ptr.resized_to needed_length
retried = true
retry
end
out_ptr.string
end | ruby | def normalize(input)
input_length = input.jlength
in_ptr = UCharPointer.from_string(input)
needed_length = capacity = 0
out_ptr = UCharPointer.new(needed_length)
retried = false
begin
Lib.check_error do |error|
needed_length = Lib.unorm2_normalize(@instance, in_ptr, input_length, out_ptr, capacity, error)
end
rescue BufferOverflowError
raise BufferOverflowError, "needed: #{needed_length}" if retried
capacity = needed_length
out_ptr = out_ptr.resized_to needed_length
retried = true
retry
end
out_ptr.string
end | [
"def",
"normalize",
"(",
"input",
")",
"input_length",
"=",
"input",
".",
"jlength",
"in_ptr",
"=",
"UCharPointer",
".",
"from_string",
"(",
"input",
")",
"needed_length",
"=",
"capacity",
"=",
"0",
"out_ptr",
"=",
"UCharPointer",
".",
"new",
"(",
"needed_length",
")",
"retried",
"=",
"false",
"begin",
"Lib",
".",
"check_error",
"do",
"|",
"error",
"|",
"needed_length",
"=",
"Lib",
".",
"unorm2_normalize",
"(",
"@instance",
",",
"in_ptr",
",",
"input_length",
",",
"out_ptr",
",",
"capacity",
",",
"error",
")",
"end",
"rescue",
"BufferOverflowError",
"raise",
"BufferOverflowError",
",",
"\"needed: #{needed_length}\"",
"if",
"retried",
"capacity",
"=",
"needed_length",
"out_ptr",
"=",
"out_ptr",
".",
"resized_to",
"needed_length",
"retried",
"=",
"true",
"retry",
"end",
"out_ptr",
".",
"string",
"end"
] | support for newer ICU normalization API | [
"support",
"for",
"newer",
"ICU",
"normalization",
"API"
] | 9694d97b5a700b613c8d3c9ce9e0d0e9dcbf4a30 | https://github.com/fantasticfears/ffi-icu/blob/9694d97b5a700b613c8d3c9ce9e0d0e9dcbf4a30/lib/ffi-icu/normalizer.rb#L11-L33 | train |
mdespuits/validates_formatting_of | lib/validates_formatting_of/model_additions.rb | ValidatesFormattingOf.ModelAdditions.validates_formatting_of | def validates_formatting_of(attribute, options = {})
validation = Method.find(attribute, options)
options.reverse_merge!(:with => validation.regex, :message => validation.message)
self.validates_format_of(attribute, options)
end | ruby | def validates_formatting_of(attribute, options = {})
validation = Method.find(attribute, options)
options.reverse_merge!(:with => validation.regex, :message => validation.message)
self.validates_format_of(attribute, options)
end | [
"def",
"validates_formatting_of",
"(",
"attribute",
",",
"options",
"=",
"{",
"}",
")",
"validation",
"=",
"Method",
".",
"find",
"(",
"attribute",
",",
"options",
")",
"options",
".",
"reverse_merge!",
"(",
":with",
"=>",
"validation",
".",
"regex",
",",
":message",
"=>",
"validation",
".",
"message",
")",
"self",
".",
"validates_format_of",
"(",
"attribute",
",",
"options",
")",
"end"
] | Using validates_formatting_of is as simple as using Rails' built-in
validation methods in models.
class User < ActiveRecord::Base
validates_formatting_of :email, :using => :email
end
If your column name is idencital to any of the built-in methods, you
may leave off the `:using` option and validates_formatting_of will
automatically use the validation with the matching name.
class User < ActiveRecord::Base
validates_formatting_of :email
end
You can also pass conditions and options for Rails to use
* :if
* :unless
* :allow_nil
* :allow_blank
* :on | [
"Using",
"validates_formatting_of",
"is",
"as",
"simple",
"as",
"using",
"Rails",
"built",
"-",
"in",
"validation",
"methods",
"in",
"models",
"."
] | 664b7c8b1ae8c9016549944fc833737c74f1d752 | https://github.com/mdespuits/validates_formatting_of/blob/664b7c8b1ae8c9016549944fc833737c74f1d752/lib/validates_formatting_of/model_additions.rb#L27-L31 | train |
phstc/sidekiq-statsd | lib/sidekiq/statsd/server_middleware.rb | Sidekiq::Statsd.ServerMiddleware.call | def call worker, msg, queue
@statsd.batch do |b|
begin
# colon causes invalid metric names
worker_name = worker.class.name.gsub('::', '.')
b.time prefix(worker_name, 'processing_time') do
yield
end
b.increment prefix(worker_name, 'success')
rescue => e
b.increment prefix(worker_name, 'failure')
raise e
ensure
if @options[:sidekiq_stats]
# Queue sizes
b.gauge prefix('enqueued'), @sidekiq_stats.enqueued
if @sidekiq_stats.respond_to?(:retry_size)
# 2.6.0 doesn't have `retry_size`
b.gauge prefix('retry_set_size'), @sidekiq_stats.retry_size
end
# All-time counts
b.gauge prefix('processed'), @sidekiq_stats.processed
b.gauge prefix('failed'), @sidekiq_stats.failed
end
# Queue metrics
queue_name = msg['queue']
sidekiq_queue = Sidekiq::Queue.new(queue_name)
b.gauge prefix('queues', queue_name, 'enqueued'), sidekiq_queue.size
if sidekiq_queue.respond_to?(:latency)
b.gauge prefix('queues', queue_name, 'latency'), sidekiq_queue.latency
end
end
end
end | ruby | def call worker, msg, queue
@statsd.batch do |b|
begin
# colon causes invalid metric names
worker_name = worker.class.name.gsub('::', '.')
b.time prefix(worker_name, 'processing_time') do
yield
end
b.increment prefix(worker_name, 'success')
rescue => e
b.increment prefix(worker_name, 'failure')
raise e
ensure
if @options[:sidekiq_stats]
# Queue sizes
b.gauge prefix('enqueued'), @sidekiq_stats.enqueued
if @sidekiq_stats.respond_to?(:retry_size)
# 2.6.0 doesn't have `retry_size`
b.gauge prefix('retry_set_size'), @sidekiq_stats.retry_size
end
# All-time counts
b.gauge prefix('processed'), @sidekiq_stats.processed
b.gauge prefix('failed'), @sidekiq_stats.failed
end
# Queue metrics
queue_name = msg['queue']
sidekiq_queue = Sidekiq::Queue.new(queue_name)
b.gauge prefix('queues', queue_name, 'enqueued'), sidekiq_queue.size
if sidekiq_queue.respond_to?(:latency)
b.gauge prefix('queues', queue_name, 'latency'), sidekiq_queue.latency
end
end
end
end | [
"def",
"call",
"worker",
",",
"msg",
",",
"queue",
"@statsd",
".",
"batch",
"do",
"|",
"b",
"|",
"begin",
"worker_name",
"=",
"worker",
".",
"class",
".",
"name",
".",
"gsub",
"(",
"'::'",
",",
"'.'",
")",
"b",
".",
"time",
"prefix",
"(",
"worker_name",
",",
"'processing_time'",
")",
"do",
"yield",
"end",
"b",
".",
"increment",
"prefix",
"(",
"worker_name",
",",
"'success'",
")",
"rescue",
"=>",
"e",
"b",
".",
"increment",
"prefix",
"(",
"worker_name",
",",
"'failure'",
")",
"raise",
"e",
"ensure",
"if",
"@options",
"[",
":sidekiq_stats",
"]",
"b",
".",
"gauge",
"prefix",
"(",
"'enqueued'",
")",
",",
"@sidekiq_stats",
".",
"enqueued",
"if",
"@sidekiq_stats",
".",
"respond_to?",
"(",
":retry_size",
")",
"b",
".",
"gauge",
"prefix",
"(",
"'retry_set_size'",
")",
",",
"@sidekiq_stats",
".",
"retry_size",
"end",
"b",
".",
"gauge",
"prefix",
"(",
"'processed'",
")",
",",
"@sidekiq_stats",
".",
"processed",
"b",
".",
"gauge",
"prefix",
"(",
"'failed'",
")",
",",
"@sidekiq_stats",
".",
"failed",
"end",
"queue_name",
"=",
"msg",
"[",
"'queue'",
"]",
"sidekiq_queue",
"=",
"Sidekiq",
"::",
"Queue",
".",
"new",
"(",
"queue_name",
")",
"b",
".",
"gauge",
"prefix",
"(",
"'queues'",
",",
"queue_name",
",",
"'enqueued'",
")",
",",
"sidekiq_queue",
".",
"size",
"if",
"sidekiq_queue",
".",
"respond_to?",
"(",
":latency",
")",
"b",
".",
"gauge",
"prefix",
"(",
"'queues'",
",",
"queue_name",
",",
"'latency'",
")",
",",
"sidekiq_queue",
".",
"latency",
"end",
"end",
"end",
"end"
] | Initializes the middleware with options.
@param [Hash] options The options to initialize the StatsD client.
@option options [Statsd] :statsd Existing statsd client.
@option options [String] :env ("production") The env to segment the metric key (e.g. env.prefix.worker_name.success|failure).
@option options [String] :prefix ("worker") The prefix to segment the metric key (e.g. env.prefix.worker_name.success|failure).
@option options [String] :host ("localhost") The StatsD host.
@option options [String] :port ("8125") The StatsD port.
@option options [String] :sidekiq_stats ("true") Send Sidekiq global stats e.g. total enqueued, processed and failed.
Pushes the metrics in a batch.
@param worker [Sidekiq::Worker] The worker the job belongs to.
@param msg [Hash] The job message.
@param queue [String] The current queue. | [
"Initializes",
"the",
"middleware",
"with",
"options",
"."
] | 8ae212173b8860ece70e903a6a8ebd266f1f818e | https://github.com/phstc/sidekiq-statsd/blob/8ae212173b8860ece70e903a6a8ebd266f1f818e/lib/sidekiq/statsd/server_middleware.rb#L37-L74 | train |
rpossan/autoit | lib/autoit/control.rb | AutoIt.Control.control_command_select_string | def control_command_select_string(title, text, control, string)
command 'ControlCommand', [title, text, control, 'SelectString', string]
end | ruby | def control_command_select_string(title, text, control, string)
command 'ControlCommand', [title, text, control, 'SelectString', string]
end | [
"def",
"control_command_select_string",
"(",
"title",
",",
"text",
",",
"control",
",",
"string",
")",
"command",
"'ControlCommand'",
",",
"[",
"title",
",",
"text",
",",
"control",
",",
"'SelectString'",
",",
"string",
"]",
"end"
] | Sets selection according to string in a ListBox or ComboBox
@param: title: The title of the window to access.
@param: text: The text of the window to access.
@param: control: The control to interact with.
@param: string: The string. | [
"Sets",
"selection",
"according",
"to",
"string",
"in",
"a",
"ListBox",
"or",
"ComboBox"
] | f24d1891dac4431830eaf9a7c6afeeada3f653f8 | https://github.com/rpossan/autoit/blob/f24d1891dac4431830eaf9a7c6afeeada3f653f8/lib/autoit/control.rb#L110-L112 | train |
rpossan/autoit | lib/autoit/control.rb | AutoIt.Control.control_set_text | def control_set_text(title, text, control, value)
command_validate'ControlSetText', [title, text, control, value]
end | ruby | def control_set_text(title, text, control, value)
command_validate'ControlSetText', [title, text, control, value]
end | [
"def",
"control_set_text",
"(",
"title",
",",
"text",
",",
"control",
",",
"value",
")",
"command_validate",
"'ControlSetText'",
",",
"[",
"title",
",",
"text",
",",
"control",
",",
"value",
"]",
"end"
] | Sets text of a control.
Sends a string of characters to a control.
@param: title: The title of the window to access.
@param: text: The text of the window to access.
@param: control: The control to interact with.
@param: string: The string.
@return True if success, false otherwise | [
"Sets",
"text",
"of",
"a",
"control",
".",
"Sends",
"a",
"string",
"of",
"characters",
"to",
"a",
"control",
"."
] | f24d1891dac4431830eaf9a7c6afeeada3f653f8 | https://github.com/rpossan/autoit/blob/f24d1891dac4431830eaf9a7c6afeeada3f653f8/lib/autoit/control.rb#L137-L139 | train |
rpossan/autoit | lib/autoit/control.rb | AutoIt.Control.control_click | def control_click(title, text, control, button, clicks, x, y)
command_validate('ControlClick', [title, text, control, button, clicks, x, y])
end | ruby | def control_click(title, text, control, button, clicks, x, y)
command_validate('ControlClick', [title, text, control, button, clicks, x, y])
end | [
"def",
"control_click",
"(",
"title",
",",
"text",
",",
"control",
",",
"button",
",",
"clicks",
",",
"x",
",",
"y",
")",
"command_validate",
"(",
"'ControlClick'",
",",
"[",
"title",
",",
"text",
",",
"control",
",",
"button",
",",
"clicks",
",",
"x",
",",
"y",
"]",
")",
"end"
] | Sends a mouse click command to a given control.
@param: title: The title of the window to access.
@param: text: The text of the window to access.
@param: controlID: The control to interact with.
@param: button: The button to click, "left", "right" or "middle".
@param: clicks: The number of times to click the mouse. Default is center.
@param: x: The x position to click within the control. Default is center.
@param: y: The y position to click within the control. Default is center.
@return: True if success, false otherwise. | [
"Sends",
"a",
"mouse",
"click",
"command",
"to",
"a",
"given",
"control",
"."
] | f24d1891dac4431830eaf9a7c6afeeada3f653f8 | https://github.com/rpossan/autoit/blob/f24d1891dac4431830eaf9a7c6afeeada3f653f8/lib/autoit/control.rb#L150-L152 | train |
rpossan/autoit | lib/autoit/control.rb | AutoIt.Control.control_command_set_current_selection | def control_command_set_current_selection(title, text, control, occurrance)
command('ControlCommand', [title, text, control, 'SetCurrentSelection', occurrance])
end | ruby | def control_command_set_current_selection(title, text, control, occurrance)
command('ControlCommand', [title, text, control, 'SetCurrentSelection', occurrance])
end | [
"def",
"control_command_set_current_selection",
"(",
"title",
",",
"text",
",",
"control",
",",
"occurrance",
")",
"command",
"(",
"'ControlCommand'",
",",
"[",
"title",
",",
"text",
",",
"control",
",",
"'SetCurrentSelection'",
",",
"occurrance",
"]",
")",
"end"
] | Sets selection to occurrence ref in a ListBox or ComboBox.
@param: title: The title of the window to access.
@param: text: The text of the window to access.
@param: control: The control to interact with.
@param: occurrance: the value. | [
"Sets",
"selection",
"to",
"occurrence",
"ref",
"in",
"a",
"ListBox",
"or",
"ComboBox",
"."
] | f24d1891dac4431830eaf9a7c6afeeada3f653f8 | https://github.com/rpossan/autoit/blob/f24d1891dac4431830eaf9a7c6afeeada3f653f8/lib/autoit/control.rb#L159-L161 | train |
stereobooster/html_press | lib/html_press/html.rb | HtmlPress.Html.process_ie_conditional_comments | def process_ie_conditional_comments (out)
out.gsub /(<!--\[[^\]]+\]>([\s\S]*?)<!\[[^\]]+\]-->)\s*/ do
m = $1
comment = $2
comment_compressed = Html.new.press(comment)
m.gsub!(comment, comment_compressed)
reserve m
end
end | ruby | def process_ie_conditional_comments (out)
out.gsub /(<!--\[[^\]]+\]>([\s\S]*?)<!\[[^\]]+\]-->)\s*/ do
m = $1
comment = $2
comment_compressed = Html.new.press(comment)
m.gsub!(comment, comment_compressed)
reserve m
end
end | [
"def",
"process_ie_conditional_comments",
"(",
"out",
")",
"out",
".",
"gsub",
"/",
"\\[",
"\\]",
"\\]",
"\\s",
"\\S",
"\\[",
"\\]",
"\\]",
"\\s",
"/",
"do",
"m",
"=",
"$1",
"comment",
"=",
"$2",
"comment_compressed",
"=",
"Html",
".",
"new",
".",
"press",
"(",
"comment",
")",
"m",
".",
"gsub!",
"(",
"comment",
",",
"comment_compressed",
")",
"reserve",
"m",
"end",
"end"
] | IE conditional comments | [
"IE",
"conditional",
"comments"
] | 4bc4599751708b6054d0d2afc76aa720973dd94f | https://github.com/stereobooster/html_press/blob/4bc4599751708b6054d0d2afc76aa720973dd94f/lib/html_press/html.rb#L57-L65 | train |
stereobooster/html_press | lib/html_press/html.rb | HtmlPress.Html.process_pres | def process_pres (out)
out.gsub /(<pre\b[^>]*?>([\s\S]*?)<\/pre>)\s*/i do
pre = $2
m = $1
pre_compressed = pre.lines.map{ |l| l.gsub(/\s+$/, '') }.join("\n")
pre_compressed = HtmlPress.entities_compressor pre_compressed
m.gsub!(pre, pre_compressed)
reserve m
end
end | ruby | def process_pres (out)
out.gsub /(<pre\b[^>]*?>([\s\S]*?)<\/pre>)\s*/i do
pre = $2
m = $1
pre_compressed = pre.lines.map{ |l| l.gsub(/\s+$/, '') }.join("\n")
pre_compressed = HtmlPress.entities_compressor pre_compressed
m.gsub!(pre, pre_compressed)
reserve m
end
end | [
"def",
"process_pres",
"(",
"out",
")",
"out",
".",
"gsub",
"/",
"\\b",
"\\s",
"\\S",
"\\/",
"\\s",
"/i",
"do",
"pre",
"=",
"$2",
"m",
"=",
"$1",
"pre_compressed",
"=",
"pre",
".",
"lines",
".",
"map",
"{",
"|",
"l",
"|",
"l",
".",
"gsub",
"(",
"/",
"\\s",
"/",
",",
"''",
")",
"}",
".",
"join",
"(",
"\"\\n\"",
")",
"pre_compressed",
"=",
"HtmlPress",
".",
"entities_compressor",
"pre_compressed",
"m",
".",
"gsub!",
"(",
"pre",
",",
"pre_compressed",
")",
"reserve",
"m",
"end",
"end"
] | replace PREs with placeholders | [
"replace",
"PREs",
"with",
"placeholders"
] | 4bc4599751708b6054d0d2afc76aa720973dd94f | https://github.com/stereobooster/html_press/blob/4bc4599751708b6054d0d2afc76aa720973dd94f/lib/html_press/html.rb#L107-L116 | train |
stereobooster/html_press | lib/html_press/html.rb | HtmlPress.Html.process_block_elements | def process_block_elements (out)
re = '\\s+(<\\/?(?:area|base(?:font)?|blockquote|body' +
'|caption|center|cite|col(?:group)?|dd|dir|div|dl|dt|fieldset|form' +
'|frame(?:set)?|h[1-6]|head|hr|html|legend|li|link|map|menu|meta' +
'|ol|opt(?:group|ion)|p|param|t(?:able|body|head|d|h|r|foot|itle)' +
'|ul)\\b[^>]*>)'
re = Regexp.new(re)
out.gsub!(re, '\\1')
# remove whitespaces outside of all elements
out.gsub! />([^<]+)</ do |m|
m.gsub(/^\s+|\s+$/, ' ')
end
out
end | ruby | def process_block_elements (out)
re = '\\s+(<\\/?(?:area|base(?:font)?|blockquote|body' +
'|caption|center|cite|col(?:group)?|dd|dir|div|dl|dt|fieldset|form' +
'|frame(?:set)?|h[1-6]|head|hr|html|legend|li|link|map|menu|meta' +
'|ol|opt(?:group|ion)|p|param|t(?:able|body|head|d|h|r|foot|itle)' +
'|ul)\\b[^>]*>)'
re = Regexp.new(re)
out.gsub!(re, '\\1')
# remove whitespaces outside of all elements
out.gsub! />([^<]+)</ do |m|
m.gsub(/^\s+|\s+$/, ' ')
end
out
end | [
"def",
"process_block_elements",
"(",
"out",
")",
"re",
"=",
"'\\\\s+(<\\\\/?(?:area|base(?:font)?|blockquote|body'",
"+",
"'|caption|center|cite|col(?:group)?|dd|dir|div|dl|dt|fieldset|form'",
"+",
"'|frame(?:set)?|h[1-6]|head|hr|html|legend|li|link|map|menu|meta'",
"+",
"'|ol|opt(?:group|ion)|p|param|t(?:able|body|head|d|h|r|foot|itle)'",
"+",
"'|ul)\\\\b[^>]*>)'",
"re",
"=",
"Regexp",
".",
"new",
"(",
"re",
")",
"out",
".",
"gsub!",
"(",
"re",
",",
"'\\\\1'",
")",
"out",
".",
"gsub!",
"/",
"/",
"do",
"|",
"m",
"|",
"m",
".",
"gsub",
"(",
"/",
"\\s",
"\\s",
"/",
",",
"' '",
")",
"end",
"out",
"end"
] | remove whitespaces outside of block elements | [
"remove",
"whitespaces",
"outside",
"of",
"block",
"elements"
] | 4bc4599751708b6054d0d2afc76aa720973dd94f | https://github.com/stereobooster/html_press/blob/4bc4599751708b6054d0d2afc76aa720973dd94f/lib/html_press/html.rb#L124-L140 | train |
haw-itn/openassets-ruby | lib/openassets/util.rb | OpenAssets.Util.address_to_oa_address | def address_to_oa_address(btc_address)
begin
btc_hex = decode_base58(btc_address)
btc_hex = '0' +btc_hex if btc_hex.size==47
address = btc_hex[0..-9] # bitcoin address without checksum
named_addr = OA_NAMESPACE.to_s(16) + address
oa_checksum = checksum(named_addr)
encode_base58(named_addr + oa_checksum)
rescue ArgumentError
nil # bech32 format fails to decode. TODO define OA address for segwit
end
end | ruby | def address_to_oa_address(btc_address)
begin
btc_hex = decode_base58(btc_address)
btc_hex = '0' +btc_hex if btc_hex.size==47
address = btc_hex[0..-9] # bitcoin address without checksum
named_addr = OA_NAMESPACE.to_s(16) + address
oa_checksum = checksum(named_addr)
encode_base58(named_addr + oa_checksum)
rescue ArgumentError
nil # bech32 format fails to decode. TODO define OA address for segwit
end
end | [
"def",
"address_to_oa_address",
"(",
"btc_address",
")",
"begin",
"btc_hex",
"=",
"decode_base58",
"(",
"btc_address",
")",
"btc_hex",
"=",
"'0'",
"+",
"btc_hex",
"if",
"btc_hex",
".",
"size",
"==",
"47",
"address",
"=",
"btc_hex",
"[",
"0",
"..",
"-",
"9",
"]",
"named_addr",
"=",
"OA_NAMESPACE",
".",
"to_s",
"(",
"16",
")",
"+",
"address",
"oa_checksum",
"=",
"checksum",
"(",
"named_addr",
")",
"encode_base58",
"(",
"named_addr",
"+",
"oa_checksum",
")",
"rescue",
"ArgumentError",
"nil",
"end",
"end"
] | convert bitcoin address to open assets address
@param [String] btc_address The Bitcoin address.
@return [String] The Open Assets Address. | [
"convert",
"bitcoin",
"address",
"to",
"open",
"assets",
"address"
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/util.rb#L17-L28 | train |
haw-itn/openassets-ruby | lib/openassets/util.rb | OpenAssets.Util.oa_address_to_address | def oa_address_to_address(oa_address)
decode_address = decode_base58(oa_address)
btc_addr = decode_address[2..-9]
btc_checksum = checksum(btc_addr)
encode_base58(btc_addr + btc_checksum)
end | ruby | def oa_address_to_address(oa_address)
decode_address = decode_base58(oa_address)
btc_addr = decode_address[2..-9]
btc_checksum = checksum(btc_addr)
encode_base58(btc_addr + btc_checksum)
end | [
"def",
"oa_address_to_address",
"(",
"oa_address",
")",
"decode_address",
"=",
"decode_base58",
"(",
"oa_address",
")",
"btc_addr",
"=",
"decode_address",
"[",
"2",
"..",
"-",
"9",
"]",
"btc_checksum",
"=",
"checksum",
"(",
"btc_addr",
")",
"encode_base58",
"(",
"btc_addr",
"+",
"btc_checksum",
")",
"end"
] | convert open assets address to bitcoin address
@param [String] oa_address The Open Assets Address.
@return [String] The Bitcoin address. | [
"convert",
"open",
"assets",
"address",
"to",
"bitcoin",
"address"
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/util.rb#L33-L38 | train |
haw-itn/openassets-ruby | lib/openassets/util.rb | OpenAssets.Util.valid_asset_id? | def valid_asset_id?(asset_id)
return false if asset_id.nil? || asset_id.length != 34
decoded = decode_base58(asset_id)
return false if decoded[0,2].to_i(16) != oa_version_byte
p2pkh_script_hash = decoded[2..-9]
address = hash160_to_address(p2pkh_script_hash)
valid_address?(address)
end | ruby | def valid_asset_id?(asset_id)
return false if asset_id.nil? || asset_id.length != 34
decoded = decode_base58(asset_id)
return false if decoded[0,2].to_i(16) != oa_version_byte
p2pkh_script_hash = decoded[2..-9]
address = hash160_to_address(p2pkh_script_hash)
valid_address?(address)
end | [
"def",
"valid_asset_id?",
"(",
"asset_id",
")",
"return",
"false",
"if",
"asset_id",
".",
"nil?",
"||",
"asset_id",
".",
"length",
"!=",
"34",
"decoded",
"=",
"decode_base58",
"(",
"asset_id",
")",
"return",
"false",
"if",
"decoded",
"[",
"0",
",",
"2",
"]",
".",
"to_i",
"(",
"16",
")",
"!=",
"oa_version_byte",
"p2pkh_script_hash",
"=",
"decoded",
"[",
"2",
"..",
"-",
"9",
"]",
"address",
"=",
"hash160_to_address",
"(",
"p2pkh_script_hash",
")",
"valid_address?",
"(",
"address",
")",
"end"
] | validate asset ID | [
"validate",
"asset",
"ID"
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/util.rb#L113-L120 | train |
haw-itn/openassets-ruby | lib/openassets/util.rb | OpenAssets.Util.read_var_integer | def read_var_integer(data, offset = 0)
raise ArgumentError, "data is nil." unless data
packed = [data].pack('H*')
return [nil, 0] if packed.bytesize < 1+offset
bytes = packed.bytes[offset..(offset + 9)] # 9 is variable integer max storage length.
first_byte = bytes[0]
if first_byte < 0xfd
[first_byte, offset + 1]
elsif first_byte == 0xfd
[calc_var_integer_val(bytes[1..2]), offset + 3]
elsif first_byte == 0xfe
[calc_var_integer_val(bytes[1..4]), offset + 5]
elsif first_byte == 0xff
[calc_var_integer_val(bytes[1..8]), offset + 9]
end
end | ruby | def read_var_integer(data, offset = 0)
raise ArgumentError, "data is nil." unless data
packed = [data].pack('H*')
return [nil, 0] if packed.bytesize < 1+offset
bytes = packed.bytes[offset..(offset + 9)] # 9 is variable integer max storage length.
first_byte = bytes[0]
if first_byte < 0xfd
[first_byte, offset + 1]
elsif first_byte == 0xfd
[calc_var_integer_val(bytes[1..2]), offset + 3]
elsif first_byte == 0xfe
[calc_var_integer_val(bytes[1..4]), offset + 5]
elsif first_byte == 0xff
[calc_var_integer_val(bytes[1..8]), offset + 9]
end
end | [
"def",
"read_var_integer",
"(",
"data",
",",
"offset",
"=",
"0",
")",
"raise",
"ArgumentError",
",",
"\"data is nil.\"",
"unless",
"data",
"packed",
"=",
"[",
"data",
"]",
".",
"pack",
"(",
"'H*'",
")",
"return",
"[",
"nil",
",",
"0",
"]",
"if",
"packed",
".",
"bytesize",
"<",
"1",
"+",
"offset",
"bytes",
"=",
"packed",
".",
"bytes",
"[",
"offset",
"..",
"(",
"offset",
"+",
"9",
")",
"]",
"first_byte",
"=",
"bytes",
"[",
"0",
"]",
"if",
"first_byte",
"<",
"0xfd",
"[",
"first_byte",
",",
"offset",
"+",
"1",
"]",
"elsif",
"first_byte",
"==",
"0xfd",
"[",
"calc_var_integer_val",
"(",
"bytes",
"[",
"1",
"..",
"2",
"]",
")",
",",
"offset",
"+",
"3",
"]",
"elsif",
"first_byte",
"==",
"0xfe",
"[",
"calc_var_integer_val",
"(",
"bytes",
"[",
"1",
"..",
"4",
"]",
")",
",",
"offset",
"+",
"5",
"]",
"elsif",
"first_byte",
"==",
"0xff",
"[",
"calc_var_integer_val",
"(",
"bytes",
"[",
"1",
"..",
"8",
"]",
")",
",",
"offset",
"+",
"9",
"]",
"end",
"end"
] | read variable integer
@param [String] data reading data
@param [Integer] offset the position when reading from data.
@return [[Integer, Integer]] decoded integer value and the reading byte length.
https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer | [
"read",
"variable",
"integer"
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/util.rb#L127-L142 | train |
haw-itn/openassets-ruby | lib/openassets/util.rb | OpenAssets.Util.read_leb128 | def read_leb128(data, offset = 0)
bytes = [data].pack('H*').bytes
result = 0
shift = 0
while true
return [nil, offset] if bytes.length < 1 + offset
byte = bytes[offset..(offset + 1)][0]
result |= (byte & 0x7f) << shift
break if byte & 0x80 == 0
shift += 7
offset += 1
end
[result, offset + 1]
end | ruby | def read_leb128(data, offset = 0)
bytes = [data].pack('H*').bytes
result = 0
shift = 0
while true
return [nil, offset] if bytes.length < 1 + offset
byte = bytes[offset..(offset + 1)][0]
result |= (byte & 0x7f) << shift
break if byte & 0x80 == 0
shift += 7
offset += 1
end
[result, offset + 1]
end | [
"def",
"read_leb128",
"(",
"data",
",",
"offset",
"=",
"0",
")",
"bytes",
"=",
"[",
"data",
"]",
".",
"pack",
"(",
"'H*'",
")",
".",
"bytes",
"result",
"=",
"0",
"shift",
"=",
"0",
"while",
"true",
"return",
"[",
"nil",
",",
"offset",
"]",
"if",
"bytes",
".",
"length",
"<",
"1",
"+",
"offset",
"byte",
"=",
"bytes",
"[",
"offset",
"..",
"(",
"offset",
"+",
"1",
")",
"]",
"[",
"0",
"]",
"result",
"|=",
"(",
"byte",
"&",
"0x7f",
")",
"<<",
"shift",
"break",
"if",
"byte",
"&",
"0x80",
"==",
"0",
"shift",
"+=",
"7",
"offset",
"+=",
"1",
"end",
"[",
"result",
",",
"offset",
"+",
"1",
"]",
"end"
] | read leb128 value
@param [String] data reading data
@param [Integer] offset start position when reading from data.
@return [[Integer, Integer]] decoded integer value and the reading byte length. | [
"read",
"leb128",
"value"
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/util.rb#L148-L161 | train |
mikerodrigues/arp_scan | lib/arp_scan/scan_report.rb | ARPScan.ScanReport.to_array | def to_array
self.instance_variables.map do |var|
if var == :@hosts
self.instance_variable_get(var).map {|host| host.to_array}
else
self.instance_variable_get(var)
end
end
end | ruby | def to_array
self.instance_variables.map do |var|
if var == :@hosts
self.instance_variable_get(var).map {|host| host.to_array}
else
self.instance_variable_get(var)
end
end
end | [
"def",
"to_array",
"self",
".",
"instance_variables",
".",
"map",
"do",
"|",
"var",
"|",
"if",
"var",
"==",
":@hosts",
"self",
".",
"instance_variable_get",
"(",
"var",
")",
".",
"map",
"{",
"|",
"host",
"|",
"host",
".",
"to_array",
"}",
"else",
"self",
".",
"instance_variable_get",
"(",
"var",
")",
"end",
"end",
"end"
] | Create a new scan report, passing in every attribute. The best way to do
this is with the ScanResultProcessor module.
Returns an array representation of the ScanReport. Metadata about the
scan, and an array of Host arrays comprise the array. | [
"Create",
"a",
"new",
"scan",
"report",
"passing",
"in",
"every",
"attribute",
".",
"The",
"best",
"way",
"to",
"do",
"this",
"is",
"with",
"the",
"ScanResultProcessor",
"module",
"."
] | c0fb8821ce9a08e43e74ed7d219b029c7b6c32c9 | https://github.com/mikerodrigues/arp_scan/blob/c0fb8821ce9a08e43e74ed7d219b029c7b6c32c9/lib/arp_scan/scan_report.rb#L60-L68 | train |
greyblake/telebot | lib/telebot/client.rb | Telebot.Client.get_updates | def get_updates(offset: nil, limit: nil, timeout: nil)
result = call(:getUpdates, offset: offset, limit: limit, timeout: timeout)
result.map { |update_hash| Update.new(update_hash) }
end | ruby | def get_updates(offset: nil, limit: nil, timeout: nil)
result = call(:getUpdates, offset: offset, limit: limit, timeout: timeout)
result.map { |update_hash| Update.new(update_hash) }
end | [
"def",
"get_updates",
"(",
"offset",
":",
"nil",
",",
"limit",
":",
"nil",
",",
"timeout",
":",
"nil",
")",
"result",
"=",
"call",
"(",
":getUpdates",
",",
"offset",
":",
"offset",
",",
"limit",
":",
"limit",
",",
"timeout",
":",
"timeout",
")",
"result",
".",
"map",
"{",
"|",
"update_hash",
"|",
"Update",
".",
"new",
"(",
"update_hash",
")",
"}",
"end"
] | Use this method to receive incoming updates using long polling.
An Array of Update objects is returned.
Note:
1. This method will not work if an outgoing webhook is set up.
2. In order to avoid getting duplicate updates, recalculate offset after each server response.
@param offset [Integer]
Identifier of the first update to be returned.
Must be greater by one than the highest among the identifiers of
previously received updates. By default, updates starting with the
earliest unconfirmed update are returned. An update is considered
confirmed as soon as getUpdates is called with an offset higher
than its update_id.
@param limit [Integer]
Limits the number of updates to be retrieved. Values between 1—100 are accepted.
Defaults to 100
@param timeout [Integer]
Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling.
@return [Array<Telebot::Update>] | [
"Use",
"this",
"method",
"to",
"receive",
"incoming",
"updates",
"using",
"long",
"polling",
".",
"An",
"Array",
"of",
"Update",
"objects",
"is",
"returned",
"."
] | 16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a | https://github.com/greyblake/telebot/blob/16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a/lib/telebot/client.rb#L50-L53 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.