repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
tumblr/collins_client | lib/collins/option.rb | Collins.Option.flat_map | def flat_map &block
if empty? then
None.new
else
res = block.call(get)
if res.is_a?(Some) then
res
else
Some.new(res)
end
end
end | ruby | def flat_map &block
if empty? then
None.new
else
res = block.call(get)
if res.is_a?(Some) then
res
else
Some.new(res)
end
end
end | [
"def",
"flat_map",
"&",
"block",
"if",
"empty?",
"then",
"None",
".",
"new",
"else",
"res",
"=",
"block",
".",
"call",
"(",
"get",
")",
"if",
"res",
".",
"is_a?",
"(",
"Some",
")",
"then",
"res",
"else",
"Some",
".",
"new",
"(",
"res",
")",
"end",
"end",
"end"
] | Same as map, but flatten the results
This is useful when operating on an object that will return an `Option`.
@example
Option(15).flat_map {|i| Option(i).filter{|i2| i2 > 0}} == Some(15)
@see #map
@return [Option<Object>] Optional value | [
"Same",
"as",
"map",
"but",
"flatten",
"the",
"results"
] | e9a58d0f0123232fe3784c8bce1f46dfb12c1637 | https://github.com/tumblr/collins_client/blob/e9a58d0f0123232fe3784c8bce1f46dfb12c1637/lib/collins/option.rb#L128-L139 | train |
jgraichen/restify | lib/restify/resource.rb | Restify.Resource.relation | def relation(name)
if @relations.key? name
Relation.new @context, @relations.fetch(name)
else
Relation.new @context, @relations.fetch(name.to_s)
end
end | ruby | def relation(name)
if @relations.key? name
Relation.new @context, @relations.fetch(name)
else
Relation.new @context, @relations.fetch(name.to_s)
end
end | [
"def",
"relation",
"(",
"name",
")",
"if",
"@relations",
".",
"key?",
"name",
"Relation",
".",
"new",
"@context",
",",
"@relations",
".",
"fetch",
"(",
"name",
")",
"else",
"Relation",
".",
"new",
"@context",
",",
"@relations",
".",
"fetch",
"(",
"name",
".",
"to_s",
")",
"end",
"end"
] | Return relation with given name.
@param name [String, Symbol] Relation name.
@return [Relation] Relation. | [
"Return",
"relation",
"with",
"given",
"name",
"."
] | 6de37f17ee97a650fb30269b5b1fc836aaab4819 | https://github.com/jgraichen/restify/blob/6de37f17ee97a650fb30269b5b1fc836aaab4819/lib/restify/resource.rb#L35-L41 | train |
bitaxis/annotate_models | lib/annotate_models/model_annotation_generator.rb | AnnotateModels.ModelAnnotationGenerator.apply_annotation | def apply_annotation(path, suffix=nil, extension="rb", plural=false)
pn_models = Pathname.new(path)
return unless pn_models.exist?
suffix = "_#{suffix}" unless suffix == nil
extension = (extension == nil) ? "" : ".#{extension}"
@annotations.each do |model, annotation|
prefix = (plural) ? model.name.pluralize : model.name
pn = pn_models + "#{ActiveSupport::Inflector.underscore(prefix)}#{suffix}#{extension}"
text = File.open(pn.to_path) { |fp| fp.read }
re = Regexp.new("^#-(?:--)+-\n# #{model.name}.*\n(?:#.+\n)+#-(?:--)+-\n", Regexp::MULTILINE)
if re =~ text
text = text.sub(re, annotation)
else
text = "#{text}\n#{annotation}"
end
File.open(pn.to_path, "w") { |fp| fp.write(text) }
puts " Annotated #{pn.to_path}."
end
end | ruby | def apply_annotation(path, suffix=nil, extension="rb", plural=false)
pn_models = Pathname.new(path)
return unless pn_models.exist?
suffix = "_#{suffix}" unless suffix == nil
extension = (extension == nil) ? "" : ".#{extension}"
@annotations.each do |model, annotation|
prefix = (plural) ? model.name.pluralize : model.name
pn = pn_models + "#{ActiveSupport::Inflector.underscore(prefix)}#{suffix}#{extension}"
text = File.open(pn.to_path) { |fp| fp.read }
re = Regexp.new("^#-(?:--)+-\n# #{model.name}.*\n(?:#.+\n)+#-(?:--)+-\n", Regexp::MULTILINE)
if re =~ text
text = text.sub(re, annotation)
else
text = "#{text}\n#{annotation}"
end
File.open(pn.to_path, "w") { |fp| fp.write(text) }
puts " Annotated #{pn.to_path}."
end
end | [
"def",
"apply_annotation",
"(",
"path",
",",
"suffix",
"=",
"nil",
",",
"extension",
"=",
"\"rb\"",
",",
"plural",
"=",
"false",
")",
"pn_models",
"=",
"Pathname",
".",
"new",
"(",
"path",
")",
"return",
"unless",
"pn_models",
".",
"exist?",
"suffix",
"=",
"\"_#{suffix}\"",
"unless",
"suffix",
"==",
"nil",
"extension",
"=",
"(",
"extension",
"==",
"nil",
")",
"?",
"\"\"",
":",
"\".#{extension}\"",
"@annotations",
".",
"each",
"do",
"|",
"model",
",",
"annotation",
"|",
"prefix",
"=",
"(",
"plural",
")",
"?",
"model",
".",
"name",
".",
"pluralize",
":",
"model",
".",
"name",
"pn",
"=",
"pn_models",
"+",
"\"#{ActiveSupport::Inflector.underscore(prefix)}#{suffix}#{extension}\"",
"text",
"=",
"File",
".",
"open",
"(",
"pn",
".",
"to_path",
")",
"{",
"|",
"fp",
"|",
"fp",
".",
"read",
"}",
"re",
"=",
"Regexp",
".",
"new",
"(",
"\"^#-(?:--)+-\\n# #{model.name}.*\\n(?:#.+\\n)+#-(?:--)+-\\n\"",
",",
"Regexp",
"::",
"MULTILINE",
")",
"if",
"re",
"=~",
"text",
"text",
"=",
"text",
".",
"sub",
"(",
"re",
",",
"annotation",
")",
"else",
"text",
"=",
"\"#{text}\\n#{annotation}\"",
"end",
"File",
".",
"open",
"(",
"pn",
".",
"to_path",
",",
"\"w\"",
")",
"{",
"|",
"fp",
"|",
"fp",
".",
"write",
"(",
"text",
")",
"}",
"puts",
"\" Annotated #{pn.to_path}.\"",
"end",
"end"
] | Apply annotations to a file
@param path [String] Relative path (from root of application) of directory to apply annotations to.
@param suffix [String] Optionally specify suffix of files to apply annotation to (e.g. "<model.name>_<suffix>.rb").
@param extension [String] Optionally specify extension of files to apply annotaations to (e.g. "<model.name>_<suffix>.<extension>"). | [
"Apply",
"annotations",
"to",
"a",
"file"
] | 0fe3e47973c01016ced9a28ad56ab417169478c7 | https://github.com/bitaxis/annotate_models/blob/0fe3e47973c01016ced9a28ad56ab417169478c7/lib/annotate_models/model_annotation_generator.rb#L20-L38 | train |
bitaxis/annotate_models | lib/annotate_models/model_annotation_generator.rb | AnnotateModels.ModelAnnotationGenerator.generate | def generate
Dir["app/models/*.rb"].each do |path|
result = File.basename(path).scan(/^(.+)\.rb/)[0][0]
model = eval(ActiveSupport::Inflector.camelize(result))
next if model.respond_to?(:abstract_class) && model.abstract_class
next unless model < ActiveRecord::Base
@annotations[model] = generate_annotation(model) unless @annotations.keys.include?(model)
end
end | ruby | def generate
Dir["app/models/*.rb"].each do |path|
result = File.basename(path).scan(/^(.+)\.rb/)[0][0]
model = eval(ActiveSupport::Inflector.camelize(result))
next if model.respond_to?(:abstract_class) && model.abstract_class
next unless model < ActiveRecord::Base
@annotations[model] = generate_annotation(model) unless @annotations.keys.include?(model)
end
end | [
"def",
"generate",
"Dir",
"[",
"\"app/models/*.rb\"",
"]",
".",
"each",
"do",
"|",
"path",
"|",
"result",
"=",
"File",
".",
"basename",
"(",
"path",
")",
".",
"scan",
"(",
"/",
"\\.",
"/",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"model",
"=",
"eval",
"(",
"ActiveSupport",
"::",
"Inflector",
".",
"camelize",
"(",
"result",
")",
")",
"next",
"if",
"model",
".",
"respond_to?",
"(",
":abstract_class",
")",
"&&",
"model",
".",
"abstract_class",
"next",
"unless",
"model",
"<",
"ActiveRecord",
"::",
"Base",
"@annotations",
"[",
"model",
"]",
"=",
"generate_annotation",
"(",
"model",
")",
"unless",
"@annotations",
".",
"keys",
".",
"include?",
"(",
"model",
")",
"end",
"end"
] | Gather model classes and generate annotation for each one. | [
"Gather",
"model",
"classes",
"and",
"generate",
"annotation",
"for",
"each",
"one",
"."
] | 0fe3e47973c01016ced9a28ad56ab417169478c7 | https://github.com/bitaxis/annotate_models/blob/0fe3e47973c01016ced9a28ad56ab417169478c7/lib/annotate_models/model_annotation_generator.rb#L59-L67 | train |
bitaxis/annotate_models | lib/annotate_models/model_annotation_generator.rb | AnnotateModels.ModelAnnotationGenerator.generate_annotation | def generate_annotation(model)
max_column_length = model.columns.collect { |c| c.name.length }.max
annotation = []
annotation << "#-#{'--' * 38}-"
annotation << "# #{model.name}"
annotation << "#"
annotation << sprintf("# %-#{max_column_length}s SQL Type Null Primary Default", "Name")
annotation << sprintf("# %s -------------------- ------- ------- ----------", "-" * max_column_length)
format = "# %-#{max_column_length}s %-20s %-7s %-7s %-10s"
model.columns.each do |column|
annotation << sprintf(
format,
column.name,
column.sql_type,
column.null,
column.name == model.primary_key,
(column.default || "")
)
end
annotation << "#"
annotation << "#-#{'--' * 38}-"
annotation.join("\n") + "\n"
end | ruby | def generate_annotation(model)
max_column_length = model.columns.collect { |c| c.name.length }.max
annotation = []
annotation << "#-#{'--' * 38}-"
annotation << "# #{model.name}"
annotation << "#"
annotation << sprintf("# %-#{max_column_length}s SQL Type Null Primary Default", "Name")
annotation << sprintf("# %s -------------------- ------- ------- ----------", "-" * max_column_length)
format = "# %-#{max_column_length}s %-20s %-7s %-7s %-10s"
model.columns.each do |column|
annotation << sprintf(
format,
column.name,
column.sql_type,
column.null,
column.name == model.primary_key,
(column.default || "")
)
end
annotation << "#"
annotation << "#-#{'--' * 38}-"
annotation.join("\n") + "\n"
end | [
"def",
"generate_annotation",
"(",
"model",
")",
"max_column_length",
"=",
"model",
".",
"columns",
".",
"collect",
"{",
"|",
"c",
"|",
"c",
".",
"name",
".",
"length",
"}",
".",
"max",
"annotation",
"=",
"[",
"]",
"annotation",
"<<",
"\"#-#{'--' * 38}-\"",
"annotation",
"<<",
"\"# #{model.name}\"",
"annotation",
"<<",
"\"#\"",
"annotation",
"<<",
"sprintf",
"(",
"\"# %-#{max_column_length}s SQL Type Null Primary Default\"",
",",
"\"Name\"",
")",
"annotation",
"<<",
"sprintf",
"(",
"\"# %s -------------------- ------- ------- ----------\"",
",",
"\"-\"",
"*",
"max_column_length",
")",
"format",
"=",
"\"# %-#{max_column_length}s %-20s %-7s %-7s %-10s\"",
"model",
".",
"columns",
".",
"each",
"do",
"|",
"column",
"|",
"annotation",
"<<",
"sprintf",
"(",
"format",
",",
"column",
".",
"name",
",",
"column",
".",
"sql_type",
",",
"column",
".",
"null",
",",
"column",
".",
"name",
"==",
"model",
".",
"primary_key",
",",
"(",
"column",
".",
"default",
"||",
"\"\"",
")",
")",
"end",
"annotation",
"<<",
"\"#\"",
"annotation",
"<<",
"\"#-#{'--' * 38}-\"",
"annotation",
".",
"join",
"(",
"\"\\n\"",
")",
"+",
"\"\\n\"",
"end"
] | Generate annotation text.
@param model [Class] An ActiveRecord model class. | [
"Generate",
"annotation",
"text",
"."
] | 0fe3e47973c01016ced9a28ad56ab417169478c7 | https://github.com/bitaxis/annotate_models/blob/0fe3e47973c01016ced9a28ad56ab417169478c7/lib/annotate_models/model_annotation_generator.rb#L85-L107 | train |
JDHeiskell/filebound_client | lib/filebound_client/connection.rb | FileboundClient.Connection.get | def get(url, params)
request = HTTPI::Request.new(resource_url(url, query_params(params[:query])))
execute_request(:get, request, params)
end | ruby | def get(url, params)
request = HTTPI::Request.new(resource_url(url, query_params(params[:query])))
execute_request(:get, request, params)
end | [
"def",
"get",
"(",
"url",
",",
"params",
")",
"request",
"=",
"HTTPI",
"::",
"Request",
".",
"new",
"(",
"resource_url",
"(",
"url",
",",
"query_params",
"(",
"params",
"[",
":query",
"]",
")",
")",
")",
"execute_request",
"(",
":get",
",",
"request",
",",
"params",
")",
"end"
] | Sends a GET request to the supplied resource using the supplied params hash
@param [String] url the url that represents the resource
@param [Hash] params the params Hash that will be sent in the request (keys: query, headers, body)
@return [Net::HTTPResponse] the response from the GET request | [
"Sends",
"a",
"GET",
"request",
"to",
"the",
"supplied",
"resource",
"using",
"the",
"supplied",
"params",
"hash"
] | cbaa56412ede796b4f088470b2b8e6dca1164d39 | https://github.com/JDHeiskell/filebound_client/blob/cbaa56412ede796b4f088470b2b8e6dca1164d39/lib/filebound_client/connection.rb#L105-L108 | train |
JDHeiskell/filebound_client | lib/filebound_client/connection.rb | FileboundClient.Connection.put | def put(url, params)
request = HTTPI::Request.new(resource_url(url, query_params(params[:query])))
request.body = params[:body].to_json
execute_request(:put, request, params)
end | ruby | def put(url, params)
request = HTTPI::Request.new(resource_url(url, query_params(params[:query])))
request.body = params[:body].to_json
execute_request(:put, request, params)
end | [
"def",
"put",
"(",
"url",
",",
"params",
")",
"request",
"=",
"HTTPI",
"::",
"Request",
".",
"new",
"(",
"resource_url",
"(",
"url",
",",
"query_params",
"(",
"params",
"[",
":query",
"]",
")",
")",
")",
"request",
".",
"body",
"=",
"params",
"[",
":body",
"]",
".",
"to_json",
"execute_request",
"(",
":put",
",",
"request",
",",
"params",
")",
"end"
] | Sends a PUT request to the supplied resource using the supplied params hash
@param [String] url the url that represents the resource
@param [Hash] params the params Hash that will be sent in the request (keys: query, headers, body)
@return [Net::HTTPResponse] the response from the PUT request | [
"Sends",
"a",
"PUT",
"request",
"to",
"the",
"supplied",
"resource",
"using",
"the",
"supplied",
"params",
"hash"
] | cbaa56412ede796b4f088470b2b8e6dca1164d39 | https://github.com/JDHeiskell/filebound_client/blob/cbaa56412ede796b4f088470b2b8e6dca1164d39/lib/filebound_client/connection.rb#L114-L118 | train |
JDHeiskell/filebound_client | lib/filebound_client/connection.rb | FileboundClient.Connection.login | def login
response = post('/login', body: { username: configuration.username, password: configuration.password },
headers: { 'Content-Type' => 'application/json' })
if response.code == 200
@token = JSON.parse(response.body, symbolize_names: true, quirks_mode: true)
true
else
false
end
end | ruby | def login
response = post('/login', body: { username: configuration.username, password: configuration.password },
headers: { 'Content-Type' => 'application/json' })
if response.code == 200
@token = JSON.parse(response.body, symbolize_names: true, quirks_mode: true)
true
else
false
end
end | [
"def",
"login",
"response",
"=",
"post",
"(",
"'/login'",
",",
"body",
":",
"{",
"username",
":",
"configuration",
".",
"username",
",",
"password",
":",
"configuration",
".",
"password",
"}",
",",
"headers",
":",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"if",
"response",
".",
"code",
"==",
"200",
"@token",
"=",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
",",
"symbolize_names",
":",
"true",
",",
"quirks_mode",
":",
"true",
")",
"true",
"else",
"false",
"end",
"end"
] | Sends a POST request to the Filebound API's login endpoint to request a new security token
@return [true, false] returns true if the login was successful and the token was set | [
"Sends",
"a",
"POST",
"request",
"to",
"the",
"Filebound",
"API",
"s",
"login",
"endpoint",
"to",
"request",
"a",
"new",
"security",
"token"
] | cbaa56412ede796b4f088470b2b8e6dca1164d39 | https://github.com/JDHeiskell/filebound_client/blob/cbaa56412ede796b4f088470b2b8e6dca1164d39/lib/filebound_client/connection.rb#L141-L150 | train |
nofxx/yamg | lib/yamg/icon.rb | YAMG.Icon.write_out | def write_out(path = nil)
return img unless path
FileUtils.mkdir_p File.dirname(path)
img.write(path)
path
rescue Errno::ENOENT
puts_and_exit("Path not found '#{path}'")
end | ruby | def write_out(path = nil)
return img unless path
FileUtils.mkdir_p File.dirname(path)
img.write(path)
path
rescue Errno::ENOENT
puts_and_exit("Path not found '#{path}'")
end | [
"def",
"write_out",
"(",
"path",
"=",
"nil",
")",
"return",
"img",
"unless",
"path",
"FileUtils",
".",
"mkdir_p",
"File",
".",
"dirname",
"(",
"path",
")",
"img",
".",
"write",
"(",
"path",
")",
"path",
"rescue",
"Errno",
"::",
"ENOENT",
"puts_and_exit",
"(",
"\"Path not found '#{path}'\"",
")",
"end"
] | Writes image to disk | [
"Writes",
"image",
"to",
"disk"
] | 0c8a922045b3271b8bdbe6f7e72c5ee02fb856a4 | https://github.com/nofxx/yamg/blob/0c8a922045b3271b8bdbe6f7e72c5ee02fb856a4/lib/yamg/icon.rb#L138-L145 | train |
jgraichen/restify | lib/restify/error.rb | Restify.ResponseError.errors | def errors
if response.decoded_body
response.decoded_body['errors'] ||
response.decoded_body[:errors] ||
response.decoded_body
else
response.body
end
end | ruby | def errors
if response.decoded_body
response.decoded_body['errors'] ||
response.decoded_body[:errors] ||
response.decoded_body
else
response.body
end
end | [
"def",
"errors",
"if",
"response",
".",
"decoded_body",
"response",
".",
"decoded_body",
"[",
"'errors'",
"]",
"||",
"response",
".",
"decoded_body",
"[",
":errors",
"]",
"||",
"response",
".",
"decoded_body",
"else",
"response",
".",
"body",
"end",
"end"
] | Return hash or array of errors if response included
such a thing otherwise it returns nil. | [
"Return",
"hash",
"or",
"array",
"of",
"errors",
"if",
"response",
"included",
"such",
"a",
"thing",
"otherwise",
"it",
"returns",
"nil",
"."
] | 6de37f17ee97a650fb30269b5b1fc836aaab4819 | https://github.com/jgraichen/restify/blob/6de37f17ee97a650fb30269b5b1fc836aaab4819/lib/restify/error.rb#L71-L79 | train |
pillowfactory/csv-mapper | lib/csv-mapper/row_map.rb | CsvMapper.RowMap.read_attributes_from_file | def read_attributes_from_file aliases = {}
attributes = FasterCSV.new(@csv_data, @parser_options).readline
@start_at_row = [ @start_at_row, 1 ].max
@csv_data.rewind
attributes.each_with_index do |name, index|
name.strip!
use_name = aliases[name] || name.gsub(/\s+/, '_').gsub(/[\W]+/, '').downcase
add_attribute use_name, index
end
end | ruby | def read_attributes_from_file aliases = {}
attributes = FasterCSV.new(@csv_data, @parser_options).readline
@start_at_row = [ @start_at_row, 1 ].max
@csv_data.rewind
attributes.each_with_index do |name, index|
name.strip!
use_name = aliases[name] || name.gsub(/\s+/, '_').gsub(/[\W]+/, '').downcase
add_attribute use_name, index
end
end | [
"def",
"read_attributes_from_file",
"aliases",
"=",
"{",
"}",
"attributes",
"=",
"FasterCSV",
".",
"new",
"(",
"@csv_data",
",",
"@parser_options",
")",
".",
"readline",
"@start_at_row",
"=",
"[",
"@start_at_row",
",",
"1",
"]",
".",
"max",
"@csv_data",
".",
"rewind",
"attributes",
".",
"each_with_index",
"do",
"|",
"name",
",",
"index",
"|",
"name",
".",
"strip!",
"use_name",
"=",
"aliases",
"[",
"name",
"]",
"||",
"name",
".",
"gsub",
"(",
"/",
"\\s",
"/",
",",
"'_'",
")",
".",
"gsub",
"(",
"/",
"\\W",
"/",
",",
"''",
")",
".",
"downcase",
"add_attribute",
"use_name",
",",
"index",
"end",
"end"
] | Allow us to read the first line of a csv file to automatically generate the attribute names.
Spaces are replaced with underscores and non-word characters are removed.
Keep in mind that there is potential for overlap in using this (i.e. you have a field named
files+ and one named files- and they both get named 'files').
You can specify aliases to rename fields to prevent conflicts and/or improve readability and compatibility.
i.e. read_attributes_from_file('files+' => 'files_plus', 'files-' => 'files_minus) | [
"Allow",
"us",
"to",
"read",
"the",
"first",
"line",
"of",
"a",
"csv",
"file",
"to",
"automatically",
"generate",
"the",
"attribute",
"names",
".",
"Spaces",
"are",
"replaced",
"with",
"underscores",
"and",
"non",
"-",
"word",
"characters",
"are",
"removed",
"."
] | 4eb58109cd9f70e29312d150e39a5d18fe1813e6 | https://github.com/pillowfactory/csv-mapper/blob/4eb58109cd9f70e29312d150e39a5d18fe1813e6/lib/csv-mapper/row_map.rb#L51-L60 | train |
pillowfactory/csv-mapper | lib/csv-mapper/row_map.rb | CsvMapper.RowMap.parse | def parse(csv_row)
target = self.map_to_class.new
@before_filters.each {|filter| filter.call(csv_row, target) }
self.mapped_attributes.each do |attr_map|
target.send("#{attr_map.name}=", attr_map.parse(csv_row))
end
@after_filters.each {|filter| filter.call(csv_row, target) }
return target
end | ruby | def parse(csv_row)
target = self.map_to_class.new
@before_filters.each {|filter| filter.call(csv_row, target) }
self.mapped_attributes.each do |attr_map|
target.send("#{attr_map.name}=", attr_map.parse(csv_row))
end
@after_filters.each {|filter| filter.call(csv_row, target) }
return target
end | [
"def",
"parse",
"(",
"csv_row",
")",
"target",
"=",
"self",
".",
"map_to_class",
".",
"new",
"@before_filters",
".",
"each",
"{",
"|",
"filter",
"|",
"filter",
".",
"call",
"(",
"csv_row",
",",
"target",
")",
"}",
"self",
".",
"mapped_attributes",
".",
"each",
"do",
"|",
"attr_map",
"|",
"target",
".",
"send",
"(",
"\"#{attr_map.name}=\"",
",",
"attr_map",
".",
"parse",
"(",
"csv_row",
")",
")",
"end",
"@after_filters",
".",
"each",
"{",
"|",
"filter",
"|",
"filter",
".",
"call",
"(",
"csv_row",
",",
"target",
")",
"}",
"return",
"target",
"end"
] | Given a CSV row return an instance of an object defined by this mapping | [
"Given",
"a",
"CSV",
"row",
"return",
"an",
"instance",
"of",
"an",
"object",
"defined",
"by",
"this",
"mapping"
] | 4eb58109cd9f70e29312d150e39a5d18fe1813e6 | https://github.com/pillowfactory/csv-mapper/blob/4eb58109cd9f70e29312d150e39a5d18fe1813e6/lib/csv-mapper/row_map.rb#L127-L138 | train |
substancelab/rconomic | lib/economic/proxies/current_invoice_proxy.rb | Economic.CurrentInvoiceProxy.initialize_properties_with_values_from_owner | def initialize_properties_with_values_from_owner(invoice)
if owner.is_a?(Debtor)
invoice.debtor = owner
invoice.debtor_name ||= owner.name
invoice.debtor_address ||= owner.address
invoice.debtor_postal_code ||= owner.postal_code
invoice.debtor_city ||= owner.city
invoice.term_of_payment_handle ||= owner.term_of_payment_handle
invoice.layout_handle ||= owner.layout_handle
invoice.currency_handle ||= owner.currency_handle
end
end | ruby | def initialize_properties_with_values_from_owner(invoice)
if owner.is_a?(Debtor)
invoice.debtor = owner
invoice.debtor_name ||= owner.name
invoice.debtor_address ||= owner.address
invoice.debtor_postal_code ||= owner.postal_code
invoice.debtor_city ||= owner.city
invoice.term_of_payment_handle ||= owner.term_of_payment_handle
invoice.layout_handle ||= owner.layout_handle
invoice.currency_handle ||= owner.currency_handle
end
end | [
"def",
"initialize_properties_with_values_from_owner",
"(",
"invoice",
")",
"if",
"owner",
".",
"is_a?",
"(",
"Debtor",
")",
"invoice",
".",
"debtor",
"=",
"owner",
"invoice",
".",
"debtor_name",
"||=",
"owner",
".",
"name",
"invoice",
".",
"debtor_address",
"||=",
"owner",
".",
"address",
"invoice",
".",
"debtor_postal_code",
"||=",
"owner",
".",
"postal_code",
"invoice",
".",
"debtor_city",
"||=",
"owner",
".",
"city",
"invoice",
".",
"term_of_payment_handle",
"||=",
"owner",
".",
"term_of_payment_handle",
"invoice",
".",
"layout_handle",
"||=",
"owner",
".",
"layout_handle",
"invoice",
".",
"currency_handle",
"||=",
"owner",
".",
"currency_handle",
"end",
"end"
] | Initialize properties in invoice with values from owner | [
"Initialize",
"properties",
"in",
"invoice",
"with",
"values",
"from",
"owner"
] | cae2dcafd640707a5d42d657b080a066efd19dc0 | https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/current_invoice_proxy.rb#L13-L26 | train |
substancelab/rconomic | lib/economic/proxies/current_invoice_line_proxy.rb | Economic.CurrentInvoiceLineProxy.find | def find(handle)
handle = Entity::Handle.build(:number => handle) unless handle.is_a?(Entity::Handle)
super(handle)
end | ruby | def find(handle)
handle = Entity::Handle.build(:number => handle) unless handle.is_a?(Entity::Handle)
super(handle)
end | [
"def",
"find",
"(",
"handle",
")",
"handle",
"=",
"Entity",
"::",
"Handle",
".",
"build",
"(",
":number",
"=>",
"handle",
")",
"unless",
"handle",
".",
"is_a?",
"(",
"Entity",
"::",
"Handle",
")",
"super",
"(",
"handle",
")",
"end"
] | Gets data for CurrentInvoiceLine from the API | [
"Gets",
"data",
"for",
"CurrentInvoiceLine",
"from",
"the",
"API"
] | cae2dcafd640707a5d42d657b080a066efd19dc0 | https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/current_invoice_line_proxy.rb#L8-L11 | train |
livingsocial/imprint | lib/imprint/log_helpers.rb | Imprint.LogHelpers.log_entrypoint | def log_entrypoint
raise "you must call Imprint.configuration and configure the gem before using LogHelpers" if Imprint.configuration.nil?
log_filter = ActionDispatch::Http::ParameterFilter.new(Imprint.configuration[:log_filters] || Rails.application.config.filter_parameters)
# I should probably switch this to be a whitelist as well, or support both white and black lists for both cookies and headers
header_blacklist = Imprint.configuration[:header_blacklist] || []
cookies_whitelist = Imprint.configuration[:cookies_whitelist] || []
param_level = Imprint.configuration[:param_level] || Imprint::QUERY_PARAMS
http_request_headers = request.headers.select{|header_name, header_value| header_name.match("^HTTP.*") && !header_blacklist.include?(header_name) }
data_append = "headers: "
if http_request_headers.respond_to?(:each_pair)
http_request_headers.each_pair{|k,v| data_append << " #{k}=\"#{v}\"" }
else
http_request_headers.each{|el| data_append << " #{el.first}=\"#{el.last}\"" }
end
data_append << " params: "
if param_level==Imprint::FULL_PARAMS
set_full_params(log_filter, data_append)
elsif param_level==Imprint::FULL_GET_PARAMS
if request.get?
set_full_params(log_filter, data_append)
else
set_query_params(log_filter, data_append)
end
else
set_query_params(log_filter, data_append)
end
if defined? cookies
cookies_whitelist.each do |cookie_key|
cookie_val = cookies[cookie_key] ? cookies[cookie_key] : 'nil'
data_append << " #{cookie_key}=\"#{cookie_val}\""
end
end
logger.info "Started request_method=#{request.method.inspect} request_url=\"#{request.path}\" request_time=\"#{Time.now.to_default_s}\" request_ip=#{request.remote_ip.inspect} #{data_append}"
rescue => e
logger.error "error logging log_entrypoint for request: #{e.inspect}"
logger.error e.backtrace.take(10).join("\n")
end | ruby | def log_entrypoint
raise "you must call Imprint.configuration and configure the gem before using LogHelpers" if Imprint.configuration.nil?
log_filter = ActionDispatch::Http::ParameterFilter.new(Imprint.configuration[:log_filters] || Rails.application.config.filter_parameters)
# I should probably switch this to be a whitelist as well, or support both white and black lists for both cookies and headers
header_blacklist = Imprint.configuration[:header_blacklist] || []
cookies_whitelist = Imprint.configuration[:cookies_whitelist] || []
param_level = Imprint.configuration[:param_level] || Imprint::QUERY_PARAMS
http_request_headers = request.headers.select{|header_name, header_value| header_name.match("^HTTP.*") && !header_blacklist.include?(header_name) }
data_append = "headers: "
if http_request_headers.respond_to?(:each_pair)
http_request_headers.each_pair{|k,v| data_append << " #{k}=\"#{v}\"" }
else
http_request_headers.each{|el| data_append << " #{el.first}=\"#{el.last}\"" }
end
data_append << " params: "
if param_level==Imprint::FULL_PARAMS
set_full_params(log_filter, data_append)
elsif param_level==Imprint::FULL_GET_PARAMS
if request.get?
set_full_params(log_filter, data_append)
else
set_query_params(log_filter, data_append)
end
else
set_query_params(log_filter, data_append)
end
if defined? cookies
cookies_whitelist.each do |cookie_key|
cookie_val = cookies[cookie_key] ? cookies[cookie_key] : 'nil'
data_append << " #{cookie_key}=\"#{cookie_val}\""
end
end
logger.info "Started request_method=#{request.method.inspect} request_url=\"#{request.path}\" request_time=\"#{Time.now.to_default_s}\" request_ip=#{request.remote_ip.inspect} #{data_append}"
rescue => e
logger.error "error logging log_entrypoint for request: #{e.inspect}"
logger.error e.backtrace.take(10).join("\n")
end | [
"def",
"log_entrypoint",
"raise",
"\"you must call Imprint.configuration and configure the gem before using LogHelpers\"",
"if",
"Imprint",
".",
"configuration",
".",
"nil?",
"log_filter",
"=",
"ActionDispatch",
"::",
"Http",
"::",
"ParameterFilter",
".",
"new",
"(",
"Imprint",
".",
"configuration",
"[",
":log_filters",
"]",
"||",
"Rails",
".",
"application",
".",
"config",
".",
"filter_parameters",
")",
"header_blacklist",
"=",
"Imprint",
".",
"configuration",
"[",
":header_blacklist",
"]",
"||",
"[",
"]",
"cookies_whitelist",
"=",
"Imprint",
".",
"configuration",
"[",
":cookies_whitelist",
"]",
"||",
"[",
"]",
"param_level",
"=",
"Imprint",
".",
"configuration",
"[",
":param_level",
"]",
"||",
"Imprint",
"::",
"QUERY_PARAMS",
"http_request_headers",
"=",
"request",
".",
"headers",
".",
"select",
"{",
"|",
"header_name",
",",
"header_value",
"|",
"header_name",
".",
"match",
"(",
"\"^HTTP.*\"",
")",
"&&",
"!",
"header_blacklist",
".",
"include?",
"(",
"header_name",
")",
"}",
"data_append",
"=",
"\"headers: \"",
"if",
"http_request_headers",
".",
"respond_to?",
"(",
":each_pair",
")",
"http_request_headers",
".",
"each_pair",
"{",
"|",
"k",
",",
"v",
"|",
"data_append",
"<<",
"\" #{k}=\\\"#{v}\\\"\"",
"}",
"else",
"http_request_headers",
".",
"each",
"{",
"|",
"el",
"|",
"data_append",
"<<",
"\" #{el.first}=\\\"#{el.last}\\\"\"",
"}",
"end",
"data_append",
"<<",
"\" params: \"",
"if",
"param_level",
"==",
"Imprint",
"::",
"FULL_PARAMS",
"set_full_params",
"(",
"log_filter",
",",
"data_append",
")",
"elsif",
"param_level",
"==",
"Imprint",
"::",
"FULL_GET_PARAMS",
"if",
"request",
".",
"get?",
"set_full_params",
"(",
"log_filter",
",",
"data_append",
")",
"else",
"set_query_params",
"(",
"log_filter",
",",
"data_append",
")",
"end",
"else",
"set_query_params",
"(",
"log_filter",
",",
"data_append",
")",
"end",
"if",
"defined?",
"cookies",
"cookies_whitelist",
".",
"each",
"do",
"|",
"cookie_key",
"|",
"cookie_val",
"=",
"cookies",
"[",
"cookie_key",
"]",
"?",
"cookies",
"[",
"cookie_key",
"]",
":",
"'nil'",
"data_append",
"<<",
"\" #{cookie_key}=\\\"#{cookie_val}\\\"\"",
"end",
"end",
"logger",
".",
"info",
"\"Started request_method=#{request.method.inspect} request_url=\\\"#{request.path}\\\" request_time=\\\"#{Time.now.to_default_s}\\\" request_ip=#{request.remote_ip.inspect} #{data_append}\"",
"rescue",
"=>",
"e",
"logger",
".",
"error",
"\"error logging log_entrypoint for request: #{e.inspect}\"",
"logger",
".",
"error",
"e",
".",
"backtrace",
".",
"take",
"(",
"10",
")",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] | Not relying on default rails logging, we more often use lograge.
We still want to log incoming params safely, which lograge doesn't include
this does the same sensative param filtering as rails defaults
It also allows for logging headers and cookies | [
"Not",
"relying",
"on",
"default",
"rails",
"logging",
"we",
"more",
"often",
"use",
"lograge",
".",
"We",
"still",
"want",
"to",
"log",
"incoming",
"params",
"safely",
"which",
"lograge",
"doesn",
"t",
"include",
"this",
"does",
"the",
"same",
"sensative",
"param",
"filtering",
"as",
"rails",
"defaults",
"It",
"also",
"allows",
"for",
"logging",
"headers",
"and",
"cookies"
] | 51a4cd9c96f9e06e98be68666f421d927965edc5 | https://github.com/livingsocial/imprint/blob/51a4cd9c96f9e06e98be68666f421d927965edc5/lib/imprint/log_helpers.rb#L8-L49 | train |
substancelab/rconomic | lib/economic/proxies/actions/find_by_date_interval.rb | Economic.FindByDateInterval.find_by_date_interval | def find_by_date_interval(from, unto)
response = request(:find_by_date_interval, "first" => from.iso8601,
"last" => unto.iso8601)
handle_key = "#{Support::String.underscore(entity_class_name)}_handle".intern
handles = [response[handle_key]].flatten.reject(&:blank?).collect do |handle|
Entity::Handle.build(handle)
end
get_data_array(handles).collect do |entity_hash|
entity = build(entity_hash)
entity.persisted = true
entity
end
end | ruby | def find_by_date_interval(from, unto)
response = request(:find_by_date_interval, "first" => from.iso8601,
"last" => unto.iso8601)
handle_key = "#{Support::String.underscore(entity_class_name)}_handle".intern
handles = [response[handle_key]].flatten.reject(&:blank?).collect do |handle|
Entity::Handle.build(handle)
end
get_data_array(handles).collect do |entity_hash|
entity = build(entity_hash)
entity.persisted = true
entity
end
end | [
"def",
"find_by_date_interval",
"(",
"from",
",",
"unto",
")",
"response",
"=",
"request",
"(",
":find_by_date_interval",
",",
"\"first\"",
"=>",
"from",
".",
"iso8601",
",",
"\"last\"",
"=>",
"unto",
".",
"iso8601",
")",
"handle_key",
"=",
"\"#{Support::String.underscore(entity_class_name)}_handle\"",
".",
"intern",
"handles",
"=",
"[",
"response",
"[",
"handle_key",
"]",
"]",
".",
"flatten",
".",
"reject",
"(",
"&",
":blank?",
")",
".",
"collect",
"do",
"|",
"handle",
"|",
"Entity",
"::",
"Handle",
".",
"build",
"(",
"handle",
")",
"end",
"get_data_array",
"(",
"handles",
")",
".",
"collect",
"do",
"|",
"entity_hash",
"|",
"entity",
"=",
"build",
"(",
"entity_hash",
")",
"entity",
".",
"persisted",
"=",
"true",
"entity",
"end",
"end"
] | Returns entity objects for a given interval of days. | [
"Returns",
"entity",
"objects",
"for",
"a",
"given",
"interval",
"of",
"days",
"."
] | cae2dcafd640707a5d42d657b080a066efd19dc0 | https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/actions/find_by_date_interval.rb#L6-L20 | train |
substancelab/rconomic | lib/economic/entity.rb | Economic.Entity.get_data | def get_data
response = proxy.get_data(handle)
update_properties(response)
self.partial = false
self.persisted = true
end | ruby | def get_data
response = proxy.get_data(handle)
update_properties(response)
self.partial = false
self.persisted = true
end | [
"def",
"get_data",
"response",
"=",
"proxy",
".",
"get_data",
"(",
"handle",
")",
"update_properties",
"(",
"response",
")",
"self",
".",
"partial",
"=",
"false",
"self",
".",
"persisted",
"=",
"true",
"end"
] | Updates Entity with its data from the API | [
"Updates",
"Entity",
"with",
"its",
"data",
"from",
"the",
"API"
] | cae2dcafd640707a5d42d657b080a066efd19dc0 | https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/entity.rb#L111-L116 | train |
substancelab/rconomic | lib/economic/entity.rb | Economic.Entity.destroy | def destroy
handleKey = "#{Support::String.camel_back(class_name)}Handle"
response = request(:delete, handleKey => handle.to_hash)
@persisted = false
@partial = true
response
end | ruby | def destroy
handleKey = "#{Support::String.camel_back(class_name)}Handle"
response = request(:delete, handleKey => handle.to_hash)
@persisted = false
@partial = true
response
end | [
"def",
"destroy",
"handleKey",
"=",
"\"#{Support::String.camel_back(class_name)}Handle\"",
"response",
"=",
"request",
"(",
":delete",
",",
"handleKey",
"=>",
"handle",
".",
"to_hash",
")",
"@persisted",
"=",
"false",
"@partial",
"=",
"true",
"response",
"end"
] | Deletes entity permanently from E-conomic. | [
"Deletes",
"entity",
"permanently",
"from",
"E",
"-",
"conomic",
"."
] | cae2dcafd640707a5d42d657b080a066efd19dc0 | https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/entity.rb#L160-L168 | train |
substancelab/rconomic | lib/economic/entity.rb | Economic.Entity.update_properties | def update_properties(hash)
hash.each do |key, value|
setter_method = "#{key}="
if respond_to?(setter_method)
send(setter_method, value)
end
end
end | ruby | def update_properties(hash)
hash.each do |key, value|
setter_method = "#{key}="
if respond_to?(setter_method)
send(setter_method, value)
end
end
end | [
"def",
"update_properties",
"(",
"hash",
")",
"hash",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"setter_method",
"=",
"\"#{key}=\"",
"if",
"respond_to?",
"(",
"setter_method",
")",
"send",
"(",
"setter_method",
",",
"value",
")",
"end",
"end",
"end"
] | Updates properties of Entity with the values from hash | [
"Updates",
"properties",
"of",
"Entity",
"with",
"the",
"values",
"from",
"hash"
] | cae2dcafd640707a5d42d657b080a066efd19dc0 | https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/entity.rb#L171-L178 | train |
errorstudio/voipfone_client | lib/voipfone_client/sms.rb | VoipfoneClient.SMS.send | def send
if @to.nil? || @from.nil? || @message.nil?
raise ArgumentError, "You need to include 'to' and 'from' numbers and a message to send an SMS"
end
to = @to.gsub(" ","")
from = @from.gsub(" ","")
parameters = {
"sms-send-to" => to,
"sms-send-from" => from,
"sms-message" => @message[0..159]
}
request = @browser.post("#{VoipfoneClient::API_POST_URL}?smsSend", parameters)
response = parse_response(request)
if response == "ok"
return true
else
raise VoipfoneAPIError, response
end
end | ruby | def send
if @to.nil? || @from.nil? || @message.nil?
raise ArgumentError, "You need to include 'to' and 'from' numbers and a message to send an SMS"
end
to = @to.gsub(" ","")
from = @from.gsub(" ","")
parameters = {
"sms-send-to" => to,
"sms-send-from" => from,
"sms-message" => @message[0..159]
}
request = @browser.post("#{VoipfoneClient::API_POST_URL}?smsSend", parameters)
response = parse_response(request)
if response == "ok"
return true
else
raise VoipfoneAPIError, response
end
end | [
"def",
"send",
"if",
"@to",
".",
"nil?",
"||",
"@from",
".",
"nil?",
"||",
"@message",
".",
"nil?",
"raise",
"ArgumentError",
",",
"\"You need to include 'to' and 'from' numbers and a message to send an SMS\"",
"end",
"to",
"=",
"@to",
".",
"gsub",
"(",
"\" \"",
",",
"\"\"",
")",
"from",
"=",
"@from",
".",
"gsub",
"(",
"\" \"",
",",
"\"\"",
")",
"parameters",
"=",
"{",
"\"sms-send-to\"",
"=>",
"to",
",",
"\"sms-send-from\"",
"=>",
"from",
",",
"\"sms-message\"",
"=>",
"@message",
"[",
"0",
"..",
"159",
"]",
"}",
"request",
"=",
"@browser",
".",
"post",
"(",
"\"#{VoipfoneClient::API_POST_URL}?smsSend\"",
",",
"parameters",
")",
"response",
"=",
"parse_response",
"(",
"request",
")",
"if",
"response",
"==",
"\"ok\"",
"return",
"true",
"else",
"raise",
"VoipfoneAPIError",
",",
"response",
"end",
"end"
] | Constructor to create an SMS - optionally pass in to, from and message
@param to [String] the phone number to send the SMS to, as a string. Spaces will be stripped; + symbol allowed.
@param from [String] the phone number to send the SMS from, as a string. Spaces will be stripped; + symbol allowed.
@param message [String] the message to send. The first 160 characters only will be sent.
Send an sms from your account. | [
"Constructor",
"to",
"create",
"an",
"SMS",
"-",
"optionally",
"pass",
"in",
"to",
"from",
"and",
"message"
] | 83bd19fdbaffd7d5029e445faf3456126bb4ca11 | https://github.com/errorstudio/voipfone_client/blob/83bd19fdbaffd7d5029e445faf3456126bb4ca11/lib/voipfone_client/sms.rb#L17-L35 | train |
substancelab/rconomic | lib/economic/proxies/entity_proxy.rb | Economic.EntityProxy.all | def all
response = request(:get_all)
handles = response.values.flatten.collect { |handle| Entity::Handle.build(handle) }
get_data_for_handles(handles)
self
end | ruby | def all
response = request(:get_all)
handles = response.values.flatten.collect { |handle| Entity::Handle.build(handle) }
get_data_for_handles(handles)
self
end | [
"def",
"all",
"response",
"=",
"request",
"(",
":get_all",
")",
"handles",
"=",
"response",
".",
"values",
".",
"flatten",
".",
"collect",
"{",
"|",
"handle",
"|",
"Entity",
"::",
"Handle",
".",
"build",
"(",
"handle",
")",
"}",
"get_data_for_handles",
"(",
"handles",
")",
"self",
"end"
] | Fetches all entities from the API. | [
"Fetches",
"all",
"entities",
"from",
"the",
"API",
"."
] | cae2dcafd640707a5d42d657b080a066efd19dc0 | https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/entity_proxy.rb#L36-L42 | train |
substancelab/rconomic | lib/economic/proxies/entity_proxy.rb | Economic.EntityProxy.find | def find(handle)
handle = build_handle(handle)
entity_hash = get_data(handle)
entity = build(entity_hash)
entity.persisted = true
entity
end | ruby | def find(handle)
handle = build_handle(handle)
entity_hash = get_data(handle)
entity = build(entity_hash)
entity.persisted = true
entity
end | [
"def",
"find",
"(",
"handle",
")",
"handle",
"=",
"build_handle",
"(",
"handle",
")",
"entity_hash",
"=",
"get_data",
"(",
"handle",
")",
"entity",
"=",
"build",
"(",
"entity_hash",
")",
"entity",
".",
"persisted",
"=",
"true",
"entity",
"end"
] | Fetches Entity data from API and returns an Entity initialized with that
data added to Proxy | [
"Fetches",
"Entity",
"data",
"from",
"API",
"and",
"returns",
"an",
"Entity",
"initialized",
"with",
"that",
"data",
"added",
"to",
"Proxy"
] | cae2dcafd640707a5d42d657b080a066efd19dc0 | https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/entity_proxy.rb#L69-L75 | train |
substancelab/rconomic | lib/economic/proxies/entity_proxy.rb | Economic.EntityProxy.get_data | def get_data(handle)
handle = Entity::Handle.new(handle)
entity_hash = request(:get_data, "entityHandle" => handle.to_hash)
entity_hash
end | ruby | def get_data(handle)
handle = Entity::Handle.new(handle)
entity_hash = request(:get_data, "entityHandle" => handle.to_hash)
entity_hash
end | [
"def",
"get_data",
"(",
"handle",
")",
"handle",
"=",
"Entity",
"::",
"Handle",
".",
"new",
"(",
"handle",
")",
"entity_hash",
"=",
"request",
"(",
":get_data",
",",
"\"entityHandle\"",
"=>",
"handle",
".",
"to_hash",
")",
"entity_hash",
"end"
] | Gets data for Entity from the API. Returns Hash with the response data | [
"Gets",
"data",
"for",
"Entity",
"from",
"the",
"API",
".",
"Returns",
"Hash",
"with",
"the",
"response",
"data"
] | cae2dcafd640707a5d42d657b080a066efd19dc0 | https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/entity_proxy.rb#L78-L82 | train |
substancelab/rconomic | lib/economic/proxies/entity_proxy.rb | Economic.EntityProxy.get_data_array | def get_data_array(handles)
return [] unless handles && handles.any?
entity_class_name_for_soap_request = entity_class.name.split("::").last
response = request(:get_data_array, "entityHandles" => {"#{entity_class_name_for_soap_request}Handle" => handles.collect(&:to_hash)})
[response["#{entity_class.key}_data".intern]].flatten
end | ruby | def get_data_array(handles)
return [] unless handles && handles.any?
entity_class_name_for_soap_request = entity_class.name.split("::").last
response = request(:get_data_array, "entityHandles" => {"#{entity_class_name_for_soap_request}Handle" => handles.collect(&:to_hash)})
[response["#{entity_class.key}_data".intern]].flatten
end | [
"def",
"get_data_array",
"(",
"handles",
")",
"return",
"[",
"]",
"unless",
"handles",
"&&",
"handles",
".",
"any?",
"entity_class_name_for_soap_request",
"=",
"entity_class",
".",
"name",
".",
"split",
"(",
"\"::\"",
")",
".",
"last",
"response",
"=",
"request",
"(",
":get_data_array",
",",
"\"entityHandles\"",
"=>",
"{",
"\"#{entity_class_name_for_soap_request}Handle\"",
"=>",
"handles",
".",
"collect",
"(",
"&",
":to_hash",
")",
"}",
")",
"[",
"response",
"[",
"\"#{entity_class.key}_data\"",
".",
"intern",
"]",
"]",
".",
"flatten",
"end"
] | Fetches all data for the given handles. Returns Array with hashes of
entity data | [
"Fetches",
"all",
"data",
"for",
"the",
"given",
"handles",
".",
"Returns",
"Array",
"with",
"hashes",
"of",
"entity",
"data"
] | cae2dcafd640707a5d42d657b080a066efd19dc0 | https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/entity_proxy.rb#L112-L118 | train |
substancelab/rconomic | lib/economic/proxies/entity_proxy.rb | Economic.EntityProxy.request | def request(action, data = nil)
session.request(
Endpoint.new.soap_action_name(entity_class, action),
data
)
end | ruby | def request(action, data = nil)
session.request(
Endpoint.new.soap_action_name(entity_class, action),
data
)
end | [
"def",
"request",
"(",
"action",
",",
"data",
"=",
"nil",
")",
"session",
".",
"request",
"(",
"Endpoint",
".",
"new",
".",
"soap_action_name",
"(",
"entity_class",
",",
"action",
")",
",",
"data",
")",
"end"
] | Requests an action from the API endpoint | [
"Requests",
"an",
"action",
"from",
"the",
"API",
"endpoint"
] | cae2dcafd640707a5d42d657b080a066efd19dc0 | https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/entity_proxy.rb#L147-L152 | train |
substancelab/rconomic | lib/economic/proxies/order_proxy.rb | Economic.OrderProxy.current | def current
response = request(:get_all_current)
handles = response.values.flatten.collect { |handle| Entity::Handle.build(handle) }
initialize_items
get_data_for_handles(handles)
self
end | ruby | def current
response = request(:get_all_current)
handles = response.values.flatten.collect { |handle| Entity::Handle.build(handle) }
initialize_items
get_data_for_handles(handles)
self
end | [
"def",
"current",
"response",
"=",
"request",
"(",
":get_all_current",
")",
"handles",
"=",
"response",
".",
"values",
".",
"flatten",
".",
"collect",
"{",
"|",
"handle",
"|",
"Entity",
"::",
"Handle",
".",
"build",
"(",
"handle",
")",
"}",
"initialize_items",
"get_data_for_handles",
"(",
"handles",
")",
"self",
"end"
] | Fetches all current orders from the API. | [
"Fetches",
"all",
"current",
"orders",
"from",
"the",
"API",
"."
] | cae2dcafd640707a5d42d657b080a066efd19dc0 | https://github.com/substancelab/rconomic/blob/cae2dcafd640707a5d42d657b080a066efd19dc0/lib/economic/proxies/order_proxy.rb#L13-L20 | train |
qburstruby/rammer-3.0.0 | lib/rammer/module_generator.rb | Rammer.ModuleGenerator.require_module_to_base | def require_module_to_base
file = File.open("#{@target_dir}/app/apis/#{@project_name}/base.rb", "r+")
file.each do |line|
while line == "require_relative './modules/#{@module_name}_apis'\n" do
$stdout.puts "\e[33mModule already mounted.\e[0m"
return true
end
end
File.open("#{@target_dir}/app/apis/#{@project_name}/base.rb", "r+") do |f|
pos = f.pos
rest = f.read
f.seek pos
f.write("require_relative './modules/")
f.write(@module_name)
f.write("_apis'\n")
f.write(rest)
end
return false
end | ruby | def require_module_to_base
file = File.open("#{@target_dir}/app/apis/#{@project_name}/base.rb", "r+")
file.each do |line|
while line == "require_relative './modules/#{@module_name}_apis'\n" do
$stdout.puts "\e[33mModule already mounted.\e[0m"
return true
end
end
File.open("#{@target_dir}/app/apis/#{@project_name}/base.rb", "r+") do |f|
pos = f.pos
rest = f.read
f.seek pos
f.write("require_relative './modules/")
f.write(@module_name)
f.write("_apis'\n")
f.write(rest)
end
return false
end | [
"def",
"require_module_to_base",
"file",
"=",
"File",
".",
"open",
"(",
"\"#{@target_dir}/app/apis/#{@project_name}/base.rb\"",
",",
"\"r+\"",
")",
"file",
".",
"each",
"do",
"|",
"line",
"|",
"while",
"line",
"==",
"\"require_relative './modules/#{@module_name}_apis'\\n\"",
"do",
"$stdout",
".",
"puts",
"\"\\e[33mModule already mounted.\\e[0m\"",
"return",
"true",
"end",
"end",
"File",
".",
"open",
"(",
"\"#{@target_dir}/app/apis/#{@project_name}/base.rb\"",
",",
"\"r+\"",
")",
"do",
"|",
"f",
"|",
"pos",
"=",
"f",
".",
"pos",
"rest",
"=",
"f",
".",
"read",
"f",
".",
"seek",
"pos",
"f",
".",
"write",
"(",
"\"require_relative './modules/\"",
")",
"f",
".",
"write",
"(",
"@module_name",
")",
"f",
".",
"write",
"(",
"\"_apis'\\n\"",
")",
"f",
".",
"write",
"(",
"rest",
")",
"end",
"return",
"false",
"end"
] | =begin
Checks whether the module is already mounted and if not then configures for mounting.
=end | [
"=",
"begin",
"Checks",
"whether",
"the",
"module",
"is",
"already",
"mounted",
"and",
"if",
"not",
"then",
"configures",
"for",
"mounting",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/module_generator.rb#L96-L115 | train |
qburstruby/rammer-3.0.0 | lib/rammer/module_generator.rb | Rammer.ModuleGenerator.copy_module | def copy_module
src = "#{@gem_path}/lib/modules/#{@module_name}/#{@module_name}_apis.rb"
dest = "#{@target_dir}/app/apis/#{@project_name}/modules"
presence = File.exists?("#{dest}/#{@module_name}_apis.rb")? true : false
FileUtils.mkdir dest unless File.exists?(dest)
FileUtils.cp(src,dest) unless presence
configure_module_files
$stdout.puts "\e[1;32m \tcreate\e[0m\tapp/apis/#{@project_name}/modules/#{@module_name}_apis.rb" unless presence
end | ruby | def copy_module
src = "#{@gem_path}/lib/modules/#{@module_name}/#{@module_name}_apis.rb"
dest = "#{@target_dir}/app/apis/#{@project_name}/modules"
presence = File.exists?("#{dest}/#{@module_name}_apis.rb")? true : false
FileUtils.mkdir dest unless File.exists?(dest)
FileUtils.cp(src,dest) unless presence
configure_module_files
$stdout.puts "\e[1;32m \tcreate\e[0m\tapp/apis/#{@project_name}/modules/#{@module_name}_apis.rb" unless presence
end | [
"def",
"copy_module",
"src",
"=",
"\"#{@gem_path}/lib/modules/#{@module_name}/#{@module_name}_apis.rb\"",
"dest",
"=",
"\"#{@target_dir}/app/apis/#{@project_name}/modules\"",
"presence",
"=",
"File",
".",
"exists?",
"(",
"\"#{dest}/#{@module_name}_apis.rb\"",
")",
"?",
"true",
":",
"false",
"FileUtils",
".",
"mkdir",
"dest",
"unless",
"File",
".",
"exists?",
"(",
"dest",
")",
"FileUtils",
".",
"cp",
"(",
"src",
",",
"dest",
")",
"unless",
"presence",
"configure_module_files",
"$stdout",
".",
"puts",
"\"\\e[1;32m \\tcreate\\e[0m\\tapp/apis/#{@project_name}/modules/#{@module_name}_apis.rb\"",
"unless",
"presence",
"end"
] | =begin
Function to copy the module of interest to project location.
=end | [
"=",
"begin",
"Function",
"to",
"copy",
"the",
"module",
"of",
"interest",
"to",
"project",
"location",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/module_generator.rb#L120-L128 | train |
qburstruby/rammer-3.0.0 | lib/rammer/module_generator.rb | Rammer.ModuleGenerator.create_migrations_and_models | def create_migrations_and_models
src = "#{@gem_path}/lib/modules/migrations"
dest = "#{@target_dir}/db/migrate"
copy_files(src,dest,AUTH_MIGRATE)
if @module_name == "oauth"
copy_files(src,dest,OAUTH_MIGRATE)
end
src_path = "#{@gem_path}/lib/modules/models"
dest_path = "#{@target_dir}/app/models"
copy_files(src_path,dest_path,AUTH_MODELS)
if @module_name == "oauth"
copy_files(src_path,dest_path,OAUTH_MODELS)
end
end | ruby | def create_migrations_and_models
src = "#{@gem_path}/lib/modules/migrations"
dest = "#{@target_dir}/db/migrate"
copy_files(src,dest,AUTH_MIGRATE)
if @module_name == "oauth"
copy_files(src,dest,OAUTH_MIGRATE)
end
src_path = "#{@gem_path}/lib/modules/models"
dest_path = "#{@target_dir}/app/models"
copy_files(src_path,dest_path,AUTH_MODELS)
if @module_name == "oauth"
copy_files(src_path,dest_path,OAUTH_MODELS)
end
end | [
"def",
"create_migrations_and_models",
"src",
"=",
"\"#{@gem_path}/lib/modules/migrations\"",
"dest",
"=",
"\"#{@target_dir}/db/migrate\"",
"copy_files",
"(",
"src",
",",
"dest",
",",
"AUTH_MIGRATE",
")",
"if",
"@module_name",
"==",
"\"oauth\"",
"copy_files",
"(",
"src",
",",
"dest",
",",
"OAUTH_MIGRATE",
")",
"end",
"src_path",
"=",
"\"#{@gem_path}/lib/modules/models\"",
"dest_path",
"=",
"\"#{@target_dir}/app/models\"",
"copy_files",
"(",
"src_path",
",",
"dest_path",
",",
"AUTH_MODELS",
")",
"if",
"@module_name",
"==",
"\"oauth\"",
"copy_files",
"(",
"src_path",
",",
"dest_path",
",",
"OAUTH_MODELS",
")",
"end",
"end"
] | =begin
Function to create the necessary migrations and models.
=end | [
"=",
"begin",
"Function",
"to",
"create",
"the",
"necessary",
"migrations",
"and",
"models",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/module_generator.rb#L133-L146 | train |
qburstruby/rammer-3.0.0 | lib/rammer/module_generator.rb | Rammer.ModuleGenerator.copy_files | def copy_files(src,dest,module_model)
module_model.each do |file|
presence = File.exists?("#{dest}/#{file}")? true : false
unless presence
FileUtils.cp("#{src}/#{file}",dest)
path = if dest.include? "app" then "app/models" else "db/migrate" end
$stdout.puts "\e[1;32m \tcreate\e[0m\t#{path}/#{file}"
end
end
end | ruby | def copy_files(src,dest,module_model)
module_model.each do |file|
presence = File.exists?("#{dest}/#{file}")? true : false
unless presence
FileUtils.cp("#{src}/#{file}",dest)
path = if dest.include? "app" then "app/models" else "db/migrate" end
$stdout.puts "\e[1;32m \tcreate\e[0m\t#{path}/#{file}"
end
end
end | [
"def",
"copy_files",
"(",
"src",
",",
"dest",
",",
"module_model",
")",
"module_model",
".",
"each",
"do",
"|",
"file",
"|",
"presence",
"=",
"File",
".",
"exists?",
"(",
"\"#{dest}/#{file}\"",
")",
"?",
"true",
":",
"false",
"unless",
"presence",
"FileUtils",
".",
"cp",
"(",
"\"#{src}/#{file}\"",
",",
"dest",
")",
"path",
"=",
"if",
"dest",
".",
"include?",
"\"app\"",
"then",
"\"app/models\"",
"else",
"\"db/migrate\"",
"end",
"$stdout",
".",
"puts",
"\"\\e[1;32m \\tcreate\\e[0m\\t#{path}/#{file}\"",
"end",
"end",
"end"
] | =begin
Function to copy the module files to project location.
=end | [
"=",
"begin",
"Function",
"to",
"copy",
"the",
"module",
"files",
"to",
"project",
"location",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/module_generator.rb#L151-L160 | train |
qburstruby/rammer-3.0.0 | lib/rammer/module_generator.rb | Rammer.ModuleGenerator.configure_module_files | def configure_module_files
source = "#{@target_dir}/app/apis/#{@project_name}/modules/#{@module_name}_apis.rb"
application_module = @project_name.split('_').map(&:capitalize)*''
file = File.read(source)
replace = file.gsub(/module Rammer/, "module #{application_module}")
File.open(source, "w"){|f|
f.puts replace
}
end | ruby | def configure_module_files
source = "#{@target_dir}/app/apis/#{@project_name}/modules/#{@module_name}_apis.rb"
application_module = @project_name.split('_').map(&:capitalize)*''
file = File.read(source)
replace = file.gsub(/module Rammer/, "module #{application_module}")
File.open(source, "w"){|f|
f.puts replace
}
end | [
"def",
"configure_module_files",
"source",
"=",
"\"#{@target_dir}/app/apis/#{@project_name}/modules/#{@module_name}_apis.rb\"",
"application_module",
"=",
"@project_name",
".",
"split",
"(",
"'_'",
")",
".",
"map",
"(",
"&",
":capitalize",
")",
"*",
"''",
"file",
"=",
"File",
".",
"read",
"(",
"source",
")",
"replace",
"=",
"file",
".",
"gsub",
"(",
"/",
"/",
",",
"\"module #{application_module}\"",
")",
"File",
".",
"open",
"(",
"source",
",",
"\"w\"",
")",
"{",
"|",
"f",
"|",
"f",
".",
"puts",
"replace",
"}",
"end"
] | =begin
Function to configure the module files.
=end | [
"=",
"begin",
"Function",
"to",
"configure",
"the",
"module",
"files",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/module_generator.rb#L165-L173 | train |
qburstruby/rammer-3.0.0 | lib/rammer/module_generator.rb | Rammer.ModuleGenerator.add_gems | def add_gems
file = File.open("#{@target_dir}/Gemfile", "r+")
file.each do |line|
while line == "gem 'oauth2'\n" do
return
end
end
File.open("#{@target_dir}/Gemfile", "a+") do |f|
f.write("gem 'multi_json'\ngem 'oauth2'\ngem 'songkick-oauth2-provider'\ngem 'ruby_regex'\ngem 'oauth'\n")
end
$stdout.puts "\e[1;35m \tGemfile\e[0m\tgem 'multi_json'\n\t\tgem 'oauth2'
\t\tgem 'songkick-oauth2-provider'\n\t\tgem 'ruby_regex'\n\t\tgem 'oauth'\n"
$stdout.puts "\e[1;32m \trun\e[0m\tbundle install"
system("bundle install")
end | ruby | def add_gems
file = File.open("#{@target_dir}/Gemfile", "r+")
file.each do |line|
while line == "gem 'oauth2'\n" do
return
end
end
File.open("#{@target_dir}/Gemfile", "a+") do |f|
f.write("gem 'multi_json'\ngem 'oauth2'\ngem 'songkick-oauth2-provider'\ngem 'ruby_regex'\ngem 'oauth'\n")
end
$stdout.puts "\e[1;35m \tGemfile\e[0m\tgem 'multi_json'\n\t\tgem 'oauth2'
\t\tgem 'songkick-oauth2-provider'\n\t\tgem 'ruby_regex'\n\t\tgem 'oauth'\n"
$stdout.puts "\e[1;32m \trun\e[0m\tbundle install"
system("bundle install")
end | [
"def",
"add_gems",
"file",
"=",
"File",
".",
"open",
"(",
"\"#{@target_dir}/Gemfile\"",
",",
"\"r+\"",
")",
"file",
".",
"each",
"do",
"|",
"line",
"|",
"while",
"line",
"==",
"\"gem 'oauth2'\\n\"",
"do",
"return",
"end",
"end",
"File",
".",
"open",
"(",
"\"#{@target_dir}/Gemfile\"",
",",
"\"a+\"",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"\"gem 'multi_json'\\ngem 'oauth2'\\ngem 'songkick-oauth2-provider'\\ngem 'ruby_regex'\\ngem 'oauth'\\n\"",
")",
"end",
"$stdout",
".",
"puts",
"\"\\e[1;35m \\tGemfile\\e[0m\\tgem 'multi_json'\\n\\t\\tgem 'oauth2'\\t\\tgem 'songkick-oauth2-provider'\\n\\t\\tgem 'ruby_regex'\\n\\t\\tgem 'oauth'\\n\"",
"$stdout",
".",
"puts",
"\"\\e[1;32m \\trun\\e[0m\\tbundle install\"",
"system",
"(",
"\"bundle install\"",
")",
"end"
] | =begin
Function to add the module dependency gems to project Gemfile.
=end | [
"=",
"begin",
"Function",
"to",
"add",
"the",
"module",
"dependency",
"gems",
"to",
"project",
"Gemfile",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/module_generator.rb#L178-L192 | train |
qburstruby/rammer-3.0.0 | lib/rammer/module_generator.rb | Rammer.ModuleGenerator.unmount_module | def unmount_module
path = "#{@target_dir}/app/apis/#{@project_name}"
temp_file = "#{path}/tmp.rb"
source = "#{path}/base.rb"
delete_file = "#{path}/modules/#{@module_name}_apis.rb"
File.open(temp_file, "w") do |out_file|
File.foreach(source) do |line|
unless line == "require_relative './modules/#{@module_name}_apis'\n"
out_file.puts line unless line == "\t\tmount #{@module_class}\n"
end
end
FileUtils.mv(temp_file, source)
end
if File.exists?(delete_file)
FileUtils.rm(delete_file)
$stdout.puts "\e[1;35m\tunmounted\e[0m\t#{@module_class}"
$stdout.puts "\e[1;31m\tdelete\e[0m\t\tapp/apis/#{@project_name}/modules/#{@module_name}_apis.rb"
else
$stdout.puts "\e[33mModule already unmounted.\e[0m"
end
end | ruby | def unmount_module
path = "#{@target_dir}/app/apis/#{@project_name}"
temp_file = "#{path}/tmp.rb"
source = "#{path}/base.rb"
delete_file = "#{path}/modules/#{@module_name}_apis.rb"
File.open(temp_file, "w") do |out_file|
File.foreach(source) do |line|
unless line == "require_relative './modules/#{@module_name}_apis'\n"
out_file.puts line unless line == "\t\tmount #{@module_class}\n"
end
end
FileUtils.mv(temp_file, source)
end
if File.exists?(delete_file)
FileUtils.rm(delete_file)
$stdout.puts "\e[1;35m\tunmounted\e[0m\t#{@module_class}"
$stdout.puts "\e[1;31m\tdelete\e[0m\t\tapp/apis/#{@project_name}/modules/#{@module_name}_apis.rb"
else
$stdout.puts "\e[33mModule already unmounted.\e[0m"
end
end | [
"def",
"unmount_module",
"path",
"=",
"\"#{@target_dir}/app/apis/#{@project_name}\"",
"temp_file",
"=",
"\"#{path}/tmp.rb\"",
"source",
"=",
"\"#{path}/base.rb\"",
"delete_file",
"=",
"\"#{path}/modules/#{@module_name}_apis.rb\"",
"File",
".",
"open",
"(",
"temp_file",
",",
"\"w\"",
")",
"do",
"|",
"out_file",
"|",
"File",
".",
"foreach",
"(",
"source",
")",
"do",
"|",
"line",
"|",
"unless",
"line",
"==",
"\"require_relative './modules/#{@module_name}_apis'\\n\"",
"out_file",
".",
"puts",
"line",
"unless",
"line",
"==",
"\"\\t\\tmount #{@module_class}\\n\"",
"end",
"end",
"FileUtils",
".",
"mv",
"(",
"temp_file",
",",
"source",
")",
"end",
"if",
"File",
".",
"exists?",
"(",
"delete_file",
")",
"FileUtils",
".",
"rm",
"(",
"delete_file",
")",
"$stdout",
".",
"puts",
"\"\\e[1;35m\\tunmounted\\e[0m\\t#{@module_class}\"",
"$stdout",
".",
"puts",
"\"\\e[1;31m\\tdelete\\e[0m\\t\\tapp/apis/#{@project_name}/modules/#{@module_name}_apis.rb\"",
"else",
"$stdout",
".",
"puts",
"\"\\e[33mModule already unmounted.\\e[0m\"",
"end",
"end"
] | =begin
Unmounts the modules by removing the respective module files.
=end | [
"=",
"begin",
"Unmounts",
"the",
"modules",
"by",
"removing",
"the",
"respective",
"module",
"files",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/module_generator.rb#L197-L219 | train |
zombor/Validator | lib/validation/validator.rb | Validation.Rules.rule | def rule(field, definition)
field = field.to_sym
rules[field] = [] if rules[field].nil?
begin
if definition.respond_to?(:each_pair)
add_parameterized_rules(field, definition)
elsif definition.respond_to?(:each)
definition.each do |item|
if item.respond_to?(:each_pair)
add_parameterized_rules(field, item)
else
add_single_rule(field, item)
end
end
else
add_single_rule(field, definition)
end
rescue NameError => e
raise InvalidRule.new(e)
end
self
end | ruby | def rule(field, definition)
field = field.to_sym
rules[field] = [] if rules[field].nil?
begin
if definition.respond_to?(:each_pair)
add_parameterized_rules(field, definition)
elsif definition.respond_to?(:each)
definition.each do |item|
if item.respond_to?(:each_pair)
add_parameterized_rules(field, item)
else
add_single_rule(field, item)
end
end
else
add_single_rule(field, definition)
end
rescue NameError => e
raise InvalidRule.new(e)
end
self
end | [
"def",
"rule",
"(",
"field",
",",
"definition",
")",
"field",
"=",
"field",
".",
"to_sym",
"rules",
"[",
"field",
"]",
"=",
"[",
"]",
"if",
"rules",
"[",
"field",
"]",
".",
"nil?",
"begin",
"if",
"definition",
".",
"respond_to?",
"(",
":each_pair",
")",
"add_parameterized_rules",
"(",
"field",
",",
"definition",
")",
"elsif",
"definition",
".",
"respond_to?",
"(",
":each",
")",
"definition",
".",
"each",
"do",
"|",
"item",
"|",
"if",
"item",
".",
"respond_to?",
"(",
":each_pair",
")",
"add_parameterized_rules",
"(",
"field",
",",
"item",
")",
"else",
"add_single_rule",
"(",
"field",
",",
"item",
")",
"end",
"end",
"else",
"add_single_rule",
"(",
"field",
",",
"definition",
")",
"end",
"rescue",
"NameError",
"=>",
"e",
"raise",
"InvalidRule",
".",
"new",
"(",
"e",
")",
"end",
"self",
"end"
] | Define a rule for this object
The rule parameter can be one of the following:
* a symbol that matches to a class in the Validation::Rule namespace
* e.g. rule(:field, :not_empty)
* a hash containing the rule as the key and it's parameters as the values
* e.g. rule(:field, :length => { :minimum => 3, :maximum => 5 })
* an array combining the two previous types | [
"Define",
"a",
"rule",
"for",
"this",
"object"
] | d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8 | https://github.com/zombor/Validator/blob/d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8/lib/validation/validator.rb#L22-L44 | train |
zombor/Validator | lib/validation/validator.rb | Validation.Rules.valid? | def valid?
valid = true
rules.each_pair do |field, rules|
if ! @obj.respond_to?(field)
raise InvalidKey, "cannot validate non-existent field '#{field}'"
end
rules.each do |r|
if ! r.valid_value?(@obj.send(field))
valid = false
errors[field] = {:rule => r.error_key, :params => r.params}
break
end
end
end
@valid = valid
end | ruby | def valid?
valid = true
rules.each_pair do |field, rules|
if ! @obj.respond_to?(field)
raise InvalidKey, "cannot validate non-existent field '#{field}'"
end
rules.each do |r|
if ! r.valid_value?(@obj.send(field))
valid = false
errors[field] = {:rule => r.error_key, :params => r.params}
break
end
end
end
@valid = valid
end | [
"def",
"valid?",
"valid",
"=",
"true",
"rules",
".",
"each_pair",
"do",
"|",
"field",
",",
"rules",
"|",
"if",
"!",
"@obj",
".",
"respond_to?",
"(",
"field",
")",
"raise",
"InvalidKey",
",",
"\"cannot validate non-existent field '#{field}'\"",
"end",
"rules",
".",
"each",
"do",
"|",
"r",
"|",
"if",
"!",
"r",
".",
"valid_value?",
"(",
"@obj",
".",
"send",
"(",
"field",
")",
")",
"valid",
"=",
"false",
"errors",
"[",
"field",
"]",
"=",
"{",
":rule",
"=>",
"r",
".",
"error_key",
",",
":params",
"=>",
"r",
".",
"params",
"}",
"break",
"end",
"end",
"end",
"@valid",
"=",
"valid",
"end"
] | Determines if this object is valid. When a rule fails for a field,
this will stop processing further rules. In this way, you'll only get
one error per field | [
"Determines",
"if",
"this",
"object",
"is",
"valid",
".",
"When",
"a",
"rule",
"fails",
"for",
"a",
"field",
"this",
"will",
"stop",
"processing",
"further",
"rules",
".",
"In",
"this",
"way",
"you",
"ll",
"only",
"get",
"one",
"error",
"per",
"field"
] | d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8 | https://github.com/zombor/Validator/blob/d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8/lib/validation/validator.rb#L49-L67 | train |
zombor/Validator | lib/validation/validator.rb | Validation.Rules.add_single_rule | def add_single_rule(field, key_or_klass, params = nil)
klass = if key_or_klass.respond_to?(:new)
key_or_klass
else
get_rule_class_by_name(key_or_klass)
end
args = [params].compact
rule = klass.new(*args)
rule.obj = @obj if rule.respond_to?(:obj=)
rules[field] << rule
end | ruby | def add_single_rule(field, key_or_klass, params = nil)
klass = if key_or_klass.respond_to?(:new)
key_or_klass
else
get_rule_class_by_name(key_or_klass)
end
args = [params].compact
rule = klass.new(*args)
rule.obj = @obj if rule.respond_to?(:obj=)
rules[field] << rule
end | [
"def",
"add_single_rule",
"(",
"field",
",",
"key_or_klass",
",",
"params",
"=",
"nil",
")",
"klass",
"=",
"if",
"key_or_klass",
".",
"respond_to?",
"(",
":new",
")",
"key_or_klass",
"else",
"get_rule_class_by_name",
"(",
"key_or_klass",
")",
"end",
"args",
"=",
"[",
"params",
"]",
".",
"compact",
"rule",
"=",
"klass",
".",
"new",
"(",
"*",
"args",
")",
"rule",
".",
"obj",
"=",
"@obj",
"if",
"rule",
".",
"respond_to?",
"(",
":obj=",
")",
"rules",
"[",
"field",
"]",
"<<",
"rule",
"end"
] | Adds a single rule to this object | [
"Adds",
"a",
"single",
"rule",
"to",
"this",
"object"
] | d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8 | https://github.com/zombor/Validator/blob/d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8/lib/validation/validator.rb#L72-L83 | train |
zombor/Validator | lib/validation/validator.rb | Validation.Rules.add_parameterized_rules | def add_parameterized_rules(field, rules)
rules.each_pair do |key, params|
add_single_rule(field, key, params)
end
end | ruby | def add_parameterized_rules(field, rules)
rules.each_pair do |key, params|
add_single_rule(field, key, params)
end
end | [
"def",
"add_parameterized_rules",
"(",
"field",
",",
"rules",
")",
"rules",
".",
"each_pair",
"do",
"|",
"key",
",",
"params",
"|",
"add_single_rule",
"(",
"field",
",",
"key",
",",
"params",
")",
"end",
"end"
] | Adds a set of parameterized rules to this object | [
"Adds",
"a",
"set",
"of",
"parameterized",
"rules",
"to",
"this",
"object"
] | d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8 | https://github.com/zombor/Validator/blob/d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8/lib/validation/validator.rb#L86-L90 | train |
zombor/Validator | lib/validation/validator.rb | Validation.Rules.get_rule_class_by_name | def get_rule_class_by_name(klass)
klass = camelize(klass)
Validation::Rule.const_get(klass)
rescue NameError => e
raise InvalidRule.new(e)
end | ruby | def get_rule_class_by_name(klass)
klass = camelize(klass)
Validation::Rule.const_get(klass)
rescue NameError => e
raise InvalidRule.new(e)
end | [
"def",
"get_rule_class_by_name",
"(",
"klass",
")",
"klass",
"=",
"camelize",
"(",
"klass",
")",
"Validation",
"::",
"Rule",
".",
"const_get",
"(",
"klass",
")",
"rescue",
"NameError",
"=>",
"e",
"raise",
"InvalidRule",
".",
"new",
"(",
"e",
")",
"end"
] | Resolves the specified rule name to a rule class | [
"Resolves",
"the",
"specified",
"rule",
"name",
"to",
"a",
"rule",
"class"
] | d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8 | https://github.com/zombor/Validator/blob/d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8/lib/validation/validator.rb#L93-L98 | train |
zombor/Validator | lib/validation/validator.rb | Validation.Rules.camelize | def camelize(term)
string = term.to_s
string = string.sub(/^[a-z\d]*/) { $&.capitalize }
string.gsub(/(?:_|(\/))([a-z\d]*)/i) { $2.capitalize }.gsub('/', '::')
end | ruby | def camelize(term)
string = term.to_s
string = string.sub(/^[a-z\d]*/) { $&.capitalize }
string.gsub(/(?:_|(\/))([a-z\d]*)/i) { $2.capitalize }.gsub('/', '::')
end | [
"def",
"camelize",
"(",
"term",
")",
"string",
"=",
"term",
".",
"to_s",
"string",
"=",
"string",
".",
"sub",
"(",
"/",
"\\d",
"/",
")",
"{",
"$&",
".",
"capitalize",
"}",
"string",
".",
"gsub",
"(",
"/",
"\\/",
"\\d",
"/i",
")",
"{",
"$2",
".",
"capitalize",
"}",
".",
"gsub",
"(",
"'/'",
",",
"'::'",
")",
"end"
] | Converts a symbol to a class name, taken from rails | [
"Converts",
"a",
"symbol",
"to",
"a",
"class",
"name",
"taken",
"from",
"rails"
] | d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8 | https://github.com/zombor/Validator/blob/d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8/lib/validation/validator.rb#L101-L105 | train |
redinger/validation_reflection | lib/validation_reflection.rb | ValidationReflection.ClassMethods.remember_validation_metadata | def remember_validation_metadata(validation_type, *attr_names)
configuration = attr_names.last.is_a?(::Hash) ? attr_names.pop : {}
self.validations ||= []
attr_names.flatten.each do |attr_name|
self.validations << ::ActiveRecord::Reflection::MacroReflection.new(validation_type, attr_name.to_sym, configuration, self)
end
end | ruby | def remember_validation_metadata(validation_type, *attr_names)
configuration = attr_names.last.is_a?(::Hash) ? attr_names.pop : {}
self.validations ||= []
attr_names.flatten.each do |attr_name|
self.validations << ::ActiveRecord::Reflection::MacroReflection.new(validation_type, attr_name.to_sym, configuration, self)
end
end | [
"def",
"remember_validation_metadata",
"(",
"validation_type",
",",
"*",
"attr_names",
")",
"configuration",
"=",
"attr_names",
".",
"last",
".",
"is_a?",
"(",
"::",
"Hash",
")",
"?",
"attr_names",
".",
"pop",
":",
"{",
"}",
"self",
".",
"validations",
"||=",
"[",
"]",
"attr_names",
".",
"flatten",
".",
"each",
"do",
"|",
"attr_name",
"|",
"self",
".",
"validations",
"<<",
"::",
"ActiveRecord",
"::",
"Reflection",
"::",
"MacroReflection",
".",
"new",
"(",
"validation_type",
",",
"attr_name",
".",
"to_sym",
",",
"configuration",
",",
"self",
")",
"end",
"end"
] | Store validation info for easy and fast access. | [
"Store",
"validation",
"info",
"for",
"easy",
"and",
"fast",
"access",
"."
] | 7c3397e3a6ab32773cf7399455e5c63a0fdc66e9 | https://github.com/redinger/validation_reflection/blob/7c3397e3a6ab32773cf7399455e5c63a0fdc66e9/lib/validation_reflection.rb#L81-L87 | train |
TWChennai/capypage | lib/capypage/element.rb | Capypage.Element.element | def element(name, selector, options = {})
define_singleton_method(name) { Element.new(selector, options.merge(:base_element => self)) }
end | ruby | def element(name, selector, options = {})
define_singleton_method(name) { Element.new(selector, options.merge(:base_element => self)) }
end | [
"def",
"element",
"(",
"name",
",",
"selector",
",",
"options",
"=",
"{",
"}",
")",
"define_singleton_method",
"(",
"name",
")",
"{",
"Element",
".",
"new",
"(",
"selector",
",",
"options",
".",
"merge",
"(",
":base_element",
"=>",
"self",
")",
")",
"}",
"end"
] | Creates an element
@param [String] selector to identify element
@param [Hash] options
@option options [Capypage::Element] :base_element Base element for the element to be created
@option options [Symbol] :select_using Selector to switch at element level | [
"Creates",
"an",
"element"
] | 9ff875b001688201a1008e751b8ccb57aeb59b8b | https://github.com/TWChennai/capypage/blob/9ff875b001688201a1008e751b8ccb57aeb59b8b/lib/capypage/element.rb#L25-L27 | train |
qburstruby/rammer-3.0.0 | lib/rammer/rammer_generator.rb | Rammer.RammerGenerator.create_base_dirs | def create_base_dirs
BASE_DIR.each do |dir|
FileUtils.mkdir "#{@project_name}/#{dir}"
$stdout.puts "\e[1;32m \tcreate\e[0m\t#{dir}"
end
FileUtils.mkdir "#{@project_name}/app/apis/#{@project_name}"
$stdout.puts "\e[1;32m \tcreate\e[0m\tapp/apis/#{@project_name}"
end | ruby | def create_base_dirs
BASE_DIR.each do |dir|
FileUtils.mkdir "#{@project_name}/#{dir}"
$stdout.puts "\e[1;32m \tcreate\e[0m\t#{dir}"
end
FileUtils.mkdir "#{@project_name}/app/apis/#{@project_name}"
$stdout.puts "\e[1;32m \tcreate\e[0m\tapp/apis/#{@project_name}"
end | [
"def",
"create_base_dirs",
"BASE_DIR",
".",
"each",
"do",
"|",
"dir",
"|",
"FileUtils",
".",
"mkdir",
"\"#{@project_name}/#{dir}\"",
"$stdout",
".",
"puts",
"\"\\e[1;32m \\tcreate\\e[0m\\t#{dir}\"",
"end",
"FileUtils",
".",
"mkdir",
"\"#{@project_name}/app/apis/#{@project_name}\"",
"$stdout",
".",
"puts",
"\"\\e[1;32m \\tcreate\\e[0m\\tapp/apis/#{@project_name}\"",
"end"
] | =begin
Creates the application base directories.
=end | [
"=",
"begin",
"Creates",
"the",
"application",
"base",
"directories",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/rammer_generator.rb#L89-L96 | train |
qburstruby/rammer-3.0.0 | lib/rammer/rammer_generator.rb | Rammer.RammerGenerator.create_api_module | def create_api_module
File.open("#{@project_name}/app/apis/#{@project_name}/base.rb", "w") do |f|
f.write('module ')
f.puts(@module_name)
f.write("\tclass Base < Grape::API\n\tend\nend")
end
$stdout.puts "\e[1;32m \tcreate\e[0m\tapp/apis/#{@project_name}/base.rb"
end | ruby | def create_api_module
File.open("#{@project_name}/app/apis/#{@project_name}/base.rb", "w") do |f|
f.write('module ')
f.puts(@module_name)
f.write("\tclass Base < Grape::API\n\tend\nend")
end
$stdout.puts "\e[1;32m \tcreate\e[0m\tapp/apis/#{@project_name}/base.rb"
end | [
"def",
"create_api_module",
"File",
".",
"open",
"(",
"\"#{@project_name}/app/apis/#{@project_name}/base.rb\"",
",",
"\"w\"",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"'module '",
")",
"f",
".",
"puts",
"(",
"@module_name",
")",
"f",
".",
"write",
"(",
"\"\\tclass Base < Grape::API\\n\\tend\\nend\"",
")",
"end",
"$stdout",
".",
"puts",
"\"\\e[1;32m \\tcreate\\e[0m\\tapp/apis/#{@project_name}/base.rb\"",
"end"
] | =begin
Function to create the API modules.
=end | [
"=",
"begin",
"Function",
"to",
"create",
"the",
"API",
"modules",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/rammer_generator.rb#L110-L117 | train |
qburstruby/rammer-3.0.0 | lib/rammer/rammer_generator.rb | Rammer.RammerGenerator.config_server | def config_server
file = File.open("#{@project_name}/server.rb", "r+")
file.each do |line|
while line == " def response(env)\n" do
pos = file.pos
rest = file.read
file.seek pos
file.write("\t::")
file.write(@module_name)
file.write("::Base.call(env)\n")
file.write(rest)
$stdout.puts "\e[1;35m \tconfig\e[0m\tserver.rb"
return
end
end
end | ruby | def config_server
file = File.open("#{@project_name}/server.rb", "r+")
file.each do |line|
while line == " def response(env)\n" do
pos = file.pos
rest = file.read
file.seek pos
file.write("\t::")
file.write(@module_name)
file.write("::Base.call(env)\n")
file.write(rest)
$stdout.puts "\e[1;35m \tconfig\e[0m\tserver.rb"
return
end
end
end | [
"def",
"config_server",
"file",
"=",
"File",
".",
"open",
"(",
"\"#{@project_name}/server.rb\"",
",",
"\"r+\"",
")",
"file",
".",
"each",
"do",
"|",
"line",
"|",
"while",
"line",
"==",
"\" def response(env)\\n\"",
"do",
"pos",
"=",
"file",
".",
"pos",
"rest",
"=",
"file",
".",
"read",
"file",
".",
"seek",
"pos",
"file",
".",
"write",
"(",
"\"\\t::\"",
")",
"file",
".",
"write",
"(",
"@module_name",
")",
"file",
".",
"write",
"(",
"\"::Base.call(env)\\n\"",
")",
"file",
".",
"write",
"(",
"rest",
")",
"$stdout",
".",
"puts",
"\"\\e[1;35m \\tconfig\\e[0m\\tserver.rb\"",
"return",
"end",
"end",
"end"
] | =begin
Function to configure the Goliath server.
=end | [
"=",
"begin",
"Function",
"to",
"configure",
"the",
"Goliath",
"server",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/rammer_generator.rb#L122-L137 | train |
qburstruby/rammer-3.0.0 | lib/rammer/rammer_generator.rb | Rammer.RammerGenerator.copy_files_to_target | def copy_files_to_target
COMMON_RAMMER_FILES.each do |file|
source = File.join("#{@gem_path}/lib/modules/common/",file)
FileUtils.cp(source,"#{@project_name}")
$stdout.puts "\e[1;32m \tcreate\e[0m\t#{file}"
end
end | ruby | def copy_files_to_target
COMMON_RAMMER_FILES.each do |file|
source = File.join("#{@gem_path}/lib/modules/common/",file)
FileUtils.cp(source,"#{@project_name}")
$stdout.puts "\e[1;32m \tcreate\e[0m\t#{file}"
end
end | [
"def",
"copy_files_to_target",
"COMMON_RAMMER_FILES",
".",
"each",
"do",
"|",
"file",
"|",
"source",
"=",
"File",
".",
"join",
"(",
"\"#{@gem_path}/lib/modules/common/\"",
",",
"file",
")",
"FileUtils",
".",
"cp",
"(",
"source",
",",
"\"#{@project_name}\"",
")",
"$stdout",
".",
"puts",
"\"\\e[1;32m \\tcreate\\e[0m\\t#{file}\"",
"end",
"end"
] | =begin
Function to copy the template files project location.
=end | [
"=",
"begin",
"Function",
"to",
"copy",
"the",
"template",
"files",
"project",
"location",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/rammer_generator.rb#L142-L148 | train |
qburstruby/rammer-3.0.0 | lib/rammer/scaffold_generator.rb | Rammer.ScaffoldGenerator.create_model_file | def create_model_file
dir = "/app/models/#{@scaffold_name}.rb"
unless File.exists?(File.join(Dir.pwd,dir))
File.join(Dir.pwd,dir)
source = "#{@gem_path}/lib/modules/scaffold/model.rb"
FileUtils.cp(source,File.join(Dir.pwd,dir))
config_model
@valid = true
$stdout.puts "\e[1;32m \tcreate\e[0m\t#{dir}"
else
$stdout.puts "\e[1;31mError:\e[0m Model named #{@scaffold_name} already exists, aborting."
end
end | ruby | def create_model_file
dir = "/app/models/#{@scaffold_name}.rb"
unless File.exists?(File.join(Dir.pwd,dir))
File.join(Dir.pwd,dir)
source = "#{@gem_path}/lib/modules/scaffold/model.rb"
FileUtils.cp(source,File.join(Dir.pwd,dir))
config_model
@valid = true
$stdout.puts "\e[1;32m \tcreate\e[0m\t#{dir}"
else
$stdout.puts "\e[1;31mError:\e[0m Model named #{@scaffold_name} already exists, aborting."
end
end | [
"def",
"create_model_file",
"dir",
"=",
"\"/app/models/#{@scaffold_name}.rb\"",
"unless",
"File",
".",
"exists?",
"(",
"File",
".",
"join",
"(",
"Dir",
".",
"pwd",
",",
"dir",
")",
")",
"File",
".",
"join",
"(",
"Dir",
".",
"pwd",
",",
"dir",
")",
"source",
"=",
"\"#{@gem_path}/lib/modules/scaffold/model.rb\"",
"FileUtils",
".",
"cp",
"(",
"source",
",",
"File",
".",
"join",
"(",
"Dir",
".",
"pwd",
",",
"dir",
")",
")",
"config_model",
"@valid",
"=",
"true",
"$stdout",
".",
"puts",
"\"\\e[1;32m \\tcreate\\e[0m\\t#{dir}\"",
"else",
"$stdout",
".",
"puts",
"\"\\e[1;31mError:\\e[0m Model named #{@scaffold_name} already exists, aborting.\"",
"end",
"end"
] | =begin
Generates the model file with CRED functionality.
=end | [
"=",
"begin",
"Generates",
"the",
"model",
"file",
"with",
"CRED",
"functionality",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L70-L82 | train |
qburstruby/rammer-3.0.0 | lib/rammer/scaffold_generator.rb | Rammer.ScaffoldGenerator.create_migration | def create_migration
migration_version = Time.now.to_i
dir = "/db/migrate/#{migration_version}_create_#{@scaffold_name}s.rb"
unless File.exists?(File.join(Dir.pwd,dir))
source = "#{@gem_path}/lib/modules/scaffold/migration.rb"
FileUtils.cp(source,File.join(Dir.pwd,dir))
config_migration(migration_version)
$stdout.puts "\e[1;32m \tcreate\e[0m\t#{dir}"
end
end | ruby | def create_migration
migration_version = Time.now.to_i
dir = "/db/migrate/#{migration_version}_create_#{@scaffold_name}s.rb"
unless File.exists?(File.join(Dir.pwd,dir))
source = "#{@gem_path}/lib/modules/scaffold/migration.rb"
FileUtils.cp(source,File.join(Dir.pwd,dir))
config_migration(migration_version)
$stdout.puts "\e[1;32m \tcreate\e[0m\t#{dir}"
end
end | [
"def",
"create_migration",
"migration_version",
"=",
"Time",
".",
"now",
".",
"to_i",
"dir",
"=",
"\"/db/migrate/#{migration_version}_create_#{@scaffold_name}s.rb\"",
"unless",
"File",
".",
"exists?",
"(",
"File",
".",
"join",
"(",
"Dir",
".",
"pwd",
",",
"dir",
")",
")",
"source",
"=",
"\"#{@gem_path}/lib/modules/scaffold/migration.rb\"",
"FileUtils",
".",
"cp",
"(",
"source",
",",
"File",
".",
"join",
"(",
"Dir",
".",
"pwd",
",",
"dir",
")",
")",
"config_migration",
"(",
"migration_version",
")",
"$stdout",
".",
"puts",
"\"\\e[1;32m \\tcreate\\e[0m\\t#{dir}\"",
"end",
"end"
] | =begin
Generates migration files for the scaffold.
=end | [
"=",
"begin",
"Generates",
"migration",
"files",
"for",
"the",
"scaffold",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L96-L105 | train |
qburstruby/rammer-3.0.0 | lib/rammer/scaffold_generator.rb | Rammer.ScaffoldGenerator.config_migration | def config_migration(migration_version)
source = "#{Dir.pwd}/db/migrate/#{migration_version}_create_#{@scaffold_name}s.rb"
modify_content(source, 'CreateMigration', "Create#{@model_class}s")
modify_content(source, 'migration', "#{@scaffold_name}s")
@arguments.each do |value|
@attributes << value.split(':').first
@data_types << value.split(':').last
end
attribute_data_types = @data_types.reverse
@attributes.reverse.each_with_index do |value,index|
add_attributes(source, value, attribute_data_types[index])
end
end | ruby | def config_migration(migration_version)
source = "#{Dir.pwd}/db/migrate/#{migration_version}_create_#{@scaffold_name}s.rb"
modify_content(source, 'CreateMigration', "Create#{@model_class}s")
modify_content(source, 'migration', "#{@scaffold_name}s")
@arguments.each do |value|
@attributes << value.split(':').first
@data_types << value.split(':').last
end
attribute_data_types = @data_types.reverse
@attributes.reverse.each_with_index do |value,index|
add_attributes(source, value, attribute_data_types[index])
end
end | [
"def",
"config_migration",
"(",
"migration_version",
")",
"source",
"=",
"\"#{Dir.pwd}/db/migrate/#{migration_version}_create_#{@scaffold_name}s.rb\"",
"modify_content",
"(",
"source",
",",
"'CreateMigration'",
",",
"\"Create#{@model_class}s\"",
")",
"modify_content",
"(",
"source",
",",
"'migration'",
",",
"\"#{@scaffold_name}s\"",
")",
"@arguments",
".",
"each",
"do",
"|",
"value",
"|",
"@attributes",
"<<",
"value",
".",
"split",
"(",
"':'",
")",
".",
"first",
"@data_types",
"<<",
"value",
".",
"split",
"(",
"':'",
")",
".",
"last",
"end",
"attribute_data_types",
"=",
"@data_types",
".",
"reverse",
"@attributes",
".",
"reverse",
".",
"each_with_index",
"do",
"|",
"value",
",",
"index",
"|",
"add_attributes",
"(",
"source",
",",
"value",
",",
"attribute_data_types",
"[",
"index",
"]",
")",
"end",
"end"
] | =begin
Configures the migration file with the required user input.
=end | [
"=",
"begin",
"Configures",
"the",
"migration",
"file",
"with",
"the",
"required",
"user",
"input",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L110-L124 | train |
qburstruby/rammer-3.0.0 | lib/rammer/scaffold_generator.rb | Rammer.ScaffoldGenerator.add_attributes | def add_attributes(source,attribute,data_type)
file = File.open(source, "r+")
file.each do |line|
while line == " create_table :#{@scaffold_name}s do |t|\n" do
pos = file.pos
rest = file.read
file.seek pos
file.write(" t.#{data_type} :#{attribute}\n")
file.write(rest)
break
end
end
end | ruby | def add_attributes(source,attribute,data_type)
file = File.open(source, "r+")
file.each do |line|
while line == " create_table :#{@scaffold_name}s do |t|\n" do
pos = file.pos
rest = file.read
file.seek pos
file.write(" t.#{data_type} :#{attribute}\n")
file.write(rest)
break
end
end
end | [
"def",
"add_attributes",
"(",
"source",
",",
"attribute",
",",
"data_type",
")",
"file",
"=",
"File",
".",
"open",
"(",
"source",
",",
"\"r+\"",
")",
"file",
".",
"each",
"do",
"|",
"line",
"|",
"while",
"line",
"==",
"\" create_table :#{@scaffold_name}s do |t|\\n\"",
"do",
"pos",
"=",
"file",
".",
"pos",
"rest",
"=",
"file",
".",
"read",
"file",
".",
"seek",
"pos",
"file",
".",
"write",
"(",
"\" t.#{data_type} :#{attribute}\\n\"",
")",
"file",
".",
"write",
"(",
"rest",
")",
"break",
"end",
"end",
"end"
] | =begin
Edits the migration file with the user specified model attributes.
=end | [
"=",
"begin",
"Edits",
"the",
"migration",
"file",
"with",
"the",
"user",
"specified",
"model",
"attributes",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L129-L141 | train |
qburstruby/rammer-3.0.0 | lib/rammer/scaffold_generator.rb | Rammer.ScaffoldGenerator.enable_apis | def enable_apis
dir = "/app/apis/#{@project_name}/#{@scaffold_name}s/base_apis.rb"
base_dir = "#{Dir.pwd}/app/apis/#{@project_name}/#{@scaffold_name}s"
unless File.exists?(File.join(Dir.pwd,dir))
FileUtils.mkdir base_dir unless File.exists?(base_dir)
source = "#{@gem_path}/lib/modules/scaffold/base_apis.rb"
FileUtils.cp(source,File.join(Dir.pwd,dir))
config_apis
$stdout.puts "\e[1;32m \tcreate\e[0m\t#{dir}"
mount_apis
end
end | ruby | def enable_apis
dir = "/app/apis/#{@project_name}/#{@scaffold_name}s/base_apis.rb"
base_dir = "#{Dir.pwd}/app/apis/#{@project_name}/#{@scaffold_name}s"
unless File.exists?(File.join(Dir.pwd,dir))
FileUtils.mkdir base_dir unless File.exists?(base_dir)
source = "#{@gem_path}/lib/modules/scaffold/base_apis.rb"
FileUtils.cp(source,File.join(Dir.pwd,dir))
config_apis
$stdout.puts "\e[1;32m \tcreate\e[0m\t#{dir}"
mount_apis
end
end | [
"def",
"enable_apis",
"dir",
"=",
"\"/app/apis/#{@project_name}/#{@scaffold_name}s/base_apis.rb\"",
"base_dir",
"=",
"\"#{Dir.pwd}/app/apis/#{@project_name}/#{@scaffold_name}s\"",
"unless",
"File",
".",
"exists?",
"(",
"File",
".",
"join",
"(",
"Dir",
".",
"pwd",
",",
"dir",
")",
")",
"FileUtils",
".",
"mkdir",
"base_dir",
"unless",
"File",
".",
"exists?",
"(",
"base_dir",
")",
"source",
"=",
"\"#{@gem_path}/lib/modules/scaffold/base_apis.rb\"",
"FileUtils",
".",
"cp",
"(",
"source",
",",
"File",
".",
"join",
"(",
"Dir",
".",
"pwd",
",",
"dir",
")",
")",
"config_apis",
"$stdout",
".",
"puts",
"\"\\e[1;32m \\tcreate\\e[0m\\t#{dir}\"",
"mount_apis",
"end",
"end"
] | =begin
Generates the api file with CRED functionality apis enabled.
=end | [
"=",
"begin",
"Generates",
"the",
"api",
"file",
"with",
"CRED",
"functionality",
"apis",
"enabled",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L146-L157 | train |
qburstruby/rammer-3.0.0 | lib/rammer/scaffold_generator.rb | Rammer.ScaffoldGenerator.config_apis | def config_apis
source = "#{Dir.pwd}/app/apis/#{@project_name}/#{@scaffold_name}s/base_apis.rb"
content = ['AppName','ScaffoldName', 'Model', 'model']
replacement = ["#{@project_class}", "#{model_class}s", "#{model_class}", "#{@scaffold_name}"]
for i in 0..3 do
modify_content(source, content[i], replacement[i])
end
end | ruby | def config_apis
source = "#{Dir.pwd}/app/apis/#{@project_name}/#{@scaffold_name}s/base_apis.rb"
content = ['AppName','ScaffoldName', 'Model', 'model']
replacement = ["#{@project_class}", "#{model_class}s", "#{model_class}", "#{@scaffold_name}"]
for i in 0..3 do
modify_content(source, content[i], replacement[i])
end
end | [
"def",
"config_apis",
"source",
"=",
"\"#{Dir.pwd}/app/apis/#{@project_name}/#{@scaffold_name}s/base_apis.rb\"",
"content",
"=",
"[",
"'AppName'",
",",
"'ScaffoldName'",
",",
"'Model'",
",",
"'model'",
"]",
"replacement",
"=",
"[",
"\"#{@project_class}\"",
",",
"\"#{model_class}s\"",
",",
"\"#{model_class}\"",
",",
"\"#{@scaffold_name}\"",
"]",
"for",
"i",
"in",
"0",
"..",
"3",
"do",
"modify_content",
"(",
"source",
",",
"content",
"[",
"i",
"]",
",",
"replacement",
"[",
"i",
"]",
")",
"end",
"end"
] | =begin
Configures the api file with respect to the user input.
=end | [
"=",
"begin",
"Configures",
"the",
"api",
"file",
"with",
"respect",
"to",
"the",
"user",
"input",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L162-L169 | train |
qburstruby/rammer-3.0.0 | lib/rammer/scaffold_generator.rb | Rammer.ScaffoldGenerator.mount_apis | def mount_apis
require_apis_to_base
mount_class = "::#{@project_class}::#{@model_class}s::BaseApis"
file = File.open("#{Dir.pwd}/app/apis/#{@project_name}/base.rb", "r+")
file.each do |line|
while line == "\tclass Base < Grape::API\n" do
pos = file.pos
rest = file.read
file.seek pos
file.write("\t\tmount ")
file.puts(mount_class)
file.write(rest)
break
end
end
$stdout.puts "\e[1;35m\tmounted\e[0m\t#{mount_class}"
end | ruby | def mount_apis
require_apis_to_base
mount_class = "::#{@project_class}::#{@model_class}s::BaseApis"
file = File.open("#{Dir.pwd}/app/apis/#{@project_name}/base.rb", "r+")
file.each do |line|
while line == "\tclass Base < Grape::API\n" do
pos = file.pos
rest = file.read
file.seek pos
file.write("\t\tmount ")
file.puts(mount_class)
file.write(rest)
break
end
end
$stdout.puts "\e[1;35m\tmounted\e[0m\t#{mount_class}"
end | [
"def",
"mount_apis",
"require_apis_to_base",
"mount_class",
"=",
"\"::#{@project_class}::#{@model_class}s::BaseApis\"",
"file",
"=",
"File",
".",
"open",
"(",
"\"#{Dir.pwd}/app/apis/#{@project_name}/base.rb\"",
",",
"\"r+\"",
")",
"file",
".",
"each",
"do",
"|",
"line",
"|",
"while",
"line",
"==",
"\"\\tclass Base < Grape::API\\n\"",
"do",
"pos",
"=",
"file",
".",
"pos",
"rest",
"=",
"file",
".",
"read",
"file",
".",
"seek",
"pos",
"file",
".",
"write",
"(",
"\"\\t\\tmount \"",
")",
"file",
".",
"puts",
"(",
"mount_class",
")",
"file",
".",
"write",
"(",
"rest",
")",
"break",
"end",
"end",
"$stdout",
".",
"puts",
"\"\\e[1;35m\\tmounted\\e[0m\\t#{mount_class}\"",
"end"
] | =begin
Mounts the scaffold apis onto the application.
=end | [
"=",
"begin",
"Mounts",
"the",
"scaffold",
"apis",
"onto",
"the",
"application",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L174-L190 | train |
qburstruby/rammer-3.0.0 | lib/rammer/scaffold_generator.rb | Rammer.ScaffoldGenerator.require_apis_to_base | def require_apis_to_base
File.open("#{Dir.pwd}/app/apis/#{@project_name}/base.rb", "r+") do |f|
pos = f.pos
rest = f.read
f.seek pos
f.write("require_relative '#{@scaffold_name}s/base_apis'\n")
f.write(rest)
end
end | ruby | def require_apis_to_base
File.open("#{Dir.pwd}/app/apis/#{@project_name}/base.rb", "r+") do |f|
pos = f.pos
rest = f.read
f.seek pos
f.write("require_relative '#{@scaffold_name}s/base_apis'\n")
f.write(rest)
end
end | [
"def",
"require_apis_to_base",
"File",
".",
"open",
"(",
"\"#{Dir.pwd}/app/apis/#{@project_name}/base.rb\"",
",",
"\"r+\"",
")",
"do",
"|",
"f",
"|",
"pos",
"=",
"f",
".",
"pos",
"rest",
"=",
"f",
".",
"read",
"f",
".",
"seek",
"pos",
"f",
".",
"write",
"(",
"\"require_relative '#{@scaffold_name}s/base_apis'\\n\"",
")",
"f",
".",
"write",
"(",
"rest",
")",
"end",
"end"
] | =begin
Configures for mounting the scaffold apis.
=end | [
"=",
"begin",
"Configures",
"for",
"mounting",
"the",
"scaffold",
"apis",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L195-L203 | train |
qburstruby/rammer-3.0.0 | lib/rammer/scaffold_generator.rb | Rammer.ScaffoldGenerator.to_underscore | def to_underscore(value)
underscore_value = value.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').tr("-", "_").downcase
return underscore_value
end | ruby | def to_underscore(value)
underscore_value = value.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').tr("-", "_").downcase
return underscore_value
end | [
"def",
"to_underscore",
"(",
"value",
")",
"underscore_value",
"=",
"value",
".",
"gsub",
"(",
"/",
"/",
",",
"'/'",
")",
".",
"gsub",
"(",
"/",
"/",
",",
"'\\1_\\2'",
")",
".",
"gsub",
"(",
"/",
"\\d",
"/",
",",
"'\\1_\\2'",
")",
".",
"tr",
"(",
"\"-\"",
",",
"\"_\"",
")",
".",
"downcase",
"return",
"underscore_value",
"end"
] | =begin
Converts the string into snake case format.
=end | [
"=",
"begin",
"Converts",
"the",
"string",
"into",
"snake",
"case",
"format",
".",
"=",
"end"
] | 72e19d2eb07fcfe0da5ae8610d74dff44906b529 | https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L210-L214 | train |
cryptape/reth | lib/reth/chain_service.rb | Reth.ChainService.knows_block | def knows_block(blockhash)
return true if @chain.include?(blockhash)
@block_queue.queue.any? {|(block, proto)| block.header.full_hash == blockhash }
end | ruby | def knows_block(blockhash)
return true if @chain.include?(blockhash)
@block_queue.queue.any? {|(block, proto)| block.header.full_hash == blockhash }
end | [
"def",
"knows_block",
"(",
"blockhash",
")",
"return",
"true",
"if",
"@chain",
".",
"include?",
"(",
"blockhash",
")",
"@block_queue",
".",
"queue",
".",
"any?",
"{",
"|",
"(",
"block",
",",
"proto",
")",
"|",
"block",
".",
"header",
".",
"full_hash",
"==",
"blockhash",
"}",
"end"
] | if block is in chain or in queue | [
"if",
"block",
"is",
"in",
"chain",
"or",
"in",
"queue"
] | 06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec | https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/chain_service.rb#L217-L220 | train |
NREL/haystack_ruby | lib/haystack_ruby/config.rb | HaystackRuby.Config.load! | def load!(path, environment = nil)
require 'yaml'
environment ||= Rails.env
conf = YAML.load(File.new(path).read).with_indifferent_access[environment]
load_configuration(conf)
end | ruby | def load!(path, environment = nil)
require 'yaml'
environment ||= Rails.env
conf = YAML.load(File.new(path).read).with_indifferent_access[environment]
load_configuration(conf)
end | [
"def",
"load!",
"(",
"path",
",",
"environment",
"=",
"nil",
")",
"require",
"'yaml'",
"environment",
"||=",
"Rails",
".",
"env",
"conf",
"=",
"YAML",
".",
"load",
"(",
"File",
".",
"new",
"(",
"path",
")",
".",
"read",
")",
".",
"with_indifferent_access",
"[",
"environment",
"]",
"load_configuration",
"(",
"conf",
")",
"end"
] | called in railtie | [
"called",
"in",
"railtie"
] | 5ebf8ff74767732f51571ab47f8d10e08ffff1fb | https://github.com/NREL/haystack_ruby/blob/5ebf8ff74767732f51571ab47f8d10e08ffff1fb/lib/haystack_ruby/config.rb#L15-L20 | train |
hck/open_nlp | lib/open_nlp/chunker.rb | OpenNlp.Chunker.chunk | def chunk(str)
raise ArgumentError, 'str must be a String' unless str.is_a?(String)
tokens = tokenizer.tokenize(str)
pos_tags = pos_tagger.tag(tokens).to_ary
chunks = j_instance.chunk(tokens.to_java(:String), pos_tags.to_java(:String)).to_ary
build_chunks(chunks, tokens, pos_tags)
end | ruby | def chunk(str)
raise ArgumentError, 'str must be a String' unless str.is_a?(String)
tokens = tokenizer.tokenize(str)
pos_tags = pos_tagger.tag(tokens).to_ary
chunks = j_instance.chunk(tokens.to_java(:String), pos_tags.to_java(:String)).to_ary
build_chunks(chunks, tokens, pos_tags)
end | [
"def",
"chunk",
"(",
"str",
")",
"raise",
"ArgumentError",
",",
"'str must be a String'",
"unless",
"str",
".",
"is_a?",
"(",
"String",
")",
"tokens",
"=",
"tokenizer",
".",
"tokenize",
"(",
"str",
")",
"pos_tags",
"=",
"pos_tagger",
".",
"tag",
"(",
"tokens",
")",
".",
"to_ary",
"chunks",
"=",
"j_instance",
".",
"chunk",
"(",
"tokens",
".",
"to_java",
"(",
":String",
")",
",",
"pos_tags",
".",
"to_java",
"(",
":String",
")",
")",
".",
"to_ary",
"build_chunks",
"(",
"chunks",
",",
"tokens",
",",
"pos_tags",
")",
"end"
] | Initializes new instance of Chunker
@param [OpenNlp::Model] model chunker model
@param [Model::Tokenizer] token_model tokenizer model
@param [Model::POSTagger] pos_model part-of-speech tagging model
Chunks a string into part-of-sentence pieces
@param [String] str string to chunk
@return [Array] array of chunks with part-of-sentence information | [
"Initializes",
"new",
"instance",
"of",
"Chunker"
] | 1c006a37747d797a41aa72ef6068fae770464862 | https://github.com/hck/open_nlp/blob/1c006a37747d797a41aa72ef6068fae770464862/lib/open_nlp/chunker.rb#L27-L36 | train |
skroutz/greeklish | lib/greeklish/greeklish_generator.rb | Greeklish.GreeklishGenerator.generate_greeklish_words | def generate_greeklish_words(greek_words)
@greeklish_list.clear
greek_words.each do |greek_word|
@per_word_greeklish.clear
initial_token = greek_word
digraphs.each_key do |key|
greek_word = greek_word.gsub(key, digraphs[key])
end
# Convert it back to array of characters. The iterations of each
# character will take place through this array.
input_token = greek_word.split(//)
# Iterate through the characters of the token and generate
# greeklish words.
input_token.each do |greek_char|
add_character(conversions[greek_char])
end
@greeklish_list << per_word_greeklish.flatten
end
@greeklish_list.flatten
end | ruby | def generate_greeklish_words(greek_words)
@greeklish_list.clear
greek_words.each do |greek_word|
@per_word_greeklish.clear
initial_token = greek_word
digraphs.each_key do |key|
greek_word = greek_word.gsub(key, digraphs[key])
end
# Convert it back to array of characters. The iterations of each
# character will take place through this array.
input_token = greek_word.split(//)
# Iterate through the characters of the token and generate
# greeklish words.
input_token.each do |greek_char|
add_character(conversions[greek_char])
end
@greeklish_list << per_word_greeklish.flatten
end
@greeklish_list.flatten
end | [
"def",
"generate_greeklish_words",
"(",
"greek_words",
")",
"@greeklish_list",
".",
"clear",
"greek_words",
".",
"each",
"do",
"|",
"greek_word",
"|",
"@per_word_greeklish",
".",
"clear",
"initial_token",
"=",
"greek_word",
"digraphs",
".",
"each_key",
"do",
"|",
"key",
"|",
"greek_word",
"=",
"greek_word",
".",
"gsub",
"(",
"key",
",",
"digraphs",
"[",
"key",
"]",
")",
"end",
"input_token",
"=",
"greek_word",
".",
"split",
"(",
"/",
"/",
")",
"input_token",
".",
"each",
"do",
"|",
"greek_char",
"|",
"add_character",
"(",
"conversions",
"[",
"greek_char",
"]",
")",
"end",
"@greeklish_list",
"<<",
"per_word_greeklish",
".",
"flatten",
"end",
"@greeklish_list",
".",
"flatten",
"end"
] | Gets a list of greek words and generates the greeklish version of
each word.
@param greek_words a list of greek words
@return a list of greeklish words | [
"Gets",
"a",
"list",
"of",
"greek",
"words",
"and",
"generates",
"the",
"greeklish",
"version",
"of",
"each",
"word",
"."
] | dcb414332d2f31fb281985e2b515b997a33f1bd9 | https://github.com/skroutz/greeklish/blob/dcb414332d2f31fb281985e2b515b997a33f1bd9/lib/greeklish/greeklish_generator.rb#L87-L113 | train |
hck/open_nlp | lib/open_nlp/sentence_detector.rb | OpenNlp.SentenceDetector.detect | def detect(str)
raise ArgumentError, 'str must be a String' unless str.is_a?(String)
j_instance.sentDetect(str).to_ary
end | ruby | def detect(str)
raise ArgumentError, 'str must be a String' unless str.is_a?(String)
j_instance.sentDetect(str).to_ary
end | [
"def",
"detect",
"(",
"str",
")",
"raise",
"ArgumentError",
",",
"'str must be a String'",
"unless",
"str",
".",
"is_a?",
"(",
"String",
")",
"j_instance",
".",
"sentDetect",
"(",
"str",
")",
".",
"to_ary",
"end"
] | Detects sentences in a string
@param [String] string string to detect sentences in
@return [Array<String>] array of detected sentences | [
"Detects",
"sentences",
"in",
"a",
"string"
] | 1c006a37747d797a41aa72ef6068fae770464862 | https://github.com/hck/open_nlp/blob/1c006a37747d797a41aa72ef6068fae770464862/lib/open_nlp/sentence_detector.rb#L9-L13 | train |
hck/open_nlp | lib/open_nlp/sentence_detector.rb | OpenNlp.SentenceDetector.pos_detect | def pos_detect(str)
raise ArgumentError, 'str must be a String' unless str.is_a?(String)
j_instance.sentPosDetect(str).map do |span|
OpenNlp::Util::Span.new(span.getStart, span.getEnd)
end
end | ruby | def pos_detect(str)
raise ArgumentError, 'str must be a String' unless str.is_a?(String)
j_instance.sentPosDetect(str).map do |span|
OpenNlp::Util::Span.new(span.getStart, span.getEnd)
end
end | [
"def",
"pos_detect",
"(",
"str",
")",
"raise",
"ArgumentError",
",",
"'str must be a String'",
"unless",
"str",
".",
"is_a?",
"(",
"String",
")",
"j_instance",
".",
"sentPosDetect",
"(",
"str",
")",
".",
"map",
"do",
"|",
"span",
"|",
"OpenNlp",
"::",
"Util",
"::",
"Span",
".",
"new",
"(",
"span",
".",
"getStart",
",",
"span",
".",
"getEnd",
")",
"end",
"end"
] | Detects sentences in a string and returns array of spans
@param [String] str
@return [Array<OpenNlp::Util::Span>] array of spans for detected sentences | [
"Detects",
"sentences",
"in",
"a",
"string",
"and",
"returns",
"array",
"of",
"spans"
] | 1c006a37747d797a41aa72ef6068fae770464862 | https://github.com/hck/open_nlp/blob/1c006a37747d797a41aa72ef6068fae770464862/lib/open_nlp/sentence_detector.rb#L19-L25 | train |
skroutz/greeklish | lib/greeklish/greek_reverse_stemmer.rb | Greeklish.GreekReverseStemmer.generate_greek_variants | def generate_greek_variants(token_string)
# clear the list from variations of the previous greek token
@greek_words.clear
# add the initial greek token in the greek words
@greek_words << token_string
# Find the first matching suffix and generate the variants
# of this word.
SUFFIX_STRINGS.each do |suffix|
if (token_string.end_with?(suffix[0]))
# Add to greek_words the tokens with the desired suffixes
generate_more_greek_words(token_string, suffix[0])
break
end
end
greek_words
end | ruby | def generate_greek_variants(token_string)
# clear the list from variations of the previous greek token
@greek_words.clear
# add the initial greek token in the greek words
@greek_words << token_string
# Find the first matching suffix and generate the variants
# of this word.
SUFFIX_STRINGS.each do |suffix|
if (token_string.end_with?(suffix[0]))
# Add to greek_words the tokens with the desired suffixes
generate_more_greek_words(token_string, suffix[0])
break
end
end
greek_words
end | [
"def",
"generate_greek_variants",
"(",
"token_string",
")",
"@greek_words",
".",
"clear",
"@greek_words",
"<<",
"token_string",
"SUFFIX_STRINGS",
".",
"each",
"do",
"|",
"suffix",
"|",
"if",
"(",
"token_string",
".",
"end_with?",
"(",
"suffix",
"[",
"0",
"]",
")",
")",
"generate_more_greek_words",
"(",
"token_string",
",",
"suffix",
"[",
"0",
"]",
")",
"break",
"end",
"end",
"greek_words",
"end"
] | This method generates the greek variants of the greek token that
receives.
@param token_string the greek word
@return a list of the generated greek word variations | [
"This",
"method",
"generates",
"the",
"greek",
"variants",
"of",
"the",
"greek",
"token",
"that",
"receives",
"."
] | dcb414332d2f31fb281985e2b515b997a33f1bd9 | https://github.com/skroutz/greeklish/blob/dcb414332d2f31fb281985e2b515b997a33f1bd9/lib/greeklish/greek_reverse_stemmer.rb#L82-L100 | train |
hck/open_nlp | lib/open_nlp/named_entity_detector.rb | OpenNlp.NamedEntityDetector.detect | def detect(tokens)
raise ArgumentError, 'tokens must be an instance of Array' unless tokens.is_a?(Array)
j_instance.find(tokens.to_java(:String)).to_ary
end | ruby | def detect(tokens)
raise ArgumentError, 'tokens must be an instance of Array' unless tokens.is_a?(Array)
j_instance.find(tokens.to_java(:String)).to_ary
end | [
"def",
"detect",
"(",
"tokens",
")",
"raise",
"ArgumentError",
",",
"'tokens must be an instance of Array'",
"unless",
"tokens",
".",
"is_a?",
"(",
"Array",
")",
"j_instance",
".",
"find",
"(",
"tokens",
".",
"to_java",
"(",
":String",
")",
")",
".",
"to_ary",
"end"
] | Detects names for provided array of tokens
@param [Array<String>] tokens tokens to run name detection on
@return [Array<Java::opennlp.tools.util.Span>] names detected | [
"Detects",
"names",
"for",
"provided",
"array",
"of",
"tokens"
] | 1c006a37747d797a41aa72ef6068fae770464862 | https://github.com/hck/open_nlp/blob/1c006a37747d797a41aa72ef6068fae770464862/lib/open_nlp/named_entity_detector.rb#L9-L13 | train |
cryptape/reth | lib/reth/synchronizer.rb | Reth.Synchronizer.receive_newblock | def receive_newblock(proto, t_block, chain_difficulty)
logger.debug 'newblock', proto: proto, block: t_block, chain_difficulty: chain_difficulty, client: proto.peer.remote_client_version
if @chain.include?(t_block.header.full_hash)
raise AssertError, 'chain difficulty mismatch' unless chain_difficulty == @chain.get(t_block.header.full_hash).chain_difficulty
end
@protocols[proto] = chain_difficulty
if @chainservice.knows_block(t_block.header.full_hash)
logger.debug 'known block'
return
end
expected_difficulty = @chain.head.chain_difficulty + t_block.header.difficulty
if chain_difficulty >= @chain.head.chain_difficulty
# broadcast duplicates filtering is done in chainservice
logger.debug 'sufficient difficulty, broadcasting', client: proto.peer.remote_client_version
@chainservice.broadcast_newblock t_block, chain_difficulty, proto
else
age = @chain.head.number - t_block.header.number
logger.debug "low difficulty", client: proto.peer.remote_client_version, chain_difficulty: chain_difficulty, expected_difficulty: expected_difficulty, block_age: age
if age > MAX_NEWBLOCK_AGE
logger.debug 'newblock is too old, not adding', block_age: age, max_age: MAX_NEWBLOCK_AGE
return
end
end
if @chainservice.knows_block(t_block.header.prevhash)
logger.debug 'adding block'
@chainservice.add_block t_block, proto
else
logger.debug 'missing parent'
if @synctask
logger.debug 'existing task, discarding'
else
@synctask = SyncTask.new self, proto, t_block.header.full_hash, chain_difficulty
end
end
end | ruby | def receive_newblock(proto, t_block, chain_difficulty)
logger.debug 'newblock', proto: proto, block: t_block, chain_difficulty: chain_difficulty, client: proto.peer.remote_client_version
if @chain.include?(t_block.header.full_hash)
raise AssertError, 'chain difficulty mismatch' unless chain_difficulty == @chain.get(t_block.header.full_hash).chain_difficulty
end
@protocols[proto] = chain_difficulty
if @chainservice.knows_block(t_block.header.full_hash)
logger.debug 'known block'
return
end
expected_difficulty = @chain.head.chain_difficulty + t_block.header.difficulty
if chain_difficulty >= @chain.head.chain_difficulty
# broadcast duplicates filtering is done in chainservice
logger.debug 'sufficient difficulty, broadcasting', client: proto.peer.remote_client_version
@chainservice.broadcast_newblock t_block, chain_difficulty, proto
else
age = @chain.head.number - t_block.header.number
logger.debug "low difficulty", client: proto.peer.remote_client_version, chain_difficulty: chain_difficulty, expected_difficulty: expected_difficulty, block_age: age
if age > MAX_NEWBLOCK_AGE
logger.debug 'newblock is too old, not adding', block_age: age, max_age: MAX_NEWBLOCK_AGE
return
end
end
if @chainservice.knows_block(t_block.header.prevhash)
logger.debug 'adding block'
@chainservice.add_block t_block, proto
else
logger.debug 'missing parent'
if @synctask
logger.debug 'existing task, discarding'
else
@synctask = SyncTask.new self, proto, t_block.header.full_hash, chain_difficulty
end
end
end | [
"def",
"receive_newblock",
"(",
"proto",
",",
"t_block",
",",
"chain_difficulty",
")",
"logger",
".",
"debug",
"'newblock'",
",",
"proto",
":",
"proto",
",",
"block",
":",
"t_block",
",",
"chain_difficulty",
":",
"chain_difficulty",
",",
"client",
":",
"proto",
".",
"peer",
".",
"remote_client_version",
"if",
"@chain",
".",
"include?",
"(",
"t_block",
".",
"header",
".",
"full_hash",
")",
"raise",
"AssertError",
",",
"'chain difficulty mismatch'",
"unless",
"chain_difficulty",
"==",
"@chain",
".",
"get",
"(",
"t_block",
".",
"header",
".",
"full_hash",
")",
".",
"chain_difficulty",
"end",
"@protocols",
"[",
"proto",
"]",
"=",
"chain_difficulty",
"if",
"@chainservice",
".",
"knows_block",
"(",
"t_block",
".",
"header",
".",
"full_hash",
")",
"logger",
".",
"debug",
"'known block'",
"return",
"end",
"expected_difficulty",
"=",
"@chain",
".",
"head",
".",
"chain_difficulty",
"+",
"t_block",
".",
"header",
".",
"difficulty",
"if",
"chain_difficulty",
">=",
"@chain",
".",
"head",
".",
"chain_difficulty",
"logger",
".",
"debug",
"'sufficient difficulty, broadcasting'",
",",
"client",
":",
"proto",
".",
"peer",
".",
"remote_client_version",
"@chainservice",
".",
"broadcast_newblock",
"t_block",
",",
"chain_difficulty",
",",
"proto",
"else",
"age",
"=",
"@chain",
".",
"head",
".",
"number",
"-",
"t_block",
".",
"header",
".",
"number",
"logger",
".",
"debug",
"\"low difficulty\"",
",",
"client",
":",
"proto",
".",
"peer",
".",
"remote_client_version",
",",
"chain_difficulty",
":",
"chain_difficulty",
",",
"expected_difficulty",
":",
"expected_difficulty",
",",
"block_age",
":",
"age",
"if",
"age",
">",
"MAX_NEWBLOCK_AGE",
"logger",
".",
"debug",
"'newblock is too old, not adding'",
",",
"block_age",
":",
"age",
",",
"max_age",
":",
"MAX_NEWBLOCK_AGE",
"return",
"end",
"end",
"if",
"@chainservice",
".",
"knows_block",
"(",
"t_block",
".",
"header",
".",
"prevhash",
")",
"logger",
".",
"debug",
"'adding block'",
"@chainservice",
".",
"add_block",
"t_block",
",",
"proto",
"else",
"logger",
".",
"debug",
"'missing parent'",
"if",
"@synctask",
"logger",
".",
"debug",
"'existing task, discarding'",
"else",
"@synctask",
"=",
"SyncTask",
".",
"new",
"self",
",",
"proto",
",",
"t_block",
".",
"header",
".",
"full_hash",
",",
"chain_difficulty",
"end",
"end",
"end"
] | Called if there's a newblock announced on the network. | [
"Called",
"if",
"there",
"s",
"a",
"newblock",
"announced",
"on",
"the",
"network",
"."
] | 06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec | https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/synchronizer.rb#L74-L114 | train |
cryptape/reth | lib/reth/synchronizer.rb | Reth.Synchronizer.receive_status | def receive_status(proto, blockhash, chain_difficulty)
logger.debug 'status received', proto: proto, chain_difficulty: chain_difficulty
@protocols[proto] = chain_difficulty
if @chainservice.knows_block(blockhash) || @synctask
logger.debug 'existing task or known hash, discarding'
return
end
if @force_sync
blockhash, difficulty = force_sync
logger.debug 'starting forced synctask', blockhash: Utils.encode_hex(blockhash)
@synctask = SyncTask.new self, proto, blockhash, difficulty
elsif chain_difficulty > @chain.head.chain_difficulty
logger.debug 'sufficient difficulty'
@synctask = SyncTask.new self, proto, blockhash, chain_difficulty
end
rescue
logger.debug $!
logger.debug $!.backtrace[0,10].join("\n")
end | ruby | def receive_status(proto, blockhash, chain_difficulty)
logger.debug 'status received', proto: proto, chain_difficulty: chain_difficulty
@protocols[proto] = chain_difficulty
if @chainservice.knows_block(blockhash) || @synctask
logger.debug 'existing task or known hash, discarding'
return
end
if @force_sync
blockhash, difficulty = force_sync
logger.debug 'starting forced synctask', blockhash: Utils.encode_hex(blockhash)
@synctask = SyncTask.new self, proto, blockhash, difficulty
elsif chain_difficulty > @chain.head.chain_difficulty
logger.debug 'sufficient difficulty'
@synctask = SyncTask.new self, proto, blockhash, chain_difficulty
end
rescue
logger.debug $!
logger.debug $!.backtrace[0,10].join("\n")
end | [
"def",
"receive_status",
"(",
"proto",
",",
"blockhash",
",",
"chain_difficulty",
")",
"logger",
".",
"debug",
"'status received'",
",",
"proto",
":",
"proto",
",",
"chain_difficulty",
":",
"chain_difficulty",
"@protocols",
"[",
"proto",
"]",
"=",
"chain_difficulty",
"if",
"@chainservice",
".",
"knows_block",
"(",
"blockhash",
")",
"||",
"@synctask",
"logger",
".",
"debug",
"'existing task or known hash, discarding'",
"return",
"end",
"if",
"@force_sync",
"blockhash",
",",
"difficulty",
"=",
"force_sync",
"logger",
".",
"debug",
"'starting forced synctask'",
",",
"blockhash",
":",
"Utils",
".",
"encode_hex",
"(",
"blockhash",
")",
"@synctask",
"=",
"SyncTask",
".",
"new",
"self",
",",
"proto",
",",
"blockhash",
",",
"difficulty",
"elsif",
"chain_difficulty",
">",
"@chain",
".",
"head",
".",
"chain_difficulty",
"logger",
".",
"debug",
"'sufficient difficulty'",
"@synctask",
"=",
"SyncTask",
".",
"new",
"self",
",",
"proto",
",",
"blockhash",
",",
"chain_difficulty",
"end",
"rescue",
"logger",
".",
"debug",
"$!",
"logger",
".",
"debug",
"$!",
".",
"backtrace",
"[",
"0",
",",
"10",
"]",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] | Called if a new peer is connected. | [
"Called",
"if",
"a",
"new",
"peer",
"is",
"connected",
"."
] | 06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec | https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/synchronizer.rb#L119-L140 | train |
cryptape/reth | lib/reth/synchronizer.rb | Reth.Synchronizer.receive_newblockhashes | def receive_newblockhashes(proto, newblockhashes)
logger.debug 'received newblockhashes', num: newblockhashes.size, proto: proto
newblockhashes = newblockhashes.select {|h| [email protected]_block(h) }
known = @protocols.include?(proto)
if !known || newblockhashes.empty? || @synctask
logger.debug 'discarding', known: known, synctask: syncing?, num: newblockhashes.size
return
end
if newblockhashes.size != 1
logger.warn 'supporting only one newblockhash', num: newblockhashes.size
end
blockhash = newblockhashes[0]
logger.debug 'starting synctask for newblockhashes', blockhash: Utils.encode_hex(blockhash)
@synctask = SyncTask.new self, proto, blockhash, 0, true
end | ruby | def receive_newblockhashes(proto, newblockhashes)
logger.debug 'received newblockhashes', num: newblockhashes.size, proto: proto
newblockhashes = newblockhashes.select {|h| [email protected]_block(h) }
known = @protocols.include?(proto)
if !known || newblockhashes.empty? || @synctask
logger.debug 'discarding', known: known, synctask: syncing?, num: newblockhashes.size
return
end
if newblockhashes.size != 1
logger.warn 'supporting only one newblockhash', num: newblockhashes.size
end
blockhash = newblockhashes[0]
logger.debug 'starting synctask for newblockhashes', blockhash: Utils.encode_hex(blockhash)
@synctask = SyncTask.new self, proto, blockhash, 0, true
end | [
"def",
"receive_newblockhashes",
"(",
"proto",
",",
"newblockhashes",
")",
"logger",
".",
"debug",
"'received newblockhashes'",
",",
"num",
":",
"newblockhashes",
".",
"size",
",",
"proto",
":",
"proto",
"newblockhashes",
"=",
"newblockhashes",
".",
"select",
"{",
"|",
"h",
"|",
"!",
"@chainservice",
".",
"knows_block",
"(",
"h",
")",
"}",
"known",
"=",
"@protocols",
".",
"include?",
"(",
"proto",
")",
"if",
"!",
"known",
"||",
"newblockhashes",
".",
"empty?",
"||",
"@synctask",
"logger",
".",
"debug",
"'discarding'",
",",
"known",
":",
"known",
",",
"synctask",
":",
"syncing?",
",",
"num",
":",
"newblockhashes",
".",
"size",
"return",
"end",
"if",
"newblockhashes",
".",
"size",
"!=",
"1",
"logger",
".",
"warn",
"'supporting only one newblockhash'",
",",
"num",
":",
"newblockhashes",
".",
"size",
"end",
"blockhash",
"=",
"newblockhashes",
"[",
"0",
"]",
"logger",
".",
"debug",
"'starting synctask for newblockhashes'",
",",
"blockhash",
":",
"Utils",
".",
"encode_hex",
"(",
"blockhash",
")",
"@synctask",
"=",
"SyncTask",
".",
"new",
"self",
",",
"proto",
",",
"blockhash",
",",
"0",
",",
"true",
"end"
] | No way to check if this really an interesting block at this point.
Might lead to an amplification attack, need to track this proto and
judge usefulness. | [
"No",
"way",
"to",
"check",
"if",
"this",
"really",
"an",
"interesting",
"block",
"at",
"this",
"point",
".",
"Might",
"lead",
"to",
"an",
"amplification",
"attack",
"need",
"to",
"track",
"this",
"proto",
"and",
"judge",
"usefulness",
"."
] | 06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec | https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/synchronizer.rb#L147-L165 | train |
NREL/haystack_ruby | lib/haystack_ruby/project.rb | HaystackRuby.Project.api_eval | def api_eval(expr_str)
body = ["ver:\"#{@haystack_version}\""]
body << "expr"
body << '"'+expr_str+'"'
res = self.connection.post('eval') do |req|
req.headers['Content-Type'] = 'text/plain'
req.body = body.join("\n")
end
JSON.parse! res.body
end | ruby | def api_eval(expr_str)
body = ["ver:\"#{@haystack_version}\""]
body << "expr"
body << '"'+expr_str+'"'
res = self.connection.post('eval') do |req|
req.headers['Content-Type'] = 'text/plain'
req.body = body.join("\n")
end
JSON.parse! res.body
end | [
"def",
"api_eval",
"(",
"expr_str",
")",
"body",
"=",
"[",
"\"ver:\\\"#{@haystack_version}\\\"\"",
"]",
"body",
"<<",
"\"expr\"",
"body",
"<<",
"'\"'",
"+",
"expr_str",
"+",
"'\"'",
"res",
"=",
"self",
".",
"connection",
".",
"post",
"(",
"'eval'",
")",
"do",
"|",
"req",
"|",
"req",
".",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'text/plain'",
"req",
".",
"body",
"=",
"body",
".",
"join",
"(",
"\"\\n\"",
")",
"end",
"JSON",
".",
"parse!",
"res",
".",
"body",
"end"
] | this function will post expr_str exactly as encoded | [
"this",
"function",
"will",
"post",
"expr_str",
"exactly",
"as",
"encoded"
] | 5ebf8ff74767732f51571ab47f8d10e08ffff1fb | https://github.com/NREL/haystack_ruby/blob/5ebf8ff74767732f51571ab47f8d10e08ffff1fb/lib/haystack_ruby/project.rb#L64-L73 | train |
NREL/haystack_ruby | lib/haystack_ruby/project.rb | HaystackRuby.Project.equip_point_meta | def equip_point_meta
begin
equips = read({filter: '"equip"'})['rows']
puts equips
equips.map! do |eq|
eq.delete('disMacro')
eq['description'] = eq['id'].match(/[(NWTC)|(\$siteRef)] (.*)/)[1]
eq['id'] = eq['id'].match(/:([a-z0-9\-]*)/)[1]
eq['points'] = []
read({filter: "\"point and equipRef==#{eq['id']}\""})['rows'].each do |p|
p.delete('analytics')
p.delete('disMacro')
p.delete('csvUnit')
p.delete('csvColumn')
p.delete('equipRef')
p.delete('point')
p.delete('siteRef')
p['id'] = p['id'].match(/:([a-z0-9\-]*)/)[1]
p['name'] = p['navName']
p.delete('navName')
eq['points'] << p
end
eq
end
rescue Exception => e
puts "error: #{e}"
nil
end
end | ruby | def equip_point_meta
begin
equips = read({filter: '"equip"'})['rows']
puts equips
equips.map! do |eq|
eq.delete('disMacro')
eq['description'] = eq['id'].match(/[(NWTC)|(\$siteRef)] (.*)/)[1]
eq['id'] = eq['id'].match(/:([a-z0-9\-]*)/)[1]
eq['points'] = []
read({filter: "\"point and equipRef==#{eq['id']}\""})['rows'].each do |p|
p.delete('analytics')
p.delete('disMacro')
p.delete('csvUnit')
p.delete('csvColumn')
p.delete('equipRef')
p.delete('point')
p.delete('siteRef')
p['id'] = p['id'].match(/:([a-z0-9\-]*)/)[1]
p['name'] = p['navName']
p.delete('navName')
eq['points'] << p
end
eq
end
rescue Exception => e
puts "error: #{e}"
nil
end
end | [
"def",
"equip_point_meta",
"begin",
"equips",
"=",
"read",
"(",
"{",
"filter",
":",
"'\"equip\"'",
"}",
")",
"[",
"'rows'",
"]",
"puts",
"equips",
"equips",
".",
"map!",
"do",
"|",
"eq",
"|",
"eq",
".",
"delete",
"(",
"'disMacro'",
")",
"eq",
"[",
"'description'",
"]",
"=",
"eq",
"[",
"'id'",
"]",
".",
"match",
"(",
"/",
"\\$",
"/",
")",
"[",
"1",
"]",
"eq",
"[",
"'id'",
"]",
"=",
"eq",
"[",
"'id'",
"]",
".",
"match",
"(",
"/",
"\\-",
"/",
")",
"[",
"1",
"]",
"eq",
"[",
"'points'",
"]",
"=",
"[",
"]",
"read",
"(",
"{",
"filter",
":",
"\"\\\"point and equipRef==#{eq['id']}\\\"\"",
"}",
")",
"[",
"'rows'",
"]",
".",
"each",
"do",
"|",
"p",
"|",
"p",
".",
"delete",
"(",
"'analytics'",
")",
"p",
".",
"delete",
"(",
"'disMacro'",
")",
"p",
".",
"delete",
"(",
"'csvUnit'",
")",
"p",
".",
"delete",
"(",
"'csvColumn'",
")",
"p",
".",
"delete",
"(",
"'equipRef'",
")",
"p",
".",
"delete",
"(",
"'point'",
")",
"p",
".",
"delete",
"(",
"'siteRef'",
")",
"p",
"[",
"'id'",
"]",
"=",
"p",
"[",
"'id'",
"]",
".",
"match",
"(",
"/",
"\\-",
"/",
")",
"[",
"1",
"]",
"p",
"[",
"'name'",
"]",
"=",
"p",
"[",
"'navName'",
"]",
"p",
".",
"delete",
"(",
"'navName'",
")",
"eq",
"[",
"'points'",
"]",
"<<",
"p",
"end",
"eq",
"end",
"rescue",
"Exception",
"=>",
"e",
"puts",
"\"error: #{e}\"",
"nil",
"end",
"end"
] | return meta data for all equip with related points | [
"return",
"meta",
"data",
"for",
"all",
"equip",
"with",
"related",
"points"
] | 5ebf8ff74767732f51571ab47f8d10e08ffff1fb | https://github.com/NREL/haystack_ruby/blob/5ebf8ff74767732f51571ab47f8d10e08ffff1fb/lib/haystack_ruby/project.rb#L76-L105 | train |
hck/open_nlp | lib/open_nlp/parser.rb | OpenNlp.Parser.parse | def parse(text)
raise ArgumentError, 'passed text must be a String' unless text.is_a?(String)
text.empty? ? {} : parse_tokens(tokenizer.tokenize(text), text)
end | ruby | def parse(text)
raise ArgumentError, 'passed text must be a String' unless text.is_a?(String)
text.empty? ? {} : parse_tokens(tokenizer.tokenize(text), text)
end | [
"def",
"parse",
"(",
"text",
")",
"raise",
"ArgumentError",
",",
"'passed text must be a String'",
"unless",
"text",
".",
"is_a?",
"(",
"String",
")",
"text",
".",
"empty?",
"?",
"{",
"}",
":",
"parse_tokens",
"(",
"tokenizer",
".",
"tokenize",
"(",
"text",
")",
",",
"text",
")",
"end"
] | Initializes new instance of Parser
@param [OpenNlp::Model::Parser] parser_model
@param [OpenNlp::Model::Tokenizer] token_model
Parses text into instance of Parse class
@param [String] text text to parse
@return [OpenNlp::Parser::Parse] | [
"Initializes",
"new",
"instance",
"of",
"Parser"
] | 1c006a37747d797a41aa72ef6068fae770464862 | https://github.com/hck/open_nlp/blob/1c006a37747d797a41aa72ef6068fae770464862/lib/open_nlp/parser.rb#L22-L26 | train |
richard-viney/ig_markets | lib/ig_markets/response_parser.rb | IGMarkets.ResponseParser.parse | def parse(response)
if response.is_a? Hash
response.each_with_object({}) do |(key, value), new_hash|
new_hash[camel_case_to_snake_case(key).to_sym] = parse(value)
end
elsif response.is_a? Array
response.map { |item| parse item }
else
response
end
end | ruby | def parse(response)
if response.is_a? Hash
response.each_with_object({}) do |(key, value), new_hash|
new_hash[camel_case_to_snake_case(key).to_sym] = parse(value)
end
elsif response.is_a? Array
response.map { |item| parse item }
else
response
end
end | [
"def",
"parse",
"(",
"response",
")",
"if",
"response",
".",
"is_a?",
"Hash",
"response",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"key",
",",
"value",
")",
",",
"new_hash",
"|",
"new_hash",
"[",
"camel_case_to_snake_case",
"(",
"key",
")",
".",
"to_sym",
"]",
"=",
"parse",
"(",
"value",
")",
"end",
"elsif",
"response",
".",
"is_a?",
"Array",
"response",
".",
"map",
"{",
"|",
"item",
"|",
"parse",
"item",
"}",
"else",
"response",
"end",
"end"
] | Parses the specified value that was returned from a call to the IG Markets API.
@param [Hash, Array, Object] response The response or part of a response that should be parsed. If this is of type
`Hash` then all hash keys will converted from camel case into snake case and their values will each be
parsed individually by a recursive call. If this is of type `Array` then each item will be parsed
individually by a recursive call. All other types are passed through unchanged.
@return [Hash, Array, Object] The parsed object, the type depends on the type of the `response` parameter. | [
"Parses",
"the",
"specified",
"value",
"that",
"was",
"returned",
"from",
"a",
"call",
"to",
"the",
"IG",
"Markets",
"API",
"."
] | c1989ec557b0ba643a76024c5bec624abd8c1c4c | https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/response_parser.rb#L16-L26 | train |
hck/open_nlp | lib/open_nlp/categorizer.rb | OpenNlp.Categorizer.categorize | def categorize(str)
raise ArgumentError, 'str param must be a String' unless str.is_a?(String)
outcomes = j_instance.categorize(str)
j_instance.getBestCategory(outcomes)
end | ruby | def categorize(str)
raise ArgumentError, 'str param must be a String' unless str.is_a?(String)
outcomes = j_instance.categorize(str)
j_instance.getBestCategory(outcomes)
end | [
"def",
"categorize",
"(",
"str",
")",
"raise",
"ArgumentError",
",",
"'str param must be a String'",
"unless",
"str",
".",
"is_a?",
"(",
"String",
")",
"outcomes",
"=",
"j_instance",
".",
"categorize",
"(",
"str",
")",
"j_instance",
".",
"getBestCategory",
"(",
"outcomes",
")",
"end"
] | Categorizes a string passed as parameter to one of the categories
@param [String] str string to be categorized
@return [String] category | [
"Categorizes",
"a",
"string",
"passed",
"as",
"parameter",
"to",
"one",
"of",
"the",
"categories"
] | 1c006a37747d797a41aa72ef6068fae770464862 | https://github.com/hck/open_nlp/blob/1c006a37747d797a41aa72ef6068fae770464862/lib/open_nlp/categorizer.rb#L9-L14 | train |
udongo/udongo | lib/udongo/pages/tree_node.rb | Udongo::Pages.TreeNode.data | def data
{
text: @page.description,
type: :file,
li_attr: list_attributes,
data: {
id: @page.id,
url: @context.edit_translation_backend_page_path(@page, Udongo.config.i18n.app.default_locale),
delete_url: @context.backend_page_path(@page, format: :json),
deletable: @page.deletable?,
draggable: @page.draggable?,
update_position_url: @context.tree_drag_and_drop_backend_page_path(@page),
visible: @page.visible?,
toggle_visibility_url: @context.toggle_visibility_backend_page_path(@page, format: :json)
},
children: [] # This gets filled through Udongo::Pages::Tree
}
end | ruby | def data
{
text: @page.description,
type: :file,
li_attr: list_attributes,
data: {
id: @page.id,
url: @context.edit_translation_backend_page_path(@page, Udongo.config.i18n.app.default_locale),
delete_url: @context.backend_page_path(@page, format: :json),
deletable: @page.deletable?,
draggable: @page.draggable?,
update_position_url: @context.tree_drag_and_drop_backend_page_path(@page),
visible: @page.visible?,
toggle_visibility_url: @context.toggle_visibility_backend_page_path(@page, format: :json)
},
children: [] # This gets filled through Udongo::Pages::Tree
}
end | [
"def",
"data",
"{",
"text",
":",
"@page",
".",
"description",
",",
"type",
":",
":file",
",",
"li_attr",
":",
"list_attributes",
",",
"data",
":",
"{",
"id",
":",
"@page",
".",
"id",
",",
"url",
":",
"@context",
".",
"edit_translation_backend_page_path",
"(",
"@page",
",",
"Udongo",
".",
"config",
".",
"i18n",
".",
"app",
".",
"default_locale",
")",
",",
"delete_url",
":",
"@context",
".",
"backend_page_path",
"(",
"@page",
",",
"format",
":",
":json",
")",
",",
"deletable",
":",
"@page",
".",
"deletable?",
",",
"draggable",
":",
"@page",
".",
"draggable?",
",",
"update_position_url",
":",
"@context",
".",
"tree_drag_and_drop_backend_page_path",
"(",
"@page",
")",
",",
"visible",
":",
"@page",
".",
"visible?",
",",
"toggle_visibility_url",
":",
"@context",
".",
"toggle_visibility_backend_page_path",
"(",
"@page",
",",
"format",
":",
":json",
")",
"}",
",",
"children",
":",
"[",
"]",
"}",
"end"
] | Context should contain accessible routes. | [
"Context",
"should",
"contain",
"accessible",
"routes",
"."
] | 868a55ab7107473ce9f3645756b6293759317d02 | https://github.com/udongo/udongo/blob/868a55ab7107473ce9f3645756b6293759317d02/lib/udongo/pages/tree_node.rb#L9-L26 | train |
skroutz/greeklish | lib/greeklish/greeklish_converter.rb | Greeklish.GreeklishConverter.identify_greek_word | def identify_greek_word(input)
input.each_char do |char|
if (!GREEK_CHARACTERS.include?(char))
return false
end
end
true
end | ruby | def identify_greek_word(input)
input.each_char do |char|
if (!GREEK_CHARACTERS.include?(char))
return false
end
end
true
end | [
"def",
"identify_greek_word",
"(",
"input",
")",
"input",
".",
"each_char",
"do",
"|",
"char",
"|",
"if",
"(",
"!",
"GREEK_CHARACTERS",
".",
"include?",
"(",
"char",
")",
")",
"return",
"false",
"end",
"end",
"true",
"end"
] | Identifies words with only Greek lowercase characters.
@param input The string that will examine
@return true if the string contains only Greek characters | [
"Identifies",
"words",
"with",
"only",
"Greek",
"lowercase",
"characters",
"."
] | dcb414332d2f31fb281985e2b515b997a33f1bd9 | https://github.com/skroutz/greeklish/blob/dcb414332d2f31fb281985e2b515b997a33f1bd9/lib/greeklish/greeklish_converter.rb#L77-L85 | train |
richard-viney/ig_markets | lib/ig_markets/position.rb | IGMarkets.Position.close | def close(options = {})
options[:deal_id] = deal_id
options[:direction] = { buy: :sell, sell: :buy }.fetch(direction)
options[:size] ||= size
model = PositionCloseAttributes.build options
model.validate
body = RequestBodyFormatter.format model
@dealing_platform.session.delete('positions/otc', body).fetch :deal_reference
end | ruby | def close(options = {})
options[:deal_id] = deal_id
options[:direction] = { buy: :sell, sell: :buy }.fetch(direction)
options[:size] ||= size
model = PositionCloseAttributes.build options
model.validate
body = RequestBodyFormatter.format model
@dealing_platform.session.delete('positions/otc', body).fetch :deal_reference
end | [
"def",
"close",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":deal_id",
"]",
"=",
"deal_id",
"options",
"[",
":direction",
"]",
"=",
"{",
"buy",
":",
":sell",
",",
"sell",
":",
":buy",
"}",
".",
"fetch",
"(",
"direction",
")",
"options",
"[",
":size",
"]",
"||=",
"size",
"model",
"=",
"PositionCloseAttributes",
".",
"build",
"options",
"model",
".",
"validate",
"body",
"=",
"RequestBodyFormatter",
".",
"format",
"model",
"@dealing_platform",
".",
"session",
".",
"delete",
"(",
"'positions/otc'",
",",
"body",
")",
".",
"fetch",
":deal_reference",
"end"
] | Closes this position. If called with no options then this position will be fully closed at current market prices,
partial closes and greater control over the close conditions can be achieved by using the relevant options.
@param [Hash] options The options for the position close.
@option options [Float] :level Required if and only if `:order_type` is `:limit` or `:quote`.
@option options [:limit, :market, :quote] :order_type The order type. `:market` indicates to fill the order at
current market level(s). `:limit` indicates to fill at the price specified by `:level` (or a more
favorable one). `:quote` is only permitted following agreement with IG Markets. Defaults to
`:market`.
@option options [String] :quote_id The Lightstreamer quote ID. Required when `:order_type` is `:quote`.
@option options [Float] :size The size of the position to close. Defaults to {#size} which will close the entire
position, or alternatively specify a smaller value to partially close this position.
@option options [:execute_and_eliminate, :fill_or_kill] :time_in_force The order fill strategy.
`:execute_and_eliminate` will fill this order as much as possible within the constraints set by
`:order_type`, `:level` and `:quote_id`. `:fill_or_kill` will try to fill this entire order within
the constraints, however if this is not possible then the order will not be filled at all. If
`:order_type` is `:market` (the default) then `:time_in_force` will be automatically set to
`:execute_and_eliminate`.
@return [String] The resulting deal reference, use {DealingPlatform#deal_confirmation} to check the result of
the position close. | [
"Closes",
"this",
"position",
".",
"If",
"called",
"with",
"no",
"options",
"then",
"this",
"position",
"will",
"be",
"fully",
"closed",
"at",
"current",
"market",
"prices",
"partial",
"closes",
"and",
"greater",
"control",
"over",
"the",
"close",
"conditions",
"can",
"be",
"achieved",
"by",
"using",
"the",
"relevant",
"options",
"."
] | c1989ec557b0ba643a76024c5bec624abd8c1c4c | https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/position.rb#L90-L101 | train |
richard-viney/ig_markets | lib/ig_markets/position.rb | IGMarkets.Position.update | def update(new_attributes)
new_attributes = { limit_level: limit_level, stop_level: stop_level, trailing_stop: trailing_stop?,
trailing_stop_distance: trailing_stop_distance, trailing_stop_increment: trailing_step }
.merge new_attributes
unless new_attributes[:trailing_stop]
new_attributes[:trailing_stop_distance] = new_attributes[:trailing_stop_increment] = nil
end
body = RequestBodyFormatter.format PositionUpdateAttributes.new(new_attributes)
@dealing_platform.session.put("positions/otc/#{deal_id}", body, API_V2).fetch(:deal_reference)
end | ruby | def update(new_attributes)
new_attributes = { limit_level: limit_level, stop_level: stop_level, trailing_stop: trailing_stop?,
trailing_stop_distance: trailing_stop_distance, trailing_stop_increment: trailing_step }
.merge new_attributes
unless new_attributes[:trailing_stop]
new_attributes[:trailing_stop_distance] = new_attributes[:trailing_stop_increment] = nil
end
body = RequestBodyFormatter.format PositionUpdateAttributes.new(new_attributes)
@dealing_platform.session.put("positions/otc/#{deal_id}", body, API_V2).fetch(:deal_reference)
end | [
"def",
"update",
"(",
"new_attributes",
")",
"new_attributes",
"=",
"{",
"limit_level",
":",
"limit_level",
",",
"stop_level",
":",
"stop_level",
",",
"trailing_stop",
":",
"trailing_stop?",
",",
"trailing_stop_distance",
":",
"trailing_stop_distance",
",",
"trailing_stop_increment",
":",
"trailing_step",
"}",
".",
"merge",
"new_attributes",
"unless",
"new_attributes",
"[",
":trailing_stop",
"]",
"new_attributes",
"[",
":trailing_stop_distance",
"]",
"=",
"new_attributes",
"[",
":trailing_stop_increment",
"]",
"=",
"nil",
"end",
"body",
"=",
"RequestBodyFormatter",
".",
"format",
"PositionUpdateAttributes",
".",
"new",
"(",
"new_attributes",
")",
"@dealing_platform",
".",
"session",
".",
"put",
"(",
"\"positions/otc/#{deal_id}\"",
",",
"body",
",",
"API_V2",
")",
".",
"fetch",
"(",
":deal_reference",
")",
"end"
] | Updates this position. No attributes are mandatory, and any attributes not specified will be kept at their
current value.
@param [Hash] new_attributes The attributes of this position to update.
@option new_attributes [Float] :limit_level The new limit level for this position.
@option new_attributes [Float] :stop_level The new stop level for this position.
@option new_attributes [Boolean] :trailing_stop Whether to use a trailing stop for this position.
@option new_attributes [Integer] :trailing_stop_distance The distance away in pips to place the trailing stop.
@option new_attributes [Integer] :trailing_stop_increment The step increment to use for the trailing stop.
@return [String] The deal reference of the update operation. Use {DealingPlatform#deal_confirmation} to check
the result of the position update. | [
"Updates",
"this",
"position",
".",
"No",
"attributes",
"are",
"mandatory",
"and",
"any",
"attributes",
"not",
"specified",
"will",
"be",
"kept",
"at",
"their",
"current",
"value",
"."
] | c1989ec557b0ba643a76024c5bec624abd8c1c4c | https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/position.rb#L115-L127 | train |
richard-viney/ig_markets | lib/ig_markets/password_encryptor.rb | IGMarkets.PasswordEncryptor.encoded_public_key= | def encoded_public_key=(encoded_public_key)
self.public_key = OpenSSL::PKey::RSA.new Base64.strict_decode64 encoded_public_key
end | ruby | def encoded_public_key=(encoded_public_key)
self.public_key = OpenSSL::PKey::RSA.new Base64.strict_decode64 encoded_public_key
end | [
"def",
"encoded_public_key",
"=",
"(",
"encoded_public_key",
")",
"self",
".",
"public_key",
"=",
"OpenSSL",
"::",
"PKey",
"::",
"RSA",
".",
"new",
"Base64",
".",
"strict_decode64",
"encoded_public_key",
"end"
] | Initializes this password encryptor with the specified encoded public key and timestamp.
@param [String] encoded_public_key
@param [String] time_stamp
Takes an encoded public key and calls {#public_key=} with the decoded key.
@param [String] encoded_public_key The public key encoded in Base64. | [
"Initializes",
"this",
"password",
"encryptor",
"with",
"the",
"specified",
"encoded",
"public",
"key",
"and",
"timestamp",
"."
] | c1989ec557b0ba643a76024c5bec624abd8c1c4c | https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/password_encryptor.rb#L28-L30 | train |
richard-viney/ig_markets | lib/ig_markets/password_encryptor.rb | IGMarkets.PasswordEncryptor.encrypt | def encrypt(password)
encoded_password = Base64.strict_encode64 "#{password}|#{time_stamp}"
encrypted_password = public_key.public_encrypt encoded_password
Base64.strict_encode64 encrypted_password
end | ruby | def encrypt(password)
encoded_password = Base64.strict_encode64 "#{password}|#{time_stamp}"
encrypted_password = public_key.public_encrypt encoded_password
Base64.strict_encode64 encrypted_password
end | [
"def",
"encrypt",
"(",
"password",
")",
"encoded_password",
"=",
"Base64",
".",
"strict_encode64",
"\"#{password}|#{time_stamp}\"",
"encrypted_password",
"=",
"public_key",
".",
"public_encrypt",
"encoded_password",
"Base64",
".",
"strict_encode64",
"encrypted_password",
"end"
] | Encrypts a password using this encryptor's public key and time stamp, which must have been set prior to calling
this method.
@param [String] password The password to encrypt.
@return [String] The encrypted password encoded in Base64. | [
"Encrypts",
"a",
"password",
"using",
"this",
"encryptor",
"s",
"public",
"key",
"and",
"time",
"stamp",
"which",
"must",
"have",
"been",
"set",
"prior",
"to",
"calling",
"this",
"method",
"."
] | c1989ec557b0ba643a76024c5bec624abd8c1c4c | https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/password_encryptor.rb#L38-L44 | train |
railslove/smurfville | lib/smurfville/typography_parser.rb | Smurfville.TypographyParser.is_typography_selector? | def is_typography_selector?(node)
node.is_a?(Sass::Tree::RuleNode) && node.rule[0].start_with?("%f-") rescue false
end | ruby | def is_typography_selector?(node)
node.is_a?(Sass::Tree::RuleNode) && node.rule[0].start_with?("%f-") rescue false
end | [
"def",
"is_typography_selector?",
"(",
"node",
")",
"node",
".",
"is_a?",
"(",
"Sass",
"::",
"Tree",
"::",
"RuleNode",
")",
"&&",
"node",
".",
"rule",
"[",
"0",
"]",
".",
"start_with?",
"(",
"\"%f-\"",
")",
"rescue",
"false",
"end"
] | determines if node is a placeholder selector starting widht the %f- convention for typography rulesets | [
"determines",
"if",
"node",
"is",
"a",
"placeholder",
"selector",
"starting",
"widht",
"the",
"%f",
"-",
"convention",
"for",
"typography",
"rulesets"
] | 0e6a84500cc3d748e25dd398acaf6d94878b3f84 | https://github.com/railslove/smurfville/blob/0e6a84500cc3d748e25dd398acaf6d94878b3f84/lib/smurfville/typography_parser.rb#L24-L26 | train |
cryptape/reth | lib/reth/account_service.rb | Reth.AccountService.coinbase | def coinbase
cb_hex = (app.config[:pow] || {})[:coinbase_hex]
if cb_hex
raise ValueError, 'coinbase must be String' unless cb_hex.is_a?(String)
begin
cb = Utils.decode_hex Utils.remove_0x_head(cb_hex)
rescue TypeError
raise ValueError, 'invalid coinbase'
end
else
accts = accounts_with_address
return DEFAULT_COINBASE if accts.empty?
cb = accts[0].address
end
raise ValueError, 'wrong coinbase length' if cb.size != 20
if config[:accounts][:must_include_coinbase]
raise ValueError, 'no account for coinbase' if [email protected](&:address).include?(cb)
end
cb
end | ruby | def coinbase
cb_hex = (app.config[:pow] || {})[:coinbase_hex]
if cb_hex
raise ValueError, 'coinbase must be String' unless cb_hex.is_a?(String)
begin
cb = Utils.decode_hex Utils.remove_0x_head(cb_hex)
rescue TypeError
raise ValueError, 'invalid coinbase'
end
else
accts = accounts_with_address
return DEFAULT_COINBASE if accts.empty?
cb = accts[0].address
end
raise ValueError, 'wrong coinbase length' if cb.size != 20
if config[:accounts][:must_include_coinbase]
raise ValueError, 'no account for coinbase' if [email protected](&:address).include?(cb)
end
cb
end | [
"def",
"coinbase",
"cb_hex",
"=",
"(",
"app",
".",
"config",
"[",
":pow",
"]",
"||",
"{",
"}",
")",
"[",
":coinbase_hex",
"]",
"if",
"cb_hex",
"raise",
"ValueError",
",",
"'coinbase must be String'",
"unless",
"cb_hex",
".",
"is_a?",
"(",
"String",
")",
"begin",
"cb",
"=",
"Utils",
".",
"decode_hex",
"Utils",
".",
"remove_0x_head",
"(",
"cb_hex",
")",
"rescue",
"TypeError",
"raise",
"ValueError",
",",
"'invalid coinbase'",
"end",
"else",
"accts",
"=",
"accounts_with_address",
"return",
"DEFAULT_COINBASE",
"if",
"accts",
".",
"empty?",
"cb",
"=",
"accts",
"[",
"0",
"]",
".",
"address",
"end",
"raise",
"ValueError",
",",
"'wrong coinbase length'",
"if",
"cb",
".",
"size",
"!=",
"20",
"if",
"config",
"[",
":accounts",
"]",
"[",
":must_include_coinbase",
"]",
"raise",
"ValueError",
",",
"'no account for coinbase'",
"if",
"!",
"@accounts",
".",
"map",
"(",
"&",
":address",
")",
".",
"include?",
"(",
"cb",
")",
"end",
"cb",
"end"
] | Return the address that should be used as coinbase for new blocks.
The coinbase address is given by the config field pow.coinbase_hex. If
this does not exist, the address of the first account is used instead.
If there are no accounts, the coinbase is `DEFAULT_COINBASE`.
@raise [ValueError] if the coinbase is invalid (no string, wrong
length) or there is no account for it and the config flag
`accounts.check_coinbase` is set (does not apply to the default
coinbase). | [
"Return",
"the",
"address",
"that",
"should",
"be",
"used",
"as",
"coinbase",
"for",
"new",
"blocks",
"."
] | 06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec | https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/account_service.rb#L80-L102 | train |
cryptape/reth | lib/reth/account_service.rb | Reth.AccountService.add_account | def add_account(account, store=true, include_address=true, include_id=true)
logger.info "adding account", account: account
if account.uuid && @accounts.any? {|acct| acct.uuid == account.uuid }
logger.error 'could not add account (UUID collision)', uuid: account.uuid
raise ValueError, 'Could not add account (UUID collision)'
end
if store
raise ValueError, 'Cannot store account without path' if account.path.nil?
if File.exist?(account.path)
logger.error 'File does already exist', path: account.path
raise IOError, 'File does already exist'
end
raise AssertError if @accounts.any? {|acct| acct.path == account.path }
begin
directory = File.dirname account.path
FileUtils.mkdir_p(directory) unless File.exist?(directory)
File.open(account.path, 'w') do |f|
f.write account.dump(include_address, include_id)
end
rescue IOError => e
logger.error "Could not write to file", path: account.path, message: e.to_s
raise e
end
end
@accounts.push account
@accounts.sort_by! {|acct| acct.path.to_s }
end | ruby | def add_account(account, store=true, include_address=true, include_id=true)
logger.info "adding account", account: account
if account.uuid && @accounts.any? {|acct| acct.uuid == account.uuid }
logger.error 'could not add account (UUID collision)', uuid: account.uuid
raise ValueError, 'Could not add account (UUID collision)'
end
if store
raise ValueError, 'Cannot store account without path' if account.path.nil?
if File.exist?(account.path)
logger.error 'File does already exist', path: account.path
raise IOError, 'File does already exist'
end
raise AssertError if @accounts.any? {|acct| acct.path == account.path }
begin
directory = File.dirname account.path
FileUtils.mkdir_p(directory) unless File.exist?(directory)
File.open(account.path, 'w') do |f|
f.write account.dump(include_address, include_id)
end
rescue IOError => e
logger.error "Could not write to file", path: account.path, message: e.to_s
raise e
end
end
@accounts.push account
@accounts.sort_by! {|acct| acct.path.to_s }
end | [
"def",
"add_account",
"(",
"account",
",",
"store",
"=",
"true",
",",
"include_address",
"=",
"true",
",",
"include_id",
"=",
"true",
")",
"logger",
".",
"info",
"\"adding account\"",
",",
"account",
":",
"account",
"if",
"account",
".",
"uuid",
"&&",
"@accounts",
".",
"any?",
"{",
"|",
"acct",
"|",
"acct",
".",
"uuid",
"==",
"account",
".",
"uuid",
"}",
"logger",
".",
"error",
"'could not add account (UUID collision)'",
",",
"uuid",
":",
"account",
".",
"uuid",
"raise",
"ValueError",
",",
"'Could not add account (UUID collision)'",
"end",
"if",
"store",
"raise",
"ValueError",
",",
"'Cannot store account without path'",
"if",
"account",
".",
"path",
".",
"nil?",
"if",
"File",
".",
"exist?",
"(",
"account",
".",
"path",
")",
"logger",
".",
"error",
"'File does already exist'",
",",
"path",
":",
"account",
".",
"path",
"raise",
"IOError",
",",
"'File does already exist'",
"end",
"raise",
"AssertError",
"if",
"@accounts",
".",
"any?",
"{",
"|",
"acct",
"|",
"acct",
".",
"path",
"==",
"account",
".",
"path",
"}",
"begin",
"directory",
"=",
"File",
".",
"dirname",
"account",
".",
"path",
"FileUtils",
".",
"mkdir_p",
"(",
"directory",
")",
"unless",
"File",
".",
"exist?",
"(",
"directory",
")",
"File",
".",
"open",
"(",
"account",
".",
"path",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"account",
".",
"dump",
"(",
"include_address",
",",
"include_id",
")",
"end",
"rescue",
"IOError",
"=>",
"e",
"logger",
".",
"error",
"\"Could not write to file\"",
",",
"path",
":",
"account",
".",
"path",
",",
"message",
":",
"e",
".",
"to_s",
"raise",
"e",
"end",
"end",
"@accounts",
".",
"push",
"account",
"@accounts",
".",
"sort_by!",
"{",
"|",
"acct",
"|",
"acct",
".",
"path",
".",
"to_s",
"}",
"end"
] | Add an account.
If `store` is true the account will be stored as a key file at the
location given by `account.path`. If this is `nil` a `ValueError` is
raised. `include_address` and `include_id` determine if address and id
should be removed for storage or not.
This method will raise a `ValueError` if the new account has the same
UUID as an account already known to the service. Note that address
collisions do not result in an exception as those may slip through
anyway for locked accounts with hidden addresses. | [
"Add",
"an",
"account",
"."
] | 06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec | https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/account_service.rb#L117-L149 | train |
cryptape/reth | lib/reth/account_service.rb | Reth.AccountService.update_account | def update_account(account, new_password, include_address=true, include_id=true)
raise ValueError, "Account not managed by account service" unless @accounts.include?(account)
raise ValueError, "Cannot update locked account" if account.locked?
raise ValueError, 'Account not stored on disk' unless account.path
logger.debug "creating new account"
new_account = Account.create new_password, account.privkey, account.uuid, account.path
backup_path = account.path + '~'
i = 1
while File.exist?(backup_path)
backup_path = backup_path[0, backup_path.rindex('~')+1] + i.to_s
i += 1
end
raise AssertError if File.exist?(backup_path)
logger.info 'moving old keystore file to backup location', from: account.path, to: backup_path
begin
FileUtils.mv account.path, backup_path
rescue
logger.error "could not backup keystore, stopping account update", from: account.path, to: backup_path
raise $!
end
raise AssertError unless File.exist?(backup_path)
raise AssertError if File.exist?(new_account.path)
account.path = backup_path
@accounts.delete account
begin
add_account new_account, include_address, include_id
rescue
logger.error 'adding new account failed, recovering from backup'
FileUtils.mv backup_path, new_account.path
account.path = new_account.path
@accounts.push account
@accounts.sort_by! {|acct| acct.path.to_s }
raise $!
end
raise AssertError unless File.exist?(new_account.path)
logger.info "deleting backup of old keystore", path: backup_path
begin
FileUtils.rm backup_path
rescue
logger.error 'failed to delete no longer needed backup of old keystore', path: account.path
raise $!
end
account.keystore = new_account.keystore
account.path = new_account.path
@accounts.push account
@accounts.delete new_account
@accounts.sort_by! {|acct| acct.path.to_s }
logger.debug "account update successful"
end | ruby | def update_account(account, new_password, include_address=true, include_id=true)
raise ValueError, "Account not managed by account service" unless @accounts.include?(account)
raise ValueError, "Cannot update locked account" if account.locked?
raise ValueError, 'Account not stored on disk' unless account.path
logger.debug "creating new account"
new_account = Account.create new_password, account.privkey, account.uuid, account.path
backup_path = account.path + '~'
i = 1
while File.exist?(backup_path)
backup_path = backup_path[0, backup_path.rindex('~')+1] + i.to_s
i += 1
end
raise AssertError if File.exist?(backup_path)
logger.info 'moving old keystore file to backup location', from: account.path, to: backup_path
begin
FileUtils.mv account.path, backup_path
rescue
logger.error "could not backup keystore, stopping account update", from: account.path, to: backup_path
raise $!
end
raise AssertError unless File.exist?(backup_path)
raise AssertError if File.exist?(new_account.path)
account.path = backup_path
@accounts.delete account
begin
add_account new_account, include_address, include_id
rescue
logger.error 'adding new account failed, recovering from backup'
FileUtils.mv backup_path, new_account.path
account.path = new_account.path
@accounts.push account
@accounts.sort_by! {|acct| acct.path.to_s }
raise $!
end
raise AssertError unless File.exist?(new_account.path)
logger.info "deleting backup of old keystore", path: backup_path
begin
FileUtils.rm backup_path
rescue
logger.error 'failed to delete no longer needed backup of old keystore', path: account.path
raise $!
end
account.keystore = new_account.keystore
account.path = new_account.path
@accounts.push account
@accounts.delete new_account
@accounts.sort_by! {|acct| acct.path.to_s }
logger.debug "account update successful"
end | [
"def",
"update_account",
"(",
"account",
",",
"new_password",
",",
"include_address",
"=",
"true",
",",
"include_id",
"=",
"true",
")",
"raise",
"ValueError",
",",
"\"Account not managed by account service\"",
"unless",
"@accounts",
".",
"include?",
"(",
"account",
")",
"raise",
"ValueError",
",",
"\"Cannot update locked account\"",
"if",
"account",
".",
"locked?",
"raise",
"ValueError",
",",
"'Account not stored on disk'",
"unless",
"account",
".",
"path",
"logger",
".",
"debug",
"\"creating new account\"",
"new_account",
"=",
"Account",
".",
"create",
"new_password",
",",
"account",
".",
"privkey",
",",
"account",
".",
"uuid",
",",
"account",
".",
"path",
"backup_path",
"=",
"account",
".",
"path",
"+",
"'~'",
"i",
"=",
"1",
"while",
"File",
".",
"exist?",
"(",
"backup_path",
")",
"backup_path",
"=",
"backup_path",
"[",
"0",
",",
"backup_path",
".",
"rindex",
"(",
"'~'",
")",
"+",
"1",
"]",
"+",
"i",
".",
"to_s",
"i",
"+=",
"1",
"end",
"raise",
"AssertError",
"if",
"File",
".",
"exist?",
"(",
"backup_path",
")",
"logger",
".",
"info",
"'moving old keystore file to backup location'",
",",
"from",
":",
"account",
".",
"path",
",",
"to",
":",
"backup_path",
"begin",
"FileUtils",
".",
"mv",
"account",
".",
"path",
",",
"backup_path",
"rescue",
"logger",
".",
"error",
"\"could not backup keystore, stopping account update\"",
",",
"from",
":",
"account",
".",
"path",
",",
"to",
":",
"backup_path",
"raise",
"$!",
"end",
"raise",
"AssertError",
"unless",
"File",
".",
"exist?",
"(",
"backup_path",
")",
"raise",
"AssertError",
"if",
"File",
".",
"exist?",
"(",
"new_account",
".",
"path",
")",
"account",
".",
"path",
"=",
"backup_path",
"@accounts",
".",
"delete",
"account",
"begin",
"add_account",
"new_account",
",",
"include_address",
",",
"include_id",
"rescue",
"logger",
".",
"error",
"'adding new account failed, recovering from backup'",
"FileUtils",
".",
"mv",
"backup_path",
",",
"new_account",
".",
"path",
"account",
".",
"path",
"=",
"new_account",
".",
"path",
"@accounts",
".",
"push",
"account",
"@accounts",
".",
"sort_by!",
"{",
"|",
"acct",
"|",
"acct",
".",
"path",
".",
"to_s",
"}",
"raise",
"$!",
"end",
"raise",
"AssertError",
"unless",
"File",
".",
"exist?",
"(",
"new_account",
".",
"path",
")",
"logger",
".",
"info",
"\"deleting backup of old keystore\"",
",",
"path",
":",
"backup_path",
"begin",
"FileUtils",
".",
"rm",
"backup_path",
"rescue",
"logger",
".",
"error",
"'failed to delete no longer needed backup of old keystore'",
",",
"path",
":",
"account",
".",
"path",
"raise",
"$!",
"end",
"account",
".",
"keystore",
"=",
"new_account",
".",
"keystore",
"account",
".",
"path",
"=",
"new_account",
".",
"path",
"@accounts",
".",
"push",
"account",
"@accounts",
".",
"delete",
"new_account",
"@accounts",
".",
"sort_by!",
"{",
"|",
"acct",
"|",
"acct",
".",
"path",
".",
"to_s",
"}",
"logger",
".",
"debug",
"\"account update successful\"",
"end"
] | Replace the password of an account.
The update is carried out in three steps:
1. the old keystore file is renamed
2. the new keystore file is created at the previous location of the old
keystore file
3. the old keystore file is removed
In this way, at least one of the keystore files exists on disk at any
time and can be recovered if the process is interrupted.
@param account [Account] which must be unlocked, stored on disk and
included in `@accounts`
@param include_address [Bool] forwarded to `add_account` during step 2
@param include_id [Bool] forwarded to `add_account` during step 2
@raise [ValueError] if the account is locked, if it is not added to the
account manager, or if it is not stored | [
"Replace",
"the",
"password",
"of",
"an",
"account",
"."
] | 06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec | https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/account_service.rb#L172-L228 | train |
cryptape/reth | lib/reth/account_service.rb | Reth.AccountService.find | def find(identifier)
identifier = identifier.downcase
if identifier =~ /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/ # uuid
return get_by_id(identifier)
end
begin
address = Address.new(identifier).to_bytes
raise AssertError unless address.size == 20
return self[address]
rescue
# do nothing
end
index = identifier.to_i
raise ValueError, 'Index must be 1 or greater' if index <= 0
raise KeyError if index > @accounts.size
@accounts[index-1]
end | ruby | def find(identifier)
identifier = identifier.downcase
if identifier =~ /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/ # uuid
return get_by_id(identifier)
end
begin
address = Address.new(identifier).to_bytes
raise AssertError unless address.size == 20
return self[address]
rescue
# do nothing
end
index = identifier.to_i
raise ValueError, 'Index must be 1 or greater' if index <= 0
raise KeyError if index > @accounts.size
@accounts[index-1]
end | [
"def",
"find",
"(",
"identifier",
")",
"identifier",
"=",
"identifier",
".",
"downcase",
"if",
"identifier",
"=~",
"/",
"\\A",
"\\z",
"/",
"return",
"get_by_id",
"(",
"identifier",
")",
"end",
"begin",
"address",
"=",
"Address",
".",
"new",
"(",
"identifier",
")",
".",
"to_bytes",
"raise",
"AssertError",
"unless",
"address",
".",
"size",
"==",
"20",
"return",
"self",
"[",
"address",
"]",
"rescue",
"end",
"index",
"=",
"identifier",
".",
"to_i",
"raise",
"ValueError",
",",
"'Index must be 1 or greater'",
"if",
"index",
"<=",
"0",
"raise",
"KeyError",
"if",
"index",
">",
"@accounts",
".",
"size",
"@accounts",
"[",
"index",
"-",
"1",
"]",
"end"
] | Find an account by either its address, its id, or its index as string.
Example identifiers:
- '9c0e0240776cfbe6fa1eb37e57721e1a88a563d1' (address)
- '0x9c0e0240776cfbe6fa1eb37e57721e1a88a563d1' (address with 0x prefix)
- '01dd527b-f4a5-4b3c-9abb-6a8e7cd6722f' (UUID)
- '3' (index)
@param identifier [String] the accounts hex encoded, case insensitive
address (with optional 0x prefix), its UUID or its index (as string,
>= 1)
@raise [ValueError] if the identifier could not be interpreted
@raise [KeyError] if the identified account is not known to the account
service | [
"Find",
"an",
"account",
"by",
"either",
"its",
"address",
"its",
"id",
"or",
"its",
"index",
"as",
"string",
"."
] | 06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec | https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/account_service.rb#L256-L275 | train |
cryptape/reth | lib/reth/account_service.rb | Reth.AccountService.get_by_id | def get_by_id(id)
accts = @accounts.select {|acct| acct.uuid == id }
if accts.size == 0
raise KeyError, "account with id #{id} unknown"
elsif accts.size > 1
logger.warn "multiple accounts with same UUID found", uuid: id
end
accts[0]
end | ruby | def get_by_id(id)
accts = @accounts.select {|acct| acct.uuid == id }
if accts.size == 0
raise KeyError, "account with id #{id} unknown"
elsif accts.size > 1
logger.warn "multiple accounts with same UUID found", uuid: id
end
accts[0]
end | [
"def",
"get_by_id",
"(",
"id",
")",
"accts",
"=",
"@accounts",
".",
"select",
"{",
"|",
"acct",
"|",
"acct",
".",
"uuid",
"==",
"id",
"}",
"if",
"accts",
".",
"size",
"==",
"0",
"raise",
"KeyError",
",",
"\"account with id #{id} unknown\"",
"elsif",
"accts",
".",
"size",
">",
"1",
"logger",
".",
"warn",
"\"multiple accounts with same UUID found\"",
",",
"uuid",
":",
"id",
"end",
"accts",
"[",
"0",
"]",
"end"
] | Return the account with a given id.
Note that accounts are not required to have an id.
@raise [KeyError] if no matching account can be found | [
"Return",
"the",
"account",
"with",
"a",
"given",
"id",
"."
] | 06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec | https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/account_service.rb#L284-L294 | train |
cryptape/reth | lib/reth/account_service.rb | Reth.AccountService.get_by_address | def get_by_address(address)
raise ArgumentError, 'address must be 20 bytes' unless address.size == 20
accts = @accounts.select {|acct| acct.address == address }
if accts.size == 0
raise KeyError, "account not found by address #{Utils.encode_hex(address)}"
elsif accts.size > 1
logger.warn "multiple accounts with same address found", address: Utils.encode_hex(address)
end
accts[0]
end | ruby | def get_by_address(address)
raise ArgumentError, 'address must be 20 bytes' unless address.size == 20
accts = @accounts.select {|acct| acct.address == address }
if accts.size == 0
raise KeyError, "account not found by address #{Utils.encode_hex(address)}"
elsif accts.size > 1
logger.warn "multiple accounts with same address found", address: Utils.encode_hex(address)
end
accts[0]
end | [
"def",
"get_by_address",
"(",
"address",
")",
"raise",
"ArgumentError",
",",
"'address must be 20 bytes'",
"unless",
"address",
".",
"size",
"==",
"20",
"accts",
"=",
"@accounts",
".",
"select",
"{",
"|",
"acct",
"|",
"acct",
".",
"address",
"==",
"address",
"}",
"if",
"accts",
".",
"size",
"==",
"0",
"raise",
"KeyError",
",",
"\"account not found by address #{Utils.encode_hex(address)}\"",
"elsif",
"accts",
".",
"size",
">",
"1",
"logger",
".",
"warn",
"\"multiple accounts with same address found\"",
",",
"address",
":",
"Utils",
".",
"encode_hex",
"(",
"address",
")",
"end",
"accts",
"[",
"0",
"]",
"end"
] | Get an account by its address.
Note that even if an account with the given address exists, it might
not be found if it is locked. Also, multiple accounts with the same
address may exist, in which case the first one is returned (and a
warning is logged).
@raise [KeyError] if no matching account can be found | [
"Get",
"an",
"account",
"by",
"its",
"address",
"."
] | 06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec | https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/account_service.rb#L306-L318 | train |
richard-viney/ig_markets | lib/ig_markets/model.rb | IGMarkets.Model.to_h | def to_h
attributes.each_with_object({}) do |(key, value), hash|
hash[key] = if value.is_a? Model
value.to_h
else
value
end
end
end | ruby | def to_h
attributes.each_with_object({}) do |(key, value), hash|
hash[key] = if value.is_a? Model
value.to_h
else
value
end
end
end | [
"def",
"to_h",
"attributes",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"key",
",",
"value",
")",
",",
"hash",
"|",
"hash",
"[",
"key",
"]",
"=",
"if",
"value",
".",
"is_a?",
"Model",
"value",
".",
"to_h",
"else",
"value",
"end",
"end",
"end"
] | Compares this model to another, the attributes and class must match for them to be considered equal.
@param [Model] other The other model to compare to.
@return [Boolean]
Converts this model into a nested hash of attributes. This is simlar to just calling {#attributes}, but in this
case any attributes that are instances of {Model} will also be transformed into a hash in the return value.
@return [Hash] | [
"Compares",
"this",
"model",
"to",
"another",
"the",
"attributes",
"and",
"class",
"must",
"match",
"for",
"them",
"to",
"be",
"considered",
"equal",
"."
] | c1989ec557b0ba643a76024c5bec624abd8c1c4c | https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/model.rb#L49-L57 | train |
richard-viney/ig_markets | lib/ig_markets/dealing_platform.rb | IGMarkets.DealingPlatform.sign_in | def sign_in(username, password, api_key, platform)
session.username = username
session.password = password
session.api_key = api_key
session.platform = platform
result = session.sign_in
@client_account_summary = instantiate_models ClientAccountSummary, result
end | ruby | def sign_in(username, password, api_key, platform)
session.username = username
session.password = password
session.api_key = api_key
session.platform = platform
result = session.sign_in
@client_account_summary = instantiate_models ClientAccountSummary, result
end | [
"def",
"sign_in",
"(",
"username",
",",
"password",
",",
"api_key",
",",
"platform",
")",
"session",
".",
"username",
"=",
"username",
"session",
".",
"password",
"=",
"password",
"session",
".",
"api_key",
"=",
"api_key",
"session",
".",
"platform",
"=",
"platform",
"result",
"=",
"session",
".",
"sign_in",
"@client_account_summary",
"=",
"instantiate_models",
"ClientAccountSummary",
",",
"result",
"end"
] | Signs in to the IG Markets Dealing Platform, either the live platform or the demo platform.
@param [String] username The IG Markets username.
@param [String] password The IG Markets password.
@param [String] api_key The IG Markets API key.
@param [:live, :demo] platform The platform to use.
@return [ClientAccountSummary] The client account summary returned by the sign in request. This result can also
be accessed later using {#client_account_summary}. | [
"Signs",
"in",
"to",
"the",
"IG",
"Markets",
"Dealing",
"Platform",
"either",
"the",
"live",
"platform",
"or",
"the",
"demo",
"platform",
"."
] | c1989ec557b0ba643a76024c5bec624abd8c1c4c | https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/dealing_platform.rb#L90-L99 | train |
richard-viney/ig_markets | lib/ig_markets/format.rb | IGMarkets.Format.colored_currency | def colored_currency(amount, currency_name)
return '' unless amount
color = amount < 0 ? :red : :green
ColorizedString[currency(amount, currency_name)].colorize color
end | ruby | def colored_currency(amount, currency_name)
return '' unless amount
color = amount < 0 ? :red : :green
ColorizedString[currency(amount, currency_name)].colorize color
end | [
"def",
"colored_currency",
"(",
"amount",
",",
"currency_name",
")",
"return",
"''",
"unless",
"amount",
"color",
"=",
"amount",
"<",
"0",
"?",
":red",
":",
":green",
"ColorizedString",
"[",
"currency",
"(",
"amount",
",",
"currency_name",
")",
"]",
".",
"colorize",
"color",
"end"
] | Returns a formatted string for the specified currency amount and currency, and colors it red for negative values
and green for positive values. Two decimal places are used for all currencies except the Japanese Yen.
@param [Float, Integer] amount The currency amount to format.
@param [String] currency_name The currency.
@return [String] The formatted and colored currency amount, e.g. `"USD -130.40"`, `"AUD 539.10"`, `"JPY 3560"`. | [
"Returns",
"a",
"formatted",
"string",
"for",
"the",
"specified",
"currency",
"amount",
"and",
"currency",
"and",
"colors",
"it",
"red",
"for",
"negative",
"values",
"and",
"green",
"for",
"positive",
"values",
".",
"Two",
"decimal",
"places",
"are",
"used",
"for",
"all",
"currencies",
"except",
"the",
"Japanese",
"Yen",
"."
] | c1989ec557b0ba643a76024c5bec624abd8c1c4c | https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/format.rb#L43-L49 | train |
richard-viney/ig_markets | lib/ig_markets/request_body_formatter.rb | IGMarkets.RequestBodyFormatter.snake_case_to_camel_case | def snake_case_to_camel_case(value)
pieces = value.to_s.split '_'
(pieces.first + pieces[1..-1].map(&:capitalize).join).to_sym
end | ruby | def snake_case_to_camel_case(value)
pieces = value.to_s.split '_'
(pieces.first + pieces[1..-1].map(&:capitalize).join).to_sym
end | [
"def",
"snake_case_to_camel_case",
"(",
"value",
")",
"pieces",
"=",
"value",
".",
"to_s",
".",
"split",
"'_'",
"(",
"pieces",
".",
"first",
"+",
"pieces",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"map",
"(",
"&",
":capitalize",
")",
".",
"join",
")",
".",
"to_sym",
"end"
] | Takes a string or symbol that uses snake case and converts it to a camel case symbol.
@param [String, Symbol] value The string or symbol to convert to camel case.
@return [Symbol] | [
"Takes",
"a",
"string",
"or",
"symbol",
"that",
"uses",
"snake",
"case",
"and",
"converts",
"it",
"to",
"a",
"camel",
"case",
"symbol",
"."
] | c1989ec557b0ba643a76024c5bec624abd8c1c4c | https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/request_body_formatter.rb#L48-L52 | train |
cryptape/reth | lib/reth/account.rb | Reth.Account.dump | def dump(include_address=true, include_id=true)
h = {}
h[:crypto] = @keystore[:crypto]
h[:version] = @keystore[:version]
h[:address] = Utils.encode_hex address if include_address && address
h[:id] = uuid if include_id && uuid
JSON.dump(h)
end | ruby | def dump(include_address=true, include_id=true)
h = {}
h[:crypto] = @keystore[:crypto]
h[:version] = @keystore[:version]
h[:address] = Utils.encode_hex address if include_address && address
h[:id] = uuid if include_id && uuid
JSON.dump(h)
end | [
"def",
"dump",
"(",
"include_address",
"=",
"true",
",",
"include_id",
"=",
"true",
")",
"h",
"=",
"{",
"}",
"h",
"[",
":crypto",
"]",
"=",
"@keystore",
"[",
":crypto",
"]",
"h",
"[",
":version",
"]",
"=",
"@keystore",
"[",
":version",
"]",
"h",
"[",
":address",
"]",
"=",
"Utils",
".",
"encode_hex",
"address",
"if",
"include_address",
"&&",
"address",
"h",
"[",
":id",
"]",
"=",
"uuid",
"if",
"include_id",
"&&",
"uuid",
"JSON",
".",
"dump",
"(",
"h",
")",
"end"
] | Dump the keystore for later disk storage.
The result inherits the entries `crypto` and `version` from `Keystore`,
and adds `address` and `id` in accordance with the parameters
`include_address` and `include_id`.
If address or id are not known, they are not added, even if requested.
@param include_address [Bool] flag denoting if the address should be
included or not
@param include_id [Bool] flag denoting if the id should be included or
not | [
"Dump",
"the",
"keystore",
"for",
"later",
"disk",
"storage",
"."
] | 06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec | https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/account.rb#L83-L92 | train |
cryptape/reth | lib/reth/account.rb | Reth.Account.sign_tx | def sign_tx(tx)
if privkey
logger.info "signing tx", tx: tx, account: self
tx.sign privkey
else
raise ValueError, "Locked account cannot sign tx"
end
end | ruby | def sign_tx(tx)
if privkey
logger.info "signing tx", tx: tx, account: self
tx.sign privkey
else
raise ValueError, "Locked account cannot sign tx"
end
end | [
"def",
"sign_tx",
"(",
"tx",
")",
"if",
"privkey",
"logger",
".",
"info",
"\"signing tx\"",
",",
"tx",
":",
"tx",
",",
"account",
":",
"self",
"tx",
".",
"sign",
"privkey",
"else",
"raise",
"ValueError",
",",
"\"Locked account cannot sign tx\"",
"end",
"end"
] | Sign a Transaction with the private key of this account.
If the account is unlocked, this is equivalent to
`tx.sign(account.privkey)`.
@param tx [Transaction] the transaction to sign
@raise [ValueError] if the account is locked | [
"Sign",
"a",
"Transaction",
"with",
"the",
"private",
"key",
"of",
"this",
"account",
"."
] | 06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec | https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/account.rb#L169-L176 | train |
projecttacoma/simplexml_parser | lib/model/document.rb | SimpleXml.Document.detect_unstratified | def detect_unstratified
missing_populations = []
# populations are keyed off of values rather than the codes
existing_populations = @populations.map{|p| p.values.join('-')}.uniq
@populations.each do |population|
keys = population.keys - ['STRAT','stratification']
missing_populations |= [population.values_at(*keys).compact.join('-')]
end
missing_populations -= existing_populations
# reverse the order and prepend them to @populations
missing_populations.reverse.each do |population|
p = {}
population.split('-').each do |code|
p[code.split('_').first] = code
end
@populations.unshift p
end
end | ruby | def detect_unstratified
missing_populations = []
# populations are keyed off of values rather than the codes
existing_populations = @populations.map{|p| p.values.join('-')}.uniq
@populations.each do |population|
keys = population.keys - ['STRAT','stratification']
missing_populations |= [population.values_at(*keys).compact.join('-')]
end
missing_populations -= existing_populations
# reverse the order and prepend them to @populations
missing_populations.reverse.each do |population|
p = {}
population.split('-').each do |code|
p[code.split('_').first] = code
end
@populations.unshift p
end
end | [
"def",
"detect_unstratified",
"missing_populations",
"=",
"[",
"]",
"existing_populations",
"=",
"@populations",
".",
"map",
"{",
"|",
"p",
"|",
"p",
".",
"values",
".",
"join",
"(",
"'-'",
")",
"}",
".",
"uniq",
"@populations",
".",
"each",
"do",
"|",
"population",
"|",
"keys",
"=",
"population",
".",
"keys",
"-",
"[",
"'STRAT'",
",",
"'stratification'",
"]",
"missing_populations",
"|=",
"[",
"population",
".",
"values_at",
"(",
"*",
"keys",
")",
".",
"compact",
".",
"join",
"(",
"'-'",
")",
"]",
"end",
"missing_populations",
"-=",
"existing_populations",
"missing_populations",
".",
"reverse",
".",
"each",
"do",
"|",
"population",
"|",
"p",
"=",
"{",
"}",
"population",
".",
"split",
"(",
"'-'",
")",
".",
"each",
"do",
"|",
"code",
"|",
"p",
"[",
"code",
".",
"split",
"(",
"'_'",
")",
".",
"first",
"]",
"=",
"code",
"end",
"@populations",
".",
"unshift",
"p",
"end",
"end"
] | Detects missing unstratified populations from the generated @populations array | [
"Detects",
"missing",
"unstratified",
"populations",
"from",
"the",
"generated"
] | 9f83211e2407f0d933afbd1648c57f500b7527af | https://github.com/projecttacoma/simplexml_parser/blob/9f83211e2407f0d933afbd1648c57f500b7527af/lib/model/document.rb#L316-L335 | train |
livingsocial/ganapati | lib/ganapati/client.rb | Ganapati.Client.put | def put(localpath, destpath)
create(destpath) { |dest|
Kernel.open(localpath) { |source|
# read 1 MB at a time
while record = source.read(1048576)
dest.write(record)
end
}
}
end | ruby | def put(localpath, destpath)
create(destpath) { |dest|
Kernel.open(localpath) { |source|
# read 1 MB at a time
while record = source.read(1048576)
dest.write(record)
end
}
}
end | [
"def",
"put",
"(",
"localpath",
",",
"destpath",
")",
"create",
"(",
"destpath",
")",
"{",
"|",
"dest",
"|",
"Kernel",
".",
"open",
"(",
"localpath",
")",
"{",
"|",
"source",
"|",
"while",
"record",
"=",
"source",
".",
"read",
"(",
"1048576",
")",
"dest",
".",
"write",
"(",
"record",
")",
"end",
"}",
"}",
"end"
] | copy local file to remote | [
"copy",
"local",
"file",
"to",
"remote"
] | c583dfbbe12b417323e54aab3aa1ed80dc38f649 | https://github.com/livingsocial/ganapati/blob/c583dfbbe12b417323e54aab3aa1ed80dc38f649/lib/ganapati/client.rb#L24-L33 | train |
livingsocial/ganapati | lib/ganapati/client.rb | Ganapati.Client.get | def get(remotepath, destpath)
Kernel.open(destpath, 'w') { |dest|
readchunks(remotepath) { |chunk|
dest.write chunk
}
}
end | ruby | def get(remotepath, destpath)
Kernel.open(destpath, 'w') { |dest|
readchunks(remotepath) { |chunk|
dest.write chunk
}
}
end | [
"def",
"get",
"(",
"remotepath",
",",
"destpath",
")",
"Kernel",
".",
"open",
"(",
"destpath",
",",
"'w'",
")",
"{",
"|",
"dest",
"|",
"readchunks",
"(",
"remotepath",
")",
"{",
"|",
"chunk",
"|",
"dest",
".",
"write",
"chunk",
"}",
"}",
"end"
] | copy remote file to local | [
"copy",
"remote",
"file",
"to",
"local"
] | c583dfbbe12b417323e54aab3aa1ed80dc38f649 | https://github.com/livingsocial/ganapati/blob/c583dfbbe12b417323e54aab3aa1ed80dc38f649/lib/ganapati/client.rb#L36-L42 | train |
livingsocial/ganapati | lib/ganapati/client.rb | Ganapati.Client.readchunks | def readchunks(path, chunksize=1048576)
open(path) { |source|
size = source.length
index = 0
while index < size
yield source.read(index, chunksize)
index += chunksize
end
}
end | ruby | def readchunks(path, chunksize=1048576)
open(path) { |source|
size = source.length
index = 0
while index < size
yield source.read(index, chunksize)
index += chunksize
end
}
end | [
"def",
"readchunks",
"(",
"path",
",",
"chunksize",
"=",
"1048576",
")",
"open",
"(",
"path",
")",
"{",
"|",
"source",
"|",
"size",
"=",
"source",
".",
"length",
"index",
"=",
"0",
"while",
"index",
"<",
"size",
"yield",
"source",
".",
"read",
"(",
"index",
",",
"chunksize",
")",
"index",
"+=",
"chunksize",
"end",
"}",
"end"
] | yeild chunksize of path one chunk at a time | [
"yeild",
"chunksize",
"of",
"path",
"one",
"chunk",
"at",
"a",
"time"
] | c583dfbbe12b417323e54aab3aa1ed80dc38f649 | https://github.com/livingsocial/ganapati/blob/c583dfbbe12b417323e54aab3aa1ed80dc38f649/lib/ganapati/client.rb#L45-L54 | train |
hck/open_nlp | lib/open_nlp/tokenizer.rb | OpenNlp.Tokenizer.tokenize | def tokenize(str)
raise ArgumentError, 'str must be a String' unless str.is_a?(String)
j_instance.tokenize(str).to_ary
end | ruby | def tokenize(str)
raise ArgumentError, 'str must be a String' unless str.is_a?(String)
j_instance.tokenize(str).to_ary
end | [
"def",
"tokenize",
"(",
"str",
")",
"raise",
"ArgumentError",
",",
"'str must be a String'",
"unless",
"str",
".",
"is_a?",
"(",
"String",
")",
"j_instance",
".",
"tokenize",
"(",
"str",
")",
".",
"to_ary",
"end"
] | Tokenizes a string
@param [String] str string to tokenize
@return [Array] array of string tokens | [
"Tokenizes",
"a",
"string"
] | 1c006a37747d797a41aa72ef6068fae770464862 | https://github.com/hck/open_nlp/blob/1c006a37747d797a41aa72ef6068fae770464862/lib/open_nlp/tokenizer.rb#L9-L13 | train |
hck/open_nlp | lib/open_nlp/pos_tagger.rb | OpenNlp.POSTagger.tag | def tag(tokens)
!tokens.is_a?(Array) && !tokens.is_a?(String) &&
raise(ArgumentError, 'tokens must be an instance of String or Array')
j_instance.tag(tokens.to_java(:String))
end | ruby | def tag(tokens)
!tokens.is_a?(Array) && !tokens.is_a?(String) &&
raise(ArgumentError, 'tokens must be an instance of String or Array')
j_instance.tag(tokens.to_java(:String))
end | [
"def",
"tag",
"(",
"tokens",
")",
"!",
"tokens",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"!",
"tokens",
".",
"is_a?",
"(",
"String",
")",
"&&",
"raise",
"(",
"ArgumentError",
",",
"'tokens must be an instance of String or Array'",
")",
"j_instance",
".",
"tag",
"(",
"tokens",
".",
"to_java",
"(",
":String",
")",
")",
"end"
] | Adds tags to tokens passed as argument
@param [Array<String>, String] tokens tokens to tag
@return [Array<String>, String] array of part-of-speech tags or string with added part-of-speech tags | [
"Adds",
"tags",
"to",
"tokens",
"passed",
"as",
"argument"
] | 1c006a37747d797a41aa72ef6068fae770464862 | https://github.com/hck/open_nlp/blob/1c006a37747d797a41aa72ef6068fae770464862/lib/open_nlp/pos_tagger.rb#L9-L14 | train |
richard-viney/ig_markets | lib/ig_markets/account.rb | IGMarkets.Account.reload | def reload
self.attributes = @dealing_platform.account.all.detect { |a| a.account_id == account_id }.attributes
end | ruby | def reload
self.attributes = @dealing_platform.account.all.detect { |a| a.account_id == account_id }.attributes
end | [
"def",
"reload",
"self",
".",
"attributes",
"=",
"@dealing_platform",
".",
"account",
".",
"all",
".",
"detect",
"{",
"|",
"a",
"|",
"a",
".",
"account_id",
"==",
"account_id",
"}",
".",
"attributes",
"end"
] | Reloads this account's attributes by re-querying the IG Markets API. | [
"Reloads",
"this",
"account",
"s",
"attributes",
"by",
"re",
"-",
"querying",
"the",
"IG",
"Markets",
"API",
"."
] | c1989ec557b0ba643a76024c5bec624abd8c1c4c | https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/account.rb#L24-L26 | train |
contentstack/contentstack-ruby | lib/contentstack/query.rb | Contentstack.Query.only | def only(fields, fields_with_base=nil)
q = {}
if [Array, String].include?(fields_with_base.class)
fields_with_base = [fields_with_base] if fields_with_base.class == String
q[fields.to_sym] = fields_with_base
else
fields = [fields] if fields.class == String
q = {BASE: fields}
end
@query[:only] = q
self
end | ruby | def only(fields, fields_with_base=nil)
q = {}
if [Array, String].include?(fields_with_base.class)
fields_with_base = [fields_with_base] if fields_with_base.class == String
q[fields.to_sym] = fields_with_base
else
fields = [fields] if fields.class == String
q = {BASE: fields}
end
@query[:only] = q
self
end | [
"def",
"only",
"(",
"fields",
",",
"fields_with_base",
"=",
"nil",
")",
"q",
"=",
"{",
"}",
"if",
"[",
"Array",
",",
"String",
"]",
".",
"include?",
"(",
"fields_with_base",
".",
"class",
")",
"fields_with_base",
"=",
"[",
"fields_with_base",
"]",
"if",
"fields_with_base",
".",
"class",
"==",
"String",
"q",
"[",
"fields",
".",
"to_sym",
"]",
"=",
"fields_with_base",
"else",
"fields",
"=",
"[",
"fields",
"]",
"if",
"fields",
".",
"class",
"==",
"String",
"q",
"=",
"{",
"BASE",
":",
"fields",
"}",
"end",
"@query",
"[",
":only",
"]",
"=",
"q",
"self",
"end"
] | Specifies an array of 'only' keys in BASE object that would be 'included' in the response.
@param [Array] fields Array of the 'only' reference keys to be included in response.
@param [Array] fields_with_base Can be used to denote 'only' fields of the reference class
Example
# Include only title and description field in response
@query = @stack.content_type('category').query
@query.only(['title', 'description'])
# Query product and include only the title and description from category reference
@query = @stack.content_type('product').query
@query.include_reference('category')
.only('category', ['title', 'description'])
@return [Contentstack::Query] | [
"Specifies",
"an",
"array",
"of",
"only",
"keys",
"in",
"BASE",
"object",
"that",
"would",
"be",
"included",
"in",
"the",
"response",
"."
] | 6aa499d6620c2741078d5a39c20dd4890004d8f2 | https://github.com/contentstack/contentstack-ruby/blob/6aa499d6620c2741078d5a39c20dd4890004d8f2/lib/contentstack/query.rb#L403-L415 | train |
richard-viney/ig_markets | lib/ig_markets/working_order.rb | IGMarkets.WorkingOrder.update | def update(new_attributes)
existing_attributes = { good_till_date: good_till_date, level: order_level, limit_distance: limit_distance,
stop_distance: stop_distance, time_in_force: time_in_force, type: order_type }
model = WorkingOrderUpdateAttributes.new existing_attributes, new_attributes
model.validate
body = RequestBodyFormatter.format model
@dealing_platform.session.put("workingorders/otc/#{deal_id}", body, API_V2).fetch(:deal_reference)
end | ruby | def update(new_attributes)
existing_attributes = { good_till_date: good_till_date, level: order_level, limit_distance: limit_distance,
stop_distance: stop_distance, time_in_force: time_in_force, type: order_type }
model = WorkingOrderUpdateAttributes.new existing_attributes, new_attributes
model.validate
body = RequestBodyFormatter.format model
@dealing_platform.session.put("workingorders/otc/#{deal_id}", body, API_V2).fetch(:deal_reference)
end | [
"def",
"update",
"(",
"new_attributes",
")",
"existing_attributes",
"=",
"{",
"good_till_date",
":",
"good_till_date",
",",
"level",
":",
"order_level",
",",
"limit_distance",
":",
"limit_distance",
",",
"stop_distance",
":",
"stop_distance",
",",
"time_in_force",
":",
"time_in_force",
",",
"type",
":",
"order_type",
"}",
"model",
"=",
"WorkingOrderUpdateAttributes",
".",
"new",
"existing_attributes",
",",
"new_attributes",
"model",
".",
"validate",
"body",
"=",
"RequestBodyFormatter",
".",
"format",
"model",
"@dealing_platform",
".",
"session",
".",
"put",
"(",
"\"workingorders/otc/#{deal_id}\"",
",",
"body",
",",
"API_V2",
")",
".",
"fetch",
"(",
":deal_reference",
")",
"end"
] | Updates this working order. No attributes are mandatory, and any attributes not specified will be kept at their
current values.
@param [Hash] new_attributes The attributes of this working order to update. See
{DealingPlatform::WorkingOrderMethods#create} for a description of the attributes.
@option new_attributes [Time] :good_till_date
@option new_attributes [Float] :level
@option new_attributes [Integer] :limit_distance
@option new_attributes [Float] :limit_level
@option new_attributes [Integer] :stop_distance
@option new_attributes [Float] :stop_level
@option new_attributes [:limit, :stop] :type
@return [String] The deal reference of the update operation. Use {DealingPlatform#deal_confirmation} to check
the result of the working order update. | [
"Updates",
"this",
"working",
"order",
".",
"No",
"attributes",
"are",
"mandatory",
"and",
"any",
"attributes",
"not",
"specified",
"will",
"be",
"kept",
"at",
"their",
"current",
"values",
"."
] | c1989ec557b0ba643a76024c5bec624abd8c1c4c | https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/working_order.rb#L53-L63 | train |
railslove/smurfville | lib/smurfville/color_variable_parser.rb | Smurfville.ColorVariableParser.add_color | def add_color(node, key = nil)
key ||= node.expr.to_s
self.colors[key] ||= { :variables => [], :alternate_values => [] }
self.colors[key][:variables] << node.name
self.colors[key][:alternate_values] |= ([node.expr.to_sass, node.expr.inspect] - [key])
end | ruby | def add_color(node, key = nil)
key ||= node.expr.to_s
self.colors[key] ||= { :variables => [], :alternate_values => [] }
self.colors[key][:variables] << node.name
self.colors[key][:alternate_values] |= ([node.expr.to_sass, node.expr.inspect] - [key])
end | [
"def",
"add_color",
"(",
"node",
",",
"key",
"=",
"nil",
")",
"key",
"||=",
"node",
".",
"expr",
".",
"to_s",
"self",
".",
"colors",
"[",
"key",
"]",
"||=",
"{",
":variables",
"=>",
"[",
"]",
",",
":alternate_values",
"=>",
"[",
"]",
"}",
"self",
".",
"colors",
"[",
"key",
"]",
"[",
":variables",
"]",
"<<",
"node",
".",
"name",
"self",
".",
"colors",
"[",
"key",
"]",
"[",
":alternate_values",
"]",
"|=",
"(",
"[",
"node",
".",
"expr",
".",
"to_sass",
",",
"node",
".",
"expr",
".",
"inspect",
"]",
"-",
"[",
"key",
"]",
")",
"end"
] | add found color to @colors | [
"add",
"found",
"color",
"to"
] | 0e6a84500cc3d748e25dd398acaf6d94878b3f84 | https://github.com/railslove/smurfville/blob/0e6a84500cc3d748e25dd398acaf6d94878b3f84/lib/smurfville/color_variable_parser.rb#L49-L56 | train |
hassox/rack-rescue | lib/rack/rescue.rb | Rack.Rescue.apply_layout | def apply_layout(env, content, opts)
if layout = env['layout']
layout.format = opts[:format]
layout.content = content
layout.template_name = opts[:layout] if layout.template_name?(opts[:layout], opts)
layout
else
content
end
end | ruby | def apply_layout(env, content, opts)
if layout = env['layout']
layout.format = opts[:format]
layout.content = content
layout.template_name = opts[:layout] if layout.template_name?(opts[:layout], opts)
layout
else
content
end
end | [
"def",
"apply_layout",
"(",
"env",
",",
"content",
",",
"opts",
")",
"if",
"layout",
"=",
"env",
"[",
"'layout'",
"]",
"layout",
".",
"format",
"=",
"opts",
"[",
":format",
"]",
"layout",
".",
"content",
"=",
"content",
"layout",
".",
"template_name",
"=",
"opts",
"[",
":layout",
"]",
"if",
"layout",
".",
"template_name?",
"(",
"opts",
"[",
":layout",
"]",
",",
"opts",
")",
"layout",
"else",
"content",
"end",
"end"
] | Apply the layout if it exists
@api private | [
"Apply",
"the",
"layout",
"if",
"it",
"exists"
] | 3826e28d9704d734659ac16374ee8b740bd42e48 | https://github.com/hassox/rack-rescue/blob/3826e28d9704d734659ac16374ee8b740bd42e48/lib/rack/rescue.rb#L58-L67 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.