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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
avinashbot/redd | lib/redd/middleware.rb | Redd.Middleware.create_session! | def create_session!
# Skip authorizing if there was an error from the authorization.
handle_token_error
# Try to get a code (the rescue block will also prevent crazy crashes)
access = @strategy.authenticate(@request.GET['code'])
@request.session[:redd_session] = access.to_h
rescue Erro... | ruby | def create_session!
# Skip authorizing if there was an error from the authorization.
handle_token_error
# Try to get a code (the rescue block will also prevent crazy crashes)
access = @strategy.authenticate(@request.GET['code'])
@request.session[:redd_session] = access.to_h
rescue Erro... | [
"def",
"create_session!",
"handle_token_error",
"access",
"=",
"@strategy",
".",
"authenticate",
"(",
"@request",
".",
"GET",
"[",
"'code'",
"]",
")",
"@request",
".",
"session",
"[",
":redd_session",
"]",
"=",
"access",
".",
"to_h",
"rescue",
"Errors",
"::",
... | Store the access token and other details in the user's browser, assigning any errors to
the 'redd.error' env variable. | [
"Store",
"the",
"access",
"token",
"and",
"other",
"details",
"in",
"the",
"user",
"s",
"browser",
"assigning",
"any",
"errors",
"to",
"the",
"redd",
".",
"error",
"env",
"variable",
"."
] | 3b1519a2d121efd18de59b935da6e652757eee90 | https://github.com/avinashbot/redd/blob/3b1519a2d121efd18de59b935da6e652757eee90/lib/redd/middleware.rb#L103-L111 | train |
avinashbot/redd | lib/redd/api_client.rb | Redd.APIClient.request | def request(verb, path, raw: false, params: {}, **options)
# Make sure @access is populated by a valid access
ensure_access_is_valid
# Setup base API params and make request
api_params = { api_type: 'json', raw_json: 1 }.merge(params)
# This loop is retried @max_retries number of times un... | ruby | def request(verb, path, raw: false, params: {}, **options)
# Make sure @access is populated by a valid access
ensure_access_is_valid
# Setup base API params and make request
api_params = { api_type: 'json', raw_json: 1 }.merge(params)
# This loop is retried @max_retries number of times un... | [
"def",
"request",
"(",
"verb",
",",
"path",
",",
"raw",
":",
"false",
",",
"params",
":",
"{",
"}",
",",
"**",
"options",
")",
"ensure_access_is_valid",
"api_params",
"=",
"{",
"api_type",
":",
"'json'",
",",
"raw_json",
":",
"1",
"}",
".",
"merge",
... | Makes a request, ensuring not to break the rate limit by sleeping.
@see Client#request | [
"Makes",
"a",
"request",
"ensuring",
"not",
"to",
"break",
"the",
"rate",
"limit",
"by",
"sleeping",
"."
] | 3b1519a2d121efd18de59b935da6e652757eee90 | https://github.com/avinashbot/redd/blob/3b1519a2d121efd18de59b935da6e652757eee90/lib/redd/api_client.rb#L65-L80 | train |
ansible/ansible_tower_client_ruby | lib/ansible_tower_client/hash_model.rb | AnsibleTowerClient.HashModel.hash_to_model | def hash_to_model(klass_name, hash)
model_klass =
if self.class.const_defined?("#{self.class}::#{klass_name}")
self.class.const_get(klass_name)
else
self.class.const_set(klass_name, Class.new(HashModel))
end
model_klass.new(hash)
end | ruby | def hash_to_model(klass_name, hash)
model_klass =
if self.class.const_defined?("#{self.class}::#{klass_name}")
self.class.const_get(klass_name)
else
self.class.const_set(klass_name, Class.new(HashModel))
end
model_klass.new(hash)
end | [
"def",
"hash_to_model",
"(",
"klass_name",
",",
"hash",
")",
"model_klass",
"=",
"if",
"self",
".",
"class",
".",
"const_defined?",
"(",
"\"#{self.class}::#{klass_name}\"",
")",
"self",
".",
"class",
".",
"const_get",
"(",
"klass_name",
")",
"else",
"self",
".... | Convert a hash to an instance of nested model class
This is the default implementation; the resulting object is based on HashModel
To be overridden by subclasses | [
"Convert",
"a",
"hash",
"to",
"an",
"instance",
"of",
"nested",
"model",
"class"
] | 39454d74b9d4ea4771b16d4c41cbbbd83ad05df5 | https://github.com/ansible/ansible_tower_client_ruby/blob/39454d74b9d4ea4771b16d4c41cbbbd83ad05df5/lib/ansible_tower_client/hash_model.rb#L133-L141 | train |
roma/roma | lib/roma/tools/mkconfig.rb | Roma.Mkconfig.save_data | def save_data(res)
if res.key?("storage")
case res["storage"].value
when "Ruby Hash"
req = "rh_storage"
storage = "RubyHashStorage"
when "Tokyo Cabinet"
req = "tc_storage"
storage = "TCStorage"
bnum = Calculate.get_bnum(res)
bnum ... | ruby | def save_data(res)
if res.key?("storage")
case res["storage"].value
when "Ruby Hash"
req = "rh_storage"
storage = "RubyHashStorage"
when "Tokyo Cabinet"
req = "tc_storage"
storage = "TCStorage"
bnum = Calculate.get_bnum(res)
bnum ... | [
"def",
"save_data",
"(",
"res",
")",
"if",
"res",
".",
"key?",
"(",
"\"storage\"",
")",
"case",
"res",
"[",
"\"storage\"",
"]",
".",
"value",
"when",
"\"Ruby Hash\"",
"req",
"=",
"\"rh_storage\"",
"storage",
"=",
"\"RubyHashStorage\"",
"when",
"\"Tokyo Cabinet... | make config.rb based on input data | [
"make",
"config",
".",
"rb",
"based",
"on",
"input",
"data"
] | 3dea10df0171742c314ff48f2ed4eebaafc80abf | https://github.com/roma/roma/blob/3dea10df0171742c314ff48f2ed4eebaafc80abf/lib/roma/tools/mkconfig.rb#L511-L574 | train |
ansible/ansible_tower_client_ruby | lib/ansible_tower_client/base_model.rb | AnsibleTowerClient.BaseModel.update_attributes! | def update_attributes!(attributes)
@api.patch(url, attributes.to_json)
attributes.each do |method_name, value|
invoke_name = "#{override_raw_attributes[method_name] || method_name}="
if respond_to?(invoke_name)
send(invoke_name, value)
else
AnsibleTowerClient.logg... | ruby | def update_attributes!(attributes)
@api.patch(url, attributes.to_json)
attributes.each do |method_name, value|
invoke_name = "#{override_raw_attributes[method_name] || method_name}="
if respond_to?(invoke_name)
send(invoke_name, value)
else
AnsibleTowerClient.logg... | [
"def",
"update_attributes!",
"(",
"attributes",
")",
"@api",
".",
"patch",
"(",
"url",
",",
"attributes",
".",
"to_json",
")",
"attributes",
".",
"each",
"do",
"|",
"method_name",
",",
"value",
"|",
"invoke_name",
"=",
"\"#{override_raw_attributes[method_name] || ... | Persist changes passed in as a Hash and return a
representation of that object to the caller.
Example:
project = connection.api.projects.find 2
project.update_attributes!(:name => 'test')
# The values passed to update_attributes! are available in calling object
project.name # => 'test'
E... | [
"Persist",
"changes",
"passed",
"in",
"as",
"a",
"Hash",
"and",
"return",
"a",
"representation",
"of",
"that",
"object",
"to",
"the",
"caller",
"."
] | 39454d74b9d4ea4771b16d4c41cbbbd83ad05df5 | https://github.com/ansible/ansible_tower_client_ruby/blob/39454d74b9d4ea4771b16d4c41cbbbd83ad05df5/lib/ansible_tower_client/base_model.rb#L82-L93 | train |
ansible/ansible_tower_client_ruby | lib/ansible_tower_client/base_model.rb | AnsibleTowerClient.BaseModel.hash_to_model | def hash_to_model(klass_name, hash)
model_klass =
if self.class.const_defined?(klass_name, false)
self.class.const_get(klass_name)
else
self.class.const_set(klass_name, Class.new(BaseModel))
end
model_klass.new(api, hash)
end | ruby | def hash_to_model(klass_name, hash)
model_klass =
if self.class.const_defined?(klass_name, false)
self.class.const_get(klass_name)
else
self.class.const_set(klass_name, Class.new(BaseModel))
end
model_klass.new(api, hash)
end | [
"def",
"hash_to_model",
"(",
"klass_name",
",",
"hash",
")",
"model_klass",
"=",
"if",
"self",
".",
"class",
".",
"const_defined?",
"(",
"klass_name",
",",
"false",
")",
"self",
".",
"class",
".",
"const_get",
"(",
"klass_name",
")",
"else",
"self",
".",
... | convert a hash to an instance of nested model class | [
"convert",
"a",
"hash",
"to",
"an",
"instance",
"of",
"nested",
"model",
"class"
] | 39454d74b9d4ea4771b16d4c41cbbbd83ad05df5 | https://github.com/ansible/ansible_tower_client_ruby/blob/39454d74b9d4ea4771b16d4c41cbbbd83ad05df5/lib/ansible_tower_client/base_model.rb#L164-L172 | train |
Fustrate/mlb_stats_api | lib/mlb_stats_api/stats.rb | MLBStatsAPI.Stats.stats | def stats(options = {})
raise ArgumentError, '#stats requires a stats arg' unless options[:stats]
raise ArgumentError, '#stats requires a group arg' unless options[:group]
get '/stats', options
end | ruby | def stats(options = {})
raise ArgumentError, '#stats requires a stats arg' unless options[:stats]
raise ArgumentError, '#stats requires a group arg' unless options[:group]
get '/stats', options
end | [
"def",
"stats",
"(",
"options",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"'#stats requires a stats arg'",
"unless",
"options",
"[",
":stats",
"]",
"raise",
"ArgumentError",
",",
"'#stats requires a group arg'",
"unless",
"options",
"[",
":group",
"]",
"g... | View statistics based on statType, group, season, and organization.
@see https://statsapi.mlb.com/docs/#operation/stats | [
"View",
"statistics",
"based",
"on",
"statType",
"group",
"season",
"and",
"organization",
"."
] | 6bbb430dbea4557b5d99c00cdd048b27aeeca231 | https://github.com/Fustrate/mlb_stats_api/blob/6bbb430dbea4557b5d99c00cdd048b27aeeca231/lib/mlb_stats_api/stats.rb#L9-L14 | train |
Fustrate/mlb_stats_api | lib/mlb_stats_api/standings.rb | MLBStatsAPI.Standings.standings | def standings(options = {})
options[:hydrate] = 'team' unless options.key?(:hydrate)
if options[:leagues] && !options[:leagueId]
league_ids = Leagues::LEAGUES.values_at(*options.delete(:leagues))
options[:leagueId] = league_ids
end
options[:leagueId] = [103, 104] unless Array(... | ruby | def standings(options = {})
options[:hydrate] = 'team' unless options.key?(:hydrate)
if options[:leagues] && !options[:leagueId]
league_ids = Leagues::LEAGUES.values_at(*options.delete(:leagues))
options[:leagueId] = league_ids
end
options[:leagueId] = [103, 104] unless Array(... | [
"def",
"standings",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":hydrate",
"]",
"=",
"'team'",
"unless",
"options",
".",
"key?",
"(",
":hydrate",
")",
"if",
"options",
"[",
":leagues",
"]",
"&&",
"!",
"options",
"[",
":leagueId",
"]",
"league_... | View standings for a league.
@see https://statsapi.mlb.com/docs/#operation/standings | [
"View",
"standings",
"for",
"a",
"league",
"."
] | 6bbb430dbea4557b5d99c00cdd048b27aeeca231 | https://github.com/Fustrate/mlb_stats_api/blob/6bbb430dbea4557b5d99c00cdd048b27aeeca231/lib/mlb_stats_api/standings.rb#L9-L21 | train |
Fustrate/mlb_stats_api | lib/mlb_stats_api/leagues.rb | MLBStatsAPI.Leagues.all_star_ballot | def all_star_ballot(league_id, season = nil, options = {})
options[:season] = season || Time.now.year
get "/league/#{league_id}/allStarBallot", options
end | ruby | def all_star_ballot(league_id, season = nil, options = {})
options[:season] = season || Time.now.year
get "/league/#{league_id}/allStarBallot", options
end | [
"def",
"all_star_ballot",
"(",
"league_id",
",",
"season",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":season",
"]",
"=",
"season",
"||",
"Time",
".",
"now",
".",
"year",
"get",
"\"/league/#{league_id}/allStarBallot\"",
",",
"options",
... | View All-Star Ballots per league.
@see https://statsapi.mlb.com/docs/#operation/allStarBallot | [
"View",
"All",
"-",
"Star",
"Ballots",
"per",
"league",
"."
] | 6bbb430dbea4557b5d99c00cdd048b27aeeca231 | https://github.com/Fustrate/mlb_stats_api/blob/6bbb430dbea4557b5d99c00cdd048b27aeeca231/lib/mlb_stats_api/leagues.rb#L38-L42 | train |
Fustrate/mlb_stats_api | lib/mlb_stats_api/leagues.rb | MLBStatsAPI.Leagues.all_star_write_ins | def all_star_write_ins(league_id, season = nil, options = {})
options[:season] = season || Time.now.year
get "/league/#{league_id}/allStarWriteIns", options
end | ruby | def all_star_write_ins(league_id, season = nil, options = {})
options[:season] = season || Time.now.year
get "/league/#{league_id}/allStarWriteIns", options
end | [
"def",
"all_star_write_ins",
"(",
"league_id",
",",
"season",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":season",
"]",
"=",
"season",
"||",
"Time",
".",
"now",
".",
"year",
"get",
"\"/league/#{league_id}/allStarWriteIns\"",
",",
"optio... | View All-Star Write-ins per league.
@see https://statsapi.mlb.com/docs/#operation/allStarWriteIns | [
"View",
"All",
"-",
"Star",
"Write",
"-",
"ins",
"per",
"league",
"."
] | 6bbb430dbea4557b5d99c00cdd048b27aeeca231 | https://github.com/Fustrate/mlb_stats_api/blob/6bbb430dbea4557b5d99c00cdd048b27aeeca231/lib/mlb_stats_api/leagues.rb#L46-L50 | train |
Fustrate/mlb_stats_api | lib/mlb_stats_api/leagues.rb | MLBStatsAPI.Leagues.all_star_final_vote | def all_star_final_vote(league_id, season = nil, options = {})
options[:season] = season || Time.now.year
get "/league/#{league_id}/allStarFinalVote", options
end | ruby | def all_star_final_vote(league_id, season = nil, options = {})
options[:season] = season || Time.now.year
get "/league/#{league_id}/allStarFinalVote", options
end | [
"def",
"all_star_final_vote",
"(",
"league_id",
",",
"season",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":season",
"]",
"=",
"season",
"||",
"Time",
".",
"now",
".",
"year",
"get",
"\"/league/#{league_id}/allStarFinalVote\"",
",",
"opt... | View All-Star Final Vote per league.
@see https://statsapi.mlb.com/docs/#operation/allStarFinalVote | [
"View",
"All",
"-",
"Star",
"Final",
"Vote",
"per",
"league",
"."
] | 6bbb430dbea4557b5d99c00cdd048b27aeeca231 | https://github.com/Fustrate/mlb_stats_api/blob/6bbb430dbea4557b5d99c00cdd048b27aeeca231/lib/mlb_stats_api/leagues.rb#L54-L58 | train |
Fustrate/mlb_stats_api | lib/mlb_stats_api/people.rb | MLBStatsAPI.People.person | def person(person_ids, options = {})
ids = Array(person_ids)
result = get('/people', options.merge(personIds: ids)).dig('people')
return result.first if ids.length == 1
result
end | ruby | def person(person_ids, options = {})
ids = Array(person_ids)
result = get('/people', options.merge(personIds: ids)).dig('people')
return result.first if ids.length == 1
result
end | [
"def",
"person",
"(",
"person_ids",
",",
"options",
"=",
"{",
"}",
")",
"ids",
"=",
"Array",
"(",
"person_ids",
")",
"result",
"=",
"get",
"(",
"'/people'",
",",
"options",
".",
"merge",
"(",
"personIds",
":",
"ids",
")",
")",
".",
"dig",
"(",
"'pe... | View one or more person's stats and biographical information.
@see https://statsapi.mlb.com/docs/#operation/person | [
"View",
"one",
"or",
"more",
"person",
"s",
"stats",
"and",
"biographical",
"information",
"."
] | 6bbb430dbea4557b5d99c00cdd048b27aeeca231 | https://github.com/Fustrate/mlb_stats_api/blob/6bbb430dbea4557b5d99c00cdd048b27aeeca231/lib/mlb_stats_api/people.rb#L9-L17 | train |
makandra/gemika | lib/gemika/rspec.rb | Gemika.RSpec.run_specs | def run_specs(options = nil)
options ||= {}
files = options.fetch(:files, 'spec')
rspec_options = options.fetch(:options, '--color')
# We need to override the gemfile explicitely, since we have a default Gemfile in the project root
gemfile = options.fetch(:gemfile, Gemika::Env.gemfile)
... | ruby | def run_specs(options = nil)
options ||= {}
files = options.fetch(:files, 'spec')
rspec_options = options.fetch(:options, '--color')
# We need to override the gemfile explicitely, since we have a default Gemfile in the project root
gemfile = options.fetch(:gemfile, Gemika::Env.gemfile)
... | [
"def",
"run_specs",
"(",
"options",
"=",
"nil",
")",
"options",
"||=",
"{",
"}",
"files",
"=",
"options",
".",
"fetch",
"(",
":files",
",",
"'spec'",
")",
"rspec_options",
"=",
"options",
".",
"fetch",
"(",
":options",
",",
"'--color'",
")",
"gemfile",
... | Runs the RSpec binary. | [
"Runs",
"the",
"RSpec",
"binary",
"."
] | 3cd120c2df2123edcde02489cf6b5b74cd710148 | https://github.com/makandra/gemika/blob/3cd120c2df2123edcde02489cf6b5b74cd710148/lib/gemika/rspec.rb#L10-L28 | train |
makandra/gemika | lib/gemika/rspec.rb | Gemika.RSpec.configure_should_syntax | def configure_should_syntax
if Env.gem?('rspec', '>= 2.11')
configure do |config|
config.expect_with(:rspec) { |c| c.syntax = [:should, :expect] }
config.mock_with(:rspec) { |c| c.syntax = [:should, :expect] }
end
else
# We have an old RSpec that only understands ... | ruby | def configure_should_syntax
if Env.gem?('rspec', '>= 2.11')
configure do |config|
config.expect_with(:rspec) { |c| c.syntax = [:should, :expect] }
config.mock_with(:rspec) { |c| c.syntax = [:should, :expect] }
end
else
# We have an old RSpec that only understands ... | [
"def",
"configure_should_syntax",
"if",
"Env",
".",
"gem?",
"(",
"'rspec'",
",",
"'>= 2.11'",
")",
"configure",
"do",
"|",
"config",
"|",
"config",
".",
"expect_with",
"(",
":rspec",
")",
"{",
"|",
"c",
"|",
"c",
".",
"syntax",
"=",
"[",
":should",
","... | Configures RSpec so it allows the `should` syntax that works across all RSpec versions. | [
"Configures",
"RSpec",
"so",
"it",
"allows",
"the",
"should",
"syntax",
"that",
"works",
"across",
"all",
"RSpec",
"versions",
"."
] | 3cd120c2df2123edcde02489cf6b5b74cd710148 | https://github.com/makandra/gemika/blob/3cd120c2df2123edcde02489cf6b5b74cd710148/lib/gemika/rspec.rb#L68-L77 | train |
makandra/gemika | lib/gemika/database.rb | Gemika.Database.adapter_config | def adapter_config
default_config = {}
default_config['database'] = guess_database_name
if Env.gem?('pg')
default_config['adapter'] = 'postgresql'
default_config['username'] = 'postgres' if Env.travis?
default_config['password'] = ''
user_config = @yaml_config['postgres... | ruby | def adapter_config
default_config = {}
default_config['database'] = guess_database_name
if Env.gem?('pg')
default_config['adapter'] = 'postgresql'
default_config['username'] = 'postgres' if Env.travis?
default_config['password'] = ''
user_config = @yaml_config['postgres... | [
"def",
"adapter_config",
"default_config",
"=",
"{",
"}",
"default_config",
"[",
"'database'",
"]",
"=",
"guess_database_name",
"if",
"Env",
".",
"gem?",
"(",
"'pg'",
")",
"default_config",
"[",
"'adapter'",
"]",
"=",
"'postgresql'",
"default_config",
"[",
"'use... | Returns a hash of ActiveRecord adapter options for the currently activated database gem. | [
"Returns",
"a",
"hash",
"of",
"ActiveRecord",
"adapter",
"options",
"for",
"the",
"currently",
"activated",
"database",
"gem",
"."
] | 3cd120c2df2123edcde02489cf6b5b74cd710148 | https://github.com/makandra/gemika/blob/3cd120c2df2123edcde02489cf6b5b74cd710148/lib/gemika/database.rb#L85-L106 | train |
makandra/gemika | lib/gemika/matrix.rb | Gemika.Matrix.each | def each(&block)
@all_passed = true
rows.each do |row|
gemfile = row.gemfile
if row.compatible_with_ruby?(current_ruby)
@compatible_count += 1
print_title gemfile
gemfile_passed = Env.with_gemfile(gemfile, row, &block)
@all_passed &= gemfile_passed
... | ruby | def each(&block)
@all_passed = true
rows.each do |row|
gemfile = row.gemfile
if row.compatible_with_ruby?(current_ruby)
@compatible_count += 1
print_title gemfile
gemfile_passed = Env.with_gemfile(gemfile, row, &block)
@all_passed &= gemfile_passed
... | [
"def",
"each",
"(",
"&",
"block",
")",
"@all_passed",
"=",
"true",
"rows",
".",
"each",
"do",
"|",
"row",
"|",
"gemfile",
"=",
"row",
".",
"gemfile",
"if",
"row",
".",
"compatible_with_ruby?",
"(",
"current_ruby",
")",
"@compatible_count",
"+=",
"1",
"pr... | Runs the given `block` for each matrix row that is compatible with the current Ruby.
The row's gemfile will be set as an environment variable, so Bundler will use that gemfile if you shell out in `block`.
At the end it will print a summary of which rows have passed, failed or were skipped (due to incompatible Ruby ... | [
"Runs",
"the",
"given",
"block",
"for",
"each",
"matrix",
"row",
"that",
"is",
"compatible",
"with",
"the",
"current",
"Ruby",
"."
] | 3cd120c2df2123edcde02489cf6b5b74cd710148 | https://github.com/makandra/gemika/blob/3cd120c2df2123edcde02489cf6b5b74cd710148/lib/gemika/matrix.rb#L107-L126 | train |
makandra/gemika | lib/gemika/env.rb | Gemika.Env.with_gemfile | def with_gemfile(path, *args, &block)
# Make sure that if block calls #gemfile we still return the gemfile for this
# process, regardless of what's in ENV temporarily
@gemfile_changed = true
@process_gemfile = ENV['BUNDLE_GEMFILE']
Bundler.with_clean_env do
ENV['BUNDLE_GEMFILE'] =... | ruby | def with_gemfile(path, *args, &block)
# Make sure that if block calls #gemfile we still return the gemfile for this
# process, regardless of what's in ENV temporarily
@gemfile_changed = true
@process_gemfile = ENV['BUNDLE_GEMFILE']
Bundler.with_clean_env do
ENV['BUNDLE_GEMFILE'] =... | [
"def",
"with_gemfile",
"(",
"path",
",",
"*",
"args",
",",
"&",
"block",
")",
"@gemfile_changed",
"=",
"true",
"@process_gemfile",
"=",
"ENV",
"[",
"'BUNDLE_GEMFILE'",
"]",
"Bundler",
".",
"with_clean_env",
"do",
"ENV",
"[",
"'BUNDLE_GEMFILE'",
"]",
"=",
"pa... | Changes the gemfile to the given `path`, runs the given `block`, then resets
the gemfile to its original path.
@example
Gemika::Env.with_gemfile('gemfiles/Gemfile.rails3') do
system('rspec spec') or raise 'RSpec failed'
end | [
"Changes",
"the",
"gemfile",
"to",
"the",
"given",
"path",
"runs",
"the",
"given",
"block",
"then",
"resets",
"the",
"gemfile",
"to",
"its",
"original",
"path",
"."
] | 3cd120c2df2123edcde02489cf6b5b74cd710148 | https://github.com/makandra/gemika/blob/3cd120c2df2123edcde02489cf6b5b74cd710148/lib/gemika/env.rb#L33-L45 | train |
makandra/gemika | lib/gemika/env.rb | Gemika.Env.gem? | def gem?(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
name, requirement_string = args
if options[:gemfile] && !process_gemfile?(options[:gemfile])
gem_in_gemfile?(options[:gemfile], name, requirement_string)
else
gem_activated?(name, requirement_string)
end
en... | ruby | def gem?(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
name, requirement_string = args
if options[:gemfile] && !process_gemfile?(options[:gemfile])
gem_in_gemfile?(options[:gemfile], name, requirement_string)
else
gem_activated?(name, requirement_string)
end
en... | [
"def",
"gem?",
"(",
"*",
"args",
")",
"options",
"=",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"name",
",",
"requirement_string",
"=",
"args",
"if",
"options",
"[",
":gemfile",
"]",
"&&",
"!",
"... | Check if the given gem was activated by the current gemfile.
It might or might not have been `require`d yet.
@example
Gemika::Env.gem?('activerecord')
Gemika::Env.gem?('activerecord', '= 5.0.0')
Gemika::Env.gem?('activerecord', '~> 4.2.0') | [
"Check",
"if",
"the",
"given",
"gem",
"was",
"activated",
"by",
"the",
"current",
"gemfile",
".",
"It",
"might",
"or",
"might",
"not",
"have",
"been",
"require",
"d",
"yet",
"."
] | 3cd120c2df2123edcde02489cf6b5b74cd710148 | https://github.com/makandra/gemika/blob/3cd120c2df2123edcde02489cf6b5b74cd710148/lib/gemika/env.rb#L56-L64 | train |
fabienpiette/fetcheable_on_api | lib/fetcheable_on_api/filterable.rb | FetcheableOnApi.Filterable.predicates | def predicates(predicate, collection, klass, column_name, value)
case predicate
when :between
klass.arel_table[column_name].between(value.first..value.last)
when :does_not_match
klass.arel_table[column_name].does_not_match("%#{value}%")
when :does_not_match_all
klass.arel... | ruby | def predicates(predicate, collection, klass, column_name, value)
case predicate
when :between
klass.arel_table[column_name].between(value.first..value.last)
when :does_not_match
klass.arel_table[column_name].does_not_match("%#{value}%")
when :does_not_match_all
klass.arel... | [
"def",
"predicates",
"(",
"predicate",
",",
"collection",
",",
"klass",
",",
"column_name",
",",
"value",
")",
"case",
"predicate",
"when",
":between",
"klass",
".",
"arel_table",
"[",
"column_name",
"]",
".",
"between",
"(",
"value",
".",
"first",
"..",
"... | Apply arel predicate on collection | [
"Apply",
"arel",
"predicate",
"on",
"collection"
] | ad19c38bc3978f4dc1c88ee6c301a09769c0f9f7 | https://github.com/fabienpiette/fetcheable_on_api/blob/ad19c38bc3978f4dc1c88ee6c301a09769c0f9f7/lib/fetcheable_on_api/filterable.rb#L141-L217 | train |
ledbettj/systemd-journal | lib/systemd/journal_entry.rb | Systemd.JournalEntry.catalog | def catalog(opts = {})
return nil unless catalog?
opts[:replace] = true unless opts.key?(:replace)
cat = Systemd::Journal.catalog_for(self[:message_id])
# catalog_for does not do field substitution for us, so we do it here
# if requested
opts[:replace] ? field_substitute(cat) : cat... | ruby | def catalog(opts = {})
return nil unless catalog?
opts[:replace] = true unless opts.key?(:replace)
cat = Systemd::Journal.catalog_for(self[:message_id])
# catalog_for does not do field substitution for us, so we do it here
# if requested
opts[:replace] ? field_substitute(cat) : cat... | [
"def",
"catalog",
"(",
"opts",
"=",
"{",
"}",
")",
"return",
"nil",
"unless",
"catalog?",
"opts",
"[",
":replace",
"]",
"=",
"true",
"unless",
"opts",
".",
"key?",
"(",
":replace",
")",
"cat",
"=",
"Systemd",
"::",
"Journal",
".",
"catalog_for",
"(",
... | Returns the catalog message that this Journal Entry references, if any.
@option opts [Boolean] :replace set to false to not replace placeholder
strings in the catalog with the associated values in this Journal Entry.
defaults to true.
@return [String] the catalog provided message for this Journal Entry, or
n... | [
"Returns",
"the",
"catalog",
"message",
"that",
"this",
"Journal",
"Entry",
"references",
"if",
"any",
"."
] | 823ac01a88da58fd3e703076b1d6e918aba73522 | https://github.com/ledbettj/systemd-journal/blob/823ac01a88da58fd3e703076b1d6e918aba73522/lib/systemd/journal_entry.rb#L71-L80 | train |
ledbettj/systemd-journal | lib/systemd/journal.rb | Systemd.Journal.query_unique | def query_unique(field)
results = []
Native.sd_journal_restart_unique(@ptr)
rc = Native.sd_journal_query_unique(@ptr, field.to_s.upcase)
raise JournalError, rc if rc < 0
while (kvpair = enumerate_helper(:sd_journal_enumerate_unique))
results << kvpair.last
end
resul... | ruby | def query_unique(field)
results = []
Native.sd_journal_restart_unique(@ptr)
rc = Native.sd_journal_query_unique(@ptr, field.to_s.upcase)
raise JournalError, rc if rc < 0
while (kvpair = enumerate_helper(:sd_journal_enumerate_unique))
results << kvpair.last
end
resul... | [
"def",
"query_unique",
"(",
"field",
")",
"results",
"=",
"[",
"]",
"Native",
".",
"sd_journal_restart_unique",
"(",
"@ptr",
")",
"rc",
"=",
"Native",
".",
"sd_journal_query_unique",
"(",
"@ptr",
",",
"field",
".",
"to_s",
".",
"upcase",
")",
"raise",
"Jou... | Get the list of unique values stored in the journal for the given field.
If passed a block, each possible value will be yielded.
@return [Array] the list of possible values.
@example Fetch all possible boot ids from the journal
j = Systemd::Journal.new
j.query_unique('_BOOT_ID') | [
"Get",
"the",
"list",
"of",
"unique",
"values",
"stored",
"in",
"the",
"journal",
"for",
"the",
"given",
"field",
".",
"If",
"passed",
"a",
"block",
"each",
"possible",
"value",
"will",
"be",
"yielded",
"."
] | 823ac01a88da58fd3e703076b1d6e918aba73522 | https://github.com/ledbettj/systemd-journal/blob/823ac01a88da58fd3e703076b1d6e918aba73522/lib/systemd/journal.rb#L155-L168 | train |
ledbettj/systemd-journal | lib/systemd/journal.rb | Systemd.Journal.data_threshold | def data_threshold
size_ptr = FFI::MemoryPointer.new(:size_t, 1)
if (rc = Native.sd_journal_get_data_threshold(@ptr, size_ptr)) < 0
raise JournalError, rc
end
size_ptr.read_size_t
end | ruby | def data_threshold
size_ptr = FFI::MemoryPointer.new(:size_t, 1)
if (rc = Native.sd_journal_get_data_threshold(@ptr, size_ptr)) < 0
raise JournalError, rc
end
size_ptr.read_size_t
end | [
"def",
"data_threshold",
"size_ptr",
"=",
"FFI",
"::",
"MemoryPointer",
".",
"new",
"(",
":size_t",
",",
"1",
")",
"if",
"(",
"rc",
"=",
"Native",
".",
"sd_journal_get_data_threshold",
"(",
"@ptr",
",",
"size_ptr",
")",
")",
"<",
"0",
"raise",
"JournalErro... | Get the maximum length of a data field that will be returned.
Fields longer than this will be truncated. Default is 64K.
@return [Integer] size in bytes. | [
"Get",
"the",
"maximum",
"length",
"of",
"a",
"data",
"field",
"that",
"will",
"be",
"returned",
".",
"Fields",
"longer",
"than",
"this",
"will",
"be",
"truncated",
".",
"Default",
"is",
"64K",
"."
] | 823ac01a88da58fd3e703076b1d6e918aba73522 | https://github.com/ledbettj/systemd-journal/blob/823ac01a88da58fd3e703076b1d6e918aba73522/lib/systemd/journal.rb#L186-L193 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/action.rb | CloudCrowd.Action.download | def download(url, path)
if url.match(FILE_URL)
FileUtils.cp(url.sub(FILE_URL, ''), path)
else
File.open(path, 'w+') do |file|
Net::HTTP.get_response(URI(url)) do |response|
response.read_body do |chunk|
file.write chunk
end
end
... | ruby | def download(url, path)
if url.match(FILE_URL)
FileUtils.cp(url.sub(FILE_URL, ''), path)
else
File.open(path, 'w+') do |file|
Net::HTTP.get_response(URI(url)) do |response|
response.read_body do |chunk|
file.write chunk
end
end
... | [
"def",
"download",
"(",
"url",
",",
"path",
")",
"if",
"url",
".",
"match",
"(",
"FILE_URL",
")",
"FileUtils",
".",
"cp",
"(",
"url",
".",
"sub",
"(",
"FILE_URL",
",",
"''",
")",
",",
"path",
")",
"else",
"File",
".",
"open",
"(",
"path",
",",
... | Download a file to the specified path. | [
"Download",
"a",
"file",
"to",
"the",
"specified",
"path",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/action.rb#L44-L57 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/action.rb | CloudCrowd.Action.` | def `(command)
result = super(command)
exit_code = $?.to_i
raise Error::CommandFailed.new(result, exit_code) unless exit_code == 0
result
end | ruby | def `(command)
result = super(command)
exit_code = $?.to_i
raise Error::CommandFailed.new(result, exit_code) unless exit_code == 0
result
end | [
"def",
"`",
"(",
"command",
")",
"result",
"=",
"super",
"(",
"command",
")",
"exit_code",
"=",
"$?",
".",
"to_i",
"raise",
"Error",
"::",
"CommandFailed",
".",
"new",
"(",
"result",
",",
"exit_code",
")",
"unless",
"exit_code",
"==",
"0",
"result",
"e... | Actions have a backticks command that raises a CommandFailed exception
on failure, so that processing doesn't just blithely continue. | [
"Actions",
"have",
"a",
"backticks",
"command",
"that",
"raises",
"a",
"CommandFailed",
"exception",
"on",
"failure",
"so",
"that",
"processing",
"doesn",
"t",
"just",
"blithely",
"continue",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/action.rb#L74-L79 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/action.rb | CloudCrowd.Action.safe_filename | def safe_filename(url)
url = url.sub(/\?.*\Z/, '')
ext = File.extname(url)
name = URI.unescape(File.basename(url)).gsub(/[^a-zA-Z0-9_\-.]/, '-').gsub(/-+/, '-')
File.basename(name, ext).gsub('.', '-') + ext
end | ruby | def safe_filename(url)
url = url.sub(/\?.*\Z/, '')
ext = File.extname(url)
name = URI.unescape(File.basename(url)).gsub(/[^a-zA-Z0-9_\-.]/, '-').gsub(/-+/, '-')
File.basename(name, ext).gsub('.', '-') + ext
end | [
"def",
"safe_filename",
"(",
"url",
")",
"url",
"=",
"url",
".",
"sub",
"(",
"/",
"\\?",
"\\Z",
"/",
",",
"''",
")",
"ext",
"=",
"File",
".",
"extname",
"(",
"url",
")",
"name",
"=",
"URI",
".",
"unescape",
"(",
"File",
".",
"basename",
"(",
"u... | Convert an unsafe URL into a filesystem-friendly filename. | [
"Convert",
"an",
"unsafe",
"URL",
"into",
"a",
"filesystem",
"-",
"friendly",
"filename",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/action.rb#L85-L90 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/action.rb | CloudCrowd.Action.download_input | def download_input
return unless input_is_url?
Dir.chdir(@work_directory) do
@input_path = File.join(@work_directory, safe_filename(@input))
@file_name = File.basename(@input_path, File.extname(@input_path))
download(@input, @input_path)
end
end | ruby | def download_input
return unless input_is_url?
Dir.chdir(@work_directory) do
@input_path = File.join(@work_directory, safe_filename(@input))
@file_name = File.basename(@input_path, File.extname(@input_path))
download(@input, @input_path)
end
end | [
"def",
"download_input",
"return",
"unless",
"input_is_url?",
"Dir",
".",
"chdir",
"(",
"@work_directory",
")",
"do",
"@input_path",
"=",
"File",
".",
"join",
"(",
"@work_directory",
",",
"safe_filename",
"(",
"@input",
")",
")",
"@file_name",
"=",
"File",
"."... | If the input is a URL, download the file before beginning processing. | [
"If",
"the",
"input",
"is",
"a",
"URL",
"download",
"the",
"file",
"before",
"beginning",
"processing",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/action.rb#L118-L125 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/models/node_record.rb | CloudCrowd.NodeRecord.send_work_unit | def send_work_unit(unit)
result = node['/work'].post(:work_unit => unit.to_json)
unit.assign_to(self, JSON.parse(result.body)['pid'])
touch && true
rescue RestClient::RequestTimeout
# The node's gone away. Destroy it and it will check in when it comes back
CloudCrowd.log "Node #{host}... | ruby | def send_work_unit(unit)
result = node['/work'].post(:work_unit => unit.to_json)
unit.assign_to(self, JSON.parse(result.body)['pid'])
touch && true
rescue RestClient::RequestTimeout
# The node's gone away. Destroy it and it will check in when it comes back
CloudCrowd.log "Node #{host}... | [
"def",
"send_work_unit",
"(",
"unit",
")",
"result",
"=",
"node",
"[",
"'/work'",
"]",
".",
"post",
"(",
":work_unit",
"=>",
"unit",
".",
"to_json",
")",
"unit",
".",
"assign_to",
"(",
"self",
",",
"JSON",
".",
"parse",
"(",
"result",
".",
"body",
")... | Dispatch a WorkUnit to this node. Places the node at back at the end of
the rotation. If we fail to send the WorkUnit, we consider the node to be
down, and remove this record, freeing up all of its checked-out work units.
If the Node responds that it's overloaded, we mark it as busy. Returns
true if the WorkUnit wa... | [
"Dispatch",
"a",
"WorkUnit",
"to",
"this",
"node",
".",
"Places",
"the",
"node",
"at",
"back",
"at",
"the",
"end",
"of",
"the",
"rotation",
".",
"If",
"we",
"fail",
"to",
"send",
"the",
"WorkUnit",
"we",
"consider",
"the",
"node",
"to",
"be",
"down",
... | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/models/node_record.rb#L53-L68 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/models/work_unit.rb | CloudCrowd.WorkUnit.fail | def fail(output, time_taken)
tries = self.attempts + 1
return try_again if tries < CloudCrowd.config[:work_unit_retries]
update_attributes({
:status => FAILED,
:node_record => nil,
:worker_pid => nil,
:attempts => tries,
:output => o... | ruby | def fail(output, time_taken)
tries = self.attempts + 1
return try_again if tries < CloudCrowd.config[:work_unit_retries]
update_attributes({
:status => FAILED,
:node_record => nil,
:worker_pid => nil,
:attempts => tries,
:output => o... | [
"def",
"fail",
"(",
"output",
",",
"time_taken",
")",
"tries",
"=",
"self",
".",
"attempts",
"+",
"1",
"return",
"try_again",
"if",
"tries",
"<",
"CloudCrowd",
".",
"config",
"[",
":work_unit_retries",
"]",
"update_attributes",
"(",
"{",
":status",
"=>",
"... | Mark this unit as having failed. May attempt a retry. | [
"Mark",
"this",
"unit",
"as",
"having",
"failed",
".",
"May",
"attempt",
"a",
"retry",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/models/work_unit.rb#L138-L150 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/worker.rb | CloudCrowd.Worker.complete_work_unit | def complete_work_unit(result)
keep_trying_to "complete work unit" do
data = base_params.merge({:status => 'succeeded', :output => result})
@node.central["/work/#{data[:id]}"].put(data)
log "finished #{display_work_unit} in #{data[:time]} seconds"
end
end | ruby | def complete_work_unit(result)
keep_trying_to "complete work unit" do
data = base_params.merge({:status => 'succeeded', :output => result})
@node.central["/work/#{data[:id]}"].put(data)
log "finished #{display_work_unit} in #{data[:time]} seconds"
end
end | [
"def",
"complete_work_unit",
"(",
"result",
")",
"keep_trying_to",
"\"complete work unit\"",
"do",
"data",
"=",
"base_params",
".",
"merge",
"(",
"{",
":status",
"=>",
"'succeeded'",
",",
":output",
"=>",
"result",
"}",
")",
"@node",
".",
"central",
"[",
"\"/w... | A new Worker customizes itself to its WorkUnit at instantiation.
Return output to the central server, marking the WorkUnit done. | [
"A",
"new",
"Worker",
"customizes",
"itself",
"to",
"its",
"WorkUnit",
"at",
"instantiation",
".",
"Return",
"output",
"to",
"the",
"central",
"server",
"marking",
"the",
"WorkUnit",
"done",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/worker.rb#L33-L39 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/worker.rb | CloudCrowd.Worker.fail_work_unit | def fail_work_unit(exception)
keep_trying_to "mark work unit as failed" do
data = base_params.merge({:status => 'failed', :output => {'output' => exception.message}.to_json})
@node.central["/work/#{data[:id]}"].put(data)
log "failed #{display_work_unit} in #{data[:time]} seconds\n#{excepti... | ruby | def fail_work_unit(exception)
keep_trying_to "mark work unit as failed" do
data = base_params.merge({:status => 'failed', :output => {'output' => exception.message}.to_json})
@node.central["/work/#{data[:id]}"].put(data)
log "failed #{display_work_unit} in #{data[:time]} seconds\n#{excepti... | [
"def",
"fail_work_unit",
"(",
"exception",
")",
"keep_trying_to",
"\"mark work unit as failed\"",
"do",
"data",
"=",
"base_params",
".",
"merge",
"(",
"{",
":status",
"=>",
"'failed'",
",",
":output",
"=>",
"{",
"'output'",
"=>",
"exception",
".",
"message",
"}"... | Mark the WorkUnit failed, returning the exception to central. | [
"Mark",
"the",
"WorkUnit",
"failed",
"returning",
"the",
"exception",
"to",
"central",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/worker.rb#L42-L48 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/worker.rb | CloudCrowd.Worker.keep_trying_to | def keep_trying_to(title)
begin
yield
rescue RestClient::ResourceNotFound => e
log "work unit ##{@unit['id']} doesn't exist. discarding..."
rescue Exception => e
log "failed to #{title} -- retry in #{@retry_wait} seconds"
log e.message
log e.backtrace
sl... | ruby | def keep_trying_to(title)
begin
yield
rescue RestClient::ResourceNotFound => e
log "work unit ##{@unit['id']} doesn't exist. discarding..."
rescue Exception => e
log "failed to #{title} -- retry in #{@retry_wait} seconds"
log e.message
log e.backtrace
sl... | [
"def",
"keep_trying_to",
"(",
"title",
")",
"begin",
"yield",
"rescue",
"RestClient",
"::",
"ResourceNotFound",
"=>",
"e",
"log",
"\"work unit ##{@unit['id']} doesn't exist. discarding...\"",
"rescue",
"Exception",
"=>",
"e",
"log",
"\"failed to #{title} -- retry in #{@retry_... | We expect and require internal communication between the central server
and the workers to succeed. If it fails for any reason, log it, and then
keep trying the same request. | [
"We",
"expect",
"and",
"require",
"internal",
"communication",
"between",
"the",
"central",
"server",
"and",
"the",
"workers",
"to",
"succeed",
".",
"If",
"it",
"fails",
"for",
"any",
"reason",
"log",
"it",
"and",
"then",
"keep",
"trying",
"the",
"same",
"... | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/worker.rb#L53-L65 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/worker.rb | CloudCrowd.Worker.run_work_unit | def run_work_unit
begin
result = nil
action_class = CloudCrowd.actions[@unit['action']]
action = action_class.new(@status, @unit['input'], enhanced_unit_options, @node.asset_store)
Dir.chdir(action.work_directory) do
result = case @status
when PROCESSING then ac... | ruby | def run_work_unit
begin
result = nil
action_class = CloudCrowd.actions[@unit['action']]
action = action_class.new(@status, @unit['input'], enhanced_unit_options, @node.asset_store)
Dir.chdir(action.work_directory) do
result = case @status
when PROCESSING then ac... | [
"def",
"run_work_unit",
"begin",
"result",
"=",
"nil",
"action_class",
"=",
"CloudCrowd",
".",
"actions",
"[",
"@unit",
"[",
"'action'",
"]",
"]",
"action",
"=",
"action_class",
".",
"new",
"(",
"@status",
",",
"@unit",
"[",
"'input'",
"]",
",",
"enhanced_... | Executes the WorkUnit by running the Action, catching all exceptions as
failures. We capture the thread so that we can kill it from the outside,
when exiting. | [
"Executes",
"the",
"WorkUnit",
"by",
"running",
"the",
"Action",
"catching",
"all",
"exceptions",
"as",
"failures",
".",
"We",
"capture",
"the",
"thread",
"so",
"that",
"we",
"can",
"kill",
"it",
"from",
"the",
"outside",
"when",
"exiting",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/worker.rb#L75-L95 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/worker.rb | CloudCrowd.Worker.run | def run
trap_signals
log "starting #{display_work_unit}"
if @unit['options']['benchmark']
log("ran #{display_work_unit} in " + Benchmark.measure { run_work_unit }.to_s)
else
run_work_unit
end
Process.exit!
end | ruby | def run
trap_signals
log "starting #{display_work_unit}"
if @unit['options']['benchmark']
log("ran #{display_work_unit} in " + Benchmark.measure { run_work_unit }.to_s)
else
run_work_unit
end
Process.exit!
end | [
"def",
"run",
"trap_signals",
"log",
"\"starting #{display_work_unit}\"",
"if",
"@unit",
"[",
"'options'",
"]",
"[",
"'benchmark'",
"]",
"log",
"(",
"\"ran #{display_work_unit} in \"",
"+",
"Benchmark",
".",
"measure",
"{",
"run_work_unit",
"}",
".",
"to_s",
")",
... | Run this worker inside of a fork. Attempts to exit cleanly.
Wraps run_work_unit to benchmark the execution time, if requested. | [
"Run",
"this",
"worker",
"inside",
"of",
"a",
"fork",
".",
"Attempts",
"to",
"exit",
"cleanly",
".",
"Wraps",
"run_work_unit",
"to",
"benchmark",
"the",
"execution",
"time",
"if",
"requested",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/worker.rb#L99-L108 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/worker.rb | CloudCrowd.Worker.trap_signals | def trap_signals
Signal.trap('QUIT') { Process.exit! }
Signal.trap('INT') { Process.exit! }
Signal.trap('TERM') { Process.exit! }
end | ruby | def trap_signals
Signal.trap('QUIT') { Process.exit! }
Signal.trap('INT') { Process.exit! }
Signal.trap('TERM') { Process.exit! }
end | [
"def",
"trap_signals",
"Signal",
".",
"trap",
"(",
"'QUIT'",
")",
"{",
"Process",
".",
"exit!",
"}",
"Signal",
".",
"trap",
"(",
"'INT'",
")",
"{",
"Process",
".",
"exit!",
"}",
"Signal",
".",
"trap",
"(",
"'TERM'",
")",
"{",
"Process",
".",
"exit!",... | When signaled to exit, make sure that the Worker shuts down without firing
the Node's at_exit callbacks. | [
"When",
"signaled",
"to",
"exit",
"make",
"sure",
"that",
"the",
"Worker",
"shuts",
"down",
"without",
"firing",
"the",
"Node",
"s",
"at_exit",
"callbacks",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/worker.rb#L144-L148 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/command_line.rb | CloudCrowd.CommandLine.start_server | def start_server
port = @options[:port] || 9173
daemonize = @options[:daemonize] ? '-d' : ''
log_path = CloudCrowd.log_path('server.log')
pid_path = CloudCrowd.pid_path('server.pid')
rackup_path = File.expand_path("#{@options[:config_path]}/config.ru")
FileUtils.mkdir_... | ruby | def start_server
port = @options[:port] || 9173
daemonize = @options[:daemonize] ? '-d' : ''
log_path = CloudCrowd.log_path('server.log')
pid_path = CloudCrowd.pid_path('server.pid')
rackup_path = File.expand_path("#{@options[:config_path]}/config.ru")
FileUtils.mkdir_... | [
"def",
"start_server",
"port",
"=",
"@options",
"[",
":port",
"]",
"||",
"9173",
"daemonize",
"=",
"@options",
"[",
":daemonize",
"]",
"?",
"'-d'",
":",
"''",
"log_path",
"=",
"CloudCrowd",
".",
"log_path",
"(",
"'server.log'",
")",
"pid_path",
"=",
"Cloud... | Convenience command for quickly spinning up the central server. More
sophisticated deployments, load-balancing across multiple app servers,
should use the config.ru rackup file directly. This method will start
a single Thin server. | [
"Convenience",
"command",
"for",
"quickly",
"spinning",
"up",
"the",
"central",
"server",
".",
"More",
"sophisticated",
"deployments",
"load",
"-",
"balancing",
"across",
"multiple",
"app",
"servers",
"should",
"use",
"the",
"config",
".",
"ru",
"rackup",
"file"... | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/command_line.rb#L80-L89 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/command_line.rb | CloudCrowd.CommandLine.run_install | def run_install(install_path)
require 'fileutils'
install_path ||= '.'
FileUtils.mkdir_p install_path unless File.exists?(install_path)
install_file "#{CC_ROOT}/config/config.example.yml", "#{install_path}/config.yml"
install_file "#{CC_ROOT}/config/config.example.ru", "#{install_path}/con... | ruby | def run_install(install_path)
require 'fileutils'
install_path ||= '.'
FileUtils.mkdir_p install_path unless File.exists?(install_path)
install_file "#{CC_ROOT}/config/config.example.yml", "#{install_path}/config.yml"
install_file "#{CC_ROOT}/config/config.example.ru", "#{install_path}/con... | [
"def",
"run_install",
"(",
"install_path",
")",
"require",
"'fileutils'",
"install_path",
"||=",
"'.'",
"FileUtils",
".",
"mkdir_p",
"install_path",
"unless",
"File",
".",
"exists?",
"(",
"install_path",
")",
"install_file",
"\"#{CC_ROOT}/config/config.example.yml\"",
"... | Install the required CloudCrowd configuration files into the specified
directory, or the current one. | [
"Install",
"the",
"required",
"CloudCrowd",
"configuration",
"files",
"into",
"the",
"specified",
"directory",
"or",
"the",
"current",
"one",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/command_line.rb#L143-L151 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/command_line.rb | CloudCrowd.CommandLine.ensure_config | def ensure_config
return if @config_found
found = CONFIG_FILES.all? {|f| File.exists? "#{@options[:config_path]}/#{f}" }
found ? @config_dir = true : config_not_found
end | ruby | def ensure_config
return if @config_found
found = CONFIG_FILES.all? {|f| File.exists? "#{@options[:config_path]}/#{f}" }
found ? @config_dir = true : config_not_found
end | [
"def",
"ensure_config",
"return",
"if",
"@config_found",
"found",
"=",
"CONFIG_FILES",
".",
"all?",
"{",
"|",
"f",
"|",
"File",
".",
"exists?",
"\"#{@options[:config_path]}/#{f}\"",
"}",
"found",
"?",
"@config_dir",
"=",
"true",
":",
"config_not_found",
"end"
] | Check for configuration files, either in the current directory, or in
the CLOUD_CROWD_CONFIG environment variable. Exit if they're not found. | [
"Check",
"for",
"configuration",
"files",
"either",
"in",
"the",
"current",
"directory",
"or",
"in",
"the",
"CLOUD_CROWD_CONFIG",
"environment",
"variable",
".",
"Exit",
"if",
"they",
"re",
"not",
"found",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/command_line.rb#L170-L174 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/command_line.rb | CloudCrowd.CommandLine.install_file | def install_file(source, dest, is_dir=false)
if File.exists?(dest)
print "#{dest} already exists. Overwrite it? (yes/no) "
return unless ['y', 'yes', 'ok'].include? gets.chomp.downcase
end
is_dir ? FileUtils.cp_r(source, dest) : FileUtils.cp(source, dest)
puts "installed #{dest}"... | ruby | def install_file(source, dest, is_dir=false)
if File.exists?(dest)
print "#{dest} already exists. Overwrite it? (yes/no) "
return unless ['y', 'yes', 'ok'].include? gets.chomp.downcase
end
is_dir ? FileUtils.cp_r(source, dest) : FileUtils.cp(source, dest)
puts "installed #{dest}"... | [
"def",
"install_file",
"(",
"source",
",",
"dest",
",",
"is_dir",
"=",
"false",
")",
"if",
"File",
".",
"exists?",
"(",
"dest",
")",
"print",
"\"#{dest} already exists. Overwrite it? (yes/no) \"",
"return",
"unless",
"[",
"'y'",
",",
"'yes'",
",",
"'ok'",
"]",... | Install a file and log the installation. If we're overwriting a file,
offer a chance to back out. | [
"Install",
"a",
"file",
"and",
"log",
"the",
"installation",
".",
"If",
"we",
"re",
"overwriting",
"a",
"file",
"offer",
"a",
"chance",
"to",
"back",
"out",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/command_line.rb#L236-L243 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/models/job.rb | CloudCrowd.Job.check_for_completion | def check_for_completion
return unless all_work_units_complete?
set_next_status
outs = gather_outputs_from_work_units
return queue_for_workers([outs]) if merging?
if complete?
update_attributes(:outputs => outs, :time => time_taken)
CloudCrowd.log "Job ##{id} (#{action}) #{... | ruby | def check_for_completion
return unless all_work_units_complete?
set_next_status
outs = gather_outputs_from_work_units
return queue_for_workers([outs]) if merging?
if complete?
update_attributes(:outputs => outs, :time => time_taken)
CloudCrowd.log "Job ##{id} (#{action}) #{... | [
"def",
"check_for_completion",
"return",
"unless",
"all_work_units_complete?",
"set_next_status",
"outs",
"=",
"gather_outputs_from_work_units",
"return",
"queue_for_workers",
"(",
"[",
"outs",
"]",
")",
"if",
"merging?",
"if",
"complete?",
"update_attributes",
"(",
":out... | After work units are marked successful, we check to see if all of them have
finished, if so, continue on to the next phase of the job. | [
"After",
"work",
"units",
"are",
"marked",
"successful",
"we",
"check",
"to",
"see",
"if",
"all",
"of",
"them",
"have",
"finished",
"if",
"so",
"continue",
"on",
"to",
"the",
"next",
"phase",
"of",
"the",
"job",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/models/job.rb#L51-L62 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/models/job.rb | CloudCrowd.Job.percent_complete | def percent_complete
return 99 if merging?
return 100 if complete?
unit_count = work_units.count
return 100 if unit_count <= 0
(work_units.complete.count / unit_count.to_f * 100).round
end | ruby | def percent_complete
return 99 if merging?
return 100 if complete?
unit_count = work_units.count
return 100 if unit_count <= 0
(work_units.complete.count / unit_count.to_f * 100).round
end | [
"def",
"percent_complete",
"return",
"99",
"if",
"merging?",
"return",
"100",
"if",
"complete?",
"unit_count",
"=",
"work_units",
".",
"count",
"return",
"100",
"if",
"unit_count",
"<=",
"0",
"(",
"work_units",
".",
"complete",
".",
"count",
"/",
"unit_count",... | How complete is this Job?
Unfortunately, with the current processing sequence, the percent_complete
can pull a fast one and go backwards. This happens when there's a single
large input that takes a long time to split, and when it finally does it
creates a whole swarm of work units. This seems unavoidable. | [
"How",
"complete",
"is",
"this",
"Job?",
"Unfortunately",
"with",
"the",
"current",
"processing",
"sequence",
"the",
"percent_complete",
"can",
"pull",
"a",
"fast",
"one",
"and",
"go",
"backwards",
".",
"This",
"happens",
"when",
"there",
"s",
"a",
"single",
... | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/models/job.rb#L143-L149 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/models/job.rb | CloudCrowd.Job.as_json | def as_json(opts={})
atts = {
'id' => id,
'color' => color,
'status' => display_status,
'percent_complete' => percent_complete,
'work_units' => work_units.count,
'time_taken' => time_taken
}
atts['outp... | ruby | def as_json(opts={})
atts = {
'id' => id,
'color' => color,
'status' => display_status,
'percent_complete' => percent_complete,
'work_units' => work_units.count,
'time_taken' => time_taken
}
atts['outp... | [
"def",
"as_json",
"(",
"opts",
"=",
"{",
"}",
")",
"atts",
"=",
"{",
"'id'",
"=>",
"id",
",",
"'color'",
"=>",
"color",
",",
"'status'",
"=>",
"display_status",
",",
"'percent_complete'",
"=>",
"percent_complete",
",",
"'work_units'",
"=>",
"work_units",
"... | A JSON representation of this job includes the statuses of its component
WorkUnits, as well as any completed outputs. | [
"A",
"JSON",
"representation",
"of",
"this",
"job",
"includes",
"the",
"statuses",
"of",
"its",
"component",
"WorkUnits",
"as",
"well",
"as",
"any",
"completed",
"outputs",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/models/job.rb#L164-L176 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/models/job.rb | CloudCrowd.Job.gather_outputs_from_work_units | def gather_outputs_from_work_units
units = self.work_units.complete
outs = self.work_units.complete.map {|u| u.parsed_output }
self.work_units.complete.destroy_all
outs.to_json
end | ruby | def gather_outputs_from_work_units
units = self.work_units.complete
outs = self.work_units.complete.map {|u| u.parsed_output }
self.work_units.complete.destroy_all
outs.to_json
end | [
"def",
"gather_outputs_from_work_units",
"units",
"=",
"self",
".",
"work_units",
".",
"complete",
"outs",
"=",
"self",
".",
"work_units",
".",
"complete",
".",
"map",
"{",
"|",
"u",
"|",
"u",
".",
"parsed_output",
"}",
"self",
".",
"work_units",
".",
"com... | When the WorkUnits are all finished, gather all their outputs together
before removing them from the database entirely. Returns their merged JSON. | [
"When",
"the",
"WorkUnits",
"are",
"all",
"finished",
"gather",
"all",
"their",
"outputs",
"together",
"before",
"removing",
"them",
"from",
"the",
"database",
"entirely",
".",
"Returns",
"their",
"merged",
"JSON",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/models/job.rb#L183-L188 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/models/job.rb | CloudCrowd.Job.queue_for_workers | def queue_for_workers(input=nil)
input ||= JSON.parse(self.inputs)
input.each {|i| WorkUnit.start(self, action, i, status) }
self
end | ruby | def queue_for_workers(input=nil)
input ||= JSON.parse(self.inputs)
input.each {|i| WorkUnit.start(self, action, i, status) }
self
end | [
"def",
"queue_for_workers",
"(",
"input",
"=",
"nil",
")",
"input",
"||=",
"JSON",
".",
"parse",
"(",
"self",
".",
"inputs",
")",
"input",
".",
"each",
"{",
"|",
"i",
"|",
"WorkUnit",
".",
"start",
"(",
"self",
",",
"action",
",",
"i",
",",
"status... | When starting a new job, or moving to a new stage, split up the inputs
into WorkUnits, and queue them. Workers will start picking them up right
away. | [
"When",
"starting",
"a",
"new",
"job",
"or",
"moving",
"to",
"a",
"new",
"stage",
"split",
"up",
"the",
"inputs",
"into",
"WorkUnits",
"and",
"queue",
"them",
".",
"Workers",
"will",
"start",
"picking",
"them",
"up",
"right",
"away",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/models/job.rb#L193-L197 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/node.rb | CloudCrowd.Node.start | def start
FileUtils.mkdir_p(CloudCrowd.log_path) if @daemon && !File.exists?(CloudCrowd.log_path)
@server = Thin::Server.new('0.0.0.0', @port, self, :signals => false)
@server.tag = 'cloud-crowd-node'
@server.pid_file = CloudCrowd.pid_path('node.pid')
@server.log_file = Cloud... | ruby | def start
FileUtils.mkdir_p(CloudCrowd.log_path) if @daemon && !File.exists?(CloudCrowd.log_path)
@server = Thin::Server.new('0.0.0.0', @port, self, :signals => false)
@server.tag = 'cloud-crowd-node'
@server.pid_file = CloudCrowd.pid_path('node.pid')
@server.log_file = Cloud... | [
"def",
"start",
"FileUtils",
".",
"mkdir_p",
"(",
"CloudCrowd",
".",
"log_path",
")",
"if",
"@daemon",
"&&",
"!",
"File",
".",
"exists?",
"(",
"CloudCrowd",
".",
"log_path",
")",
"@server",
"=",
"Thin",
"::",
"Server",
".",
"new",
"(",
"'0.0.0.0'",
",",
... | When creating a node, specify the port it should run on.
Starting up a Node registers with the central server and begins to listen
for incoming WorkUnits. | [
"When",
"creating",
"a",
"node",
"specify",
"the",
"port",
"it",
"should",
"run",
"on",
".",
"Starting",
"up",
"a",
"Node",
"registers",
"with",
"the",
"central",
"server",
"and",
"begins",
"to",
"listen",
"for",
"incoming",
"WorkUnits",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/node.rb#L92-L106 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/node.rb | CloudCrowd.Node.check_in | def check_in(critical=false)
@central["/node/#{@id}"].put(
:busy => @overloaded,
:tag => @tag,
:max_workers => CloudCrowd.config[:max_workers],
:enabled_actions => @enabled_actions.join(',')
)
rescue RestClient::Exception, Errno::ECONNREFUSE... | ruby | def check_in(critical=false)
@central["/node/#{@id}"].put(
:busy => @overloaded,
:tag => @tag,
:max_workers => CloudCrowd.config[:max_workers],
:enabled_actions => @enabled_actions.join(',')
)
rescue RestClient::Exception, Errno::ECONNREFUSE... | [
"def",
"check_in",
"(",
"critical",
"=",
"false",
")",
"@central",
"[",
"\"/node/#{@id}\"",
"]",
".",
"put",
"(",
":busy",
"=>",
"@overloaded",
",",
":tag",
"=>",
"@tag",
",",
":max_workers",
"=>",
"CloudCrowd",
".",
"config",
"[",
":max_workers",
"]",
","... | Checking in with the central server informs it of the location and
configuration of this Node. If it can't check-in, there's no point in
starting. | [
"Checking",
"in",
"with",
"the",
"central",
"server",
"informs",
"it",
"of",
"the",
"location",
"and",
"configuration",
"of",
"this",
"Node",
".",
"If",
"it",
"can",
"t",
"check",
"-",
"in",
"there",
"s",
"no",
"point",
"in",
"starting",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/node.rb#L111-L121 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/node.rb | CloudCrowd.Node.free_memory | def free_memory
case RUBY_PLATFORM
when /darwin/
stats = `vm_stat`
@mac_page_size ||= stats.match(SCRAPE_MAC_PAGE)[1].to_f / 1048576.0
stats.match(SCRAPE_MAC_MEMORY)[1].to_f * @mac_page_size
when /linux/
`cat /proc/meminfo`.match(SCRAPE_LINUX_MEMORY)[1].to_f / 1024.0
... | ruby | def free_memory
case RUBY_PLATFORM
when /darwin/
stats = `vm_stat`
@mac_page_size ||= stats.match(SCRAPE_MAC_PAGE)[1].to_f / 1048576.0
stats.match(SCRAPE_MAC_MEMORY)[1].to_f * @mac_page_size
when /linux/
`cat /proc/meminfo`.match(SCRAPE_LINUX_MEMORY)[1].to_f / 1024.0
... | [
"def",
"free_memory",
"case",
"RUBY_PLATFORM",
"when",
"/",
"/",
"stats",
"=",
"`",
"`",
"@mac_page_size",
"||=",
"stats",
".",
"match",
"(",
"SCRAPE_MAC_PAGE",
")",
"[",
"1",
"]",
".",
"to_f",
"/",
"1048576.0",
"stats",
".",
"match",
"(",
"SCRAPE_MAC_MEMO... | The current amount of free memory in megabytes. | [
"The",
"current",
"amount",
"of",
"free",
"memory",
"in",
"megabytes",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/node.rb#L148-L159 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/node.rb | CloudCrowd.Node.monitor_system | def monitor_system
@monitor_thread = Thread.new do
loop do
was_overloaded = @overloaded
@overloaded = overloaded?
check_in if was_overloaded && !@overloaded
sleep MONITOR_INTERVAL
end
end
end | ruby | def monitor_system
@monitor_thread = Thread.new do
loop do
was_overloaded = @overloaded
@overloaded = overloaded?
check_in if was_overloaded && !@overloaded
sleep MONITOR_INTERVAL
end
end
end | [
"def",
"monitor_system",
"@monitor_thread",
"=",
"Thread",
".",
"new",
"do",
"loop",
"do",
"was_overloaded",
"=",
"@overloaded",
"@overloaded",
"=",
"overloaded?",
"check_in",
"if",
"was_overloaded",
"&&",
"!",
"@overloaded",
"sleep",
"MONITOR_INTERVAL",
"end",
"end... | Launch a monitoring thread that periodically checks the node's load
average and the amount of free memory remaining. If we transition out of
the overloaded state, let central know. | [
"Launch",
"a",
"monitoring",
"thread",
"that",
"periodically",
"checks",
"the",
"node",
"s",
"load",
"average",
"and",
"the",
"amount",
"of",
"free",
"memory",
"remaining",
".",
"If",
"we",
"transition",
"out",
"of",
"the",
"overloaded",
"state",
"let",
"cen... | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/node.rb#L196-L205 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/node.rb | CloudCrowd.Node.check_in_periodically | def check_in_periodically
@check_in_thread = Thread.new do
loop do
check_on_workers
reply = ""
1.upto(5).each do | attempt_number |
# sleep for an ever increasing amount of time to prevent overloading the server
sleep CHECK_IN_INTERVAL * attempt_number... | ruby | def check_in_periodically
@check_in_thread = Thread.new do
loop do
check_on_workers
reply = ""
1.upto(5).each do | attempt_number |
# sleep for an ever increasing amount of time to prevent overloading the server
sleep CHECK_IN_INTERVAL * attempt_number... | [
"def",
"check_in_periodically",
"@check_in_thread",
"=",
"Thread",
".",
"new",
"do",
"loop",
"do",
"check_on_workers",
"reply",
"=",
"\"\"",
"1",
".",
"upto",
"(",
"5",
")",
".",
"each",
"do",
"|",
"attempt_number",
"|",
"sleep",
"CHECK_IN_INTERVAL",
"*",
"a... | If communication is interrupted for external reasons, the central server
will assume that the node has gone down. Checking in will let central know
it's still online. | [
"If",
"communication",
"is",
"interrupted",
"for",
"external",
"reasons",
"the",
"central",
"server",
"will",
"assume",
"that",
"the",
"node",
"has",
"gone",
"down",
".",
"Checking",
"in",
"will",
"let",
"central",
"know",
"it",
"s",
"still",
"online",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/node.rb#L210-L233 | train |
documentcloud/cloud-crowd | lib/cloud_crowd/node.rb | CloudCrowd.Node.trap_signals | def trap_signals
Signal.trap('QUIT') { shut_down }
Signal.trap('INT') { shut_down }
Signal.trap('TERM') { shut_down }
end | ruby | def trap_signals
Signal.trap('QUIT') { shut_down }
Signal.trap('INT') { shut_down }
Signal.trap('TERM') { shut_down }
end | [
"def",
"trap_signals",
"Signal",
".",
"trap",
"(",
"'QUIT'",
")",
"{",
"shut_down",
"}",
"Signal",
".",
"trap",
"(",
"'INT'",
")",
"{",
"shut_down",
"}",
"Signal",
".",
"trap",
"(",
"'TERM'",
")",
"{",
"shut_down",
"}",
"end"
] | Trap exit signals in order to shut down cleanly. | [
"Trap",
"exit",
"signals",
"in",
"order",
"to",
"shut",
"down",
"cleanly",
"."
] | a66172eabc6cb526b27be2bb821e2ea4258c82d4 | https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/node.rb#L236-L240 | train |
rob-murray/jekyll-twitter-plugin | lib/jekyll-twitter-plugin.rb | TwitterJekyll.ApiClient.fetch | def fetch(api_request)
uri = api_request.to_uri
response = Net::HTTP.start(uri.host, use_ssl: api_request.ssl?) do |http|
http.read_timeout = 5
http.open_timeout = 5
http.get uri.request_uri, REQUEST_HEADERS
end
handle_response(api_request, response)
rescue Timeout:... | ruby | def fetch(api_request)
uri = api_request.to_uri
response = Net::HTTP.start(uri.host, use_ssl: api_request.ssl?) do |http|
http.read_timeout = 5
http.open_timeout = 5
http.get uri.request_uri, REQUEST_HEADERS
end
handle_response(api_request, response)
rescue Timeout:... | [
"def",
"fetch",
"(",
"api_request",
")",
"uri",
"=",
"api_request",
".",
"to_uri",
"response",
"=",
"Net",
"::",
"HTTP",
".",
"start",
"(",
"uri",
".",
"host",
",",
"use_ssl",
":",
"api_request",
".",
"ssl?",
")",
"do",
"|",
"http",
"|",
"http",
".",... | Perform API request; return hash with html content | [
"Perform",
"API",
"request",
";",
"return",
"hash",
"with",
"html",
"content"
] | 6f6aa9466c9da5effa72ff24730599bc574285bc | https://github.com/rob-murray/jekyll-twitter-plugin/blob/6f6aa9466c9da5effa72ff24730599bc574285bc/lib/jekyll-twitter-plugin.rb#L71-L83 | train |
rob-murray/jekyll-twitter-plugin | lib/jekyll-twitter-plugin.rb | TwitterJekyll.TwitterTag.live_response | def live_response
if response = api_client.fetch(@api_request)
cache.write(@api_request.cache_key, response)
build_response(response)
end
end | ruby | def live_response
if response = api_client.fetch(@api_request)
cache.write(@api_request.cache_key, response)
build_response(response)
end
end | [
"def",
"live_response",
"if",
"response",
"=",
"api_client",
".",
"fetch",
"(",
"@api_request",
")",
"cache",
".",
"write",
"(",
"@api_request",
".",
"cache_key",
",",
"response",
")",
"build_response",
"(",
"response",
")",
"end",
"end"
] | Return response from API and write to cache
@api private | [
"Return",
"response",
"from",
"API",
"and",
"write",
"to",
"cache"
] | 6f6aa9466c9da5effa72ff24730599bc574285bc | https://github.com/rob-murray/jekyll-twitter-plugin/blob/6f6aa9466c9da5effa72ff24730599bc574285bc/lib/jekyll-twitter-plugin.rb#L188-L193 | train |
rob-murray/jekyll-twitter-plugin | lib/jekyll-twitter-plugin.rb | TwitterJekyll.TwitterTag.parse_params | def parse_params(params)
args = params.split(/\s+/).map(&:strip)
invalid_args!(args) unless args.any?
if args[0].to_s == OEMBED_ARG # TODO: remove after deprecation cycle
arguments_deprecation_warning(args)
args.shift
end
url, *api_args = args
ApiRequest.new(url, pa... | ruby | def parse_params(params)
args = params.split(/\s+/).map(&:strip)
invalid_args!(args) unless args.any?
if args[0].to_s == OEMBED_ARG # TODO: remove after deprecation cycle
arguments_deprecation_warning(args)
args.shift
end
url, *api_args = args
ApiRequest.new(url, pa... | [
"def",
"parse_params",
"(",
"params",
")",
"args",
"=",
"params",
".",
"split",
"(",
"/",
"\\s",
"/",
")",
".",
"map",
"(",
"&",
":strip",
")",
"invalid_args!",
"(",
"args",
")",
"unless",
"args",
".",
"any?",
"if",
"args",
"[",
"0",
"]",
".",
"t... | Return an `ApiRequest` with the url and arguments
@api private | [
"Return",
"an",
"ApiRequest",
"with",
"the",
"url",
"and",
"arguments"
] | 6f6aa9466c9da5effa72ff24730599bc574285bc | https://github.com/rob-murray/jekyll-twitter-plugin/blob/6f6aa9466c9da5effa72ff24730599bc574285bc/lib/jekyll-twitter-plugin.rb#L204-L215 | train |
michaelherold/interactor-contracts | lib/interactor/contracts.rb | Interactor.Contracts.enforce_contracts | def enforce_contracts(contracts)
outcome = contracts.call(context)
unless outcome.success?
contract.consequences.each do |handler|
instance_exec(outcome.breaches, &handler)
end
end
end | ruby | def enforce_contracts(contracts)
outcome = contracts.call(context)
unless outcome.success?
contract.consequences.each do |handler|
instance_exec(outcome.breaches, &handler)
end
end
end | [
"def",
"enforce_contracts",
"(",
"contracts",
")",
"outcome",
"=",
"contracts",
".",
"call",
"(",
"context",
")",
"unless",
"outcome",
".",
"success?",
"contract",
".",
"consequences",
".",
"each",
"do",
"|",
"handler",
"|",
"instance_exec",
"(",
"outcome",
... | Checks for a breach of contract and applies consequences for a breach
@api private
@param [#call] contracts a callable object
@return [void] | [
"Checks",
"for",
"a",
"breach",
"of",
"contract",
"and",
"applies",
"consequences",
"for",
"a",
"breach"
] | 75b7a98e89d8bc4682ed8fd71143437f00a83496 | https://github.com/michaelherold/interactor-contracts/blob/75b7a98e89d8bc4682ed8fd71143437f00a83496/lib/interactor/contracts.rb#L37-L45 | train |
liveh2o/active_remote | lib/active_remote/persistence.rb | ActiveRemote.Persistence.remote | def remote(endpoint, request_args = scope_key_hash)
response = remote_call(endpoint, request_args)
assign_attributes_from_rpc(response)
success?
end | ruby | def remote(endpoint, request_args = scope_key_hash)
response = remote_call(endpoint, request_args)
assign_attributes_from_rpc(response)
success?
end | [
"def",
"remote",
"(",
"endpoint",
",",
"request_args",
"=",
"scope_key_hash",
")",
"response",
"=",
"remote_call",
"(",
"endpoint",
",",
"request_args",
")",
"assign_attributes_from_rpc",
"(",
"response",
")",
"success?",
"end"
] | Executes a remote call on the current object and serializes it's attributes and
errors from the response.
Defaults request args to the scope key hash (e.g., { guid: 'ABC-123' }) when none are given.
Returns false if the response contained errors; otherwise, returns true. | [
"Executes",
"a",
"remote",
"call",
"on",
"the",
"current",
"object",
"and",
"serializes",
"it",
"s",
"attributes",
"and",
"errors",
"from",
"the",
"response",
"."
] | 5939c8e9f8515d8600d59ab26932a0de31076674 | https://github.com/liveh2o/active_remote/blob/5939c8e9f8515d8600d59ab26932a0de31076674/lib/active_remote/persistence.rb#L167-L172 | train |
liveh2o/active_remote | lib/active_remote/attributes.rb | ActiveRemote.Attributes.read_attribute | def read_attribute(name)
name = name.to_s
if respond_to?(name)
attribute(name)
else
raise ::ActiveRemote::UnknownAttributeError, "unknown attribute: #{name}"
end
end | ruby | def read_attribute(name)
name = name.to_s
if respond_to?(name)
attribute(name)
else
raise ::ActiveRemote::UnknownAttributeError, "unknown attribute: #{name}"
end
end | [
"def",
"read_attribute",
"(",
"name",
")",
"name",
"=",
"name",
".",
"to_s",
"if",
"respond_to?",
"(",
"name",
")",
"attribute",
"(",
"name",
")",
"else",
"raise",
"::",
"ActiveRemote",
"::",
"UnknownAttributeError",
",",
"\"unknown attribute: #{name}\"",
"end",... | Read attribute from the attributes hash | [
"Read",
"attribute",
"from",
"the",
"attributes",
"hash"
] | 5939c8e9f8515d8600d59ab26932a0de31076674 | https://github.com/liveh2o/active_remote/blob/5939c8e9f8515d8600d59ab26932a0de31076674/lib/active_remote/attributes.rb#L39-L47 | train |
liveh2o/active_remote | lib/active_remote/attributes.rb | ActiveRemote.Attributes.write_attribute | def write_attribute(name, value)
name = name.to_s
if respond_to?("#{name}=")
__send__("attribute=", name, value)
else
raise ::ActiveRemote::UnknownAttributeError, "unknown attribute: #{name}"
end
end | ruby | def write_attribute(name, value)
name = name.to_s
if respond_to?("#{name}=")
__send__("attribute=", name, value)
else
raise ::ActiveRemote::UnknownAttributeError, "unknown attribute: #{name}"
end
end | [
"def",
"write_attribute",
"(",
"name",
",",
"value",
")",
"name",
"=",
"name",
".",
"to_s",
"if",
"respond_to?",
"(",
"\"#{name}=\"",
")",
"__send__",
"(",
"\"attribute=\"",
",",
"name",
",",
"value",
")",
"else",
"raise",
"::",
"ActiveRemote",
"::",
"Unkn... | Update an attribute in the attributes hash | [
"Update",
"an",
"attribute",
"in",
"the",
"attributes",
"hash"
] | 5939c8e9f8515d8600d59ab26932a0de31076674 | https://github.com/liveh2o/active_remote/blob/5939c8e9f8515d8600d59ab26932a0de31076674/lib/active_remote/attributes.rb#L52-L60 | train |
liveh2o/active_remote | lib/active_remote/serialization.rb | ActiveRemote.Serialization.add_errors | def add_errors(errors)
errors.each do |error|
if error.respond_to?(:message)
self.errors.add(error.field, error.message)
elsif error.respond_to?(:messages)
error.messages.each do |message|
self.errors.add(error.field, message)
end
end
end
... | ruby | def add_errors(errors)
errors.each do |error|
if error.respond_to?(:message)
self.errors.add(error.field, error.message)
elsif error.respond_to?(:messages)
error.messages.each do |message|
self.errors.add(error.field, message)
end
end
end
... | [
"def",
"add_errors",
"(",
"errors",
")",
"errors",
".",
"each",
"do",
"|",
"error",
"|",
"if",
"error",
".",
"respond_to?",
"(",
":message",
")",
"self",
".",
"errors",
".",
"add",
"(",
"error",
".",
"field",
",",
"error",
".",
"message",
")",
"elsif... | Add the given errors to our internal errors list
====Examples
response = remote_call(:action_that_returns_errors, { :stuff => 'foo' })
add_errors(response.errors) | [
"Add",
"the",
"given",
"errors",
"to",
"our",
"internal",
"errors",
"list"
] | 5939c8e9f8515d8600d59ab26932a0de31076674 | https://github.com/liveh2o/active_remote/blob/5939c8e9f8515d8600d59ab26932a0de31076674/lib/active_remote/serialization.rb#L35-L45 | train |
liveh2o/active_remote | lib/active_remote/integration.rb | ActiveRemote.Integration.cache_key | def cache_key
case
when new_record? then
"#{self.class.name.underscore}/new"
when ::ActiveRemote.config.default_cache_key_updated_at? && (timestamp = self[:updated_at]) then
timestamp = timestamp.utc.to_s(self.class.cache_timestamp_format)
"#{self.class.name.underscore}/#{self.... | ruby | def cache_key
case
when new_record? then
"#{self.class.name.underscore}/new"
when ::ActiveRemote.config.default_cache_key_updated_at? && (timestamp = self[:updated_at]) then
timestamp = timestamp.utc.to_s(self.class.cache_timestamp_format)
"#{self.class.name.underscore}/#{self.... | [
"def",
"cache_key",
"case",
"when",
"new_record?",
"then",
"\"#{self.class.name.underscore}/new\"",
"when",
"::",
"ActiveRemote",
".",
"config",
".",
"default_cache_key_updated_at?",
"&&",
"(",
"timestamp",
"=",
"self",
"[",
":updated_at",
"]",
")",
"then",
"timestamp... | Returns a cache key that can be used to identify this record.
==== Examples
Product.new.cache_key # => "products/new"
Person.search(:guid => "derp-5").cache_key # => "people/derp-5-20071224150000" (include updated_at)
Product.search(:guid => "derp-5").cache_key # => "products/derp-5" | [
"Returns",
"a",
"cache",
"key",
"that",
"can",
"be",
"used",
"to",
"identify",
"this",
"record",
"."
] | 5939c8e9f8515d8600d59ab26932a0de31076674 | https://github.com/liveh2o/active_remote/blob/5939c8e9f8515d8600d59ab26932a0de31076674/lib/active_remote/integration.rb#L39-L49 | train |
msg7086/rb1drv | lib/rb1drv/onedrive_file.rb | Rb1drv.OneDriveFile.save_as | def save_as(target_name=nil, overwrite: false, resume: true, &block)
target_name ||= @name
tmpfile = "#{target_name}.incomplete"
return if !overwrite && File.exist?(target_name)
if resume && File.size(tmpfile) > 0
from = File.size(tmpfile)
len = @size - from
fmode = 'ab... | ruby | def save_as(target_name=nil, overwrite: false, resume: true, &block)
target_name ||= @name
tmpfile = "#{target_name}.incomplete"
return if !overwrite && File.exist?(target_name)
if resume && File.size(tmpfile) > 0
from = File.size(tmpfile)
len = @size - from
fmode = 'ab... | [
"def",
"save_as",
"(",
"target_name",
"=",
"nil",
",",
"overwrite",
":",
"false",
",",
"resume",
":",
"true",
",",
"&",
"block",
")",
"target_name",
"||=",
"@name",
"tmpfile",
"=",
"\"#{target_name}.incomplete\"",
"return",
"if",
"!",
"overwrite",
"&&",
"Fil... | Saves current remote file as local file.
Unfinished download is stored as +target_name.incomplete+ and renamed upon completion.
@param target_name [String] desired local filename, a relative path to current directory or an absolute path
@param overwrite [Boolean] whether to overwrite local file, or skip this
@par... | [
"Saves",
"current",
"remote",
"file",
"as",
"local",
"file",
"."
] | 090429252cd0a0d13bbbdfb2bffdf99e3921c893 | https://github.com/msg7086/rb1drv/blob/090429252cd0a0d13bbbdfb2bffdf99e3921c893/lib/rb1drv/onedrive_file.rb#L30-L59 | train |
msg7086/rb1drv | lib/rb1drv/onedrive_file.rb | Rb1drv.OneDriveFile.set_mtime | def set_mtime(time)
attempt = 0
OneDriveFile.new(@od, @od.request(api_path, {fileSystemInfo: {lastModifiedDateTime: time.utc.iso8601}}, :patch))
rescue
sleep 10
attempt += 1
retry if attempt <= 3
end | ruby | def set_mtime(time)
attempt = 0
OneDriveFile.new(@od, @od.request(api_path, {fileSystemInfo: {lastModifiedDateTime: time.utc.iso8601}}, :patch))
rescue
sleep 10
attempt += 1
retry if attempt <= 3
end | [
"def",
"set_mtime",
"(",
"time",
")",
"attempt",
"=",
"0",
"OneDriveFile",
".",
"new",
"(",
"@od",
",",
"@od",
".",
"request",
"(",
"api_path",
",",
"{",
"fileSystemInfo",
":",
"{",
"lastModifiedDateTime",
":",
"time",
".",
"utc",
".",
"iso8601",
"}",
... | Change last modified time for a remote file.
NOTICE: OneDrive by default keeps multiple history version for this operation.
NOTICE: You must turn off versioning to prevent multiple counts on disk quota.
3 attempts will be made due to delay after a file upload.
@param time [Time] desired last modified time
@retu... | [
"Change",
"last",
"modified",
"time",
"for",
"a",
"remote",
"file",
"."
] | 090429252cd0a0d13bbbdfb2bffdf99e3921c893 | https://github.com/msg7086/rb1drv/blob/090429252cd0a0d13bbbdfb2bffdf99e3921c893/lib/rb1drv/onedrive_file.rb#L70-L77 | train |
msg7086/rb1drv | lib/rb1drv.rb | Rb1drv.OneDrive.request | def request(uri, data=nil, verb=:post)
@logger.info(uri) if @logger
auth_check
query = {
path: File.join('v1.0/me/', URI.escape(uri)),
headers: {
'Authorization': "Bearer #{@access_token.token}"
}
}
if data
query[:body] = JSON.generate(data)
... | ruby | def request(uri, data=nil, verb=:post)
@logger.info(uri) if @logger
auth_check
query = {
path: File.join('v1.0/me/', URI.escape(uri)),
headers: {
'Authorization': "Bearer #{@access_token.token}"
}
}
if data
query[:body] = JSON.generate(data)
... | [
"def",
"request",
"(",
"uri",
",",
"data",
"=",
"nil",
",",
"verb",
"=",
":post",
")",
"@logger",
".",
"info",
"(",
"uri",
")",
"if",
"@logger",
"auth_check",
"query",
"=",
"{",
"path",
":",
"File",
".",
"join",
"(",
"'v1.0/me/'",
",",
"URI",
".",
... | Instanciates with app id and secret.
Issues requests to API endpoint.
@param uri [String] relative path of the API
@param data [Hash] JSON data to be post
@param verb [Symbol] HTTP request verb if data is given
@return [Hash] response from API. | [
"Instanciates",
"with",
"app",
"id",
"and",
"secret",
".",
"Issues",
"requests",
"to",
"API",
"endpoint",
"."
] | 090429252cd0a0d13bbbdfb2bffdf99e3921c893 | https://github.com/msg7086/rb1drv/blob/090429252cd0a0d13bbbdfb2bffdf99e3921c893/lib/rb1drv.rb#L31-L50 | train |
msg7086/rb1drv | lib/rb1drv/onedrive_dir.rb | Rb1drv.OneDriveDir.get_child | def get_child(path)
children.find { |child| child.name == path } || OneDrive404.new
end | ruby | def get_child(path)
children.find { |child| child.name == path } || OneDrive404.new
end | [
"def",
"get_child",
"(",
"path",
")",
"children",
".",
"find",
"{",
"|",
"child",
"|",
"child",
".",
"name",
"==",
"path",
"}",
"||",
"OneDrive404",
".",
"new",
"end"
] | Get a child object by name inside current directory.
@param path [String] name of a child
@return [OneDriveDir,OneDriveFile,OneDrive404] the drive item you asked | [
"Get",
"a",
"child",
"object",
"by",
"name",
"inside",
"current",
"directory",
"."
] | 090429252cd0a0d13bbbdfb2bffdf99e3921c893 | https://github.com/msg7086/rb1drv/blob/090429252cd0a0d13bbbdfb2bffdf99e3921c893/lib/rb1drv/onedrive_dir.rb#L30-L32 | train |
msg7086/rb1drv | lib/rb1drv/onedrive_dir.rb | Rb1drv.OneDriveDir.mkdir | def mkdir(name)
return self if name == '.'
name = name[1..-1] if name[0] == '/'
newdir, *remainder = name.split('/')
subdir = get(newdir)
unless subdir.dir?
result = @od.request("#{api_path}/children",
name: newdir,
folder: {},
'@microsoft.graph.confli... | ruby | def mkdir(name)
return self if name == '.'
name = name[1..-1] if name[0] == '/'
newdir, *remainder = name.split('/')
subdir = get(newdir)
unless subdir.dir?
result = @od.request("#{api_path}/children",
name: newdir,
folder: {},
'@microsoft.graph.confli... | [
"def",
"mkdir",
"(",
"name",
")",
"return",
"self",
"if",
"name",
"==",
"'.'",
"name",
"=",
"name",
"[",
"1",
"..",
"-",
"1",
"]",
"if",
"name",
"[",
"0",
"]",
"==",
"'/'",
"newdir",
",",
"*",
"remainder",
"=",
"name",
".",
"split",
"(",
"'/'",... | Recursively creates empty directories.
@param name [String] directories you'd like to create
@return [OneDriveDir] the directory you created | [
"Recursively",
"creates",
"empty",
"directories",
"."
] | 090429252cd0a0d13bbbdfb2bffdf99e3921c893 | https://github.com/msg7086/rb1drv/blob/090429252cd0a0d13bbbdfb2bffdf99e3921c893/lib/rb1drv/onedrive_dir.rb#L71-L85 | train |
msg7086/rb1drv | lib/rb1drv/onedrive_dir.rb | Rb1drv.OneDriveDir.upload_simple | def upload_simple(filename, overwrite:, target_name:)
target_file = get(target_name)
exist = target_file.file?
return if exist && !overwrite
path = nil
if exist
path = "#{target_file.api_path}/content"
else
path = "#{api_path}:/#{target_name}:/content"
end
... | ruby | def upload_simple(filename, overwrite:, target_name:)
target_file = get(target_name)
exist = target_file.file?
return if exist && !overwrite
path = nil
if exist
path = "#{target_file.api_path}/content"
else
path = "#{api_path}:/#{target_name}:/content"
end
... | [
"def",
"upload_simple",
"(",
"filename",
",",
"overwrite",
":",
",",
"target_name",
":",
")",
"target_file",
"=",
"get",
"(",
"target_name",
")",
"exist",
"=",
"target_file",
".",
"file?",
"return",
"if",
"exist",
"&&",
"!",
"overwrite",
"path",
"=",
"nil"... | Uploads a local file into current remote directory using simple upload mode.
@return [OneDriveFile,nil] uploaded file | [
"Uploads",
"a",
"local",
"file",
"into",
"current",
"remote",
"directory",
"using",
"simple",
"upload",
"mode",
"."
] | 090429252cd0a0d13bbbdfb2bffdf99e3921c893 | https://github.com/msg7086/rb1drv/blob/090429252cd0a0d13bbbdfb2bffdf99e3921c893/lib/rb1drv/onedrive_dir.rb#L206-L229 | train |
jugyo/eeepub | lib/eeepub/ocf.rb | EeePub.OCF.save | def save(output_path)
output_path = File.expand_path(output_path)
create_epub do
mimetype = Zip::ZipOutputStream::open(output_path) do |os|
os.put_next_entry("mimetype", nil, nil, Zip::ZipEntry::STORED, Zlib::NO_COMPRESSION)
os << "application/epub+zip"
end
zipfi... | ruby | def save(output_path)
output_path = File.expand_path(output_path)
create_epub do
mimetype = Zip::ZipOutputStream::open(output_path) do |os|
os.put_next_entry("mimetype", nil, nil, Zip::ZipEntry::STORED, Zlib::NO_COMPRESSION)
os << "application/epub+zip"
end
zipfi... | [
"def",
"save",
"(",
"output_path",
")",
"output_path",
"=",
"File",
".",
"expand_path",
"(",
"output_path",
")",
"create_epub",
"do",
"mimetype",
"=",
"Zip",
"::",
"ZipOutputStream",
"::",
"open",
"(",
"output_path",
")",
"do",
"|",
"os",
"|",
"os",
".",
... | Save as OCF
@param [String] output_path the output file path of ePub | [
"Save",
"as",
"OCF"
] | e120406d599d1ca27927e106c02caf3e14ff3976 | https://github.com/jugyo/eeepub/blob/e120406d599d1ca27927e106c02caf3e14ff3976/lib/eeepub/ocf.rb#L91-L106 | train |
jugyo/eeepub | lib/eeepub/container_item.rb | EeePub.ContainerItem.to_xml | def to_xml
out = ""
builder = Builder::XmlMarkup.new(:target => out, :indent => 2)
builder.instruct!
build_xml(builder)
out
end | ruby | def to_xml
out = ""
builder = Builder::XmlMarkup.new(:target => out, :indent => 2)
builder.instruct!
build_xml(builder)
out
end | [
"def",
"to_xml",
"out",
"=",
"\"\"",
"builder",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"(",
":target",
"=>",
"out",
",",
":indent",
"=>",
"2",
")",
"builder",
".",
"instruct!",
"build_xml",
"(",
"builder",
")",
"out",
"end"
] | Convert to xml of container item
@return [String] the xml of container item | [
"Convert",
"to",
"xml",
"of",
"container",
"item"
] | e120406d599d1ca27927e106c02caf3e14ff3976 | https://github.com/jugyo/eeepub/blob/e120406d599d1ca27927e106c02caf3e14ff3976/lib/eeepub/container_item.rb#L51-L57 | train |
jugyo/eeepub | lib/eeepub/container_item.rb | EeePub.ContainerItem.convert_to_xml_attributes | def convert_to_xml_attributes(hash)
result = {}
hash.each do |k, v|
key = k.to_s.gsub('_', '-').to_sym
result[key] = v
end
result
end | ruby | def convert_to_xml_attributes(hash)
result = {}
hash.each do |k, v|
key = k.to_s.gsub('_', '-').to_sym
result[key] = v
end
result
end | [
"def",
"convert_to_xml_attributes",
"(",
"hash",
")",
"result",
"=",
"{",
"}",
"hash",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"key",
"=",
"k",
".",
"to_s",
".",
"gsub",
"(",
"'_'",
",",
"'-'",
")",
".",
"to_sym",
"result",
"[",
"key",
"]",
... | Convert options for xml attributes
@param [Hash<Symbol, Object>] hash the hash of symbols and objects for xml attributes
@return [Hash<String, Object>] the options for xml attributes | [
"Convert",
"options",
"for",
"xml",
"attributes"
] | e120406d599d1ca27927e106c02caf3e14ff3976 | https://github.com/jugyo/eeepub/blob/e120406d599d1ca27927e106c02caf3e14ff3976/lib/eeepub/container_item.rb#L99-L106 | train |
chaintope/bitcoinrb | lib/bitcoin/tx.rb | Bitcoin.Tx.witness_commitment | def witness_commitment
return nil unless coinbase_tx?
outputs.each do |output|
commitment = output.script_pubkey.witness_commitment
return commitment if commitment
end
nil
end | ruby | def witness_commitment
return nil unless coinbase_tx?
outputs.each do |output|
commitment = output.script_pubkey.witness_commitment
return commitment if commitment
end
nil
end | [
"def",
"witness_commitment",
"return",
"nil",
"unless",
"coinbase_tx?",
"outputs",
".",
"each",
"do",
"|",
"output",
"|",
"commitment",
"=",
"output",
".",
"script_pubkey",
".",
"witness_commitment",
"return",
"commitment",
"if",
"commitment",
"end",
"nil",
"end"
... | get the witness commitment of coinbase tx.
if this tx does not coinbase or not have commitment, return nil. | [
"get",
"the",
"witness",
"commitment",
"of",
"coinbase",
"tx",
".",
"if",
"this",
"tx",
"does",
"not",
"coinbase",
"or",
"not",
"have",
"commitment",
"return",
"nil",
"."
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L94-L101 | train |
chaintope/bitcoinrb | lib/bitcoin/tx.rb | Bitcoin.Tx.serialize_old_format | def serialize_old_format
buf = [version].pack('V')
buf << Bitcoin.pack_var_int(inputs.length) << inputs.map(&:to_payload).join
buf << Bitcoin.pack_var_int(outputs.length) << outputs.map(&:to_payload).join
buf << [lock_time].pack('V')
buf
end | ruby | def serialize_old_format
buf = [version].pack('V')
buf << Bitcoin.pack_var_int(inputs.length) << inputs.map(&:to_payload).join
buf << Bitcoin.pack_var_int(outputs.length) << outputs.map(&:to_payload).join
buf << [lock_time].pack('V')
buf
end | [
"def",
"serialize_old_format",
"buf",
"=",
"[",
"version",
"]",
".",
"pack",
"(",
"'V'",
")",
"buf",
"<<",
"Bitcoin",
".",
"pack_var_int",
"(",
"inputs",
".",
"length",
")",
"<<",
"inputs",
".",
"map",
"(",
"&",
":to_payload",
")",
".",
"join",
"buf",
... | serialize tx with old tx format | [
"serialize",
"tx",
"with",
"old",
"tx",
"format"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L120-L126 | train |
chaintope/bitcoinrb | lib/bitcoin/tx.rb | Bitcoin.Tx.standard? | def standard?
return false if version > MAX_STANDARD_VERSION
return false if weight > MAX_STANDARD_TX_WEIGHT
inputs.each do |i|
# Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed keys (remember the 520 byte limit on redeemScript size).
# That works out to a (15*(33+1... | ruby | def standard?
return false if version > MAX_STANDARD_VERSION
return false if weight > MAX_STANDARD_TX_WEIGHT
inputs.each do |i|
# Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed keys (remember the 520 byte limit on redeemScript size).
# That works out to a (15*(33+1... | [
"def",
"standard?",
"return",
"false",
"if",
"version",
">",
"MAX_STANDARD_VERSION",
"return",
"false",
"if",
"weight",
">",
"MAX_STANDARD_TX_WEIGHT",
"inputs",
".",
"each",
"do",
"|",
"i",
"|",
"return",
"false",
"if",
"i",
".",
"script_sig",
".",
"size",
"... | check this tx is standard. | [
"check",
"this",
"tx",
"is",
"standard",
"."
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L143-L163 | train |
chaintope/bitcoinrb | lib/bitcoin/tx.rb | Bitcoin.Tx.sighash_for_input | def sighash_for_input(input_index, output_script, hash_type: SIGHASH_TYPE[:all],
sig_version: :base, amount: nil, skip_separator_index: 0)
raise ArgumentError, 'input_index must be specified.' unless input_index
raise ArgumentError, 'does not exist input corresponding to input_inde... | ruby | def sighash_for_input(input_index, output_script, hash_type: SIGHASH_TYPE[:all],
sig_version: :base, amount: nil, skip_separator_index: 0)
raise ArgumentError, 'input_index must be specified.' unless input_index
raise ArgumentError, 'does not exist input corresponding to input_inde... | [
"def",
"sighash_for_input",
"(",
"input_index",
",",
"output_script",
",",
"hash_type",
":",
"SIGHASH_TYPE",
"[",
":all",
"]",
",",
"sig_version",
":",
":base",
",",
"amount",
":",
"nil",
",",
"skip_separator_index",
":",
"0",
")",
"raise",
"ArgumentError",
",... | get signature hash
@param [Integer] input_index input index.
@param [Integer] hash_type signature hash type
@param [Bitcoin::Script] output_script script pubkey or script code. if script pubkey is P2WSH, set witness script to this.
@param [Integer] amount bitcoin amount locked in input. required for witness input o... | [
"get",
"signature",
"hash"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L192-L205 | train |
chaintope/bitcoinrb | lib/bitcoin/tx.rb | Bitcoin.Tx.verify_input_sig | def verify_input_sig(input_index, script_pubkey, amount: nil, flags: STANDARD_SCRIPT_VERIFY_FLAGS)
script_sig = inputs[input_index].script_sig
has_witness = inputs[input_index].has_witness?
if script_pubkey.p2sh?
flags << SCRIPT_VERIFY_P2SH
redeem_script = Script.parse_from_payload(sc... | ruby | def verify_input_sig(input_index, script_pubkey, amount: nil, flags: STANDARD_SCRIPT_VERIFY_FLAGS)
script_sig = inputs[input_index].script_sig
has_witness = inputs[input_index].has_witness?
if script_pubkey.p2sh?
flags << SCRIPT_VERIFY_P2SH
redeem_script = Script.parse_from_payload(sc... | [
"def",
"verify_input_sig",
"(",
"input_index",
",",
"script_pubkey",
",",
"amount",
":",
"nil",
",",
"flags",
":",
"STANDARD_SCRIPT_VERIFY_FLAGS",
")",
"script_sig",
"=",
"inputs",
"[",
"input_index",
"]",
".",
"script_sig",
"has_witness",
"=",
"inputs",
"[",
"i... | verify input signature.
@param [Integer] input_index
@param [Bitcoin::Script] script_pubkey the script pubkey for target input.
@param [Integer] amount the amount of bitcoin, require for witness program only.
@param [Array] flags the flags used when execute script interpreter. | [
"verify",
"input",
"signature",
"."
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L212-L227 | train |
chaintope/bitcoinrb | lib/bitcoin/tx.rb | Bitcoin.Tx.sighash_for_legacy | def sighash_for_legacy(index, script_code, hash_type)
ins = inputs.map.with_index do |i, idx|
if idx == index
i.to_payload(script_code.delete_opcode(Bitcoin::Opcodes::OP_CODESEPARATOR))
else
case hash_type & 0x1f
when SIGHASH_TYPE[:none], SIGHASH_TYPE[:single]
... | ruby | def sighash_for_legacy(index, script_code, hash_type)
ins = inputs.map.with_index do |i, idx|
if idx == index
i.to_payload(script_code.delete_opcode(Bitcoin::Opcodes::OP_CODESEPARATOR))
else
case hash_type & 0x1f
when SIGHASH_TYPE[:none], SIGHASH_TYPE[:single]
... | [
"def",
"sighash_for_legacy",
"(",
"index",
",",
"script_code",
",",
"hash_type",
")",
"ins",
"=",
"inputs",
".",
"map",
".",
"with_index",
"do",
"|",
"i",
",",
"idx",
"|",
"if",
"idx",
"==",
"index",
"i",
".",
"to_payload",
"(",
"script_code",
".",
"de... | generate sighash with legacy format | [
"generate",
"sighash",
"with",
"legacy",
"format"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L239-L274 | train |
chaintope/bitcoinrb | lib/bitcoin/tx.rb | Bitcoin.Tx.verify_input_sig_for_legacy | def verify_input_sig_for_legacy(input_index, script_pubkey, flags)
script_sig = inputs[input_index].script_sig
checker = Bitcoin::TxChecker.new(tx: self, input_index: input_index)
interpreter = Bitcoin::ScriptInterpreter.new(checker: checker, flags: flags)
interpreter.verify_script(script_sig, ... | ruby | def verify_input_sig_for_legacy(input_index, script_pubkey, flags)
script_sig = inputs[input_index].script_sig
checker = Bitcoin::TxChecker.new(tx: self, input_index: input_index)
interpreter = Bitcoin::ScriptInterpreter.new(checker: checker, flags: flags)
interpreter.verify_script(script_sig, ... | [
"def",
"verify_input_sig_for_legacy",
"(",
"input_index",
",",
"script_pubkey",
",",
"flags",
")",
"script_sig",
"=",
"inputs",
"[",
"input_index",
"]",
".",
"script_sig",
"checker",
"=",
"Bitcoin",
"::",
"TxChecker",
".",
"new",
"(",
"tx",
":",
"self",
",",
... | verify input signature for legacy tx. | [
"verify",
"input",
"signature",
"for",
"legacy",
"tx",
"."
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L306-L312 | train |
chaintope/bitcoinrb | lib/bitcoin/tx.rb | Bitcoin.Tx.verify_input_sig_for_witness | def verify_input_sig_for_witness(input_index, script_pubkey, amount, flags)
flags |= SCRIPT_VERIFY_WITNESS
flags |= SCRIPT_VERIFY_WITNESS_PUBKEYTYPE
checker = Bitcoin::TxChecker.new(tx: self, input_index: input_index, amount: amount)
interpreter = Bitcoin::ScriptInterpreter.new(checker: checker,... | ruby | def verify_input_sig_for_witness(input_index, script_pubkey, amount, flags)
flags |= SCRIPT_VERIFY_WITNESS
flags |= SCRIPT_VERIFY_WITNESS_PUBKEYTYPE
checker = Bitcoin::TxChecker.new(tx: self, input_index: input_index, amount: amount)
interpreter = Bitcoin::ScriptInterpreter.new(checker: checker,... | [
"def",
"verify_input_sig_for_witness",
"(",
"input_index",
",",
"script_pubkey",
",",
"amount",
",",
"flags",
")",
"flags",
"|=",
"SCRIPT_VERIFY_WITNESS",
"flags",
"|=",
"SCRIPT_VERIFY_WITNESS_PUBKEYTYPE",
"checker",
"=",
"Bitcoin",
"::",
"TxChecker",
".",
"new",
"(",... | verify input signature for witness tx. | [
"verify",
"input",
"signature",
"for",
"witness",
"tx",
"."
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L315-L325 | train |
chaintope/bitcoinrb | lib/bitcoin/ext_key.rb | Bitcoin.ExtKey.ext_pubkey | def ext_pubkey
k = ExtPubkey.new
k.depth = depth
k.number = number
k.parent_fingerprint = parent_fingerprint
k.chain_code = chain_code
k.pubkey = key.pubkey
k.ver = priv_ver_to_pub_ver
k
end | ruby | def ext_pubkey
k = ExtPubkey.new
k.depth = depth
k.number = number
k.parent_fingerprint = parent_fingerprint
k.chain_code = chain_code
k.pubkey = key.pubkey
k.ver = priv_ver_to_pub_ver
k
end | [
"def",
"ext_pubkey",
"k",
"=",
"ExtPubkey",
".",
"new",
"k",
".",
"depth",
"=",
"depth",
"k",
".",
"number",
"=",
"number",
"k",
".",
"parent_fingerprint",
"=",
"parent_fingerprint",
"k",
".",
"chain_code",
"=",
"chain_code",
"k",
".",
"pubkey",
"=",
"ke... | get ExtPubkey from priv_key | [
"get",
"ExtPubkey",
"from",
"priv_key"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L33-L42 | train |
chaintope/bitcoinrb | lib/bitcoin/ext_key.rb | Bitcoin.ExtKey.to_payload | def to_payload
version.htb << [depth].pack('C') << parent_fingerprint.htb <<
[number].pack('N') << chain_code << [0x00].pack('C') << key.priv_key.htb
end | ruby | def to_payload
version.htb << [depth].pack('C') << parent_fingerprint.htb <<
[number].pack('N') << chain_code << [0x00].pack('C') << key.priv_key.htb
end | [
"def",
"to_payload",
"version",
".",
"htb",
"<<",
"[",
"depth",
"]",
".",
"pack",
"(",
"'C'",
")",
"<<",
"parent_fingerprint",
".",
"htb",
"<<",
"[",
"number",
"]",
".",
"pack",
"(",
"'N'",
")",
"<<",
"chain_code",
"<<",
"[",
"0x00",
"]",
".",
"pac... | serialize extended private key | [
"serialize",
"extended",
"private",
"key"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L45-L48 | train |
chaintope/bitcoinrb | lib/bitcoin/ext_key.rb | Bitcoin.ExtKey.to_base58 | def to_base58
h = to_payload.bth
hex = h + Bitcoin.calc_checksum(h)
Base58.encode(hex)
end | ruby | def to_base58
h = to_payload.bth
hex = h + Bitcoin.calc_checksum(h)
Base58.encode(hex)
end | [
"def",
"to_base58",
"h",
"=",
"to_payload",
".",
"bth",
"hex",
"=",
"h",
"+",
"Bitcoin",
".",
"calc_checksum",
"(",
"h",
")",
"Base58",
".",
"encode",
"(",
"hex",
")",
"end"
] | Base58 encoded extended private key | [
"Base58",
"encoded",
"extended",
"private",
"key"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L51-L55 | train |
chaintope/bitcoinrb | lib/bitcoin/ext_key.rb | Bitcoin.ExtKey.derive | def derive(number, harden = false)
number += HARDENED_THRESHOLD if harden
new_key = ExtKey.new
new_key.depth = depth + 1
new_key.number = number
new_key.parent_fingerprint = fingerprint
if number > (HARDENED_THRESHOLD - 1)
data = [0x00].pack('C') << key.priv_key.htb << [numbe... | ruby | def derive(number, harden = false)
number += HARDENED_THRESHOLD if harden
new_key = ExtKey.new
new_key.depth = depth + 1
new_key.number = number
new_key.parent_fingerprint = fingerprint
if number > (HARDENED_THRESHOLD - 1)
data = [0x00].pack('C') << key.priv_key.htb << [numbe... | [
"def",
"derive",
"(",
"number",
",",
"harden",
"=",
"false",
")",
"number",
"+=",
"HARDENED_THRESHOLD",
"if",
"harden",
"new_key",
"=",
"ExtKey",
".",
"new",
"new_key",
".",
"depth",
"=",
"depth",
"+",
"1",
"new_key",
".",
"number",
"=",
"number",
"new_k... | derive new key
@param [Integer] number a child index
@param [Boolean] harden whether hardened key or not. If true, 2^31 is added to +number+.
@return [Bitcoin::ExtKey] derived new key. | [
"derive",
"new",
"key"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L95-L116 | train |
chaintope/bitcoinrb | lib/bitcoin/ext_key.rb | Bitcoin.ExtKey.priv_ver_to_pub_ver | def priv_ver_to_pub_ver
case version
when Bitcoin.chain_params.bip49_privkey_p2wpkh_p2sh_version
Bitcoin.chain_params.bip49_pubkey_p2wpkh_p2sh_version
when Bitcoin.chain_params.bip84_privkey_p2wpkh_version
Bitcoin.chain_params.bip84_pubkey_p2wpkh_version
else
... | ruby | def priv_ver_to_pub_ver
case version
when Bitcoin.chain_params.bip49_privkey_p2wpkh_p2sh_version
Bitcoin.chain_params.bip49_pubkey_p2wpkh_p2sh_version
when Bitcoin.chain_params.bip84_privkey_p2wpkh_version
Bitcoin.chain_params.bip84_pubkey_p2wpkh_version
else
... | [
"def",
"priv_ver_to_pub_ver",
"case",
"version",
"when",
"Bitcoin",
".",
"chain_params",
".",
"bip49_privkey_p2wpkh_p2sh_version",
"Bitcoin",
".",
"chain_params",
".",
"bip49_pubkey_p2wpkh_p2sh_version",
"when",
"Bitcoin",
".",
"chain_params",
".",
"bip84_privkey_p2wpkh_versi... | convert privkey version to pubkey version | [
"convert",
"privkey",
"version",
"to",
"pubkey",
"version"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L176-L185 | train |
chaintope/bitcoinrb | lib/bitcoin/ext_key.rb | Bitcoin.ExtPubkey.to_payload | def to_payload
version.htb << [depth].pack('C') <<
parent_fingerprint.htb << [number].pack('N') << chain_code << pub.htb
end | ruby | def to_payload
version.htb << [depth].pack('C') <<
parent_fingerprint.htb << [number].pack('N') << chain_code << pub.htb
end | [
"def",
"to_payload",
"version",
".",
"htb",
"<<",
"[",
"depth",
"]",
".",
"pack",
"(",
"'C'",
")",
"<<",
"parent_fingerprint",
".",
"htb",
"<<",
"[",
"number",
"]",
".",
"pack",
"(",
"'N'",
")",
"<<",
"chain_code",
"<<",
"pub",
".",
"htb",
"end"
] | serialize extended pubkey | [
"serialize",
"extended",
"pubkey"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L200-L203 | train |
chaintope/bitcoinrb | lib/bitcoin/ext_key.rb | Bitcoin.ExtPubkey.derive | def derive(number)
new_key = ExtPubkey.new
new_key.depth = depth + 1
new_key.number = number
new_key.parent_fingerprint = fingerprint
raise 'hardened key is not support' if number > (HARDENED_THRESHOLD - 1)
data = pub.htb << [number].pack('N')
l = Bitcoin.hmac_sha512(chain_code... | ruby | def derive(number)
new_key = ExtPubkey.new
new_key.depth = depth + 1
new_key.number = number
new_key.parent_fingerprint = fingerprint
raise 'hardened key is not support' if number > (HARDENED_THRESHOLD - 1)
data = pub.htb << [number].pack('N')
l = Bitcoin.hmac_sha512(chain_code... | [
"def",
"derive",
"(",
"number",
")",
"new_key",
"=",
"ExtPubkey",
".",
"new",
"new_key",
".",
"depth",
"=",
"depth",
"+",
"1",
"new_key",
".",
"number",
"=",
"number",
"new_key",
".",
"parent_fingerprint",
"=",
"fingerprint",
"raise",
"'hardened key is not sup... | derive child key | [
"derive",
"child",
"key"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L254-L270 | train |
chaintope/bitcoinrb | lib/bitcoin/script/script.rb | Bitcoin.Script.p2pkh? | def p2pkh?
return false unless chunks.size == 5
[OP_DUP, OP_HASH160, OP_EQUALVERIFY, OP_CHECKSIG] ==
(chunks[0..1]+ chunks[3..4]).map(&:ord) && chunks[2].bytesize == 21
end | ruby | def p2pkh?
return false unless chunks.size == 5
[OP_DUP, OP_HASH160, OP_EQUALVERIFY, OP_CHECKSIG] ==
(chunks[0..1]+ chunks[3..4]).map(&:ord) && chunks[2].bytesize == 21
end | [
"def",
"p2pkh?",
"return",
"false",
"unless",
"chunks",
".",
"size",
"==",
"5",
"[",
"OP_DUP",
",",
"OP_HASH160",
",",
"OP_EQUALVERIFY",
",",
"OP_CHECKSIG",
"]",
"==",
"(",
"chunks",
"[",
"0",
"..",
"1",
"]",
"+",
"chunks",
"[",
"3",
"..",
"4",
"]",
... | whether this script is a P2PKH format script. | [
"whether",
"this",
"script",
"is",
"a",
"P2PKH",
"format",
"script",
"."
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L169-L173 | train |
chaintope/bitcoinrb | lib/bitcoin/script/script.rb | Bitcoin.Script.push_only? | def push_only?
chunks.each do |c|
return false if !c.opcode.nil? && c.opcode > OP_16
end
true
end | ruby | def push_only?
chunks.each do |c|
return false if !c.opcode.nil? && c.opcode > OP_16
end
true
end | [
"def",
"push_only?",
"chunks",
".",
"each",
"do",
"|",
"c",
"|",
"return",
"false",
"if",
"!",
"c",
".",
"opcode",
".",
"nil?",
"&&",
"c",
".",
"opcode",
">",
"OP_16",
"end",
"true",
"end"
] | whether data push only script which dose not include other opcode | [
"whether",
"data",
"push",
"only",
"script",
"which",
"dose",
"not",
"include",
"other",
"opcode"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L215-L220 | train |
chaintope/bitcoinrb | lib/bitcoin/script/script.rb | Bitcoin.Script.witness_program? | def witness_program?
return false if size < 4 || size > 42 || chunks.size < 2
opcode = chunks[0].opcode
return false if opcode != OP_0 && (opcode < OP_1 || opcode > OP_16)
return false unless chunks[1].pushdata?
if size == (chunks[1][0].unpack('C').first + 2)
program_size = chun... | ruby | def witness_program?
return false if size < 4 || size > 42 || chunks.size < 2
opcode = chunks[0].opcode
return false if opcode != OP_0 && (opcode < OP_1 || opcode > OP_16)
return false unless chunks[1].pushdata?
if size == (chunks[1][0].unpack('C').first + 2)
program_size = chun... | [
"def",
"witness_program?",
"return",
"false",
"if",
"size",
"<",
"4",
"||",
"size",
">",
"42",
"||",
"chunks",
".",
"size",
"<",
"2",
"opcode",
"=",
"chunks",
"[",
"0",
"]",
".",
"opcode",
"return",
"false",
"if",
"opcode",
"!=",
"OP_0",
"&&",
"(",
... | A witness program is any valid Script that consists of a 1-byte push opcode followed by a data push between 2 and 40 bytes. | [
"A",
"witness",
"program",
"is",
"any",
"valid",
"Script",
"that",
"consists",
"of",
"a",
"1",
"-",
"byte",
"push",
"opcode",
"followed",
"by",
"a",
"data",
"push",
"between",
"2",
"and",
"40",
"bytes",
"."
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L223-L237 | train |
chaintope/bitcoinrb | lib/bitcoin/script/script.rb | Bitcoin.Script.witness_commitment | def witness_commitment
return nil if !op_return? || op_return_data.bytesize < 36
buf = StringIO.new(op_return_data)
return nil unless buf.read(4).bth == WITNESS_COMMITMENT_HEADER
buf.read(32).bth
end | ruby | def witness_commitment
return nil if !op_return? || op_return_data.bytesize < 36
buf = StringIO.new(op_return_data)
return nil unless buf.read(4).bth == WITNESS_COMMITMENT_HEADER
buf.read(32).bth
end | [
"def",
"witness_commitment",
"return",
"nil",
"if",
"!",
"op_return?",
"||",
"op_return_data",
".",
"bytesize",
"<",
"36",
"buf",
"=",
"StringIO",
".",
"new",
"(",
"op_return_data",
")",
"return",
"nil",
"unless",
"buf",
".",
"read",
"(",
"4",
")",
".",
... | get witness commitment | [
"get",
"witness",
"commitment"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L240-L245 | train |
chaintope/bitcoinrb | lib/bitcoin/script/script.rb | Bitcoin.Script.to_script_code | def to_script_code(skip_separator_index = 0)
payload = to_payload
if p2wpkh?
payload = Script.to_p2pkh(chunks[1].pushed_data.bth).to_payload
elsif skip_separator_index > 0
payload = subscript_codeseparator(skip_separator_index)
end
Bitcoin.pack_var_string(payload)
end | ruby | def to_script_code(skip_separator_index = 0)
payload = to_payload
if p2wpkh?
payload = Script.to_p2pkh(chunks[1].pushed_data.bth).to_payload
elsif skip_separator_index > 0
payload = subscript_codeseparator(skip_separator_index)
end
Bitcoin.pack_var_string(payload)
end | [
"def",
"to_script_code",
"(",
"skip_separator_index",
"=",
"0",
")",
"payload",
"=",
"to_payload",
"if",
"p2wpkh?",
"payload",
"=",
"Script",
".",
"to_p2pkh",
"(",
"chunks",
"[",
"1",
"]",
".",
"pushed_data",
".",
"bth",
")",
".",
"to_payload",
"elsif",
"s... | If this script is witness program, return its script code,
otherwise returns the self payload. ScriptInterpreter does not use this. | [
"If",
"this",
"script",
"is",
"witness",
"program",
"return",
"its",
"script",
"code",
"otherwise",
"returns",
"the",
"self",
"payload",
".",
"ScriptInterpreter",
"does",
"not",
"use",
"this",
"."
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L249-L257 | train |
chaintope/bitcoinrb | lib/bitcoin/script/script.rb | Bitcoin.Script.witness_data | def witness_data
version = opcode_to_small_int(chunks[0].opcode)
program = chunks[1].pushed_data
[version, program]
end | ruby | def witness_data
version = opcode_to_small_int(chunks[0].opcode)
program = chunks[1].pushed_data
[version, program]
end | [
"def",
"witness_data",
"version",
"=",
"opcode_to_small_int",
"(",
"chunks",
"[",
"0",
"]",
".",
"opcode",
")",
"program",
"=",
"chunks",
"[",
"1",
"]",
".",
"pushed_data",
"[",
"version",
",",
"program",
"]",
"end"
] | get witness version and witness program | [
"get",
"witness",
"version",
"and",
"witness",
"program"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L260-L264 | train |
chaintope/bitcoinrb | lib/bitcoin/script/script.rb | Bitcoin.Script.<< | def <<(obj)
if obj.is_a?(Integer)
push_int(obj)
elsif obj.is_a?(String)
append_data(obj)
elsif obj.is_a?(Array)
obj.each { |o| self.<< o}
self
end
end | ruby | def <<(obj)
if obj.is_a?(Integer)
push_int(obj)
elsif obj.is_a?(String)
append_data(obj)
elsif obj.is_a?(Array)
obj.each { |o| self.<< o}
self
end
end | [
"def",
"<<",
"(",
"obj",
")",
"if",
"obj",
".",
"is_a?",
"(",
"Integer",
")",
"push_int",
"(",
"obj",
")",
"elsif",
"obj",
".",
"is_a?",
"(",
"String",
")",
"append_data",
"(",
"obj",
")",
"elsif",
"obj",
".",
"is_a?",
"(",
"Array",
")",
"obj",
"... | append object to payload | [
"append",
"object",
"to",
"payload"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L267-L276 | train |
chaintope/bitcoinrb | lib/bitcoin/script/script.rb | Bitcoin.Script.append_opcode | def append_opcode(opcode)
opcode = Opcodes.small_int_to_opcode(opcode) if -1 <= opcode && opcode <= 16
raise ArgumentError, "specified invalid opcode #{opcode}." unless Opcodes.defined?(opcode)
chunks << opcode.chr
self
end | ruby | def append_opcode(opcode)
opcode = Opcodes.small_int_to_opcode(opcode) if -1 <= opcode && opcode <= 16
raise ArgumentError, "specified invalid opcode #{opcode}." unless Opcodes.defined?(opcode)
chunks << opcode.chr
self
end | [
"def",
"append_opcode",
"(",
"opcode",
")",
"opcode",
"=",
"Opcodes",
".",
"small_int_to_opcode",
"(",
"opcode",
")",
"if",
"-",
"1",
"<=",
"opcode",
"&&",
"opcode",
"<=",
"16",
"raise",
"ArgumentError",
",",
"\"specified invalid opcode #{opcode}.\"",
"unless",
... | append opcode to payload
@param [Integer] opcode append opcode which defined by Bitcoin::Opcodes
@return [Script] return self | [
"append",
"opcode",
"to",
"payload"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L291-L296 | train |
chaintope/bitcoinrb | lib/bitcoin/script/script.rb | Bitcoin.Script.append_data | def append_data(data)
data = Encoding::ASCII_8BIT == data.encoding ? data : data.htb
chunks << Bitcoin::Script.pack_pushdata(data)
self
end | ruby | def append_data(data)
data = Encoding::ASCII_8BIT == data.encoding ? data : data.htb
chunks << Bitcoin::Script.pack_pushdata(data)
self
end | [
"def",
"append_data",
"(",
"data",
")",
"data",
"=",
"Encoding",
"::",
"ASCII_8BIT",
"==",
"data",
".",
"encoding",
"?",
"data",
":",
"data",
".",
"htb",
"chunks",
"<<",
"Bitcoin",
"::",
"Script",
".",
"pack_pushdata",
"(",
"data",
")",
"self",
"end"
] | append data to payload with pushdata opcode
@param [String] data append data. this data is not binary
@return [Script] return self | [
"append",
"data",
"to",
"payload",
"with",
"pushdata",
"opcode"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L301-L305 | train |
chaintope/bitcoinrb | lib/bitcoin/script/script.rb | Bitcoin.Script.include? | def include?(item)
chunk_item = if item.is_a?(Integer)
item.chr
elsif item.is_a?(String)
data = Encoding::ASCII_8BIT == item.encoding ? item : item.htb
Bitcoin::Script.pack_pushdata(data)
end
return false un... | ruby | def include?(item)
chunk_item = if item.is_a?(Integer)
item.chr
elsif item.is_a?(String)
data = Encoding::ASCII_8BIT == item.encoding ? item : item.htb
Bitcoin::Script.pack_pushdata(data)
end
return false un... | [
"def",
"include?",
"(",
"item",
")",
"chunk_item",
"=",
"if",
"item",
".",
"is_a?",
"(",
"Integer",
")",
"item",
".",
"chr",
"elsif",
"item",
".",
"is_a?",
"(",
"String",
")",
"data",
"=",
"Encoding",
"::",
"ASCII_8BIT",
"==",
"item",
".",
"encoding",
... | Check the item is in the chunk of the script. | [
"Check",
"the",
"item",
"is",
"in",
"the",
"chunk",
"of",
"the",
"script",
"."
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L308-L317 | train |
chaintope/bitcoinrb | lib/bitcoin/script/script.rb | Bitcoin.Script.find_and_delete | def find_and_delete(subscript)
raise ArgumentError, 'subscript must be Bitcoin::Script' unless subscript.is_a?(Script)
return self if subscript.chunks.empty?
buf = []
i = 0
result = Script.new
chunks.each do |chunk|
sub_chunk = subscript.chunks[i]
if chunk.start_with?... | ruby | def find_and_delete(subscript)
raise ArgumentError, 'subscript must be Bitcoin::Script' unless subscript.is_a?(Script)
return self if subscript.chunks.empty?
buf = []
i = 0
result = Script.new
chunks.each do |chunk|
sub_chunk = subscript.chunks[i]
if chunk.start_with?... | [
"def",
"find_and_delete",
"(",
"subscript",
")",
"raise",
"ArgumentError",
",",
"'subscript must be Bitcoin::Script'",
"unless",
"subscript",
".",
"is_a?",
"(",
"Script",
")",
"return",
"self",
"if",
"subscript",
".",
"chunks",
".",
"empty?",
"buf",
"=",
"[",
"]... | removes chunks matching subscript byte-for-byte and returns as a new object. | [
"removes",
"chunks",
"matching",
"subscript",
"byte",
"-",
"for",
"-",
"byte",
"and",
"returns",
"as",
"a",
"new",
"object",
"."
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L422-L453 | train |
chaintope/bitcoinrb | lib/bitcoin/script/script.rb | Bitcoin.Script.subscript_codeseparator | def subscript_codeseparator(separator_index)
buf = []
process_separator_index = 0
chunks.each{|chunk|
buf << chunk if process_separator_index == separator_index
if chunk.ord == OP_CODESEPARATOR && process_separator_index < separator_index
process_separator_index += 1
... | ruby | def subscript_codeseparator(separator_index)
buf = []
process_separator_index = 0
chunks.each{|chunk|
buf << chunk if process_separator_index == separator_index
if chunk.ord == OP_CODESEPARATOR && process_separator_index < separator_index
process_separator_index += 1
... | [
"def",
"subscript_codeseparator",
"(",
"separator_index",
")",
"buf",
"=",
"[",
"]",
"process_separator_index",
"=",
"0",
"chunks",
".",
"each",
"{",
"|",
"chunk",
"|",
"buf",
"<<",
"chunk",
"if",
"process_separator_index",
"==",
"separator_index",
"if",
"chunk"... | Returns a script that deleted the script before the index specified by separator_index. | [
"Returns",
"a",
"script",
"that",
"deleted",
"the",
"script",
"before",
"the",
"index",
"specified",
"by",
"separator_index",
"."
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L462-L472 | train |
chaintope/bitcoinrb | lib/bitcoin/script/script.rb | Bitcoin.Script.p2pkh_addr | def p2pkh_addr
return nil unless p2pkh?
hash160 = chunks[2].pushed_data.bth
return nil unless hash160.htb.bytesize == 20
Bitcoin.encode_base58_address(hash160, Bitcoin.chain_params.address_version)
end | ruby | def p2pkh_addr
return nil unless p2pkh?
hash160 = chunks[2].pushed_data.bth
return nil unless hash160.htb.bytesize == 20
Bitcoin.encode_base58_address(hash160, Bitcoin.chain_params.address_version)
end | [
"def",
"p2pkh_addr",
"return",
"nil",
"unless",
"p2pkh?",
"hash160",
"=",
"chunks",
"[",
"2",
"]",
".",
"pushed_data",
".",
"bth",
"return",
"nil",
"unless",
"hash160",
".",
"htb",
".",
"bytesize",
"==",
"20",
"Bitcoin",
".",
"encode_base58_address",
"(",
... | generate p2pkh address. if script dose not p2pkh, return nil. | [
"generate",
"p2pkh",
"address",
".",
"if",
"script",
"dose",
"not",
"p2pkh",
"return",
"nil",
"."
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L501-L506 | train |
chaintope/bitcoinrb | lib/bitcoin/script/script.rb | Bitcoin.Script.p2sh_addr | def p2sh_addr
return nil unless p2sh?
hash160 = chunks[1].pushed_data.bth
return nil unless hash160.htb.bytesize == 20
Bitcoin.encode_base58_address(hash160, Bitcoin.chain_params.p2sh_version)
end | ruby | def p2sh_addr
return nil unless p2sh?
hash160 = chunks[1].pushed_data.bth
return nil unless hash160.htb.bytesize == 20
Bitcoin.encode_base58_address(hash160, Bitcoin.chain_params.p2sh_version)
end | [
"def",
"p2sh_addr",
"return",
"nil",
"unless",
"p2sh?",
"hash160",
"=",
"chunks",
"[",
"1",
"]",
".",
"pushed_data",
".",
"bth",
"return",
"nil",
"unless",
"hash160",
".",
"htb",
".",
"bytesize",
"==",
"20",
"Bitcoin",
".",
"encode_base58_address",
"(",
"h... | generate p2sh address. if script dose not p2sh, return nil. | [
"generate",
"p2sh",
"address",
".",
"if",
"script",
"dose",
"not",
"p2sh",
"return",
"nil",
"."
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L514-L519 | train |
chaintope/bitcoinrb | lib/bitcoin/script/script.rb | Bitcoin.Script.bech32_addr | def bech32_addr
segwit_addr = Bech32::SegwitAddr.new
segwit_addr.hrp = Bitcoin.chain_params.bech32_hrp
segwit_addr.script_pubkey = to_payload.bth
segwit_addr.addr
end | ruby | def bech32_addr
segwit_addr = Bech32::SegwitAddr.new
segwit_addr.hrp = Bitcoin.chain_params.bech32_hrp
segwit_addr.script_pubkey = to_payload.bth
segwit_addr.addr
end | [
"def",
"bech32_addr",
"segwit_addr",
"=",
"Bech32",
"::",
"SegwitAddr",
".",
"new",
"segwit_addr",
".",
"hrp",
"=",
"Bitcoin",
".",
"chain_params",
".",
"bech32_hrp",
"segwit_addr",
".",
"script_pubkey",
"=",
"to_payload",
".",
"bth",
"segwit_addr",
".",
"addr",... | return bech32 address for payload | [
"return",
"bech32",
"address",
"for",
"payload"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L527-L532 | train |
chaintope/bitcoinrb | lib/bitcoin/mnemonic.rb | Bitcoin.Mnemonic.to_entropy | def to_entropy(words)
word_master = load_words
mnemonic = words.map do |w|
index = word_master.index(w.downcase)
raise IndexError, 'word not found in words list.' unless index
index.to_s(2).rjust(11, '0')
end.join
entropy = mnemonic.slice(0, (mnemonic.length * 32) / 33)
... | ruby | def to_entropy(words)
word_master = load_words
mnemonic = words.map do |w|
index = word_master.index(w.downcase)
raise IndexError, 'word not found in words list.' unless index
index.to_s(2).rjust(11, '0')
end.join
entropy = mnemonic.slice(0, (mnemonic.length * 32) / 33)
... | [
"def",
"to_entropy",
"(",
"words",
")",
"word_master",
"=",
"load_words",
"mnemonic",
"=",
"words",
".",
"map",
"do",
"|",
"w",
"|",
"index",
"=",
"word_master",
".",
"index",
"(",
"w",
".",
"downcase",
")",
"raise",
"IndexError",
",",
"'word not found in ... | generate entropy from mnemonic word
@param [Array[String]] words the array of mnemonic word.
@return [String] an entropy with hex format. | [
"generate",
"entropy",
"from",
"mnemonic",
"word"
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/mnemonic.rb#L24-L35 | train |
chaintope/bitcoinrb | lib/bitcoin/mnemonic.rb | Bitcoin.Mnemonic.to_mnemonic | def to_mnemonic(entropy)
raise ArgumentError, 'entropy is empty.' if entropy.nil? || entropy.empty?
e = entropy.htb.unpack('B*').first
seed = e + checksum(e)
mnemonic_index = seed.chars.each_slice(11).map{|i|i.join.to_i(2)}
word_master = load_words
mnemonic_index.map{|i|word_master[i... | ruby | def to_mnemonic(entropy)
raise ArgumentError, 'entropy is empty.' if entropy.nil? || entropy.empty?
e = entropy.htb.unpack('B*').first
seed = e + checksum(e)
mnemonic_index = seed.chars.each_slice(11).map{|i|i.join.to_i(2)}
word_master = load_words
mnemonic_index.map{|i|word_master[i... | [
"def",
"to_mnemonic",
"(",
"entropy",
")",
"raise",
"ArgumentError",
",",
"'entropy is empty.'",
"if",
"entropy",
".",
"nil?",
"||",
"entropy",
".",
"empty?",
"e",
"=",
"entropy",
".",
"htb",
".",
"unpack",
"(",
"'B*'",
")",
".",
"first",
"seed",
"=",
"e... | generate mnemonic words from entropy.
@param [String] entropy an entropy with hex format.
@return [Array] the array of mnemonic word. | [
"generate",
"mnemonic",
"words",
"from",
"entropy",
"."
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/mnemonic.rb#L40-L47 | train |
chaintope/bitcoinrb | lib/bitcoin/mnemonic.rb | Bitcoin.Mnemonic.to_seed | def to_seed(mnemonic, passphrase: '')
to_entropy(mnemonic)
OpenSSL::PKCS5.pbkdf2_hmac(mnemonic.join(' ').downcase,
'mnemonic' + passphrase, 2048, 64, OpenSSL::Digest::SHA512.new).bth
end | ruby | def to_seed(mnemonic, passphrase: '')
to_entropy(mnemonic)
OpenSSL::PKCS5.pbkdf2_hmac(mnemonic.join(' ').downcase,
'mnemonic' + passphrase, 2048, 64, OpenSSL::Digest::SHA512.new).bth
end | [
"def",
"to_seed",
"(",
"mnemonic",
",",
"passphrase",
":",
"''",
")",
"to_entropy",
"(",
"mnemonic",
")",
"OpenSSL",
"::",
"PKCS5",
".",
"pbkdf2_hmac",
"(",
"mnemonic",
".",
"join",
"(",
"' '",
")",
".",
"downcase",
",",
"'mnemonic'",
"+",
"passphrase",
... | generate seed from mnemonic
if mnemonic protected with passphrase, specify that passphrase.
@param [Array] mnemonic a array of mnemonic word.
@param [String] passphrase a passphrase which protects mnemonic. the default value is an empty string.
@return [String] seed | [
"generate",
"seed",
"from",
"mnemonic",
"if",
"mnemonic",
"protected",
"with",
"passphrase",
"specify",
"that",
"passphrase",
"."
] | 39396e4c9815214d6b0ab694fa8326978a7f5438 | https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/mnemonic.rb#L54-L58 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.