id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
|
---|---|---|---|---|---|---|---|---|---|---|---|
21,400 |
heroku/configvar
|
lib/configvar/context.rb
|
ConfigVar.Context.optional_string
|
def optional_string(name, default)
optional_custom(name) do |env|
if value = env[name.to_s.upcase]
{name => value}
else
{name => default}
end
end
end
|
ruby
|
def optional_string(name, default)
optional_custom(name) do |env|
if value = env[name.to_s.upcase]
{name => value}
else
{name => default}
end
end
end
|
[
"def",
"optional_string",
"(",
"name",
",",
"default",
")",
"optional_custom",
"(",
"name",
")",
"do",
"|",
"env",
"|",
"if",
"value",
"=",
"env",
"[",
"name",
".",
"to_s",
".",
"upcase",
"]",
"{",
"name",
"=>",
"value",
"}",
"else",
"{",
"name",
"=>",
"default",
"}",
"end",
"end",
"end"
] |
Define a required string config var with a default value.
|
[
"Define",
"a",
"required",
"string",
"config",
"var",
"with",
"a",
"default",
"value",
"."
] |
1778604a7878bb49d4512a189c3e7664a0874295
|
https://github.com/heroku/configvar/blob/1778604a7878bb49d4512a189c3e7664a0874295/lib/configvar/context.rb#L72-L80
|
21,401 |
heroku/configvar
|
lib/configvar/context.rb
|
ConfigVar.Context.optional_int
|
def optional_int(name, default)
optional_custom(name) do |env|
if value = env[name.to_s.upcase]
{name => parse_int(name, value)}
else
{name => default}
end
end
end
|
ruby
|
def optional_int(name, default)
optional_custom(name) do |env|
if value = env[name.to_s.upcase]
{name => parse_int(name, value)}
else
{name => default}
end
end
end
|
[
"def",
"optional_int",
"(",
"name",
",",
"default",
")",
"optional_custom",
"(",
"name",
")",
"do",
"|",
"env",
"|",
"if",
"value",
"=",
"env",
"[",
"name",
".",
"to_s",
".",
"upcase",
"]",
"{",
"name",
"=>",
"parse_int",
"(",
"name",
",",
"value",
")",
"}",
"else",
"{",
"name",
"=>",
"default",
"}",
"end",
"end",
"end"
] |
Define a required integer config var with a default value.
|
[
"Define",
"a",
"required",
"integer",
"config",
"var",
"with",
"a",
"default",
"value",
"."
] |
1778604a7878bb49d4512a189c3e7664a0874295
|
https://github.com/heroku/configvar/blob/1778604a7878bb49d4512a189c3e7664a0874295/lib/configvar/context.rb#L83-L91
|
21,402 |
heroku/configvar
|
lib/configvar/context.rb
|
ConfigVar.Context.optional_bool
|
def optional_bool(name, default)
optional_custom(name) do |env|
if value = env[name.to_s.upcase]
{name => parse_bool(name, value)}
else
{name => default}
end
end
end
|
ruby
|
def optional_bool(name, default)
optional_custom(name) do |env|
if value = env[name.to_s.upcase]
{name => parse_bool(name, value)}
else
{name => default}
end
end
end
|
[
"def",
"optional_bool",
"(",
"name",
",",
"default",
")",
"optional_custom",
"(",
"name",
")",
"do",
"|",
"env",
"|",
"if",
"value",
"=",
"env",
"[",
"name",
".",
"to_s",
".",
"upcase",
"]",
"{",
"name",
"=>",
"parse_bool",
"(",
"name",
",",
"value",
")",
"}",
"else",
"{",
"name",
"=>",
"default",
"}",
"end",
"end",
"end"
] |
Define a required boolean config var with a default value.
|
[
"Define",
"a",
"required",
"boolean",
"config",
"var",
"with",
"a",
"default",
"value",
"."
] |
1778604a7878bb49d4512a189c3e7664a0874295
|
https://github.com/heroku/configvar/blob/1778604a7878bb49d4512a189c3e7664a0874295/lib/configvar/context.rb#L94-L102
|
21,403 |
heroku/configvar
|
lib/configvar/context.rb
|
ConfigVar.Context.parse_bool
|
def parse_bool(name, value)
if ['1', 'true', 'enabled'].include?(value.downcase)
true
elsif ['0', 'false'].include?(value.downcase)
false
else
raise ArgumentError.new("#{value} is not a valid boolean for #{name.to_s.upcase}")
end
end
|
ruby
|
def parse_bool(name, value)
if ['1', 'true', 'enabled'].include?(value.downcase)
true
elsif ['0', 'false'].include?(value.downcase)
false
else
raise ArgumentError.new("#{value} is not a valid boolean for #{name.to_s.upcase}")
end
end
|
[
"def",
"parse_bool",
"(",
"name",
",",
"value",
")",
"if",
"[",
"'1'",
",",
"'true'",
",",
"'enabled'",
"]",
".",
"include?",
"(",
"value",
".",
"downcase",
")",
"true",
"elsif",
"[",
"'0'",
",",
"'false'",
"]",
".",
"include?",
"(",
"value",
".",
"downcase",
")",
"false",
"else",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"#{value} is not a valid boolean for #{name.to_s.upcase}\"",
")",
"end",
"end"
] |
Convert a string to boolean. An ArgumentError is raised if the string
is not a valid boolean.
|
[
"Convert",
"a",
"string",
"to",
"boolean",
".",
"An",
"ArgumentError",
"is",
"raised",
"if",
"the",
"string",
"is",
"not",
"a",
"valid",
"boolean",
"."
] |
1778604a7878bb49d4512a189c3e7664a0874295
|
https://github.com/heroku/configvar/blob/1778604a7878bb49d4512a189c3e7664a0874295/lib/configvar/context.rb#L125-L133
|
21,404 |
heroku/configvar
|
lib/configvar/context.rb
|
ConfigVar.Context.define_config
|
def define_config(name, &blk)
if @definitions.has_key?(name)
raise ConfigError.new("#{name.to_s.upcase} is already registered")
end
@definitions[name] = Proc.new do |env|
value = yield env
if value.kind_of?(Hash)
value
else
{name => value}
end
end
end
|
ruby
|
def define_config(name, &blk)
if @definitions.has_key?(name)
raise ConfigError.new("#{name.to_s.upcase} is already registered")
end
@definitions[name] = Proc.new do |env|
value = yield env
if value.kind_of?(Hash)
value
else
{name => value}
end
end
end
|
[
"def",
"define_config",
"(",
"name",
",",
"&",
"blk",
")",
"if",
"@definitions",
".",
"has_key?",
"(",
"name",
")",
"raise",
"ConfigError",
".",
"new",
"(",
"\"#{name.to_s.upcase} is already registered\"",
")",
"end",
"@definitions",
"[",
"name",
"]",
"=",
"Proc",
".",
"new",
"do",
"|",
"env",
"|",
"value",
"=",
"yield",
"env",
"if",
"value",
".",
"kind_of?",
"(",
"Hash",
")",
"value",
"else",
"{",
"name",
"=>",
"value",
"}",
"end",
"end",
"end"
] |
Define a handler for a configuration value.
|
[
"Define",
"a",
"handler",
"for",
"a",
"configuration",
"value",
"."
] |
1778604a7878bb49d4512a189c3e7664a0874295
|
https://github.com/heroku/configvar/blob/1778604a7878bb49d4512a189c3e7664a0874295/lib/configvar/context.rb#L136-L148
|
21,405 |
danmayer/churn
|
lib/churn/calculator.rb
|
Churn.ChurnCalculator.analyze
|
def analyze
@changes = sort_changes(@changes)
@changes = @changes.map {|file_path, times_changed| {:file_path => file_path, :times_changed => times_changed }}
calculate_revision_changes
@method_changes = sort_changes(@method_changes)
@method_changes = @method_changes.map {|method, times_changed| {'method' => method, 'times_changed' => times_changed }}
@class_changes = sort_changes(@class_changes)
@class_changes = @class_changes.map {|klass, times_changed| {'klass' => klass, 'times_changed' => times_changed }}
end
|
ruby
|
def analyze
@changes = sort_changes(@changes)
@changes = @changes.map {|file_path, times_changed| {:file_path => file_path, :times_changed => times_changed }}
calculate_revision_changes
@method_changes = sort_changes(@method_changes)
@method_changes = @method_changes.map {|method, times_changed| {'method' => method, 'times_changed' => times_changed }}
@class_changes = sort_changes(@class_changes)
@class_changes = @class_changes.map {|klass, times_changed| {'klass' => klass, 'times_changed' => times_changed }}
end
|
[
"def",
"analyze",
"@changes",
"=",
"sort_changes",
"(",
"@changes",
")",
"@changes",
"=",
"@changes",
".",
"map",
"{",
"|",
"file_path",
",",
"times_changed",
"|",
"{",
":file_path",
"=>",
"file_path",
",",
":times_changed",
"=>",
"times_changed",
"}",
"}",
"calculate_revision_changes",
"@method_changes",
"=",
"sort_changes",
"(",
"@method_changes",
")",
"@method_changes",
"=",
"@method_changes",
".",
"map",
"{",
"|",
"method",
",",
"times_changed",
"|",
"{",
"'method'",
"=>",
"method",
",",
"'times_changed'",
"=>",
"times_changed",
"}",
"}",
"@class_changes",
"=",
"sort_changes",
"(",
"@class_changes",
")",
"@class_changes",
"=",
"@class_changes",
".",
"map",
"{",
"|",
"klass",
",",
"times_changed",
"|",
"{",
"'klass'",
"=>",
"klass",
",",
"'times_changed'",
"=>",
"times_changed",
"}",
"}",
"end"
] |
Analyze the source control data, filter, sort, and find more information
on the edited files
|
[
"Analyze",
"the",
"source",
"control",
"data",
"filter",
"sort",
"and",
"find",
"more",
"information",
"on",
"the",
"edited",
"files"
] |
f48ba8f0712697d052c37846109b6ada10e332c5
|
https://github.com/danmayer/churn/blob/f48ba8f0712697d052c37846109b6ada10e332c5/lib/churn/calculator.rb#L90-L100
|
21,406 |
danmayer/churn
|
lib/churn/calculator.rb
|
Churn.ChurnCalculator.to_h
|
def to_h
hash = {:churn => {:changes => @changes}}
hash[:churn][:class_churn] = @class_changes
hash[:churn][:method_churn] = @method_changes
#detail the most recent changes made this revision
first_revision = @revisions.first
first_revision_changes = @revision_changes[first_revision]
if first_revision_changes
changes = first_revision_changes
hash[:churn][:changed_files] = changes[:files]
hash[:churn][:changed_classes] = changes[:classes]
hash[:churn][:changed_methods] = changes[:methods]
end
# TODO crappy place to do this but save hash to revision file but
# while entirely under metric_fu only choice
ChurnHistory.store_revision_history(first_revision, hash, @churn_options.data_directory)
hash
end
|
ruby
|
def to_h
hash = {:churn => {:changes => @changes}}
hash[:churn][:class_churn] = @class_changes
hash[:churn][:method_churn] = @method_changes
#detail the most recent changes made this revision
first_revision = @revisions.first
first_revision_changes = @revision_changes[first_revision]
if first_revision_changes
changes = first_revision_changes
hash[:churn][:changed_files] = changes[:files]
hash[:churn][:changed_classes] = changes[:classes]
hash[:churn][:changed_methods] = changes[:methods]
end
# TODO crappy place to do this but save hash to revision file but
# while entirely under metric_fu only choice
ChurnHistory.store_revision_history(first_revision, hash, @churn_options.data_directory)
hash
end
|
[
"def",
"to_h",
"hash",
"=",
"{",
":churn",
"=>",
"{",
":changes",
"=>",
"@changes",
"}",
"}",
"hash",
"[",
":churn",
"]",
"[",
":class_churn",
"]",
"=",
"@class_changes",
"hash",
"[",
":churn",
"]",
"[",
":method_churn",
"]",
"=",
"@method_changes",
"#detail the most recent changes made this revision",
"first_revision",
"=",
"@revisions",
".",
"first",
"first_revision_changes",
"=",
"@revision_changes",
"[",
"first_revision",
"]",
"if",
"first_revision_changes",
"changes",
"=",
"first_revision_changes",
"hash",
"[",
":churn",
"]",
"[",
":changed_files",
"]",
"=",
"changes",
"[",
":files",
"]",
"hash",
"[",
":churn",
"]",
"[",
":changed_classes",
"]",
"=",
"changes",
"[",
":classes",
"]",
"hash",
"[",
":churn",
"]",
"[",
":changed_methods",
"]",
"=",
"changes",
"[",
":methods",
"]",
"end",
"# TODO crappy place to do this but save hash to revision file but",
"# while entirely under metric_fu only choice",
"ChurnHistory",
".",
"store_revision_history",
"(",
"first_revision",
",",
"hash",
",",
"@churn_options",
".",
"data_directory",
")",
"hash",
"end"
] |
collect all the data into a single hash data structure.
|
[
"collect",
"all",
"the",
"data",
"into",
"a",
"single",
"hash",
"data",
"structure",
"."
] |
f48ba8f0712697d052c37846109b6ada10e332c5
|
https://github.com/danmayer/churn/blob/f48ba8f0712697d052c37846109b6ada10e332c5/lib/churn/calculator.rb#L103-L120
|
21,407 |
OSC/pbs-ruby
|
lib/pbs/batch.rb
|
PBS.Batch.get_status
|
def get_status(filters: [])
connect do |cid|
filters = PBS::Torque::Attrl.from_list filters
batch_status = Torque.pbs_statserver cid, filters, nil
batch_status.to_h.tap { Torque.pbs_statfree batch_status }
end
end
|
ruby
|
def get_status(filters: [])
connect do |cid|
filters = PBS::Torque::Attrl.from_list filters
batch_status = Torque.pbs_statserver cid, filters, nil
batch_status.to_h.tap { Torque.pbs_statfree batch_status }
end
end
|
[
"def",
"get_status",
"(",
"filters",
":",
"[",
"]",
")",
"connect",
"do",
"|",
"cid",
"|",
"filters",
"=",
"PBS",
"::",
"Torque",
"::",
"Attrl",
".",
"from_list",
"filters",
"batch_status",
"=",
"Torque",
".",
"pbs_statserver",
"cid",
",",
"filters",
",",
"nil",
"batch_status",
".",
"to_h",
".",
"tap",
"{",
"Torque",
".",
"pbs_statfree",
"batch_status",
"}",
"end",
"end"
] |
Get a hash with status info for this batch server
@example Status info for OSC Oakley batch server
my_conn.get_status
#=>
#{
# "oak-batch.osc.edu:15001" => {
# :server_state => "Idle",
# ...
# }
#}
@param filters [Array<Symbol>] list of attribs to filter on
@return [Hash] status info for batch server
|
[
"Get",
"a",
"hash",
"with",
"status",
"info",
"for",
"this",
"batch",
"server"
] |
8f07c38db23392d10d4e1e3cc248b07a3e43730f
|
https://github.com/OSC/pbs-ruby/blob/8f07c38db23392d10d4e1e3cc248b07a3e43730f/lib/pbs/batch.rb#L89-L95
|
21,408 |
OSC/pbs-ruby
|
lib/pbs/batch.rb
|
PBS.Batch.get_queues
|
def get_queues(id: '', filters: [])
connect do |cid|
filters = PBS::Torque::Attrl.from_list(filters)
batch_status = Torque.pbs_statque cid, id.to_s, filters, nil
batch_status.to_h.tap { Torque.pbs_statfree batch_status }
end
end
|
ruby
|
def get_queues(id: '', filters: [])
connect do |cid|
filters = PBS::Torque::Attrl.from_list(filters)
batch_status = Torque.pbs_statque cid, id.to_s, filters, nil
batch_status.to_h.tap { Torque.pbs_statfree batch_status }
end
end
|
[
"def",
"get_queues",
"(",
"id",
":",
"''",
",",
"filters",
":",
"[",
"]",
")",
"connect",
"do",
"|",
"cid",
"|",
"filters",
"=",
"PBS",
"::",
"Torque",
"::",
"Attrl",
".",
"from_list",
"(",
"filters",
")",
"batch_status",
"=",
"Torque",
".",
"pbs_statque",
"cid",
",",
"id",
".",
"to_s",
",",
"filters",
",",
"nil",
"batch_status",
".",
"to_h",
".",
"tap",
"{",
"Torque",
".",
"pbs_statfree",
"batch_status",
"}",
"end",
"end"
] |
Get a list of hashes of the queues on the batch server
@example Status info for OSC Oakley queues
my_conn.get_queues
#=>
#{
# "parallel" => {
# :queue_type => "Execution",
# ...
# },
# "serial" => {
# :queue_type => "Execution",
# ...
# },
# ...
#}
@param id [#to_s] the id of requested information
@param filters [Array<Symbol>] list of attribs to filter on
@return [Hash] hash of details for the queues
|
[
"Get",
"a",
"list",
"of",
"hashes",
"of",
"the",
"queues",
"on",
"the",
"batch",
"server"
] |
8f07c38db23392d10d4e1e3cc248b07a3e43730f
|
https://github.com/OSC/pbs-ruby/blob/8f07c38db23392d10d4e1e3cc248b07a3e43730f/lib/pbs/batch.rb#L115-L121
|
21,409 |
OSC/pbs-ruby
|
lib/pbs/batch.rb
|
PBS.Batch.get_nodes
|
def get_nodes(id: '', filters: [])
connect do |cid|
filters = PBS::Torque::Attrl.from_list(filters)
batch_status = Torque.pbs_statnode cid, id.to_s, filters, nil
batch_status.to_h.tap { Torque.pbs_statfree batch_status }
end
end
|
ruby
|
def get_nodes(id: '', filters: [])
connect do |cid|
filters = PBS::Torque::Attrl.from_list(filters)
batch_status = Torque.pbs_statnode cid, id.to_s, filters, nil
batch_status.to_h.tap { Torque.pbs_statfree batch_status }
end
end
|
[
"def",
"get_nodes",
"(",
"id",
":",
"''",
",",
"filters",
":",
"[",
"]",
")",
"connect",
"do",
"|",
"cid",
"|",
"filters",
"=",
"PBS",
"::",
"Torque",
"::",
"Attrl",
".",
"from_list",
"(",
"filters",
")",
"batch_status",
"=",
"Torque",
".",
"pbs_statnode",
"cid",
",",
"id",
".",
"to_s",
",",
"filters",
",",
"nil",
"batch_status",
".",
"to_h",
".",
"tap",
"{",
"Torque",
".",
"pbs_statfree",
"batch_status",
"}",
"end",
"end"
] |
Get a list of hashes of the nodes on the batch server
@example Status info for OSC Oakley nodes
my_conn.get_nodes
#=>
#{
# "n0001" => {
# :np => "12",
# ...
# },
# "n0002" => {
# :np => "12",
# ...
# },
# ...
#}
@param id [#to_s] the id of requested information
@param filters [Array<Symbol>] list of attribs to filter on
@return [Hash] hash of details for nodes
|
[
"Get",
"a",
"list",
"of",
"hashes",
"of",
"the",
"nodes",
"on",
"the",
"batch",
"server"
] |
8f07c38db23392d10d4e1e3cc248b07a3e43730f
|
https://github.com/OSC/pbs-ruby/blob/8f07c38db23392d10d4e1e3cc248b07a3e43730f/lib/pbs/batch.rb#L158-L164
|
21,410 |
OSC/pbs-ruby
|
lib/pbs/batch.rb
|
PBS.Batch.select_jobs
|
def select_jobs(attribs: [])
connect do |cid|
attribs = PBS::Torque::Attropl.from_list(attribs.map(&:to_h))
batch_status = Torque.pbs_selstat cid, attribs, nil
batch_status.to_h.tap { Torque.pbs_statfree batch_status }
end
end
|
ruby
|
def select_jobs(attribs: [])
connect do |cid|
attribs = PBS::Torque::Attropl.from_list(attribs.map(&:to_h))
batch_status = Torque.pbs_selstat cid, attribs, nil
batch_status.to_h.tap { Torque.pbs_statfree batch_status }
end
end
|
[
"def",
"select_jobs",
"(",
"attribs",
":",
"[",
"]",
")",
"connect",
"do",
"|",
"cid",
"|",
"attribs",
"=",
"PBS",
"::",
"Torque",
"::",
"Attropl",
".",
"from_list",
"(",
"attribs",
".",
"map",
"(",
":to_h",
")",
")",
"batch_status",
"=",
"Torque",
".",
"pbs_selstat",
"cid",
",",
"attribs",
",",
"nil",
"batch_status",
".",
"to_h",
".",
"tap",
"{",
"Torque",
".",
"pbs_statfree",
"batch_status",
"}",
"end",
"end"
] |
Get a list of hashes of the selected jobs on the batch server
@example Status info for jobs owned by Bob
my_conn.select_jobs(attribs: [{name: "User_List", value: "bob", op: :eq}])
#=>
#{
# "10219837.oak-batch.osc.edu" => {
# :Job_Owner => "[email protected]",
# :Job_Name => "CFD_Solver",
# ...
# },
# "10219839.oak-batch.osc.edu" => {
# :Job_Owner => "[email protected]",
# :Job_Name => "CFD_Solver2",
# ...
# },
# ...
#}
@param attribs [Array<#to_h>] list of hashes describing attributes to
select on
@return [Hash] hash of details of selected jobs
|
[
"Get",
"a",
"list",
"of",
"hashes",
"of",
"the",
"selected",
"jobs",
"on",
"the",
"batch",
"server"
] |
8f07c38db23392d10d4e1e3cc248b07a3e43730f
|
https://github.com/OSC/pbs-ruby/blob/8f07c38db23392d10d4e1e3cc248b07a3e43730f/lib/pbs/batch.rb#L203-L209
|
21,411 |
OSC/pbs-ruby
|
lib/pbs/batch.rb
|
PBS.Batch.get_jobs
|
def get_jobs(id: '', filters: [])
connect do |cid|
filters = PBS::Torque::Attrl.from_list(filters)
batch_status = Torque.pbs_statjob cid, id.to_s, filters, nil
batch_status.to_h.tap { Torque.pbs_statfree batch_status }
end
end
|
ruby
|
def get_jobs(id: '', filters: [])
connect do |cid|
filters = PBS::Torque::Attrl.from_list(filters)
batch_status = Torque.pbs_statjob cid, id.to_s, filters, nil
batch_status.to_h.tap { Torque.pbs_statfree batch_status }
end
end
|
[
"def",
"get_jobs",
"(",
"id",
":",
"''",
",",
"filters",
":",
"[",
"]",
")",
"connect",
"do",
"|",
"cid",
"|",
"filters",
"=",
"PBS",
"::",
"Torque",
"::",
"Attrl",
".",
"from_list",
"(",
"filters",
")",
"batch_status",
"=",
"Torque",
".",
"pbs_statjob",
"cid",
",",
"id",
".",
"to_s",
",",
"filters",
",",
"nil",
"batch_status",
".",
"to_h",
".",
"tap",
"{",
"Torque",
".",
"pbs_statfree",
"batch_status",
"}",
"end",
"end"
] |
Get a list of hashes of the jobs on the batch server
@example Status info for OSC Oakley jobs
my_conn.get_jobs
#=>
#{
# "10219837.oak-batch.osc.edu" => {
# :Job_Owner => "[email protected]",
# :Job_Name => "CFD_Solver",
# ...
# },
# "10219838.oak-batch.osc.edu" => {
# :Job_Owner => "[email protected]",
# :Job_Name => "FEA_Solver",
# ...
# },
# ...
#}
@param id [#to_s] the id of requested information
@param filters [Array<Symbol>] list of attribs to filter on
@return [Hash] hash of details for jobs
|
[
"Get",
"a",
"list",
"of",
"hashes",
"of",
"the",
"jobs",
"on",
"the",
"batch",
"server"
] |
8f07c38db23392d10d4e1e3cc248b07a3e43730f
|
https://github.com/OSC/pbs-ruby/blob/8f07c38db23392d10d4e1e3cc248b07a3e43730f/lib/pbs/batch.rb#L231-L237
|
21,412 |
OSC/pbs-ruby
|
lib/pbs/batch.rb
|
PBS.Batch.submit_script
|
def submit_script(script, queue: nil, headers: {}, resources: {}, envvars: {}, qsub: true)
send(qsub ? :qsub_submit : :pbs_submit, script.to_s, queue.to_s, headers, resources, envvars)
end
|
ruby
|
def submit_script(script, queue: nil, headers: {}, resources: {}, envvars: {}, qsub: true)
send(qsub ? :qsub_submit : :pbs_submit, script.to_s, queue.to_s, headers, resources, envvars)
end
|
[
"def",
"submit_script",
"(",
"script",
",",
"queue",
":",
"nil",
",",
"headers",
":",
"{",
"}",
",",
"resources",
":",
"{",
"}",
",",
"envvars",
":",
"{",
"}",
",",
"qsub",
":",
"true",
")",
"send",
"(",
"qsub",
"?",
":qsub_submit",
":",
":pbs_submit",
",",
"script",
".",
"to_s",
",",
"queue",
".",
"to_s",
",",
"headers",
",",
"resources",
",",
"envvars",
")",
"end"
] |
Submit a script to the batch server
@example Submit a script with a few PBS directives
my_conn.submit_script("/path/to/script",
headers: {
Job_Name: "myjob",
Join_Path: "oe"
},
resources: {
nodes: "4:ppn=12",
walltime: "12:00:00"
},
envvars: {
TOKEN: "asd90f9sd8g90hk34"
}
)
#=> "6621251.oak-batch.osc.edu"
@param script [#to_s] path to the script
@param queue [#to_s] queue to submit script to
@param headers [Hash] pbs headers
@param resources [Hash] pbs resources
@param envvars [Hash] pbs environment variables
@param qsub [Boolean] whether use library or binary for submission
@return [String] the id of the job that was created
@deprecated Use {#submit} instead.
|
[
"Submit",
"a",
"script",
"to",
"the",
"batch",
"server"
] |
8f07c38db23392d10d4e1e3cc248b07a3e43730f
|
https://github.com/OSC/pbs-ruby/blob/8f07c38db23392d10d4e1e3cc248b07a3e43730f/lib/pbs/batch.rb#L323-L325
|
21,413 |
OSC/pbs-ruby
|
lib/pbs/batch.rb
|
PBS.Batch.submit_string
|
def submit_string(string, **kwargs)
Tempfile.open('qsub.') do |f|
f.write string.to_s
f.close
submit_script(f.path, **kwargs)
end
end
|
ruby
|
def submit_string(string, **kwargs)
Tempfile.open('qsub.') do |f|
f.write string.to_s
f.close
submit_script(f.path, **kwargs)
end
end
|
[
"def",
"submit_string",
"(",
"string",
",",
"**",
"kwargs",
")",
"Tempfile",
".",
"open",
"(",
"'qsub.'",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"string",
".",
"to_s",
"f",
".",
"close",
"submit_script",
"(",
"f",
".",
"path",
",",
"**",
"kwargs",
")",
"end",
"end"
] |
Submit a script expanded into a string to the batch server
@param string [#to_s] script as a string
@param (see #submit_script)
@return [String] the id of the job that was created
@deprecated Use {#submit} instead.
|
[
"Submit",
"a",
"script",
"expanded",
"into",
"a",
"string",
"to",
"the",
"batch",
"server"
] |
8f07c38db23392d10d4e1e3cc248b07a3e43730f
|
https://github.com/OSC/pbs-ruby/blob/8f07c38db23392d10d4e1e3cc248b07a3e43730f/lib/pbs/batch.rb#L332-L338
|
21,414 |
OSC/pbs-ruby
|
lib/pbs/batch.rb
|
PBS.Batch.submit
|
def submit(content, args: [], env: {}, chdir: nil)
call(:qsub, *args, env: env, stdin: content, chdir: chdir).strip
end
|
ruby
|
def submit(content, args: [], env: {}, chdir: nil)
call(:qsub, *args, env: env, stdin: content, chdir: chdir).strip
end
|
[
"def",
"submit",
"(",
"content",
",",
"args",
":",
"[",
"]",
",",
"env",
":",
"{",
"}",
",",
"chdir",
":",
"nil",
")",
"call",
"(",
":qsub",
",",
"args",
",",
"env",
":",
"env",
",",
"stdin",
":",
"content",
",",
"chdir",
":",
"chdir",
")",
".",
"strip",
"end"
] |
Submit a script expanded as a string to the batch server
@param content [#to_s] script as a string
@param args [Array<#to_s>] arguments passed to `qsub` command
@param env [Hash{#to_s => #to_s}] environment variables set
@param chdir [#to_s, nil] working directory where `qsub` is called from
@raise [Error] if `qsub` command exited unsuccessfully
@return [String] the id of the job that was created
|
[
"Submit",
"a",
"script",
"expanded",
"as",
"a",
"string",
"to",
"the",
"batch",
"server"
] |
8f07c38db23392d10d4e1e3cc248b07a3e43730f
|
https://github.com/OSC/pbs-ruby/blob/8f07c38db23392d10d4e1e3cc248b07a3e43730f/lib/pbs/batch.rb#L347-L349
|
21,415 |
OSC/pbs-ruby
|
lib/pbs/batch.rb
|
PBS.Batch.pbs_submit
|
def pbs_submit(script, queue, headers, resources, envvars)
attribs = []
headers.each do |name, value|
attribs << { name: name, value: value }
end
resources.each do |rsc, value|
attribs << { name: :Resource_List, resource: rsc, value: value }
end
unless envvars.empty?
attribs << {
name: :Variable_List,
value: envvars.map {|k,v| "#{k}=#{v}"}.join(",")
}
end
connect do |cid|
attropl = Torque::Attropl.from_list attribs
Torque.pbs_submit cid, attropl, script, queue, nil
end
end
|
ruby
|
def pbs_submit(script, queue, headers, resources, envvars)
attribs = []
headers.each do |name, value|
attribs << { name: name, value: value }
end
resources.each do |rsc, value|
attribs << { name: :Resource_List, resource: rsc, value: value }
end
unless envvars.empty?
attribs << {
name: :Variable_List,
value: envvars.map {|k,v| "#{k}=#{v}"}.join(",")
}
end
connect do |cid|
attropl = Torque::Attropl.from_list attribs
Torque.pbs_submit cid, attropl, script, queue, nil
end
end
|
[
"def",
"pbs_submit",
"(",
"script",
",",
"queue",
",",
"headers",
",",
"resources",
",",
"envvars",
")",
"attribs",
"=",
"[",
"]",
"headers",
".",
"each",
"do",
"|",
"name",
",",
"value",
"|",
"attribs",
"<<",
"{",
"name",
":",
"name",
",",
"value",
":",
"value",
"}",
"end",
"resources",
".",
"each",
"do",
"|",
"rsc",
",",
"value",
"|",
"attribs",
"<<",
"{",
"name",
":",
":Resource_List",
",",
"resource",
":",
"rsc",
",",
"value",
":",
"value",
"}",
"end",
"unless",
"envvars",
".",
"empty?",
"attribs",
"<<",
"{",
"name",
":",
":Variable_List",
",",
"value",
":",
"envvars",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"\"#{k}=#{v}\"",
"}",
".",
"join",
"(",
"\",\"",
")",
"}",
"end",
"connect",
"do",
"|",
"cid",
"|",
"attropl",
"=",
"Torque",
"::",
"Attropl",
".",
"from_list",
"attribs",
"Torque",
".",
"pbs_submit",
"cid",
",",
"attropl",
",",
"script",
",",
"queue",
",",
"nil",
"end",
"end"
] |
Submit a script using Torque library
|
[
"Submit",
"a",
"script",
"using",
"Torque",
"library"
] |
8f07c38db23392d10d4e1e3cc248b07a3e43730f
|
https://github.com/OSC/pbs-ruby/blob/8f07c38db23392d10d4e1e3cc248b07a3e43730f/lib/pbs/batch.rb#L353-L372
|
21,416 |
OSC/pbs-ruby
|
lib/pbs/batch.rb
|
PBS.Batch.qsub_arg
|
def qsub_arg(key, value)
case key
# common attributes
when :Execution_Time
['-a', value.to_s]
when :Checkpoint
['-c', value.to_s]
when :Error_Path
['-e', value.to_s]
when :fault_tolerant
['-f']
when :Hold_Types
['-h']
when :Join_Path
['-j', value.to_s]
when :Keep_Files
['-k', value.to_s]
when :Mail_Points
['-m', value.to_s]
when :Output_Path
['-o', value.to_s]
when :Priority
['-p', value.to_s]
when :Rerunable
['-r', value.to_s]
when :job_array_request
['-t', value.to_s]
when :User_List
['-u', value.to_s]
when :Account_Name
['-A', value.to_s]
when :Mail_Users
['-M', value.to_s]
when :Job_Name
['-N', value.to_s]
when :Shell_Path_List
['-S', value.to_s]
# uncommon attributes
when :job_arguments
['-F', value.to_s]
when :init_work_dir
['-d', value.to_s] # sets PBS_O_INITDIR
when :reservation_id
['-W', "x=advres:#{value}"] # use resource manager extensions for Moab
# everything else
else
['-W', "#{key}=#{value}"]
end
end
|
ruby
|
def qsub_arg(key, value)
case key
# common attributes
when :Execution_Time
['-a', value.to_s]
when :Checkpoint
['-c', value.to_s]
when :Error_Path
['-e', value.to_s]
when :fault_tolerant
['-f']
when :Hold_Types
['-h']
when :Join_Path
['-j', value.to_s]
when :Keep_Files
['-k', value.to_s]
when :Mail_Points
['-m', value.to_s]
when :Output_Path
['-o', value.to_s]
when :Priority
['-p', value.to_s]
when :Rerunable
['-r', value.to_s]
when :job_array_request
['-t', value.to_s]
when :User_List
['-u', value.to_s]
when :Account_Name
['-A', value.to_s]
when :Mail_Users
['-M', value.to_s]
when :Job_Name
['-N', value.to_s]
when :Shell_Path_List
['-S', value.to_s]
# uncommon attributes
when :job_arguments
['-F', value.to_s]
when :init_work_dir
['-d', value.to_s] # sets PBS_O_INITDIR
when :reservation_id
['-W', "x=advres:#{value}"] # use resource manager extensions for Moab
# everything else
else
['-W', "#{key}=#{value}"]
end
end
|
[
"def",
"qsub_arg",
"(",
"key",
",",
"value",
")",
"case",
"key",
"# common attributes",
"when",
":Execution_Time",
"[",
"'-a'",
",",
"value",
".",
"to_s",
"]",
"when",
":Checkpoint",
"[",
"'-c'",
",",
"value",
".",
"to_s",
"]",
"when",
":Error_Path",
"[",
"'-e'",
",",
"value",
".",
"to_s",
"]",
"when",
":fault_tolerant",
"[",
"'-f'",
"]",
"when",
":Hold_Types",
"[",
"'-h'",
"]",
"when",
":Join_Path",
"[",
"'-j'",
",",
"value",
".",
"to_s",
"]",
"when",
":Keep_Files",
"[",
"'-k'",
",",
"value",
".",
"to_s",
"]",
"when",
":Mail_Points",
"[",
"'-m'",
",",
"value",
".",
"to_s",
"]",
"when",
":Output_Path",
"[",
"'-o'",
",",
"value",
".",
"to_s",
"]",
"when",
":Priority",
"[",
"'-p'",
",",
"value",
".",
"to_s",
"]",
"when",
":Rerunable",
"[",
"'-r'",
",",
"value",
".",
"to_s",
"]",
"when",
":job_array_request",
"[",
"'-t'",
",",
"value",
".",
"to_s",
"]",
"when",
":User_List",
"[",
"'-u'",
",",
"value",
".",
"to_s",
"]",
"when",
":Account_Name",
"[",
"'-A'",
",",
"value",
".",
"to_s",
"]",
"when",
":Mail_Users",
"[",
"'-M'",
",",
"value",
".",
"to_s",
"]",
"when",
":Job_Name",
"[",
"'-N'",
",",
"value",
".",
"to_s",
"]",
"when",
":Shell_Path_List",
"[",
"'-S'",
",",
"value",
".",
"to_s",
"]",
"# uncommon attributes",
"when",
":job_arguments",
"[",
"'-F'",
",",
"value",
".",
"to_s",
"]",
"when",
":init_work_dir",
"[",
"'-d'",
",",
"value",
".",
"to_s",
"]",
"# sets PBS_O_INITDIR",
"when",
":reservation_id",
"[",
"'-W'",
",",
"\"x=advres:#{value}\"",
"]",
"# use resource manager extensions for Moab",
"# everything else",
"else",
"[",
"'-W'",
",",
"\"#{key}=#{value}\"",
"]",
"end",
"end"
] |
Mapping of Torque attribute to `qsub` arguments
|
[
"Mapping",
"of",
"Torque",
"attribute",
"to",
"qsub",
"arguments"
] |
8f07c38db23392d10d4e1e3cc248b07a3e43730f
|
https://github.com/OSC/pbs-ruby/blob/8f07c38db23392d10d4e1e3cc248b07a3e43730f/lib/pbs/batch.rb#L375-L423
|
21,417 |
OSC/pbs-ruby
|
lib/pbs/batch.rb
|
PBS.Batch.call
|
def call(cmd, *args, env: {}, stdin: "", chdir: nil)
cmd = bin.join(cmd.to_s).to_s
args = args.map(&:to_s)
env = env.to_h.each_with_object({}) {|(k,v), h| h[k.to_s] = v.to_s}.merge({
"PBS_DEFAULT" => host,
"LD_LIBRARY_PATH" => %{#{lib}:#{ENV["LD_LIBRARY_PATH"]}}
})
stdin = stdin.to_s
chdir ||= "."
o, e, s = Open3.capture3(env, cmd, *args, stdin_data: stdin, chdir: chdir.to_s)
s.success? ? o : raise(PBS::Error, e)
end
|
ruby
|
def call(cmd, *args, env: {}, stdin: "", chdir: nil)
cmd = bin.join(cmd.to_s).to_s
args = args.map(&:to_s)
env = env.to_h.each_with_object({}) {|(k,v), h| h[k.to_s] = v.to_s}.merge({
"PBS_DEFAULT" => host,
"LD_LIBRARY_PATH" => %{#{lib}:#{ENV["LD_LIBRARY_PATH"]}}
})
stdin = stdin.to_s
chdir ||= "."
o, e, s = Open3.capture3(env, cmd, *args, stdin_data: stdin, chdir: chdir.to_s)
s.success? ? o : raise(PBS::Error, e)
end
|
[
"def",
"call",
"(",
"cmd",
",",
"*",
"args",
",",
"env",
":",
"{",
"}",
",",
"stdin",
":",
"\"\"",
",",
"chdir",
":",
"nil",
")",
"cmd",
"=",
"bin",
".",
"join",
"(",
"cmd",
".",
"to_s",
")",
".",
"to_s",
"args",
"=",
"args",
".",
"map",
"(",
":to_s",
")",
"env",
"=",
"env",
".",
"to_h",
".",
"each_with_object",
"(",
"{",
"}",
")",
"{",
"|",
"(",
"k",
",",
"v",
")",
",",
"h",
"|",
"h",
"[",
"k",
".",
"to_s",
"]",
"=",
"v",
".",
"to_s",
"}",
".",
"merge",
"(",
"{",
"\"PBS_DEFAULT\"",
"=>",
"host",
",",
"\"LD_LIBRARY_PATH\"",
"=>",
"%{#{lib}:#{ENV[\"LD_LIBRARY_PATH\"]}}",
"}",
")",
"stdin",
"=",
"stdin",
".",
"to_s",
"chdir",
"||=",
"\".\"",
"o",
",",
"e",
",",
"s",
"=",
"Open3",
".",
"capture3",
"(",
"env",
",",
"cmd",
",",
"args",
",",
"stdin_data",
":",
"stdin",
",",
"chdir",
":",
"chdir",
".",
"to_s",
")",
"s",
".",
"success?",
"?",
"o",
":",
"raise",
"(",
"PBS",
"::",
"Error",
",",
"e",
")",
"end"
] |
Call a forked PBS command for a given host
|
[
"Call",
"a",
"forked",
"PBS",
"command",
"for",
"a",
"given",
"host"
] |
8f07c38db23392d10d4e1e3cc248b07a3e43730f
|
https://github.com/OSC/pbs-ruby/blob/8f07c38db23392d10d4e1e3cc248b07a3e43730f/lib/pbs/batch.rb#L446-L457
|
21,418 |
luke-gru/riml
|
lib/riml/include_cache.rb
|
Riml.IncludeCache.fetch
|
def fetch(included_filename)
if source = @cache[included_filename]
return source
end
if @m.locked? && @owns_lock == Thread.current
@cache[included_filename] = yield
else
ret = nil
@cache[included_filename] = @m.synchronize do
begin
@owns_lock = Thread.current
ret = yield
ensure
@owns_lock = nil
end
end
ret
end
end
|
ruby
|
def fetch(included_filename)
if source = @cache[included_filename]
return source
end
if @m.locked? && @owns_lock == Thread.current
@cache[included_filename] = yield
else
ret = nil
@cache[included_filename] = @m.synchronize do
begin
@owns_lock = Thread.current
ret = yield
ensure
@owns_lock = nil
end
end
ret
end
end
|
[
"def",
"fetch",
"(",
"included_filename",
")",
"if",
"source",
"=",
"@cache",
"[",
"included_filename",
"]",
"return",
"source",
"end",
"if",
"@m",
".",
"locked?",
"&&",
"@owns_lock",
"==",
"Thread",
".",
"current",
"@cache",
"[",
"included_filename",
"]",
"=",
"yield",
"else",
"ret",
"=",
"nil",
"@cache",
"[",
"included_filename",
"]",
"=",
"@m",
".",
"synchronize",
"do",
"begin",
"@owns_lock",
"=",
"Thread",
".",
"current",
"ret",
"=",
"yield",
"ensure",
"@owns_lock",
"=",
"nil",
"end",
"end",
"ret",
"end",
"end"
] |
`fetch` can be called recursively in the `yield`ed block, so must
make sure not to try to lock the Mutex if it's already locked by the
current thread, as this would result in an error.
|
[
"fetch",
"can",
"be",
"called",
"recursively",
"in",
"the",
"yield",
"ed",
"block",
"so",
"must",
"make",
"sure",
"not",
"to",
"try",
"to",
"lock",
"the",
"Mutex",
"if",
"it",
"s",
"already",
"locked",
"by",
"the",
"current",
"thread",
"as",
"this",
"would",
"result",
"in",
"an",
"error",
"."
] |
27e26e5fb66bfd1259bf9fbfda25ae0d93596d7e
|
https://github.com/luke-gru/riml/blob/27e26e5fb66bfd1259bf9fbfda25ae0d93596d7e/lib/riml/include_cache.rb#L14-L33
|
21,419 |
luke-gru/riml
|
lib/riml/compiler.rb
|
Riml.Compiler.compile
|
def compile(root_node)
root_node.extend CompilerAccessible
root_node.current_compiler = self
root_node.accept(NodesVisitor.new)
root_node.compiled_output
end
|
ruby
|
def compile(root_node)
root_node.extend CompilerAccessible
root_node.current_compiler = self
root_node.accept(NodesVisitor.new)
root_node.compiled_output
end
|
[
"def",
"compile",
"(",
"root_node",
")",
"root_node",
".",
"extend",
"CompilerAccessible",
"root_node",
".",
"current_compiler",
"=",
"self",
"root_node",
".",
"accept",
"(",
"NodesVisitor",
".",
"new",
")",
"root_node",
".",
"compiled_output",
"end"
] |
compiles nodes into output code
|
[
"compiles",
"nodes",
"into",
"output",
"code"
] |
27e26e5fb66bfd1259bf9fbfda25ae0d93596d7e
|
https://github.com/luke-gru/riml/blob/27e26e5fb66bfd1259bf9fbfda25ae0d93596d7e/lib/riml/compiler.rb#L816-L821
|
21,420 |
zuazo/dockerspec
|
lib/dockerspec/docker_exception_parser.rb
|
Dockerspec.DockerExceptionParser.parse_exception
|
def parse_exception(e)
msg = e.to_s
json = msg.to_s.sub(/^Couldn't find id: /, '').split("\n").map(&:chomp)
json.map { |str| JSON.parse(str) }
rescue JSON::ParserError
raise e
end
|
ruby
|
def parse_exception(e)
msg = e.to_s
json = msg.to_s.sub(/^Couldn't find id: /, '').split("\n").map(&:chomp)
json.map { |str| JSON.parse(str) }
rescue JSON::ParserError
raise e
end
|
[
"def",
"parse_exception",
"(",
"e",
")",
"msg",
"=",
"e",
".",
"to_s",
"json",
"=",
"msg",
".",
"to_s",
".",
"sub",
"(",
"/",
"/",
",",
"''",
")",
".",
"split",
"(",
"\"\\n\"",
")",
".",
"map",
"(",
":chomp",
")",
"json",
".",
"map",
"{",
"|",
"str",
"|",
"JSON",
".",
"parse",
"(",
"str",
")",
"}",
"rescue",
"JSON",
"::",
"ParserError",
"raise",
"e",
"end"
] |
Parses the exception JSON message.
The message must be a list of JSON messages merged by a new line.
A valid exception message example:
```
{"stream":"Step 1 : FROM alpine:3.2\n"}
{"stream":" ---\u003e d6ead20d5571\n"}
{"stream":"Step 2 : RUN apk add --update wrong-package-name\n"}
{"stream":" ---\u003e Running in 290a46fa8bf4\n"}
{"stream":"fetch http://dl-4.alpinelinux.org/alpine/v3.2/main/...\n"}
{"stream":"ERROR: unsatisfiable constraints:\n"}
{"stream":" wrong-package-name (missing):\n required by: world...\n"}
{"errorDetail":{"message":"The command ..."},"error":"The command ..."}
```
@example
self.parse_exception(e)
#=> [{ "stream" => "Step 1 : FROM alpine:3.2\n" }, "errorDetail" => ...
@param e [Exception] The exception object to parse.
@return [Array<Hash>] The list of JSON messages parsed.
@return
@api private
|
[
"Parses",
"the",
"exception",
"JSON",
"message",
"."
] |
cb3868684cc2fdf39cf9e807d6a8844944275fff
|
https://github.com/zuazo/dockerspec/blob/cb3868684cc2fdf39cf9e807d6a8844944275fff/lib/dockerspec/docker_exception_parser.rb#L83-L89
|
21,421 |
zuazo/dockerspec
|
lib/dockerspec/docker_exception_parser.rb
|
Dockerspec.DockerExceptionParser.parse_streams
|
def parse_streams(e_ary)
e_ary.map { |x| x.is_a?(Hash) && x['stream'] }.compact.join
end
|
ruby
|
def parse_streams(e_ary)
e_ary.map { |x| x.is_a?(Hash) && x['stream'] }.compact.join
end
|
[
"def",
"parse_streams",
"(",
"e_ary",
")",
"e_ary",
".",
"map",
"{",
"|",
"x",
"|",
"x",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"x",
"[",
"'stream'",
"]",
"}",
".",
"compact",
".",
"join",
"end"
] |
Gets all the console output from the stream logs.
@param e_ary [Array<Hash>] The list of JSON messages already parsed.
@return [String] The generated stdout output.
@api private
|
[
"Gets",
"all",
"the",
"console",
"output",
"from",
"the",
"stream",
"logs",
"."
] |
cb3868684cc2fdf39cf9e807d6a8844944275fff
|
https://github.com/zuazo/dockerspec/blob/cb3868684cc2fdf39cf9e807d6a8844944275fff/lib/dockerspec/docker_exception_parser.rb#L116-L118
|
21,422 |
zuazo/dockerspec
|
lib/dockerspec/builder.rb
|
Dockerspec.Builder.source
|
def source
return @source unless @source.nil?
@source = %i(string template id path).find { |from| @options.key?(from) }
end
|
ruby
|
def source
return @source unless @source.nil?
@source = %i(string template id path).find { |from| @options.key?(from) }
end
|
[
"def",
"source",
"return",
"@source",
"unless",
"@source",
".",
"nil?",
"@source",
"=",
"%i(",
"string",
"template",
"id",
"path",
")",
".",
"find",
"{",
"|",
"from",
"|",
"@options",
".",
"key?",
"(",
"from",
")",
"}",
"end"
] |
Gets the source to generate the image from.
Possible values: `:string`, `:template`, `:id`, `:path`.
@example Building an Image from a Path
self.source #=> :path
@example Building an Image from a Template
self.source #=> :template
@return [Symbol] The source.
@api private
|
[
"Gets",
"the",
"source",
"to",
"generate",
"the",
"image",
"from",
"."
] |
cb3868684cc2fdf39cf9e807d6a8844944275fff
|
https://github.com/zuazo/dockerspec/blob/cb3868684cc2fdf39cf9e807d6a8844944275fff/lib/dockerspec/builder.rb#L166-L169
|
21,423 |
zuazo/dockerspec
|
lib/dockerspec/builder.rb
|
Dockerspec.Builder.image
|
def image(img = nil)
return @image if img.nil?
ImageGC.instance.add(img.id) if @options[:rm]
@image = img
end
|
ruby
|
def image(img = nil)
return @image if img.nil?
ImageGC.instance.add(img.id) if @options[:rm]
@image = img
end
|
[
"def",
"image",
"(",
"img",
"=",
"nil",
")",
"return",
"@image",
"if",
"img",
".",
"nil?",
"ImageGC",
".",
"instance",
".",
"add",
"(",
"img",
".",
"id",
")",
"if",
"@options",
"[",
":rm",
"]",
"@image",
"=",
"img",
"end"
] |
Sets or gets the Docker image.
@param img [Docker::Image] The Docker image to set.
@return [Docker::Image] The Docker image object.
@api private
|
[
"Sets",
"or",
"gets",
"the",
"Docker",
"image",
"."
] |
cb3868684cc2fdf39cf9e807d6a8844944275fff
|
https://github.com/zuazo/dockerspec/blob/cb3868684cc2fdf39cf9e807d6a8844944275fff/lib/dockerspec/builder.rb#L194-L198
|
21,424 |
zuazo/dockerspec
|
lib/dockerspec/builder.rb
|
Dockerspec.Builder.rspec_options
|
def rspec_options
config = ::RSpec.configuration
{}.tap do |opts|
opts[:path] = config.dockerfile_path if config.dockerfile_path?
opts[:rm] = config.rm_build if config.rm_build?
opts[:log_level] = config.log_level if config.log_level?
end
end
|
ruby
|
def rspec_options
config = ::RSpec.configuration
{}.tap do |opts|
opts[:path] = config.dockerfile_path if config.dockerfile_path?
opts[:rm] = config.rm_build if config.rm_build?
opts[:log_level] = config.log_level if config.log_level?
end
end
|
[
"def",
"rspec_options",
"config",
"=",
"::",
"RSpec",
".",
"configuration",
"{",
"}",
".",
"tap",
"do",
"|",
"opts",
"|",
"opts",
"[",
":path",
"]",
"=",
"config",
".",
"dockerfile_path",
"if",
"config",
".",
"dockerfile_path?",
"opts",
"[",
":rm",
"]",
"=",
"config",
".",
"rm_build",
"if",
"config",
".",
"rm_build?",
"opts",
"[",
":log_level",
"]",
"=",
"config",
".",
"log_level",
"if",
"config",
".",
"log_level?",
"end",
"end"
] |
Gets the default options configured using `RSpec.configuration`.
@example
self.rspec_options #=> {:path=>".", :rm=>true, :log_level=>:silent}
@return [Hash] The configuration options.
@api private
|
[
"Gets",
"the",
"default",
"options",
"configured",
"using",
"RSpec",
".",
"configuration",
"."
] |
cb3868684cc2fdf39cf9e807d6a8844944275fff
|
https://github.com/zuazo/dockerspec/blob/cb3868684cc2fdf39cf9e807d6a8844944275fff/lib/dockerspec/builder.rb#L210-L217
|
21,425 |
zuazo/dockerspec
|
lib/dockerspec/builder.rb
|
Dockerspec.Builder.default_options
|
def default_options
{
path: ENV['DOCKERFILE_PATH'] || '.',
# Autoremove images in all CIs except Travis (not supported):
rm: ci? && !travis_ci?,
# Avoid CI timeout errors:
log_level: ci? ? :ci : :silent
}.merge(rspec_options)
end
|
ruby
|
def default_options
{
path: ENV['DOCKERFILE_PATH'] || '.',
# Autoremove images in all CIs except Travis (not supported):
rm: ci? && !travis_ci?,
# Avoid CI timeout errors:
log_level: ci? ? :ci : :silent
}.merge(rspec_options)
end
|
[
"def",
"default_options",
"{",
"path",
":",
"ENV",
"[",
"'DOCKERFILE_PATH'",
"]",
"||",
"'.'",
",",
"# Autoremove images in all CIs except Travis (not supported):",
"rm",
":",
"ci?",
"&&",
"!",
"travis_ci?",
",",
"# Avoid CI timeout errors:",
"log_level",
":",
"ci?",
"?",
":ci",
":",
":silent",
"}",
".",
"merge",
"(",
"rspec_options",
")",
"end"
] |
Gets the default configuration options after merging them with RSpec
configuration options.
@example
self.default_options #=> {:path=>".", :rm=>true, :log_level=>:silent}
@return [Hash] The configuration options.
@api private
|
[
"Gets",
"the",
"default",
"configuration",
"options",
"after",
"merging",
"them",
"with",
"RSpec",
"configuration",
"options",
"."
] |
cb3868684cc2fdf39cf9e807d6a8844944275fff
|
https://github.com/zuazo/dockerspec/blob/cb3868684cc2fdf39cf9e807d6a8844944275fff/lib/dockerspec/builder.rb#L230-L238
|
21,426 |
zuazo/dockerspec
|
lib/dockerspec/builder.rb
|
Dockerspec.Builder.parse_options
|
def parse_options(opts)
opts_hs_ary = opts.map { |x| x.is_a?(Hash) ? x : { path: x } }
opts_hs_ary.reduce(default_options) { |a, e| a.merge(e) }
end
|
ruby
|
def parse_options(opts)
opts_hs_ary = opts.map { |x| x.is_a?(Hash) ? x : { path: x } }
opts_hs_ary.reduce(default_options) { |a, e| a.merge(e) }
end
|
[
"def",
"parse_options",
"(",
"opts",
")",
"opts_hs_ary",
"=",
"opts",
".",
"map",
"{",
"|",
"x",
"|",
"x",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"x",
":",
"{",
"path",
":",
"x",
"}",
"}",
"opts_hs_ary",
".",
"reduce",
"(",
"default_options",
")",
"{",
"|",
"a",
",",
"e",
"|",
"a",
".",
"merge",
"(",
"e",
")",
"}",
"end"
] |
Parses the configuration options passed to the constructor.
@example
self.parse_options #=> {:path=>".", :rm=>true, :log_level=>:silent}
@param opts [Array<String, Hash>] The list of optitag. The strings will
be interpreted as `:path`, others will be merged.
@return [Hash] The configuration options.
@see #initialize
@api private
|
[
"Parses",
"the",
"configuration",
"options",
"passed",
"to",
"the",
"constructor",
"."
] |
cb3868684cc2fdf39cf9e807d6a8844944275fff
|
https://github.com/zuazo/dockerspec/blob/cb3868684cc2fdf39cf9e807d6a8844944275fff/lib/dockerspec/builder.rb#L255-L258
|
21,427 |
zuazo/dockerspec
|
lib/dockerspec/builder.rb
|
Dockerspec.Builder.build_from_string
|
def build_from_string(string, dir = '.')
dir = @options[:string_build_path] if @options[:string_build_path]
Dir.mktmpdir do |tmpdir|
FileUtils.cp_r("#{dir}/.", tmpdir)
dockerfile = File.join(tmpdir, 'Dockerfile')
File.open(dockerfile, 'w') { |f| f.write(string) }
build_from_dir(tmpdir)
end
end
|
ruby
|
def build_from_string(string, dir = '.')
dir = @options[:string_build_path] if @options[:string_build_path]
Dir.mktmpdir do |tmpdir|
FileUtils.cp_r("#{dir}/.", tmpdir)
dockerfile = File.join(tmpdir, 'Dockerfile')
File.open(dockerfile, 'w') { |f| f.write(string) }
build_from_dir(tmpdir)
end
end
|
[
"def",
"build_from_string",
"(",
"string",
",",
"dir",
"=",
"'.'",
")",
"dir",
"=",
"@options",
"[",
":string_build_path",
"]",
"if",
"@options",
"[",
":string_build_path",
"]",
"Dir",
".",
"mktmpdir",
"do",
"|",
"tmpdir",
"|",
"FileUtils",
".",
"cp_r",
"(",
"\"#{dir}/.\"",
",",
"tmpdir",
")",
"dockerfile",
"=",
"File",
".",
"join",
"(",
"tmpdir",
",",
"'Dockerfile'",
")",
"File",
".",
"open",
"(",
"dockerfile",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"string",
")",
"}",
"build_from_dir",
"(",
"tmpdir",
")",
"end",
"end"
] |
Builds the image from a string. Generates the Docker tag if required.
It also saves the generated image in the object internally.
This creates a temporary directory where it copies all the files and
generates the temporary Dockerfile.
@param string [String] The Dockerfile content.
@param dir [String] The directory to copy the files from. Files that are
required by the Dockerfile passed in *string*. If not passed, then
the 'string_build_path' option is used. If that is not used, '.' is
assumed.
@return void
@api private
|
[
"Builds",
"the",
"image",
"from",
"a",
"string",
".",
"Generates",
"the",
"Docker",
"tag",
"if",
"required",
"."
] |
cb3868684cc2fdf39cf9e807d6a8844944275fff
|
https://github.com/zuazo/dockerspec/blob/cb3868684cc2fdf39cf9e807d6a8844944275fff/lib/dockerspec/builder.rb#L289-L297
|
21,428 |
zuazo/dockerspec
|
lib/dockerspec/builder.rb
|
Dockerspec.Builder.build_from_dir
|
def build_from_dir(dir)
image(::Docker::Image.build_from_dir(dir, &build_block))
add_repository_tag
rescue ::Docker::Error::DockerError => e
DockerExceptionParser.new(e)
end
|
ruby
|
def build_from_dir(dir)
image(::Docker::Image.build_from_dir(dir, &build_block))
add_repository_tag
rescue ::Docker::Error::DockerError => e
DockerExceptionParser.new(e)
end
|
[
"def",
"build_from_dir",
"(",
"dir",
")",
"image",
"(",
"::",
"Docker",
"::",
"Image",
".",
"build_from_dir",
"(",
"dir",
",",
"build_block",
")",
")",
"add_repository_tag",
"rescue",
"::",
"Docker",
"::",
"Error",
"::",
"DockerError",
"=>",
"e",
"DockerExceptionParser",
".",
"new",
"(",
"e",
")",
"end"
] |
Builds the image from a directory with a Dockerfile.
It also saves the generated image in the object internally.
@param dir [String] The directory path.
@return void
@raise [Dockerspec::DockerError] For underlaying docker errors.
@api private
|
[
"Builds",
"the",
"image",
"from",
"a",
"directory",
"with",
"a",
"Dockerfile",
"."
] |
cb3868684cc2fdf39cf9e807d6a8844944275fff
|
https://github.com/zuazo/dockerspec/blob/cb3868684cc2fdf39cf9e807d6a8844944275fff/lib/dockerspec/builder.rb#L332-L337
|
21,429 |
zuazo/dockerspec
|
lib/dockerspec/builder.rb
|
Dockerspec.Builder.build_from_path
|
def build_from_path(path)
if !File.directory?(path) && File.basename(path) == 'Dockerfile'
path = File.dirname(path)
end
File.directory?(path) ? build_from_dir(path) : build_from_file(path)
end
|
ruby
|
def build_from_path(path)
if !File.directory?(path) && File.basename(path) == 'Dockerfile'
path = File.dirname(path)
end
File.directory?(path) ? build_from_dir(path) : build_from_file(path)
end
|
[
"def",
"build_from_path",
"(",
"path",
")",
"if",
"!",
"File",
".",
"directory?",
"(",
"path",
")",
"&&",
"File",
".",
"basename",
"(",
"path",
")",
"==",
"'Dockerfile'",
"path",
"=",
"File",
".",
"dirname",
"(",
"path",
")",
"end",
"File",
".",
"directory?",
"(",
"path",
")",
"?",
"build_from_dir",
"(",
"path",
")",
":",
"build_from_file",
"(",
"path",
")",
"end"
] |
Builds the image from a directory or a file.
It also saves the generated image in the object internally.
@param path [String] The path.
@return void
@api private
|
[
"Builds",
"the",
"image",
"from",
"a",
"directory",
"or",
"a",
"file",
"."
] |
cb3868684cc2fdf39cf9e807d6a8844944275fff
|
https://github.com/zuazo/dockerspec/blob/cb3868684cc2fdf39cf9e807d6a8844944275fff/lib/dockerspec/builder.rb#L350-L355
|
21,430 |
zuazo/dockerspec
|
lib/dockerspec/builder.rb
|
Dockerspec.Builder.build_from_template
|
def build_from_template(file)
context = @options[:context] || {}
template = IO.read(file)
eruby = Erubis::Eruby.new(template)
string = eruby.evaluate(context)
build_from_string(string, File.dirname(file))
end
|
ruby
|
def build_from_template(file)
context = @options[:context] || {}
template = IO.read(file)
eruby = Erubis::Eruby.new(template)
string = eruby.evaluate(context)
build_from_string(string, File.dirname(file))
end
|
[
"def",
"build_from_template",
"(",
"file",
")",
"context",
"=",
"@options",
"[",
":context",
"]",
"||",
"{",
"}",
"template",
"=",
"IO",
".",
"read",
"(",
"file",
")",
"eruby",
"=",
"Erubis",
"::",
"Eruby",
".",
"new",
"(",
"template",
")",
"string",
"=",
"eruby",
".",
"evaluate",
"(",
"context",
")",
"build_from_string",
"(",
"string",
",",
"File",
".",
"dirname",
"(",
"file",
")",
")",
"end"
] |
Builds the image from a template.
It also saves the generated image in the object internally.
@param file [String] The Dockerfile [Erubis]
(http://www.kuwata-lab.com/erubis/users-guide.html) template path.
@return void
@api private
|
[
"Builds",
"the",
"image",
"from",
"a",
"template",
"."
] |
cb3868684cc2fdf39cf9e807d6a8844944275fff
|
https://github.com/zuazo/dockerspec/blob/cb3868684cc2fdf39cf9e807d6a8844944275fff/lib/dockerspec/builder.rb#L369-L376
|
21,431 |
zuazo/dockerspec
|
lib/dockerspec/builder.rb
|
Dockerspec.Builder.build_from_id
|
def build_from_id(id)
@image = ::Docker::Image.get(id)
add_repository_tag
rescue ::Docker::Error::NotFoundError
@image = ::Docker::Image.create('fromImage' => id)
add_repository_tag
rescue ::Docker::Error::DockerError => e
DockerExceptionParser.new(e)
end
|
ruby
|
def build_from_id(id)
@image = ::Docker::Image.get(id)
add_repository_tag
rescue ::Docker::Error::NotFoundError
@image = ::Docker::Image.create('fromImage' => id)
add_repository_tag
rescue ::Docker::Error::DockerError => e
DockerExceptionParser.new(e)
end
|
[
"def",
"build_from_id",
"(",
"id",
")",
"@image",
"=",
"::",
"Docker",
"::",
"Image",
".",
"get",
"(",
"id",
")",
"add_repository_tag",
"rescue",
"::",
"Docker",
"::",
"Error",
"::",
"NotFoundError",
"@image",
"=",
"::",
"Docker",
"::",
"Image",
".",
"create",
"(",
"'fromImage'",
"=>",
"id",
")",
"add_repository_tag",
"rescue",
"::",
"Docker",
"::",
"Error",
"::",
"DockerError",
"=>",
"e",
"DockerExceptionParser",
".",
"new",
"(",
"e",
")",
"end"
] |
Gets the image from a Image ID.
It also saves the image in the object internally.
@param id [String] The Docker image ID.
@return void
@raise [Dockerspec::DockerError] For underlaying docker errors.
@api private
|
[
"Gets",
"the",
"image",
"from",
"a",
"Image",
"ID",
"."
] |
cb3868684cc2fdf39cf9e807d6a8844944275fff
|
https://github.com/zuazo/dockerspec/blob/cb3868684cc2fdf39cf9e807d6a8844944275fff/lib/dockerspec/builder.rb#L391-L399
|
21,432 |
zuazo/dockerspec
|
lib/dockerspec/builder.rb
|
Dockerspec.Builder.add_repository_tag
|
def add_repository_tag
return unless @options.key?(:tag)
repo, repo_tag = @options[:tag].split(':', 2)
@image.tag(repo: repo, tag: repo_tag, force: true)
end
|
ruby
|
def add_repository_tag
return unless @options.key?(:tag)
repo, repo_tag = @options[:tag].split(':', 2)
@image.tag(repo: repo, tag: repo_tag, force: true)
end
|
[
"def",
"add_repository_tag",
"return",
"unless",
"@options",
".",
"key?",
"(",
":tag",
")",
"repo",
",",
"repo_tag",
"=",
"@options",
"[",
":tag",
"]",
".",
"split",
"(",
"':'",
",",
"2",
")",
"@image",
".",
"tag",
"(",
"repo",
":",
"repo",
",",
"tag",
":",
"repo_tag",
",",
"force",
":",
"true",
")",
"end"
] |
Adds a repository name and a tag to the Docker image.
@return void
@api private
|
[
"Adds",
"a",
"repository",
"name",
"and",
"a",
"tag",
"to",
"the",
"Docker",
"image",
"."
] |
cb3868684cc2fdf39cf9e807d6a8844944275fff
|
https://github.com/zuazo/dockerspec/blob/cb3868684cc2fdf39cf9e807d6a8844944275fff/lib/dockerspec/builder.rb#L408-L412
|
21,433 |
Intrepidd/working_hours
|
lib/working_hours/computation.rb
|
WorkingHours.Computation.in_config_zone
|
def in_config_zone time, config: nil
if time.respond_to? :in_time_zone
time.in_time_zone(config[:time_zone])
elsif time.is_a? Date
config[:time_zone].local(time.year, time.month, time.day)
else
raise TypeError.new("Can't convert #{time.class} to a Time")
end
end
|
ruby
|
def in_config_zone time, config: nil
if time.respond_to? :in_time_zone
time.in_time_zone(config[:time_zone])
elsif time.is_a? Date
config[:time_zone].local(time.year, time.month, time.day)
else
raise TypeError.new("Can't convert #{time.class} to a Time")
end
end
|
[
"def",
"in_config_zone",
"time",
",",
"config",
":",
"nil",
"if",
"time",
".",
"respond_to?",
":in_time_zone",
"time",
".",
"in_time_zone",
"(",
"config",
"[",
":time_zone",
"]",
")",
"elsif",
"time",
".",
"is_a?",
"Date",
"config",
"[",
":time_zone",
"]",
".",
"local",
"(",
"time",
".",
"year",
",",
"time",
".",
"month",
",",
"time",
".",
"day",
")",
"else",
"raise",
"TypeError",
".",
"new",
"(",
"\"Can't convert #{time.class} to a Time\"",
")",
"end",
"end"
] |
fix for ActiveRecord < 4, doesn't implement in_time_zone for Date
|
[
"fix",
"for",
"ActiveRecord",
"<",
"4",
"doesn",
"t",
"implement",
"in_time_zone",
"for",
"Date"
] |
ae17ce1935378505e0baa678038cbd6ef70d812d
|
https://github.com/Intrepidd/working_hours/blob/ae17ce1935378505e0baa678038cbd6ef70d812d/lib/working_hours/computation.rb#L208-L216
|
21,434 |
forever-inc/forever-style-guide
|
app/helpers/forever_style_guide/application_helper.rb
|
ForeverStyleGuide.ApplicationHelper.is_active?
|
def is_active?(page_name, product_types = nil)
controller.controller_name.include?(page_name) || controller.action_name.include?(page_name) || (@product != nil && product_types !=nil && product_types.split(',').include?(@product.product_type) && [email protected]?('Historian'))
end
|
ruby
|
def is_active?(page_name, product_types = nil)
controller.controller_name.include?(page_name) || controller.action_name.include?(page_name) || (@product != nil && product_types !=nil && product_types.split(',').include?(@product.product_type) && [email protected]?('Historian'))
end
|
[
"def",
"is_active?",
"(",
"page_name",
",",
"product_types",
"=",
"nil",
")",
"controller",
".",
"controller_name",
".",
"include?",
"(",
"page_name",
")",
"||",
"controller",
".",
"action_name",
".",
"include?",
"(",
"page_name",
")",
"||",
"(",
"@product",
"!=",
"nil",
"&&",
"product_types",
"!=",
"nil",
"&&",
"product_types",
".",
"split",
"(",
"','",
")",
".",
"include?",
"(",
"@product",
".",
"product_type",
")",
"&&",
"!",
"@product",
".",
"name",
".",
"include?",
"(",
"'Historian'",
")",
")",
"end"
] |
active state nav
|
[
"active",
"state",
"nav"
] |
9027ea3040e3c1f46cf2a68d187551768557d259
|
https://github.com/forever-inc/forever-style-guide/blob/9027ea3040e3c1f46cf2a68d187551768557d259/app/helpers/forever_style_guide/application_helper.rb#L71-L73
|
21,435 |
kytrinyx/etsy
|
lib/etsy/listing.rb
|
Etsy.Listing.admirers
|
def admirers(options = {})
options = options.merge(:access_token => token, :access_secret => secret) if (token && secret)
favorite_listings = FavoriteListing.find_all_listings_favored_by(id, options)
user_ids = favorite_listings.map {|f| f.user_id }.uniq
(user_ids.size > 0) ? Array(Etsy::User.find(user_ids, options)) : []
end
|
ruby
|
def admirers(options = {})
options = options.merge(:access_token => token, :access_secret => secret) if (token && secret)
favorite_listings = FavoriteListing.find_all_listings_favored_by(id, options)
user_ids = favorite_listings.map {|f| f.user_id }.uniq
(user_ids.size > 0) ? Array(Etsy::User.find(user_ids, options)) : []
end
|
[
"def",
"admirers",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"options",
".",
"merge",
"(",
":access_token",
"=>",
"token",
",",
":access_secret",
"=>",
"secret",
")",
"if",
"(",
"token",
"&&",
"secret",
")",
"favorite_listings",
"=",
"FavoriteListing",
".",
"find_all_listings_favored_by",
"(",
"id",
",",
"options",
")",
"user_ids",
"=",
"favorite_listings",
".",
"map",
"{",
"|",
"f",
"|",
"f",
".",
"user_id",
"}",
".",
"uniq",
"(",
"user_ids",
".",
"size",
">",
"0",
")",
"?",
"Array",
"(",
"Etsy",
"::",
"User",
".",
"find",
"(",
"user_ids",
",",
"options",
")",
")",
":",
"[",
"]",
"end"
] |
Return a list of users who have favorited this listing
|
[
"Return",
"a",
"list",
"of",
"users",
"who",
"have",
"favorited",
"this",
"listing"
] |
4d20e0cedea197aa6400ac9e4c64c1a3587c9af2
|
https://github.com/kytrinyx/etsy/blob/4d20e0cedea197aa6400ac9e4c64c1a3587c9af2/lib/etsy/listing.rb#L244-L249
|
21,436 |
kytrinyx/etsy
|
lib/etsy/shop.rb
|
Etsy.Shop.listings
|
def listings(state = nil, options = {})
state = state ? {:state => state} : {}
Listing.find_all_by_shop_id(id, state.merge(options).merge(oauth))
end
|
ruby
|
def listings(state = nil, options = {})
state = state ? {:state => state} : {}
Listing.find_all_by_shop_id(id, state.merge(options).merge(oauth))
end
|
[
"def",
"listings",
"(",
"state",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"state",
"=",
"state",
"?",
"{",
":state",
"=>",
"state",
"}",
":",
"{",
"}",
"Listing",
".",
"find_all_by_shop_id",
"(",
"id",
",",
"state",
".",
"merge",
"(",
"options",
")",
".",
"merge",
"(",
"oauth",
")",
")",
"end"
] |
The collection of listings associated with this shop
|
[
"The",
"collection",
"of",
"listings",
"associated",
"with",
"this",
"shop"
] |
4d20e0cedea197aa6400ac9e4c64c1a3587c9af2
|
https://github.com/kytrinyx/etsy/blob/4d20e0cedea197aa6400ac9e4c64c1a3587c9af2/lib/etsy/shop.rb#L70-L73
|
21,437 |
kytrinyx/etsy
|
lib/etsy/user.rb
|
Etsy.User.addresses
|
def addresses
options = (token && secret) ? {:access_token => token, :access_secret => secret} : {}
@addresses ||= Address.find(username, options)
end
|
ruby
|
def addresses
options = (token && secret) ? {:access_token => token, :access_secret => secret} : {}
@addresses ||= Address.find(username, options)
end
|
[
"def",
"addresses",
"options",
"=",
"(",
"token",
"&&",
"secret",
")",
"?",
"{",
":access_token",
"=>",
"token",
",",
":access_secret",
"=>",
"secret",
"}",
":",
"{",
"}",
"@addresses",
"||=",
"Address",
".",
"find",
"(",
"username",
",",
"options",
")",
"end"
] |
The addresses associated with this user.
|
[
"The",
"addresses",
"associated",
"with",
"this",
"user",
"."
] |
4d20e0cedea197aa6400ac9e4c64c1a3587c9af2
|
https://github.com/kytrinyx/etsy/blob/4d20e0cedea197aa6400ac9e4c64c1a3587c9af2/lib/etsy/user.rb#L51-L54
|
21,438 |
kytrinyx/etsy
|
lib/etsy/user.rb
|
Etsy.User.profile
|
def profile
unless @profile
if associated_profile
@profile = Profile.new(associated_profile)
else
options = {:fields => 'user_id', :includes => 'Profile'}
options = options.merge(:access_token => token, :access_secret => secret) if (token && secret)
tmp = User.find(username, options)
@profile = Profile.new(tmp.associated_profile)
end
end
@profile
end
|
ruby
|
def profile
unless @profile
if associated_profile
@profile = Profile.new(associated_profile)
else
options = {:fields => 'user_id', :includes => 'Profile'}
options = options.merge(:access_token => token, :access_secret => secret) if (token && secret)
tmp = User.find(username, options)
@profile = Profile.new(tmp.associated_profile)
end
end
@profile
end
|
[
"def",
"profile",
"unless",
"@profile",
"if",
"associated_profile",
"@profile",
"=",
"Profile",
".",
"new",
"(",
"associated_profile",
")",
"else",
"options",
"=",
"{",
":fields",
"=>",
"'user_id'",
",",
":includes",
"=>",
"'Profile'",
"}",
"options",
"=",
"options",
".",
"merge",
"(",
":access_token",
"=>",
"token",
",",
":access_secret",
"=>",
"secret",
")",
"if",
"(",
"token",
"&&",
"secret",
")",
"tmp",
"=",
"User",
".",
"find",
"(",
"username",
",",
"options",
")",
"@profile",
"=",
"Profile",
".",
"new",
"(",
"tmp",
".",
"associated_profile",
")",
"end",
"end",
"@profile",
"end"
] |
The profile associated with this user.
|
[
"The",
"profile",
"associated",
"with",
"this",
"user",
"."
] |
4d20e0cedea197aa6400ac9e4c64c1a3587c9af2
|
https://github.com/kytrinyx/etsy/blob/4d20e0cedea197aa6400ac9e4c64c1a3587c9af2/lib/etsy/user.rb#L58-L70
|
21,439 |
kytrinyx/etsy
|
lib/etsy/response.rb
|
Etsy.Response.result
|
def result
if success?
results = to_hash['results'] || []
count == 1 ? results.first : results
else
Etsy.silent_errors ? [] : validate!
end
end
|
ruby
|
def result
if success?
results = to_hash['results'] || []
count == 1 ? results.first : results
else
Etsy.silent_errors ? [] : validate!
end
end
|
[
"def",
"result",
"if",
"success?",
"results",
"=",
"to_hash",
"[",
"'results'",
"]",
"||",
"[",
"]",
"count",
"==",
"1",
"?",
"results",
".",
"first",
":",
"results",
"else",
"Etsy",
".",
"silent_errors",
"?",
"[",
"]",
":",
"validate!",
"end",
"end"
] |
Results of the API request
|
[
"Results",
"of",
"the",
"API",
"request"
] |
4d20e0cedea197aa6400ac9e4c64c1a3587c9af2
|
https://github.com/kytrinyx/etsy/blob/4d20e0cedea197aa6400ac9e4c64c1a3587c9af2/lib/etsy/response.rb#L53-L60
|
21,440 |
kytrinyx/etsy
|
lib/etsy/basic_client.rb
|
Etsy.BasicClient.client
|
def client # :nodoc:
if @client
return @client
else
@client = Net::HTTP.new(@host, Etsy.protocol == "http" ? 80 : 443)
@client.use_ssl = true if Etsy.protocol == "https"
return @client
end
end
|
ruby
|
def client # :nodoc:
if @client
return @client
else
@client = Net::HTTP.new(@host, Etsy.protocol == "http" ? 80 : 443)
@client.use_ssl = true if Etsy.protocol == "https"
return @client
end
end
|
[
"def",
"client",
"# :nodoc:",
"if",
"@client",
"return",
"@client",
"else",
"@client",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"@host",
",",
"Etsy",
".",
"protocol",
"==",
"\"http\"",
"?",
"80",
":",
"443",
")",
"@client",
".",
"use_ssl",
"=",
"true",
"if",
"Etsy",
".",
"protocol",
"==",
"\"https\"",
"return",
"@client",
"end",
"end"
] |
Create a new client that will connect to the specified host
|
[
"Create",
"a",
"new",
"client",
"that",
"will",
"connect",
"to",
"the",
"specified",
"host"
] |
4d20e0cedea197aa6400ac9e4c64c1a3587c9af2
|
https://github.com/kytrinyx/etsy/blob/4d20e0cedea197aa6400ac9e4c64c1a3587c9af2/lib/etsy/basic_client.rb#L15-L23
|
21,441 |
kytrinyx/etsy
|
lib/etsy/secure_client.rb
|
Etsy.SecureClient.add_multipart_data
|
def add_multipart_data(req, params)
crlf = "\r\n"
boundary = Time.now.to_i.to_s(16)
req["Content-Type"] = "multipart/form-data; boundary=#{boundary}"
body = ""
params.each do |key,value|
esc_key = CGI.escape(key.to_s)
body << "--#{boundary}#{crlf}"
if value.respond_to?(:read)
body << "Content-Disposition: form-data; name=\"#{esc_key}\"; filename=\"#{File.basename(value.path)}\"#{crlf}"
body << "Content-Type: image/jpeg#{crlf*2}"
body << open(value.path, "rb") {|io| io.read}
else
body << "Content-Disposition: form-data; name=\"#{esc_key}\"#{crlf*2}#{value}"
end
body << crlf
end
body << "--#{boundary}--#{crlf*2}"
req.body = body
req["Content-Length"] = req.body.size
end
|
ruby
|
def add_multipart_data(req, params)
crlf = "\r\n"
boundary = Time.now.to_i.to_s(16)
req["Content-Type"] = "multipart/form-data; boundary=#{boundary}"
body = ""
params.each do |key,value|
esc_key = CGI.escape(key.to_s)
body << "--#{boundary}#{crlf}"
if value.respond_to?(:read)
body << "Content-Disposition: form-data; name=\"#{esc_key}\"; filename=\"#{File.basename(value.path)}\"#{crlf}"
body << "Content-Type: image/jpeg#{crlf*2}"
body << open(value.path, "rb") {|io| io.read}
else
body << "Content-Disposition: form-data; name=\"#{esc_key}\"#{crlf*2}#{value}"
end
body << crlf
end
body << "--#{boundary}--#{crlf*2}"
req.body = body
req["Content-Length"] = req.body.size
end
|
[
"def",
"add_multipart_data",
"(",
"req",
",",
"params",
")",
"crlf",
"=",
"\"\\r\\n\"",
"boundary",
"=",
"Time",
".",
"now",
".",
"to_i",
".",
"to_s",
"(",
"16",
")",
"req",
"[",
"\"Content-Type\"",
"]",
"=",
"\"multipart/form-data; boundary=#{boundary}\"",
"body",
"=",
"\"\"",
"params",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"esc_key",
"=",
"CGI",
".",
"escape",
"(",
"key",
".",
"to_s",
")",
"body",
"<<",
"\"--#{boundary}#{crlf}\"",
"if",
"value",
".",
"respond_to?",
"(",
":read",
")",
"body",
"<<",
"\"Content-Disposition: form-data; name=\\\"#{esc_key}\\\"; filename=\\\"#{File.basename(value.path)}\\\"#{crlf}\"",
"body",
"<<",
"\"Content-Type: image/jpeg#{crlf*2}\"",
"body",
"<<",
"open",
"(",
"value",
".",
"path",
",",
"\"rb\"",
")",
"{",
"|",
"io",
"|",
"io",
".",
"read",
"}",
"else",
"body",
"<<",
"\"Content-Disposition: form-data; name=\\\"#{esc_key}\\\"#{crlf*2}#{value}\"",
"end",
"body",
"<<",
"crlf",
"end",
"body",
"<<",
"\"--#{boundary}--#{crlf*2}\"",
"req",
".",
"body",
"=",
"body",
"req",
"[",
"\"Content-Length\"",
"]",
"=",
"req",
".",
"body",
".",
"size",
"end"
] |
Encodes the request as multipart
|
[
"Encodes",
"the",
"request",
"as",
"multipart"
] |
4d20e0cedea197aa6400ac9e4c64c1a3587c9af2
|
https://github.com/kytrinyx/etsy/blob/4d20e0cedea197aa6400ac9e4c64c1a3587c9af2/lib/etsy/secure_client.rb#L99-L119
|
21,442 |
Flipkart/multitenancy
|
lib/multitenancy/rack/filter.rb
|
Multitenancy.Filter.fix_headers!
|
def fix_headers!(env)
env.keys.select { |k| k =~ /^HTTP_X_/ }.each do |k|
env[k.gsub("HTTP_", "")] = env[k]
env.delete(k)
end
env
end
|
ruby
|
def fix_headers!(env)
env.keys.select { |k| k =~ /^HTTP_X_/ }.each do |k|
env[k.gsub("HTTP_", "")] = env[k]
env.delete(k)
end
env
end
|
[
"def",
"fix_headers!",
"(",
"env",
")",
"env",
".",
"keys",
".",
"select",
"{",
"|",
"k",
"|",
"k",
"=~",
"/",
"/",
"}",
".",
"each",
"do",
"|",
"k",
"|",
"env",
"[",
"k",
".",
"gsub",
"(",
"\"HTTP_\"",
",",
"\"\"",
")",
"]",
"=",
"env",
"[",
"k",
"]",
"env",
".",
"delete",
"(",
"k",
")",
"end",
"env",
"end"
] |
rack converts X_FOO to HTTP_X_FOO, so strip "HTTP_"
|
[
"rack",
"converts",
"X_FOO",
"to",
"HTTP_X_FOO",
"so",
"strip",
"HTTP_"
] |
cc91557edf0ccb2b92dabbfd88217ae6c498d4be
|
https://github.com/Flipkart/multitenancy/blob/cc91557edf0ccb2b92dabbfd88217ae6c498d4be/lib/multitenancy/rack/filter.rb#L19-L25
|
21,443 |
stackbuilders/stub_shell
|
lib/stub_shell/shell.rb
|
StubShell.Shell.resolve
|
def resolve command_string
if detected_command = @commands.detect{|cmd| cmd.matches? command_string }
detected_command
elsif parent_context
parent_context.resolve(command_string)
else
raise "Command #{command_string} could not be resolved from the current context."
end
end
|
ruby
|
def resolve command_string
if detected_command = @commands.detect{|cmd| cmd.matches? command_string }
detected_command
elsif parent_context
parent_context.resolve(command_string)
else
raise "Command #{command_string} could not be resolved from the current context."
end
end
|
[
"def",
"resolve",
"command_string",
"if",
"detected_command",
"=",
"@commands",
".",
"detect",
"{",
"|",
"cmd",
"|",
"cmd",
".",
"matches?",
"command_string",
"}",
"detected_command",
"elsif",
"parent_context",
"parent_context",
".",
"resolve",
"(",
"command_string",
")",
"else",
"raise",
"\"Command #{command_string} could not be resolved from the current context.\"",
"end",
"end"
] |
Look in current context and recursively through any available parent contexts to
find definition of command. An Exception is raised if no implementation of command
is found.
|
[
"Look",
"in",
"current",
"context",
"and",
"recursively",
"through",
"any",
"available",
"parent",
"contexts",
"to",
"find",
"definition",
"of",
"command",
".",
"An",
"Exception",
"is",
"raised",
"if",
"no",
"implementation",
"of",
"command",
"is",
"found",
"."
] |
e54ad6b40be5982cb8c72a2bbfbe8f749241142c
|
https://github.com/stackbuilders/stub_shell/blob/e54ad6b40be5982cb8c72a2bbfbe8f749241142c/lib/stub_shell/shell.rb#L28-L36
|
21,444 |
cognitect/transit-ruby
|
lib/transit/decoder.rb
|
Transit.Decoder.decode
|
def decode(node, cache=RollingCache.new, as_map_key=false)
case node
when String
if cache.has_key?(node)
cache.read(node)
else
parsed = if !node.start_with?(ESC)
node
elsif node.start_with?(TAG)
Tag.new(node[2..-1])
elsif handler = @handlers[node[1]]
handler.from_rep(node[2..-1])
elsif node.start_with?(ESC_ESC, ESC_SUB, ESC_RES)
node[1..-1]
else
@default_handler.from_rep(node[1], node[2..-1])
end
if cache.cacheable?(node, as_map_key)
cache.write(parsed)
end
parsed
end
when Array
return node if node.empty?
e0 = decode(node.shift, cache, false)
if e0 == MAP_AS_ARRAY
decode(Hash[*node], cache)
elsif Tag === e0
v = decode(node.shift, cache)
if handler = @handlers[e0.value]
handler.from_rep(v)
else
@default_handler.from_rep(e0.value,v)
end
else
[e0] + node.map {|e| decode(e, cache, as_map_key)}
end
when Hash
if node.size == 1
k = decode(node.keys.first, cache, true)
v = decode(node.values.first, cache, false)
if Tag === k
if handler = @handlers[k.value]
handler.from_rep(v)
else
@default_handler.from_rep(k.value,v)
end
else
{k => v}
end
else
node.keys.each do |k|
node.store(decode(k, cache, true), decode(node.delete(k), cache))
end
node
end
else
node
end
end
|
ruby
|
def decode(node, cache=RollingCache.new, as_map_key=false)
case node
when String
if cache.has_key?(node)
cache.read(node)
else
parsed = if !node.start_with?(ESC)
node
elsif node.start_with?(TAG)
Tag.new(node[2..-1])
elsif handler = @handlers[node[1]]
handler.from_rep(node[2..-1])
elsif node.start_with?(ESC_ESC, ESC_SUB, ESC_RES)
node[1..-1]
else
@default_handler.from_rep(node[1], node[2..-1])
end
if cache.cacheable?(node, as_map_key)
cache.write(parsed)
end
parsed
end
when Array
return node if node.empty?
e0 = decode(node.shift, cache, false)
if e0 == MAP_AS_ARRAY
decode(Hash[*node], cache)
elsif Tag === e0
v = decode(node.shift, cache)
if handler = @handlers[e0.value]
handler.from_rep(v)
else
@default_handler.from_rep(e0.value,v)
end
else
[e0] + node.map {|e| decode(e, cache, as_map_key)}
end
when Hash
if node.size == 1
k = decode(node.keys.first, cache, true)
v = decode(node.values.first, cache, false)
if Tag === k
if handler = @handlers[k.value]
handler.from_rep(v)
else
@default_handler.from_rep(k.value,v)
end
else
{k => v}
end
else
node.keys.each do |k|
node.store(decode(k, cache, true), decode(node.delete(k), cache))
end
node
end
else
node
end
end
|
[
"def",
"decode",
"(",
"node",
",",
"cache",
"=",
"RollingCache",
".",
"new",
",",
"as_map_key",
"=",
"false",
")",
"case",
"node",
"when",
"String",
"if",
"cache",
".",
"has_key?",
"(",
"node",
")",
"cache",
".",
"read",
"(",
"node",
")",
"else",
"parsed",
"=",
"if",
"!",
"node",
".",
"start_with?",
"(",
"ESC",
")",
"node",
"elsif",
"node",
".",
"start_with?",
"(",
"TAG",
")",
"Tag",
".",
"new",
"(",
"node",
"[",
"2",
"..",
"-",
"1",
"]",
")",
"elsif",
"handler",
"=",
"@handlers",
"[",
"node",
"[",
"1",
"]",
"]",
"handler",
".",
"from_rep",
"(",
"node",
"[",
"2",
"..",
"-",
"1",
"]",
")",
"elsif",
"node",
".",
"start_with?",
"(",
"ESC_ESC",
",",
"ESC_SUB",
",",
"ESC_RES",
")",
"node",
"[",
"1",
"..",
"-",
"1",
"]",
"else",
"@default_handler",
".",
"from_rep",
"(",
"node",
"[",
"1",
"]",
",",
"node",
"[",
"2",
"..",
"-",
"1",
"]",
")",
"end",
"if",
"cache",
".",
"cacheable?",
"(",
"node",
",",
"as_map_key",
")",
"cache",
".",
"write",
"(",
"parsed",
")",
"end",
"parsed",
"end",
"when",
"Array",
"return",
"node",
"if",
"node",
".",
"empty?",
"e0",
"=",
"decode",
"(",
"node",
".",
"shift",
",",
"cache",
",",
"false",
")",
"if",
"e0",
"==",
"MAP_AS_ARRAY",
"decode",
"(",
"Hash",
"[",
"node",
"]",
",",
"cache",
")",
"elsif",
"Tag",
"===",
"e0",
"v",
"=",
"decode",
"(",
"node",
".",
"shift",
",",
"cache",
")",
"if",
"handler",
"=",
"@handlers",
"[",
"e0",
".",
"value",
"]",
"handler",
".",
"from_rep",
"(",
"v",
")",
"else",
"@default_handler",
".",
"from_rep",
"(",
"e0",
".",
"value",
",",
"v",
")",
"end",
"else",
"[",
"e0",
"]",
"+",
"node",
".",
"map",
"{",
"|",
"e",
"|",
"decode",
"(",
"e",
",",
"cache",
",",
"as_map_key",
")",
"}",
"end",
"when",
"Hash",
"if",
"node",
".",
"size",
"==",
"1",
"k",
"=",
"decode",
"(",
"node",
".",
"keys",
".",
"first",
",",
"cache",
",",
"true",
")",
"v",
"=",
"decode",
"(",
"node",
".",
"values",
".",
"first",
",",
"cache",
",",
"false",
")",
"if",
"Tag",
"===",
"k",
"if",
"handler",
"=",
"@handlers",
"[",
"k",
".",
"value",
"]",
"handler",
".",
"from_rep",
"(",
"v",
")",
"else",
"@default_handler",
".",
"from_rep",
"(",
"k",
".",
"value",
",",
"v",
")",
"end",
"else",
"{",
"k",
"=>",
"v",
"}",
"end",
"else",
"node",
".",
"keys",
".",
"each",
"do",
"|",
"k",
"|",
"node",
".",
"store",
"(",
"decode",
"(",
"k",
",",
"cache",
",",
"true",
")",
",",
"decode",
"(",
"node",
".",
"delete",
"(",
"k",
")",
",",
"cache",
")",
")",
"end",
"node",
"end",
"else",
"node",
"end",
"end"
] |
Decodes a transit value to a corresponding object
@param node a transit value to be decoded
@param cache
@param as_map_key
@return decoded object
|
[
"Decodes",
"a",
"transit",
"value",
"to",
"a",
"corresponding",
"object"
] |
b4973f8c21d44657da8b486dc855a7d6a8bdf5a0
|
https://github.com/cognitect/transit-ruby/blob/b4973f8c21d44657da8b486dc855a7d6a8bdf5a0/lib/transit/decoder.rb#L58-L117
|
21,445 |
djezzzl/database_consistency
|
lib/database_consistency/helper.rb
|
DatabaseConsistency.Helper.parent_models
|
def parent_models
models.group_by(&:table_name).each_value.map do |models|
models.min_by { |model| models.include?(model.superclass) ? 1 : 0 }
end
end
|
ruby
|
def parent_models
models.group_by(&:table_name).each_value.map do |models|
models.min_by { |model| models.include?(model.superclass) ? 1 : 0 }
end
end
|
[
"def",
"parent_models",
"models",
".",
"group_by",
"(",
":table_name",
")",
".",
"each_value",
".",
"map",
"do",
"|",
"models",
"|",
"models",
".",
"min_by",
"{",
"|",
"model",
"|",
"models",
".",
"include?",
"(",
"model",
".",
"superclass",
")",
"?",
"1",
":",
"0",
"}",
"end",
"end"
] |
Return list of not inherited models
|
[
"Return",
"list",
"of",
"not",
"inherited",
"models"
] |
cac53c79dcd36284298b9c60a4c784eb184fd6bc
|
https://github.com/djezzzl/database_consistency/blob/cac53c79dcd36284298b9c60a4c784eb184fd6bc/lib/database_consistency/helper.rb#L14-L18
|
21,446 |
cloudfoundry/vcap-common
|
lib/vcap/subprocess.rb
|
VCAP.Subprocess.run
|
def run(command, expected_exit_status=0, timeout=nil, options={}, env={})
# We use a pipe to ourself to time out long running commands (if desired) as follows:
# 1. Set up a pipe to ourselves
# 2. Install a signal handler that writes to one end of our pipe on SIGCHLD
# 3. Select on the read end of our pipe and check if our process exited
sigchld_r, sigchld_w = IO.pipe
prev_sigchld_handler = install_sigchld_handler(sigchld_w)
start = Time.now.to_i
child_pid, stdin, stdout, stderr = POSIX::Spawn.popen4(env, command, options)
stdin.close
# Used to look up the name of an io object when an errors occurs while
# reading from it, as well as to look up the corresponding buffer to
# append to.
io_map = {
stderr => { :name => 'stderr', :buf => '' },
stdout => { :name => 'stdout', :buf => '' },
sigchld_r => { :name => 'sigchld_r', :buf => '' },
sigchld_w => { :name => 'sigchld_w', :buf => '' },
}
status = nil
time_left = timeout
read_cands = [stdout, stderr, sigchld_r]
error_cands = read_cands.dup
begin
while read_cands.length > 0
active_ios = IO.select(read_cands, nil, error_cands, time_left)
# Check if timeout was hit
if timeout
time_left = timeout - (Time.now.to_i - start)
unless active_ios && (time_left > 0)
raise VCAP::SubprocessTimeoutError.new(timeout,
command,
io_map[stdout][:buf],
io_map[stderr][:buf])
end
end
# Read as much as we can from the readable ios before blocking
for io in active_ios[0]
begin
io_map[io][:buf] << io.read_nonblock(READ_SIZE)
rescue IO::WaitReadable
# Reading would block, so put ourselves back on the loop
rescue EOFError
# Pipe has no more data, remove it from the readable/error set
# NB: We cannot break from the loop here, as the other pipes may have data to be read
read_cands.delete(io)
error_cands.delete(io)
end
# Our signal handler notified us that >= 1 children have exited;
# check if our child has exited.
if (io == sigchld_r) && Process.waitpid(child_pid, Process::WNOHANG)
status = $?
read_cands.delete(sigchld_r)
error_cands.delete(sigchld_r)
end
end
# Error reading from one or more pipes.
unless active_ios[2].empty?
io_names = active_ios[2].map {|io| io_map[io][:name] }
raise SubprocessReadError.new(io_names.join(', '),
command,
io_map[stdout][:buf],
io_map[stderr][:buf])
end
end
rescue
# A timeout or an error occurred while reading from one or more pipes.
# Kill the process if we haven't reaped its exit status already.
kill_pid(child_pid) unless status
raise
ensure
# Make sure we reap the child's exit status, close our fds, and restore
# the previous SIGCHLD handler
unless status
Process.waitpid(child_pid)
status = $?
end
io_map.each_key {|io| io.close unless io.closed? }
trap('CLD') { prev_sigchld_handler.call } if prev_sigchld_handler
end
unless status.exitstatus == expected_exit_status
raise SubprocessStatusError.new(command,
io_map[stdout][:buf],
io_map[stderr][:buf],
status)
end
[io_map[stdout][:buf], io_map[stderr][:buf], status]
end
|
ruby
|
def run(command, expected_exit_status=0, timeout=nil, options={}, env={})
# We use a pipe to ourself to time out long running commands (if desired) as follows:
# 1. Set up a pipe to ourselves
# 2. Install a signal handler that writes to one end of our pipe on SIGCHLD
# 3. Select on the read end of our pipe and check if our process exited
sigchld_r, sigchld_w = IO.pipe
prev_sigchld_handler = install_sigchld_handler(sigchld_w)
start = Time.now.to_i
child_pid, stdin, stdout, stderr = POSIX::Spawn.popen4(env, command, options)
stdin.close
# Used to look up the name of an io object when an errors occurs while
# reading from it, as well as to look up the corresponding buffer to
# append to.
io_map = {
stderr => { :name => 'stderr', :buf => '' },
stdout => { :name => 'stdout', :buf => '' },
sigchld_r => { :name => 'sigchld_r', :buf => '' },
sigchld_w => { :name => 'sigchld_w', :buf => '' },
}
status = nil
time_left = timeout
read_cands = [stdout, stderr, sigchld_r]
error_cands = read_cands.dup
begin
while read_cands.length > 0
active_ios = IO.select(read_cands, nil, error_cands, time_left)
# Check if timeout was hit
if timeout
time_left = timeout - (Time.now.to_i - start)
unless active_ios && (time_left > 0)
raise VCAP::SubprocessTimeoutError.new(timeout,
command,
io_map[stdout][:buf],
io_map[stderr][:buf])
end
end
# Read as much as we can from the readable ios before blocking
for io in active_ios[0]
begin
io_map[io][:buf] << io.read_nonblock(READ_SIZE)
rescue IO::WaitReadable
# Reading would block, so put ourselves back on the loop
rescue EOFError
# Pipe has no more data, remove it from the readable/error set
# NB: We cannot break from the loop here, as the other pipes may have data to be read
read_cands.delete(io)
error_cands.delete(io)
end
# Our signal handler notified us that >= 1 children have exited;
# check if our child has exited.
if (io == sigchld_r) && Process.waitpid(child_pid, Process::WNOHANG)
status = $?
read_cands.delete(sigchld_r)
error_cands.delete(sigchld_r)
end
end
# Error reading from one or more pipes.
unless active_ios[2].empty?
io_names = active_ios[2].map {|io| io_map[io][:name] }
raise SubprocessReadError.new(io_names.join(', '),
command,
io_map[stdout][:buf],
io_map[stderr][:buf])
end
end
rescue
# A timeout or an error occurred while reading from one or more pipes.
# Kill the process if we haven't reaped its exit status already.
kill_pid(child_pid) unless status
raise
ensure
# Make sure we reap the child's exit status, close our fds, and restore
# the previous SIGCHLD handler
unless status
Process.waitpid(child_pid)
status = $?
end
io_map.each_key {|io| io.close unless io.closed? }
trap('CLD') { prev_sigchld_handler.call } if prev_sigchld_handler
end
unless status.exitstatus == expected_exit_status
raise SubprocessStatusError.new(command,
io_map[stdout][:buf],
io_map[stderr][:buf],
status)
end
[io_map[stdout][:buf], io_map[stderr][:buf], status]
end
|
[
"def",
"run",
"(",
"command",
",",
"expected_exit_status",
"=",
"0",
",",
"timeout",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
",",
"env",
"=",
"{",
"}",
")",
"# We use a pipe to ourself to time out long running commands (if desired) as follows:",
"# 1. Set up a pipe to ourselves",
"# 2. Install a signal handler that writes to one end of our pipe on SIGCHLD",
"# 3. Select on the read end of our pipe and check if our process exited",
"sigchld_r",
",",
"sigchld_w",
"=",
"IO",
".",
"pipe",
"prev_sigchld_handler",
"=",
"install_sigchld_handler",
"(",
"sigchld_w",
")",
"start",
"=",
"Time",
".",
"now",
".",
"to_i",
"child_pid",
",",
"stdin",
",",
"stdout",
",",
"stderr",
"=",
"POSIX",
"::",
"Spawn",
".",
"popen4",
"(",
"env",
",",
"command",
",",
"options",
")",
"stdin",
".",
"close",
"# Used to look up the name of an io object when an errors occurs while",
"# reading from it, as well as to look up the corresponding buffer to",
"# append to.",
"io_map",
"=",
"{",
"stderr",
"=>",
"{",
":name",
"=>",
"'stderr'",
",",
":buf",
"=>",
"''",
"}",
",",
"stdout",
"=>",
"{",
":name",
"=>",
"'stdout'",
",",
":buf",
"=>",
"''",
"}",
",",
"sigchld_r",
"=>",
"{",
":name",
"=>",
"'sigchld_r'",
",",
":buf",
"=>",
"''",
"}",
",",
"sigchld_w",
"=>",
"{",
":name",
"=>",
"'sigchld_w'",
",",
":buf",
"=>",
"''",
"}",
",",
"}",
"status",
"=",
"nil",
"time_left",
"=",
"timeout",
"read_cands",
"=",
"[",
"stdout",
",",
"stderr",
",",
"sigchld_r",
"]",
"error_cands",
"=",
"read_cands",
".",
"dup",
"begin",
"while",
"read_cands",
".",
"length",
">",
"0",
"active_ios",
"=",
"IO",
".",
"select",
"(",
"read_cands",
",",
"nil",
",",
"error_cands",
",",
"time_left",
")",
"# Check if timeout was hit",
"if",
"timeout",
"time_left",
"=",
"timeout",
"-",
"(",
"Time",
".",
"now",
".",
"to_i",
"-",
"start",
")",
"unless",
"active_ios",
"&&",
"(",
"time_left",
">",
"0",
")",
"raise",
"VCAP",
"::",
"SubprocessTimeoutError",
".",
"new",
"(",
"timeout",
",",
"command",
",",
"io_map",
"[",
"stdout",
"]",
"[",
":buf",
"]",
",",
"io_map",
"[",
"stderr",
"]",
"[",
":buf",
"]",
")",
"end",
"end",
"# Read as much as we can from the readable ios before blocking",
"for",
"io",
"in",
"active_ios",
"[",
"0",
"]",
"begin",
"io_map",
"[",
"io",
"]",
"[",
":buf",
"]",
"<<",
"io",
".",
"read_nonblock",
"(",
"READ_SIZE",
")",
"rescue",
"IO",
"::",
"WaitReadable",
"# Reading would block, so put ourselves back on the loop",
"rescue",
"EOFError",
"# Pipe has no more data, remove it from the readable/error set",
"# NB: We cannot break from the loop here, as the other pipes may have data to be read",
"read_cands",
".",
"delete",
"(",
"io",
")",
"error_cands",
".",
"delete",
"(",
"io",
")",
"end",
"# Our signal handler notified us that >= 1 children have exited;",
"# check if our child has exited.",
"if",
"(",
"io",
"==",
"sigchld_r",
")",
"&&",
"Process",
".",
"waitpid",
"(",
"child_pid",
",",
"Process",
"::",
"WNOHANG",
")",
"status",
"=",
"$?",
"read_cands",
".",
"delete",
"(",
"sigchld_r",
")",
"error_cands",
".",
"delete",
"(",
"sigchld_r",
")",
"end",
"end",
"# Error reading from one or more pipes.",
"unless",
"active_ios",
"[",
"2",
"]",
".",
"empty?",
"io_names",
"=",
"active_ios",
"[",
"2",
"]",
".",
"map",
"{",
"|",
"io",
"|",
"io_map",
"[",
"io",
"]",
"[",
":name",
"]",
"}",
"raise",
"SubprocessReadError",
".",
"new",
"(",
"io_names",
".",
"join",
"(",
"', '",
")",
",",
"command",
",",
"io_map",
"[",
"stdout",
"]",
"[",
":buf",
"]",
",",
"io_map",
"[",
"stderr",
"]",
"[",
":buf",
"]",
")",
"end",
"end",
"rescue",
"# A timeout or an error occurred while reading from one or more pipes.",
"# Kill the process if we haven't reaped its exit status already.",
"kill_pid",
"(",
"child_pid",
")",
"unless",
"status",
"raise",
"ensure",
"# Make sure we reap the child's exit status, close our fds, and restore",
"# the previous SIGCHLD handler",
"unless",
"status",
"Process",
".",
"waitpid",
"(",
"child_pid",
")",
"status",
"=",
"$?",
"end",
"io_map",
".",
"each_key",
"{",
"|",
"io",
"|",
"io",
".",
"close",
"unless",
"io",
".",
"closed?",
"}",
"trap",
"(",
"'CLD'",
")",
"{",
"prev_sigchld_handler",
".",
"call",
"}",
"if",
"prev_sigchld_handler",
"end",
"unless",
"status",
".",
"exitstatus",
"==",
"expected_exit_status",
"raise",
"SubprocessStatusError",
".",
"new",
"(",
"command",
",",
"io_map",
"[",
"stdout",
"]",
"[",
":buf",
"]",
",",
"io_map",
"[",
"stderr",
"]",
"[",
":buf",
"]",
",",
"status",
")",
"end",
"[",
"io_map",
"[",
"stdout",
"]",
"[",
":buf",
"]",
",",
"io_map",
"[",
"stderr",
"]",
"[",
":buf",
"]",
",",
"status",
"]",
"end"
] |
Runs the supplied command in a subshell.
@param command String The command to be run
@param expected_exit_status Integer The expected exit status of the command in [0, 255]
@param timeout Integer How long the command should be allowed to run for
nil indicates no timeout
@param options Hash Options to be passed to Posix::Spawn
See https://github.com/rtomayko/posix-spawn
@param env Hash Environment to be passed to Posix::Spawn
See https://github.com/rtomayko/posix-spawn
@raise VCAP::SubprocessStatusError Thrown if the exit status does not match the expected
exit status.
@raise VCAP::SubprocessTimeoutError Thrown if a timeout occurs.
@raise VCAP::SubprocessReadError Thrown if there is an error reading from any of the pipes
to the child.
@return Array An array of [stdout, stderr, status]. Note that status
is an instance of Process::Status.
|
[
"Runs",
"the",
"supplied",
"command",
"in",
"a",
"subshell",
"."
] |
8d2825c7c678ffa3cf1854a635c7c4722fd054e5
|
https://github.com/cloudfoundry/vcap-common/blob/8d2825c7c678ffa3cf1854a635c7c4722fd054e5/lib/vcap/subprocess.rb#L85-L184
|
21,447 |
LeakyBucket/google_apps
|
lib/google_apps/document_handler.rb
|
GoogleApps.DocumentHandler.create_doc
|
def create_doc(text, type = nil)
@documents.include?(type) ? doc_of_type(text, type) : unknown_type(text)
end
|
ruby
|
def create_doc(text, type = nil)
@documents.include?(type) ? doc_of_type(text, type) : unknown_type(text)
end
|
[
"def",
"create_doc",
"(",
"text",
",",
"type",
"=",
"nil",
")",
"@documents",
".",
"include?",
"(",
"type",
")",
"?",
"doc_of_type",
"(",
"text",
",",
"type",
")",
":",
"unknown_type",
"(",
"text",
")",
"end"
] |
create_doc creates a document of the specified format
from the given string.
|
[
"create_doc",
"creates",
"a",
"document",
"of",
"the",
"specified",
"format",
"from",
"the",
"given",
"string",
"."
] |
5fb2cdf8abe0e92f86d321460ab392a2a2276d09
|
https://github.com/LeakyBucket/google_apps/blob/5fb2cdf8abe0e92f86d321460ab392a2a2276d09/lib/google_apps/document_handler.rb#L9-L11
|
21,448 |
LeakyBucket/google_apps
|
lib/google_apps/document_handler.rb
|
GoogleApps.DocumentHandler.doc_of_type
|
def doc_of_type(text, type)
raise "No Atom document of type: #{type}" unless @documents.include?(type.to_s)
GoogleApps::Atom.send(type, text)
end
|
ruby
|
def doc_of_type(text, type)
raise "No Atom document of type: #{type}" unless @documents.include?(type.to_s)
GoogleApps::Atom.send(type, text)
end
|
[
"def",
"doc_of_type",
"(",
"text",
",",
"type",
")",
"raise",
"\"No Atom document of type: #{type}\"",
"unless",
"@documents",
".",
"include?",
"(",
"type",
".",
"to_s",
")",
"GoogleApps",
"::",
"Atom",
".",
"send",
"(",
"type",
",",
"text",
")",
"end"
] |
doc_of_type takes a document type and a string and
returns a document of that type in the current format.
|
[
"doc_of_type",
"takes",
"a",
"document",
"type",
"and",
"a",
"string",
"and",
"returns",
"a",
"document",
"of",
"that",
"type",
"in",
"the",
"current",
"format",
"."
] |
5fb2cdf8abe0e92f86d321460ab392a2a2276d09
|
https://github.com/LeakyBucket/google_apps/blob/5fb2cdf8abe0e92f86d321460ab392a2a2276d09/lib/google_apps/document_handler.rb#L21-L25
|
21,449 |
LeakyBucket/google_apps
|
lib/google_apps/client.rb
|
GoogleApps.Client.export_status
|
def export_status(username, id)
response = make_request(:get, URI(export + "/#{username}" + build_id(id)).to_s, headers: {'content-type' => 'application/atom+xml'})
create_doc(response.body, :export_status)
end
|
ruby
|
def export_status(username, id)
response = make_request(:get, URI(export + "/#{username}" + build_id(id)).to_s, headers: {'content-type' => 'application/atom+xml'})
create_doc(response.body, :export_status)
end
|
[
"def",
"export_status",
"(",
"username",
",",
"id",
")",
"response",
"=",
"make_request",
"(",
":get",
",",
"URI",
"(",
"export",
"+",
"\"/#{username}\"",
"+",
"build_id",
"(",
"id",
")",
")",
".",
"to_s",
",",
"headers",
":",
"{",
"'content-type'",
"=>",
"'application/atom+xml'",
"}",
")",
"create_doc",
"(",
"response",
".",
"body",
",",
":export_status",
")",
"end"
] |
export_status checks the status of a mailbox export
request. It takes the username and the request_id
as arguments
export_status 'username', 847576
export_status will return the body of the HTTP response
from Google
|
[
"export_status",
"checks",
"the",
"status",
"of",
"a",
"mailbox",
"export",
"request",
".",
"It",
"takes",
"the",
"username",
"and",
"the",
"request_id",
"as",
"arguments"
] |
5fb2cdf8abe0e92f86d321460ab392a2a2276d09
|
https://github.com/LeakyBucket/google_apps/blob/5fb2cdf8abe0e92f86d321460ab392a2a2276d09/lib/google_apps/client.rb#L42-L45
|
21,450 |
LeakyBucket/google_apps
|
lib/google_apps/client.rb
|
GoogleApps.Client.fetch_export
|
def fetch_export(username, req_id, filename)
export_status_doc = export_status(username, req_id)
if export_ready?(export_status_doc)
download_export(export_status_doc, filename).each_with_index { |url, index| url.gsub!(/.*/, "#{filename}#{index}") }
else
nil
end
end
|
ruby
|
def fetch_export(username, req_id, filename)
export_status_doc = export_status(username, req_id)
if export_ready?(export_status_doc)
download_export(export_status_doc, filename).each_with_index { |url, index| url.gsub!(/.*/, "#{filename}#{index}") }
else
nil
end
end
|
[
"def",
"fetch_export",
"(",
"username",
",",
"req_id",
",",
"filename",
")",
"export_status_doc",
"=",
"export_status",
"(",
"username",
",",
"req_id",
")",
"if",
"export_ready?",
"(",
"export_status_doc",
")",
"download_export",
"(",
"export_status_doc",
",",
"filename",
")",
".",
"each_with_index",
"{",
"|",
"url",
",",
"index",
"|",
"url",
".",
"gsub!",
"(",
"/",
"/",
",",
"\"#{filename}#{index}\"",
")",
"}",
"else",
"nil",
"end",
"end"
] |
fetch_export downloads the mailbox export from Google.
It takes a username, request id and a filename as
arguments. If the export consists of more than one file
the file name will have numbers appended to indicate the
piece of the export.
fetch_export 'lholcomb2', 838382, 'lholcomb2'
fetch_export reutrns nil in the event that the export is
not yet ready.
|
[
"fetch_export",
"downloads",
"the",
"mailbox",
"export",
"from",
"Google",
".",
"It",
"takes",
"a",
"username",
"request",
"id",
"and",
"a",
"filename",
"as",
"arguments",
".",
"If",
"the",
"export",
"consists",
"of",
"more",
"than",
"one",
"file",
"the",
"file",
"name",
"will",
"have",
"numbers",
"appended",
"to",
"indicate",
"the",
"piece",
"of",
"the",
"export",
"."
] |
5fb2cdf8abe0e92f86d321460ab392a2a2276d09
|
https://github.com/LeakyBucket/google_apps/blob/5fb2cdf8abe0e92f86d321460ab392a2a2276d09/lib/google_apps/client.rb#L74-L81
|
21,451 |
LeakyBucket/google_apps
|
lib/google_apps/client.rb
|
GoogleApps.Client.download
|
def download(url, filename)
File.open(filename, "w") do |file|
file.puts(make_request(:get, url, headers: {'content-type' => 'application/atom+xml'}).body)
end
end
|
ruby
|
def download(url, filename)
File.open(filename, "w") do |file|
file.puts(make_request(:get, url, headers: {'content-type' => 'application/atom+xml'}).body)
end
end
|
[
"def",
"download",
"(",
"url",
",",
"filename",
")",
"File",
".",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"do",
"|",
"file",
"|",
"file",
".",
"puts",
"(",
"make_request",
"(",
":get",
",",
"url",
",",
"headers",
":",
"{",
"'content-type'",
"=>",
"'application/atom+xml'",
"}",
")",
".",
"body",
")",
"end",
"end"
] |
download makes a get request of the provided url
and writes the body to the provided filename.
download 'url', 'save_file'
|
[
"download",
"makes",
"a",
"get",
"request",
"of",
"the",
"provided",
"url",
"and",
"writes",
"the",
"body",
"to",
"the",
"provided",
"filename",
"."
] |
5fb2cdf8abe0e92f86d321460ab392a2a2276d09
|
https://github.com/LeakyBucket/google_apps/blob/5fb2cdf8abe0e92f86d321460ab392a2a2276d09/lib/google_apps/client.rb#L87-L91
|
21,452 |
LeakyBucket/google_apps
|
lib/google_apps/client.rb
|
GoogleApps.Client.get_groups
|
def get_groups(options = {})
limit = options[:limit] || 1000000
response = make_request(:get, group + "#{options[:extra]}" + "?startGroup=#{options[:start]}", headers: {'content-type' => 'application/atom+xml'})
pages = fetch_pages(response, limit, :feed)
return_all(pages)
end
|
ruby
|
def get_groups(options = {})
limit = options[:limit] || 1000000
response = make_request(:get, group + "#{options[:extra]}" + "?startGroup=#{options[:start]}", headers: {'content-type' => 'application/atom+xml'})
pages = fetch_pages(response, limit, :feed)
return_all(pages)
end
|
[
"def",
"get_groups",
"(",
"options",
"=",
"{",
"}",
")",
"limit",
"=",
"options",
"[",
":limit",
"]",
"||",
"1000000",
"response",
"=",
"make_request",
"(",
":get",
",",
"group",
"+",
"\"#{options[:extra]}\"",
"+",
"\"?startGroup=#{options[:start]}\"",
",",
"headers",
":",
"{",
"'content-type'",
"=>",
"'application/atom+xml'",
"}",
")",
"pages",
"=",
"fetch_pages",
"(",
"response",
",",
"limit",
",",
":feed",
")",
"return_all",
"(",
"pages",
")",
"end"
] |
get_groups retrieves all the groups from the domain
get_groups
get_groups returns the final response from Google.
|
[
"get_groups",
"retrieves",
"all",
"the",
"groups",
"from",
"the",
"domain"
] |
5fb2cdf8abe0e92f86d321460ab392a2a2276d09
|
https://github.com/LeakyBucket/google_apps/blob/5fb2cdf8abe0e92f86d321460ab392a2a2276d09/lib/google_apps/client.rb#L114-L120
|
21,453 |
LeakyBucket/google_apps
|
lib/google_apps/client.rb
|
GoogleApps.Client.get_next_page
|
def get_next_page(next_page_url, type)
response = make_request(:get, next_page_url, headers: {'content-type' => 'application/atom+xml'})
GoogleApps::Atom.feed(response.body)
end
|
ruby
|
def get_next_page(next_page_url, type)
response = make_request(:get, next_page_url, headers: {'content-type' => 'application/atom+xml'})
GoogleApps::Atom.feed(response.body)
end
|
[
"def",
"get_next_page",
"(",
"next_page_url",
",",
"type",
")",
"response",
"=",
"make_request",
"(",
":get",
",",
"next_page_url",
",",
"headers",
":",
"{",
"'content-type'",
"=>",
"'application/atom+xml'",
"}",
")",
"GoogleApps",
"::",
"Atom",
".",
"feed",
"(",
"response",
".",
"body",
")",
"end"
] |
get_next_page retrieves the next page in the response.
|
[
"get_next_page",
"retrieves",
"the",
"next",
"page",
"in",
"the",
"response",
"."
] |
5fb2cdf8abe0e92f86d321460ab392a2a2276d09
|
https://github.com/LeakyBucket/google_apps/blob/5fb2cdf8abe0e92f86d321460ab392a2a2276d09/lib/google_apps/client.rb#L285-L288
|
21,454 |
LeakyBucket/google_apps
|
lib/google_apps/client.rb
|
GoogleApps.Client.fetch_pages
|
def fetch_pages(response, limit, type)
pages = [GoogleApps::Atom.feed(response.body)]
while (pages.last.next_page) and (pages.count * PAGE_SIZE[:user] < limit)
pages << get_next_page(pages.last.next_page, type)
end
pages
end
|
ruby
|
def fetch_pages(response, limit, type)
pages = [GoogleApps::Atom.feed(response.body)]
while (pages.last.next_page) and (pages.count * PAGE_SIZE[:user] < limit)
pages << get_next_page(pages.last.next_page, type)
end
pages
end
|
[
"def",
"fetch_pages",
"(",
"response",
",",
"limit",
",",
"type",
")",
"pages",
"=",
"[",
"GoogleApps",
"::",
"Atom",
".",
"feed",
"(",
"response",
".",
"body",
")",
"]",
"while",
"(",
"pages",
".",
"last",
".",
"next_page",
")",
"and",
"(",
"pages",
".",
"count",
"*",
"PAGE_SIZE",
"[",
":user",
"]",
"<",
"limit",
")",
"pages",
"<<",
"get_next_page",
"(",
"pages",
".",
"last",
".",
"next_page",
",",
"type",
")",
"end",
"pages",
"end"
] |
fetch_feed retrieves the remaining pages in the request.
It takes a page and a limit as arguments.
|
[
"fetch_feed",
"retrieves",
"the",
"remaining",
"pages",
"in",
"the",
"request",
".",
"It",
"takes",
"a",
"page",
"and",
"a",
"limit",
"as",
"arguments",
"."
] |
5fb2cdf8abe0e92f86d321460ab392a2a2276d09
|
https://github.com/LeakyBucket/google_apps/blob/5fb2cdf8abe0e92f86d321460ab392a2a2276d09/lib/google_apps/client.rb#L292-L299
|
21,455 |
samuelgiles/duckface
|
lib/duckface/parameter_pair.rb
|
Duckface.ParameterPair.argument_name_without_leading_underscore
|
def argument_name_without_leading_underscore
name = if argument_name_string[FIRST_CHARACTER] == UNDERSCORE
argument_name_string.reverse.chop.reverse
else
argument_name_string
end
name.to_sym
end
|
ruby
|
def argument_name_without_leading_underscore
name = if argument_name_string[FIRST_CHARACTER] == UNDERSCORE
argument_name_string.reverse.chop.reverse
else
argument_name_string
end
name.to_sym
end
|
[
"def",
"argument_name_without_leading_underscore",
"name",
"=",
"if",
"argument_name_string",
"[",
"FIRST_CHARACTER",
"]",
"==",
"UNDERSCORE",
"argument_name_string",
".",
"reverse",
".",
"chop",
".",
"reverse",
"else",
"argument_name_string",
"end",
"name",
".",
"to_sym",
"end"
] |
Leading underscores are used to indicate a parameter isn't used
|
[
"Leading",
"underscores",
"are",
"used",
"to",
"indicate",
"a",
"parameter",
"isn",
"t",
"used"
] |
c297c1f8abb5dfaea7009da06c7d6026811a08ea
|
https://github.com/samuelgiles/duckface/blob/c297c1f8abb5dfaea7009da06c7d6026811a08ea/lib/duckface/parameter_pair.rb#L20-L27
|
21,456 |
conduit/conduit
|
lib/conduit/cli.rb
|
Conduit.CLI.copy_files
|
def copy_files
files_to_copy.each do |origin, destination|
template(origin, destination, force: true)
end
end
|
ruby
|
def copy_files
files_to_copy.each do |origin, destination|
template(origin, destination, force: true)
end
end
|
[
"def",
"copy_files",
"files_to_copy",
".",
"each",
"do",
"|",
"origin",
",",
"destination",
"|",
"template",
"(",
"origin",
",",
"destination",
",",
"force",
":",
"true",
")",
"end",
"end"
] |
Copy template files
|
[
"Copy",
"template",
"files"
] |
34546f71d59eb30ecc4b3172ee4459a8b37dd5ba
|
https://github.com/conduit/conduit/blob/34546f71d59eb30ecc4b3172ee4459a8b37dd5ba/lib/conduit/cli.rb#L103-L107
|
21,457 |
conduit/conduit
|
lib/conduit/cli.rb
|
Conduit.CLI.modify_files
|
def modify_files
gemspec_file = "#{@base_path}/conduit-#{@dasherized_name}.gemspec"
# add gemspec dependencies
str = " # Dependencies\n"\
" #\n"\
" spec.add_dependency \"conduit\", \"~> 1.0.6\"\n"\
" # xml parser\n"\
" spec.add_dependency \"nokogiri\"\n\n"\
" # Development Dependencies\n"\
" #\n"\
" # to compare xml files in tests\n"\
" spec.add_development_dependency \"equivalent-xml\"\n"\
" spec.add_development_dependency \"rspec-its\"\n"\
" # for building CLI\n"\
" spec.add_development_dependency \"thor\"\n"\
" # for debugging\n"\
" spec.add_development_dependency \"byebug\"\n"
insert_into_file gemspec_file, str, after: "spec.require_paths = [\"lib\"]\n\n"
# remove description
gsub_file(gemspec_file, /spec\.description(.*)\n/, "")
# update summary
new_summary = "spec.summary = \"#{ActiveSupport::Inflector.humanize @underscored_name} Driver for Conduit\""
gsub_file(gemspec_file, /spec\.summary(.*)/, new_summary)
# update homepage
new_homepage = "spec.homepage = \"http://www.github.com/conduit/conduit-#{@dasherized_name}\""
gsub_file(gemspec_file, /spec\.homepage(.*)/, new_homepage)
end
|
ruby
|
def modify_files
gemspec_file = "#{@base_path}/conduit-#{@dasherized_name}.gemspec"
# add gemspec dependencies
str = " # Dependencies\n"\
" #\n"\
" spec.add_dependency \"conduit\", \"~> 1.0.6\"\n"\
" # xml parser\n"\
" spec.add_dependency \"nokogiri\"\n\n"\
" # Development Dependencies\n"\
" #\n"\
" # to compare xml files in tests\n"\
" spec.add_development_dependency \"equivalent-xml\"\n"\
" spec.add_development_dependency \"rspec-its\"\n"\
" # for building CLI\n"\
" spec.add_development_dependency \"thor\"\n"\
" # for debugging\n"\
" spec.add_development_dependency \"byebug\"\n"
insert_into_file gemspec_file, str, after: "spec.require_paths = [\"lib\"]\n\n"
# remove description
gsub_file(gemspec_file, /spec\.description(.*)\n/, "")
# update summary
new_summary = "spec.summary = \"#{ActiveSupport::Inflector.humanize @underscored_name} Driver for Conduit\""
gsub_file(gemspec_file, /spec\.summary(.*)/, new_summary)
# update homepage
new_homepage = "spec.homepage = \"http://www.github.com/conduit/conduit-#{@dasherized_name}\""
gsub_file(gemspec_file, /spec\.homepage(.*)/, new_homepage)
end
|
[
"def",
"modify_files",
"gemspec_file",
"=",
"\"#{@base_path}/conduit-#{@dasherized_name}.gemspec\"",
"# add gemspec dependencies",
"str",
"=",
"\" # Dependencies\\n\"",
"\" #\\n\"",
"\" spec.add_dependency \\\"conduit\\\", \\\"~> 1.0.6\\\"\\n\"",
"\" # xml parser\\n\"",
"\" spec.add_dependency \\\"nokogiri\\\"\\n\\n\"",
"\" # Development Dependencies\\n\"",
"\" #\\n\"",
"\" # to compare xml files in tests\\n\"",
"\" spec.add_development_dependency \\\"equivalent-xml\\\"\\n\"",
"\" spec.add_development_dependency \\\"rspec-its\\\"\\n\"",
"\" # for building CLI\\n\"",
"\" spec.add_development_dependency \\\"thor\\\"\\n\"",
"\" # for debugging\\n\"",
"\" spec.add_development_dependency \\\"byebug\\\"\\n\"",
"insert_into_file",
"gemspec_file",
",",
"str",
",",
"after",
":",
"\"spec.require_paths = [\\\"lib\\\"]\\n\\n\"",
"# remove description",
"gsub_file",
"(",
"gemspec_file",
",",
"/",
"\\.",
"\\n",
"/",
",",
"\"\"",
")",
"# update summary",
"new_summary",
"=",
"\"spec.summary = \\\"#{ActiveSupport::Inflector.humanize @underscored_name} Driver for Conduit\\\"\"",
"gsub_file",
"(",
"gemspec_file",
",",
"/",
"\\.",
"/",
",",
"new_summary",
")",
"# update homepage",
"new_homepage",
"=",
"\"spec.homepage = \\\"http://www.github.com/conduit/conduit-#{@dasherized_name}\\\"\"",
"gsub_file",
"(",
"gemspec_file",
",",
"/",
"\\.",
"/",
",",
"new_homepage",
")",
"end"
] |
Adds missing lines to the files
|
[
"Adds",
"missing",
"lines",
"to",
"the",
"files"
] |
34546f71d59eb30ecc4b3172ee4459a8b37dd5ba
|
https://github.com/conduit/conduit/blob/34546f71d59eb30ecc4b3172ee4459a8b37dd5ba/lib/conduit/cli.rb#L110-L141
|
21,458 |
makersacademy/pipekit
|
lib/pipekit/deal.rb
|
Pipekit.Deal.update_by_person
|
def update_by_person(email, params, person_repo: Person.new)
person = person_repo.find_exactly_by_email(email)
deal = get_by_person_id(person[:id], person_repo: person_repo).first
update(deal[:id], params)
end
|
ruby
|
def update_by_person(email, params, person_repo: Person.new)
person = person_repo.find_exactly_by_email(email)
deal = get_by_person_id(person[:id], person_repo: person_repo).first
update(deal[:id], params)
end
|
[
"def",
"update_by_person",
"(",
"email",
",",
"params",
",",
"person_repo",
":",
"Person",
".",
"new",
")",
"person",
"=",
"person_repo",
".",
"find_exactly_by_email",
"(",
"email",
")",
"deal",
"=",
"get_by_person_id",
"(",
"person",
"[",
":id",
"]",
",",
"person_repo",
":",
"person_repo",
")",
".",
"first",
"update",
"(",
"deal",
"[",
":id",
"]",
",",
"params",
")",
"end"
] |
Finds a person by their email, then finds the first deal related to that
person and updates it with the params provided
|
[
"Finds",
"a",
"person",
"by",
"their",
"email",
"then",
"finds",
"the",
"first",
"deal",
"related",
"to",
"that",
"person",
"and",
"updates",
"it",
"with",
"the",
"params",
"provided"
] |
ac8a0e6adbc875637cc87587fa4d4795927b1f11
|
https://github.com/makersacademy/pipekit/blob/ac8a0e6adbc875637cc87587fa4d4795927b1f11/lib/pipekit/deal.rb#L14-L18
|
21,459 |
pjotrp/bioruby-alignment
|
lib/bio-alignment/tree.rb
|
Bio.Tree.clone_subtree
|
def clone_subtree start_node
new_tree = self.class.new
list = [start_node] + start_node.descendents
list.each do |x|
new_tree.add_node(x)
end
each_edge do |node1, node2, edge|
if new_tree.include?(node1) and new_tree.include?(node2)
new_tree.add_edge(node1, node2, edge)
end
end
new_tree
end
|
ruby
|
def clone_subtree start_node
new_tree = self.class.new
list = [start_node] + start_node.descendents
list.each do |x|
new_tree.add_node(x)
end
each_edge do |node1, node2, edge|
if new_tree.include?(node1) and new_tree.include?(node2)
new_tree.add_edge(node1, node2, edge)
end
end
new_tree
end
|
[
"def",
"clone_subtree",
"start_node",
"new_tree",
"=",
"self",
".",
"class",
".",
"new",
"list",
"=",
"[",
"start_node",
"]",
"+",
"start_node",
".",
"descendents",
"list",
".",
"each",
"do",
"|",
"x",
"|",
"new_tree",
".",
"add_node",
"(",
"x",
")",
"end",
"each_edge",
"do",
"|",
"node1",
",",
"node2",
",",
"edge",
"|",
"if",
"new_tree",
".",
"include?",
"(",
"node1",
")",
"and",
"new_tree",
".",
"include?",
"(",
"node2",
")",
"new_tree",
".",
"add_edge",
"(",
"node1",
",",
"node2",
",",
"edge",
")",
"end",
"end",
"new_tree",
"end"
] |
Create a deep clone of the tree
|
[
"Create",
"a",
"deep",
"clone",
"of",
"the",
"tree"
] |
39430b55a6cfcb39f057ad696da2966a3d8c3068
|
https://github.com/pjotrp/bioruby-alignment/blob/39430b55a6cfcb39f057ad696da2966a3d8c3068/lib/bio-alignment/tree.rb#L128-L140
|
21,460 |
pjotrp/bioruby-alignment
|
lib/bio-alignment/tree.rb
|
Bio.Tree.clone_tree_without_branch
|
def clone_tree_without_branch node
new_tree = self.class.new
original = [root] + root.descendents
# p "Original",original
skip = [node] + node.descendents
# p "Skip",skip
# p "Retain",root.descendents - skip
nodes.each do |x|
if not skip.include?(x)
new_tree.add_node(x)
else
end
end
each_edge do |node1, node2, edge|
if new_tree.include?(node1) and new_tree.include?(node2)
new_tree.add_edge(node1, node2, edge)
end
end
new_tree
end
|
ruby
|
def clone_tree_without_branch node
new_tree = self.class.new
original = [root] + root.descendents
# p "Original",original
skip = [node] + node.descendents
# p "Skip",skip
# p "Retain",root.descendents - skip
nodes.each do |x|
if not skip.include?(x)
new_tree.add_node(x)
else
end
end
each_edge do |node1, node2, edge|
if new_tree.include?(node1) and new_tree.include?(node2)
new_tree.add_edge(node1, node2, edge)
end
end
new_tree
end
|
[
"def",
"clone_tree_without_branch",
"node",
"new_tree",
"=",
"self",
".",
"class",
".",
"new",
"original",
"=",
"[",
"root",
"]",
"+",
"root",
".",
"descendents",
"# p \"Original\",original",
"skip",
"=",
"[",
"node",
"]",
"+",
"node",
".",
"descendents",
"# p \"Skip\",skip",
"# p \"Retain\",root.descendents - skip",
"nodes",
".",
"each",
"do",
"|",
"x",
"|",
"if",
"not",
"skip",
".",
"include?",
"(",
"x",
")",
"new_tree",
".",
"add_node",
"(",
"x",
")",
"else",
"end",
"end",
"each_edge",
"do",
"|",
"node1",
",",
"node2",
",",
"edge",
"|",
"if",
"new_tree",
".",
"include?",
"(",
"node1",
")",
"and",
"new_tree",
".",
"include?",
"(",
"node2",
")",
"new_tree",
".",
"add_edge",
"(",
"node1",
",",
"node2",
",",
"edge",
")",
"end",
"end",
"new_tree",
"end"
] |
Clone a tree without the branch starting at node
|
[
"Clone",
"a",
"tree",
"without",
"the",
"branch",
"starting",
"at",
"node"
] |
39430b55a6cfcb39f057ad696da2966a3d8c3068
|
https://github.com/pjotrp/bioruby-alignment/blob/39430b55a6cfcb39f057ad696da2966a3d8c3068/lib/bio-alignment/tree.rb#L143-L162
|
21,461 |
ridiculous/usable
|
lib/usable/config_multi.rb
|
Usable.ConfigMulti.+
|
def +(other)
config = clone
specs = other.spec.to_h
specs.each { |key, val| config[key] = val }
methods = other.spec.singleton_methods
methods.map! { |name| name.to_s.tr('=', '').to_sym }
methods.uniq!
methods -= specs.keys
methods.each do |name|
config.spec.define_singleton_method(name) do
other.spec.public_method(name).call
end
config.instance_variable_get(:@lazy_loads) << name
end
config
end
|
ruby
|
def +(other)
config = clone
specs = other.spec.to_h
specs.each { |key, val| config[key] = val }
methods = other.spec.singleton_methods
methods.map! { |name| name.to_s.tr('=', '').to_sym }
methods.uniq!
methods -= specs.keys
methods.each do |name|
config.spec.define_singleton_method(name) do
other.spec.public_method(name).call
end
config.instance_variable_get(:@lazy_loads) << name
end
config
end
|
[
"def",
"+",
"(",
"other",
")",
"config",
"=",
"clone",
"specs",
"=",
"other",
".",
"spec",
".",
"to_h",
"specs",
".",
"each",
"{",
"|",
"key",
",",
"val",
"|",
"config",
"[",
"key",
"]",
"=",
"val",
"}",
"methods",
"=",
"other",
".",
"spec",
".",
"singleton_methods",
"methods",
".",
"map!",
"{",
"|",
"name",
"|",
"name",
".",
"to_s",
".",
"tr",
"(",
"'='",
",",
"''",
")",
".",
"to_sym",
"}",
"methods",
".",
"uniq!",
"methods",
"-=",
"specs",
".",
"keys",
"methods",
".",
"each",
"do",
"|",
"name",
"|",
"config",
".",
"spec",
".",
"define_singleton_method",
"(",
"name",
")",
"do",
"other",
".",
"spec",
".",
"public_method",
"(",
"name",
")",
".",
"call",
"end",
"config",
".",
"instance_variable_get",
"(",
":@lazy_loads",
")",
"<<",
"name",
"end",
"config",
"end"
] |
It's important to define all block specs we need to lazy load
|
[
"It",
"s",
"important",
"to",
"define",
"all",
"block",
"specs",
"we",
"need",
"to",
"lazy",
"load"
] |
1b985164480a0a551af2a0c2037c0a155be51857
|
https://github.com/ridiculous/usable/blob/1b985164480a0a551af2a0c2037c0a155be51857/lib/usable/config_multi.rb#L4-L19
|
21,462 |
makersacademy/pipekit
|
lib/pipekit/request.rb
|
Pipekit.Request.parse_body
|
def parse_body(body)
body.reduce({}) do |result, (field, value)|
value = Config.field_value_id(resource.singular, field, value)
field = Config.field_id(resource.singular, field)
result.tap { |result| result[field] = value }
end
end
|
ruby
|
def parse_body(body)
body.reduce({}) do |result, (field, value)|
value = Config.field_value_id(resource.singular, field, value)
field = Config.field_id(resource.singular, field)
result.tap { |result| result[field] = value }
end
end
|
[
"def",
"parse_body",
"(",
"body",
")",
"body",
".",
"reduce",
"(",
"{",
"}",
")",
"do",
"|",
"result",
",",
"(",
"field",
",",
"value",
")",
"|",
"value",
"=",
"Config",
".",
"field_value_id",
"(",
"resource",
".",
"singular",
",",
"field",
",",
"value",
")",
"field",
"=",
"Config",
".",
"field_id",
"(",
"resource",
".",
"singular",
",",
"field",
")",
"result",
".",
"tap",
"{",
"|",
"result",
"|",
"result",
"[",
"field",
"]",
"=",
"value",
"}",
"end",
"end"
] |
Replaces custom fields with their Pipedrive ID
if the ID is defined in the configuration
So if the body looked like this with a custom field
called middle_name:
{ middle_name: "Dave" }
And it has a Pipedrive ID ("123abc"), this will put in this custom ID
{ "123abc": "Dave" }
meaning you don't have to worry about the custom IDs
|
[
"Replaces",
"custom",
"fields",
"with",
"their",
"Pipedrive",
"ID",
"if",
"the",
"ID",
"is",
"defined",
"in",
"the",
"configuration"
] |
ac8a0e6adbc875637cc87587fa4d4795927b1f11
|
https://github.com/makersacademy/pipekit/blob/ac8a0e6adbc875637cc87587fa4d4795927b1f11/lib/pipekit/request.rb#L106-L112
|
21,463 |
hongshu-corp/liquigen
|
lib/liquigen/scaffold/config.rb
|
Liquigen::Scaffold.Config.process
|
def process
# if not exist the .liquigen file create it
File.write(CONFIG_FILE, prepare_default_content.join("\n")) unless File.exist?(CONFIG_FILE)
# then open the vim editor
system('vi ' + CONFIG_FILE)
end
|
ruby
|
def process
# if not exist the .liquigen file create it
File.write(CONFIG_FILE, prepare_default_content.join("\n")) unless File.exist?(CONFIG_FILE)
# then open the vim editor
system('vi ' + CONFIG_FILE)
end
|
[
"def",
"process",
"# if not exist the .liquigen file create it",
"File",
".",
"write",
"(",
"CONFIG_FILE",
",",
"prepare_default_content",
".",
"join",
"(",
"\"\\n\"",
")",
")",
"unless",
"File",
".",
"exist?",
"(",
"CONFIG_FILE",
")",
"# then open the vim editor",
"system",
"(",
"'vi '",
"+",
"CONFIG_FILE",
")",
"end"
] |
write config file
|
[
"write",
"config",
"file"
] |
faa2f20eebed519bbe117fc4d374bb9750797873
|
https://github.com/hongshu-corp/liquigen/blob/faa2f20eebed519bbe117fc4d374bb9750797873/lib/liquigen/scaffold/config.rb#L5-L11
|
21,464 |
gocardless/callcredit-ruby
|
lib/callcredit/request.rb
|
Callcredit.Request.perform
|
def perform(checks, check_data = {})
# check_data = Callcredit::Validator.clean_check_data(check_data)
response = @connection.get do |request|
request.path = @config[:api_endpoint]
request.body = build_request_xml(checks, check_data).to_s
end
@config[:raw] ? response : response.body
rescue Faraday::Error::ClientError => e
if e.response.nil?
raise APIError.new
else
raise APIError.new(e.response[:body], e.response[:status], e.response)
end
end
|
ruby
|
def perform(checks, check_data = {})
# check_data = Callcredit::Validator.clean_check_data(check_data)
response = @connection.get do |request|
request.path = @config[:api_endpoint]
request.body = build_request_xml(checks, check_data).to_s
end
@config[:raw] ? response : response.body
rescue Faraday::Error::ClientError => e
if e.response.nil?
raise APIError.new
else
raise APIError.new(e.response[:body], e.response[:status], e.response)
end
end
|
[
"def",
"perform",
"(",
"checks",
",",
"check_data",
"=",
"{",
"}",
")",
"# check_data = Callcredit::Validator.clean_check_data(check_data)",
"response",
"=",
"@connection",
".",
"get",
"do",
"|",
"request",
"|",
"request",
".",
"path",
"=",
"@config",
"[",
":api_endpoint",
"]",
"request",
".",
"body",
"=",
"build_request_xml",
"(",
"checks",
",",
"check_data",
")",
".",
"to_s",
"end",
"@config",
"[",
":raw",
"]",
"?",
"response",
":",
"response",
".",
"body",
"rescue",
"Faraday",
"::",
"Error",
"::",
"ClientError",
"=>",
"e",
"if",
"e",
".",
"response",
".",
"nil?",
"raise",
"APIError",
".",
"new",
"else",
"raise",
"APIError",
".",
"new",
"(",
"e",
".",
"response",
"[",
":body",
"]",
",",
"e",
".",
"response",
"[",
":status",
"]",
",",
"e",
".",
"response",
")",
"end",
"end"
] |
Perform a credit check
|
[
"Perform",
"a",
"credit",
"check"
] |
cb48ddae90ac7245abb5b7aa0d1cfd6a28f20eb3
|
https://github.com/gocardless/callcredit-ruby/blob/cb48ddae90ac7245abb5b7aa0d1cfd6a28f20eb3/lib/callcredit/request.rb#L9-L22
|
21,465 |
gocardless/callcredit-ruby
|
lib/callcredit/request.rb
|
Callcredit.Request.build_request_xml
|
def build_request_xml(checks, check_data = {})
builder = Nokogiri::XML::Builder.new do |xml|
xml.callvalidate do
authentication(xml)
xml.sessions do
xml.session("RID" => Time.now.to_f) do
xml.data do
personal_data(xml, check_data[:personal_data])
card_data(xml, check_data[:card_data])
bank_data(xml, check_data[:bank_data])
income_data(xml, check_data[:income_data])
required_checks(xml, checks)
end
end
end
xml.application @config[:application_name]
end
end
builder.doc
end
|
ruby
|
def build_request_xml(checks, check_data = {})
builder = Nokogiri::XML::Builder.new do |xml|
xml.callvalidate do
authentication(xml)
xml.sessions do
xml.session("RID" => Time.now.to_f) do
xml.data do
personal_data(xml, check_data[:personal_data])
card_data(xml, check_data[:card_data])
bank_data(xml, check_data[:bank_data])
income_data(xml, check_data[:income_data])
required_checks(xml, checks)
end
end
end
xml.application @config[:application_name]
end
end
builder.doc
end
|
[
"def",
"build_request_xml",
"(",
"checks",
",",
"check_data",
"=",
"{",
"}",
")",
"builder",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Builder",
".",
"new",
"do",
"|",
"xml",
"|",
"xml",
".",
"callvalidate",
"do",
"authentication",
"(",
"xml",
")",
"xml",
".",
"sessions",
"do",
"xml",
".",
"session",
"(",
"\"RID\"",
"=>",
"Time",
".",
"now",
".",
"to_f",
")",
"do",
"xml",
".",
"data",
"do",
"personal_data",
"(",
"xml",
",",
"check_data",
"[",
":personal_data",
"]",
")",
"card_data",
"(",
"xml",
",",
"check_data",
"[",
":card_data",
"]",
")",
"bank_data",
"(",
"xml",
",",
"check_data",
"[",
":bank_data",
"]",
")",
"income_data",
"(",
"xml",
",",
"check_data",
"[",
":income_data",
"]",
")",
"required_checks",
"(",
"xml",
",",
"checks",
")",
"end",
"end",
"end",
"xml",
".",
"application",
"@config",
"[",
":application_name",
"]",
"end",
"end",
"builder",
".",
"doc",
"end"
] |
Compile the complete XML request to send to Callcredit
|
[
"Compile",
"the",
"complete",
"XML",
"request",
"to",
"send",
"to",
"Callcredit"
] |
cb48ddae90ac7245abb5b7aa0d1cfd6a28f20eb3
|
https://github.com/gocardless/callcredit-ruby/blob/cb48ddae90ac7245abb5b7aa0d1cfd6a28f20eb3/lib/callcredit/request.rb#L25-L44
|
21,466 |
gocardless/callcredit-ruby
|
lib/callcredit/request.rb
|
Callcredit.Request.required_checks
|
def required_checks(xml, checks)
required_checks = [*checks].map { |c| Util.underscore(c).to_sym }
xml.ChecksRequired do
Constants::CHECKS.each do |check|
included = required_checks.include?(Util.underscore(check).to_sym)
xml.send(check, included ? "yes" : "no")
end
end
end
|
ruby
|
def required_checks(xml, checks)
required_checks = [*checks].map { |c| Util.underscore(c).to_sym }
xml.ChecksRequired do
Constants::CHECKS.each do |check|
included = required_checks.include?(Util.underscore(check).to_sym)
xml.send(check, included ? "yes" : "no")
end
end
end
|
[
"def",
"required_checks",
"(",
"xml",
",",
"checks",
")",
"required_checks",
"=",
"[",
"checks",
"]",
".",
"map",
"{",
"|",
"c",
"|",
"Util",
".",
"underscore",
"(",
"c",
")",
".",
"to_sym",
"}",
"xml",
".",
"ChecksRequired",
"do",
"Constants",
"::",
"CHECKS",
".",
"each",
"do",
"|",
"check",
"|",
"included",
"=",
"required_checks",
".",
"include?",
"(",
"Util",
".",
"underscore",
"(",
"check",
")",
".",
"to_sym",
")",
"xml",
".",
"send",
"(",
"check",
",",
"included",
"?",
"\"yes\"",
":",
"\"no\"",
")",
"end",
"end",
"end"
] |
Checks to be performed
|
[
"Checks",
"to",
"be",
"performed"
] |
cb48ddae90ac7245abb5b7aa0d1cfd6a28f20eb3
|
https://github.com/gocardless/callcredit-ruby/blob/cb48ddae90ac7245abb5b7aa0d1cfd6a28f20eb3/lib/callcredit/request.rb#L58-L66
|
21,467 |
songkick/queue
|
lib/songkick_queue/worker.rb
|
SongkickQueue.Worker.stop_if_signal_caught
|
def stop_if_signal_caught
Thread.new do
loop do
sleep 1
if @shutdown
logger.info "Recevied SIG#{@shutdown}, shutting down consumers"
@consumer_instances.each { |instance| instance.shutdown }
@client.channel.work_pool.shutdown
@shutdown = nil
end
end
end
end
|
ruby
|
def stop_if_signal_caught
Thread.new do
loop do
sleep 1
if @shutdown
logger.info "Recevied SIG#{@shutdown}, shutting down consumers"
@consumer_instances.each { |instance| instance.shutdown }
@client.channel.work_pool.shutdown
@shutdown = nil
end
end
end
end
|
[
"def",
"stop_if_signal_caught",
"Thread",
".",
"new",
"do",
"loop",
"do",
"sleep",
"1",
"if",
"@shutdown",
"logger",
".",
"info",
"\"Recevied SIG#{@shutdown}, shutting down consumers\"",
"@consumer_instances",
".",
"each",
"{",
"|",
"instance",
"|",
"instance",
".",
"shutdown",
"}",
"@client",
".",
"channel",
".",
"work_pool",
".",
"shutdown",
"@shutdown",
"=",
"nil",
"end",
"end",
"end",
"end"
] |
Checks for presence of @shutdown every 1 second and if found instructs
all the channel's work pool consumers to shutdown. Each work pool thread
will finish its current task and then join the main thread. Once all the
threads have joined then `channel.work_pool.join` will cease blocking and
return, causing the process to terminate.
|
[
"Checks",
"for",
"presence",
"of"
] |
856c5ecaf40259526e01c472e1c13fa6d00d5ff0
|
https://github.com/songkick/queue/blob/856c5ecaf40259526e01c472e1c13fa6d00d5ff0/lib/songkick_queue/worker.rb#L49-L64
|
21,468 |
songkick/queue
|
lib/songkick_queue/worker.rb
|
SongkickQueue.Worker.subscribe_to_queue
|
def subscribe_to_queue(consumer_class)
queue = channel.queue(consumer_class.queue_name, durable: true,
arguments: { 'x-ha-policy' => 'all' })
queue.subscribe(manual_ack: true) do |delivery_info, properties, message|
process_message(consumer_class, delivery_info, properties, message)
end
logger.info "Subscribed #{consumer_class} to #{consumer_class.queue_name}"
end
|
ruby
|
def subscribe_to_queue(consumer_class)
queue = channel.queue(consumer_class.queue_name, durable: true,
arguments: { 'x-ha-policy' => 'all' })
queue.subscribe(manual_ack: true) do |delivery_info, properties, message|
process_message(consumer_class, delivery_info, properties, message)
end
logger.info "Subscribed #{consumer_class} to #{consumer_class.queue_name}"
end
|
[
"def",
"subscribe_to_queue",
"(",
"consumer_class",
")",
"queue",
"=",
"channel",
".",
"queue",
"(",
"consumer_class",
".",
"queue_name",
",",
"durable",
":",
"true",
",",
"arguments",
":",
"{",
"'x-ha-policy'",
"=>",
"'all'",
"}",
")",
"queue",
".",
"subscribe",
"(",
"manual_ack",
":",
"true",
")",
"do",
"|",
"delivery_info",
",",
"properties",
",",
"message",
"|",
"process_message",
"(",
"consumer_class",
",",
"delivery_info",
",",
"properties",
",",
"message",
")",
"end",
"logger",
".",
"info",
"\"Subscribed #{consumer_class} to #{consumer_class.queue_name}\"",
"end"
] |
Declare a queue and subscribe to it
@param consumer_class [Class] to subscribe to
|
[
"Declare",
"a",
"queue",
"and",
"subscribe",
"to",
"it"
] |
856c5ecaf40259526e01c472e1c13fa6d00d5ff0
|
https://github.com/songkick/queue/blob/856c5ecaf40259526e01c472e1c13fa6d00d5ff0/lib/songkick_queue/worker.rb#L69-L78
|
21,469 |
songkick/queue
|
lib/songkick_queue/worker.rb
|
SongkickQueue.Worker.process_message
|
def process_message(consumer_class, delivery_info, properties, message)
message = JSON.parse(message, symbolize_names: true)
message_id = message.fetch(:message_id)
produced_at = message.fetch(:produced_at)
payload = message.fetch(:payload)
logger.info "Processing message #{message_id} via #{consumer_class}, produced at #{produced_at}"
set_process_name(consumer_class, message_id)
consumer = consumer_class.new(delivery_info, logger)
@consumer_instances << consumer
instrumentation_options = {
consumer_class: consumer_class.to_s,
queue_name: consumer_class.queue_name,
message_id: message_id,
produced_at: produced_at,
}
ActiveSupport::Notifications.instrument('consume_message.songkick_queue', instrumentation_options) do
begin
consumer.process(payload)
ensure
@consumer_instances.delete(consumer)
end
end
rescue Object => exception
logger.error(exception)
channel.reject(delivery_info.delivery_tag, config.requeue_rejected_messages)
else
channel.ack(delivery_info.delivery_tag, false)
ensure
set_process_name
end
|
ruby
|
def process_message(consumer_class, delivery_info, properties, message)
message = JSON.parse(message, symbolize_names: true)
message_id = message.fetch(:message_id)
produced_at = message.fetch(:produced_at)
payload = message.fetch(:payload)
logger.info "Processing message #{message_id} via #{consumer_class}, produced at #{produced_at}"
set_process_name(consumer_class, message_id)
consumer = consumer_class.new(delivery_info, logger)
@consumer_instances << consumer
instrumentation_options = {
consumer_class: consumer_class.to_s,
queue_name: consumer_class.queue_name,
message_id: message_id,
produced_at: produced_at,
}
ActiveSupport::Notifications.instrument('consume_message.songkick_queue', instrumentation_options) do
begin
consumer.process(payload)
ensure
@consumer_instances.delete(consumer)
end
end
rescue Object => exception
logger.error(exception)
channel.reject(delivery_info.delivery_tag, config.requeue_rejected_messages)
else
channel.ack(delivery_info.delivery_tag, false)
ensure
set_process_name
end
|
[
"def",
"process_message",
"(",
"consumer_class",
",",
"delivery_info",
",",
"properties",
",",
"message",
")",
"message",
"=",
"JSON",
".",
"parse",
"(",
"message",
",",
"symbolize_names",
":",
"true",
")",
"message_id",
"=",
"message",
".",
"fetch",
"(",
":message_id",
")",
"produced_at",
"=",
"message",
".",
"fetch",
"(",
":produced_at",
")",
"payload",
"=",
"message",
".",
"fetch",
"(",
":payload",
")",
"logger",
".",
"info",
"\"Processing message #{message_id} via #{consumer_class}, produced at #{produced_at}\"",
"set_process_name",
"(",
"consumer_class",
",",
"message_id",
")",
"consumer",
"=",
"consumer_class",
".",
"new",
"(",
"delivery_info",
",",
"logger",
")",
"@consumer_instances",
"<<",
"consumer",
"instrumentation_options",
"=",
"{",
"consumer_class",
":",
"consumer_class",
".",
"to_s",
",",
"queue_name",
":",
"consumer_class",
".",
"queue_name",
",",
"message_id",
":",
"message_id",
",",
"produced_at",
":",
"produced_at",
",",
"}",
"ActiveSupport",
"::",
"Notifications",
".",
"instrument",
"(",
"'consume_message.songkick_queue'",
",",
"instrumentation_options",
")",
"do",
"begin",
"consumer",
".",
"process",
"(",
"payload",
")",
"ensure",
"@consumer_instances",
".",
"delete",
"(",
"consumer",
")",
"end",
"end",
"rescue",
"Object",
"=>",
"exception",
"logger",
".",
"error",
"(",
"exception",
")",
"channel",
".",
"reject",
"(",
"delivery_info",
".",
"delivery_tag",
",",
"config",
".",
"requeue_rejected_messages",
")",
"else",
"channel",
".",
"ack",
"(",
"delivery_info",
".",
"delivery_tag",
",",
"false",
")",
"ensure",
"set_process_name",
"end"
] |
Handle receipt of a subscribed message
@param consumer_class [Class] that was subscribed to
@param delivery_info [Bunny::DeliveryInfo]
@param properties [Bunny::MessageProperties]
@param message [String] to deserialize
|
[
"Handle",
"receipt",
"of",
"a",
"subscribed",
"message"
] |
856c5ecaf40259526e01c472e1c13fa6d00d5ff0
|
https://github.com/songkick/queue/blob/856c5ecaf40259526e01c472e1c13fa6d00d5ff0/lib/songkick_queue/worker.rb#L86-L119
|
21,470 |
songkick/queue
|
lib/songkick_queue/worker.rb
|
SongkickQueue.Worker.set_process_name
|
def set_process_name(status = 'idle', message_id = nil)
formatted_status = String(status)
.split('::')
.last
ident = [formatted_status, message_id]
.compact
.join('#')
$PROGRAM_NAME = "#{process_name}[#{ident}]"
end
|
ruby
|
def set_process_name(status = 'idle', message_id = nil)
formatted_status = String(status)
.split('::')
.last
ident = [formatted_status, message_id]
.compact
.join('#')
$PROGRAM_NAME = "#{process_name}[#{ident}]"
end
|
[
"def",
"set_process_name",
"(",
"status",
"=",
"'idle'",
",",
"message_id",
"=",
"nil",
")",
"formatted_status",
"=",
"String",
"(",
"status",
")",
".",
"split",
"(",
"'::'",
")",
".",
"last",
"ident",
"=",
"[",
"formatted_status",
",",
"message_id",
"]",
".",
"compact",
".",
"join",
"(",
"'#'",
")",
"$PROGRAM_NAME",
"=",
"\"#{process_name}[#{ident}]\"",
"end"
] |
Update the name of this process, as viewed in `ps` or `top`
@example idle
set_process_name #=> "songkick_queue[idle]"
@example consumer running, namespace is removed
set_process_name(Foo::TweetConsumer, 'a729bcd8') #=> "songkick_queue[TweetConsumer#a729bcd8]"
@param status [String] of the program
@param message_id [String] identifying the message currently being consumed
|
[
"Update",
"the",
"name",
"of",
"this",
"process",
"as",
"viewed",
"in",
"ps",
"or",
"top"
] |
856c5ecaf40259526e01c472e1c13fa6d00d5ff0
|
https://github.com/songkick/queue/blob/856c5ecaf40259526e01c472e1c13fa6d00d5ff0/lib/songkick_queue/worker.rb#L141-L151
|
21,471 |
songkick/queue
|
lib/songkick_queue/producer.rb
|
SongkickQueue.Producer.publish
|
def publish(queue_name, payload, options = {})
message_id = options.fetch(:message_id) { SecureRandom.hex(6) }
produced_at = options.fetch(:produced_at) { Time.now.utc.iso8601 }
message = {
message_id: message_id,
produced_at: produced_at,
payload: payload
}
message = JSON.generate(message)
exchange = client.default_exchange
instrumentation_options = {
queue_name: String(queue_name),
message_id: message_id,
produced_at: produced_at,
}
ActiveSupport::Notifications.instrument('produce_message.songkick_queue', instrumentation_options) do
exchange.publish(message, routing_key: String(queue_name))
end
self.reconnect_attempts = 0
logger.info "Published message #{message_id} to '#{queue_name}' at #{produced_at}"
exchange
rescue Bunny::ConnectionClosedError
self.reconnect_attempts += 1
if (reconnect_attempts > config.max_reconnect_attempts)
fail TooManyReconnectAttemptsError, "Attempted to reconnect more than " +
"#{config.max_reconnect_attempts} times"
end
logger.info "Attempting to reconnect to RabbitMQ, attempt #{reconnect_attempts} " +
"of #{config.max_reconnect_attempts}"
wait_for_bunny_session_to_reconnect
retry
end
|
ruby
|
def publish(queue_name, payload, options = {})
message_id = options.fetch(:message_id) { SecureRandom.hex(6) }
produced_at = options.fetch(:produced_at) { Time.now.utc.iso8601 }
message = {
message_id: message_id,
produced_at: produced_at,
payload: payload
}
message = JSON.generate(message)
exchange = client.default_exchange
instrumentation_options = {
queue_name: String(queue_name),
message_id: message_id,
produced_at: produced_at,
}
ActiveSupport::Notifications.instrument('produce_message.songkick_queue', instrumentation_options) do
exchange.publish(message, routing_key: String(queue_name))
end
self.reconnect_attempts = 0
logger.info "Published message #{message_id} to '#{queue_name}' at #{produced_at}"
exchange
rescue Bunny::ConnectionClosedError
self.reconnect_attempts += 1
if (reconnect_attempts > config.max_reconnect_attempts)
fail TooManyReconnectAttemptsError, "Attempted to reconnect more than " +
"#{config.max_reconnect_attempts} times"
end
logger.info "Attempting to reconnect to RabbitMQ, attempt #{reconnect_attempts} " +
"of #{config.max_reconnect_attempts}"
wait_for_bunny_session_to_reconnect
retry
end
|
[
"def",
"publish",
"(",
"queue_name",
",",
"payload",
",",
"options",
"=",
"{",
"}",
")",
"message_id",
"=",
"options",
".",
"fetch",
"(",
":message_id",
")",
"{",
"SecureRandom",
".",
"hex",
"(",
"6",
")",
"}",
"produced_at",
"=",
"options",
".",
"fetch",
"(",
":produced_at",
")",
"{",
"Time",
".",
"now",
".",
"utc",
".",
"iso8601",
"}",
"message",
"=",
"{",
"message_id",
":",
"message_id",
",",
"produced_at",
":",
"produced_at",
",",
"payload",
":",
"payload",
"}",
"message",
"=",
"JSON",
".",
"generate",
"(",
"message",
")",
"exchange",
"=",
"client",
".",
"default_exchange",
"instrumentation_options",
"=",
"{",
"queue_name",
":",
"String",
"(",
"queue_name",
")",
",",
"message_id",
":",
"message_id",
",",
"produced_at",
":",
"produced_at",
",",
"}",
"ActiveSupport",
"::",
"Notifications",
".",
"instrument",
"(",
"'produce_message.songkick_queue'",
",",
"instrumentation_options",
")",
"do",
"exchange",
".",
"publish",
"(",
"message",
",",
"routing_key",
":",
"String",
"(",
"queue_name",
")",
")",
"end",
"self",
".",
"reconnect_attempts",
"=",
"0",
"logger",
".",
"info",
"\"Published message #{message_id} to '#{queue_name}' at #{produced_at}\"",
"exchange",
"rescue",
"Bunny",
"::",
"ConnectionClosedError",
"self",
".",
"reconnect_attempts",
"+=",
"1",
"if",
"(",
"reconnect_attempts",
">",
"config",
".",
"max_reconnect_attempts",
")",
"fail",
"TooManyReconnectAttemptsError",
",",
"\"Attempted to reconnect more than \"",
"+",
"\"#{config.max_reconnect_attempts} times\"",
"end",
"logger",
".",
"info",
"\"Attempting to reconnect to RabbitMQ, attempt #{reconnect_attempts} \"",
"+",
"\"of #{config.max_reconnect_attempts}\"",
"wait_for_bunny_session_to_reconnect",
"retry",
"end"
] |
Serializes the given message and publishes it to the default RabbitMQ exchange
@param queue_name [String] to publish to
@param message [#to_json] to serialize and enqueue
@option options [String] :message_id to pass through to the consumer (will be logged)
@option options [String] :produced_at time when the message was created, ISO8601 formatted
@raise [TooManyReconnectAttemptsError] if max reconnect attempts is exceeded
@return [Bunny::Exchange]
|
[
"Serializes",
"the",
"given",
"message",
"and",
"publishes",
"it",
"to",
"the",
"default",
"RabbitMQ",
"exchange"
] |
856c5ecaf40259526e01c472e1c13fa6d00d5ff0
|
https://github.com/songkick/queue/blob/856c5ecaf40259526e01c472e1c13fa6d00d5ff0/lib/songkick_queue/producer.rb#L21-L63
|
21,472 |
guard/rb-inotify
|
lib/rb-inotify/watcher.rb
|
INotify.Watcher.close
|
def close
if Native.inotify_rm_watch(@notifier.fd, @id) == 0
@notifier.watchers.delete(@id)
return
end
raise SystemCallError.new("Failed to stop watching #{path.inspect}",
FFI.errno)
end
|
ruby
|
def close
if Native.inotify_rm_watch(@notifier.fd, @id) == 0
@notifier.watchers.delete(@id)
return
end
raise SystemCallError.new("Failed to stop watching #{path.inspect}",
FFI.errno)
end
|
[
"def",
"close",
"if",
"Native",
".",
"inotify_rm_watch",
"(",
"@notifier",
".",
"fd",
",",
"@id",
")",
"==",
"0",
"@notifier",
".",
"watchers",
".",
"delete",
"(",
"@id",
")",
"return",
"end",
"raise",
"SystemCallError",
".",
"new",
"(",
"\"Failed to stop watching #{path.inspect}\"",
",",
"FFI",
".",
"errno",
")",
"end"
] |
Disables this Watcher, so that it doesn't fire any more events.
@raise [SystemCallError] if the watch fails to be disabled for some reason
|
[
"Disables",
"this",
"Watcher",
"so",
"that",
"it",
"doesn",
"t",
"fire",
"any",
"more",
"events",
"."
] |
3fae270905c7bd259e69fe420dbdcd59bb47fa3d
|
https://github.com/guard/rb-inotify/blob/3fae270905c7bd259e69fe420dbdcd59bb47fa3d/lib/rb-inotify/watcher.rb#L47-L55
|
21,473 |
guard/rb-inotify
|
lib/rb-inotify/event.rb
|
INotify.Event.absolute_name
|
def absolute_name
return watcher.path if name.empty?
return File.join(watcher.path, name)
end
|
ruby
|
def absolute_name
return watcher.path if name.empty?
return File.join(watcher.path, name)
end
|
[
"def",
"absolute_name",
"return",
"watcher",
".",
"path",
"if",
"name",
".",
"empty?",
"return",
"File",
".",
"join",
"(",
"watcher",
".",
"path",
",",
"name",
")",
"end"
] |
The absolute path of the file that the event occurred on.
This is actually only as absolute as the path passed to the {Watcher}
that created this event.
However, it is relative to the working directory,
assuming that hasn't changed since the watcher started.
@return [String]
|
[
"The",
"absolute",
"path",
"of",
"the",
"file",
"that",
"the",
"event",
"occurred",
"on",
"."
] |
3fae270905c7bd259e69fe420dbdcd59bb47fa3d
|
https://github.com/guard/rb-inotify/blob/3fae270905c7bd259e69fe420dbdcd59bb47fa3d/lib/rb-inotify/event.rb#L66-L69
|
21,474 |
guard/rb-inotify
|
lib/rb-inotify/notifier.rb
|
INotify.Notifier.process
|
def process
read_events.each do |event|
event.callback!
event.flags.include?(:ignored) && event.notifier.watchers.delete(event.watcher_id)
end
end
|
ruby
|
def process
read_events.each do |event|
event.callback!
event.flags.include?(:ignored) && event.notifier.watchers.delete(event.watcher_id)
end
end
|
[
"def",
"process",
"read_events",
".",
"each",
"do",
"|",
"event",
"|",
"event",
".",
"callback!",
"event",
".",
"flags",
".",
"include?",
"(",
":ignored",
")",
"&&",
"event",
".",
"notifier",
".",
"watchers",
".",
"delete",
"(",
"event",
".",
"watcher_id",
")",
"end",
"end"
] |
Blocks until there are one or more filesystem events
that this notifier has watchers registered for.
Once there are events, the appropriate callbacks are called
and this function returns.
@see #run
|
[
"Blocks",
"until",
"there",
"are",
"one",
"or",
"more",
"filesystem",
"events",
"that",
"this",
"notifier",
"has",
"watchers",
"registered",
"for",
".",
"Once",
"there",
"are",
"events",
"the",
"appropriate",
"callbacks",
"are",
"called",
"and",
"this",
"function",
"returns",
"."
] |
3fae270905c7bd259e69fe420dbdcd59bb47fa3d
|
https://github.com/guard/rb-inotify/blob/3fae270905c7bd259e69fe420dbdcd59bb47fa3d/lib/rb-inotify/notifier.rb#L251-L256
|
21,475 |
chefspec/fauxhai
|
lib/fauxhai/mocker.rb
|
Fauxhai.Mocker.data
|
def data
@fauxhai_data ||= lambda do
# If a path option was specified, use it
if @options[:path]
filepath = File.expand_path(@options[:path])
unless File.exist?(filepath)
raise Fauxhai::Exception::InvalidPlatform.new("You specified a path to a JSON file on the local system that does not exist: '#{filepath}'")
end
else
filepath = File.join(platform_path, "#{version}.json")
end
if File.exist?(filepath)
parse_and_validate(File.read(filepath))
elsif @options[:github_fetching]
# Try loading from github (in case someone submitted a PR with a new file, but we haven't
# yet updated the gem version). Cache the response locally so it's faster next time.
begin
response = open("#{RAW_BASE}/lib/fauxhai/platforms/#{platform}/#{version}.json")
rescue OpenURI::HTTPError
raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and an HTTP error was encountered when fetching from Github. #{PLATFORM_LIST_MESSAGE}")
end
if response.status.first.to_i == 200
response_body = response.read
path = Pathname.new(filepath)
FileUtils.mkdir_p(path.dirname)
begin
File.open(filepath, 'w') { |f| f.write(response_body) }
rescue Errno::EACCES # a pretty common problem in CI systems
puts "Fetched '#{platform}/#{version}' from GitHub, but could not write to the local path: #{filepath}. Fix the local file permissions to avoid downloading this file every run."
end
return parse_and_validate(response_body)
else
raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and an Github fetching returned http error code #{response.status.first.to_i}! #{PLATFORM_LIST_MESSAGE}")
end
else
raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and Github fetching is disabled! #{PLATFORM_LIST_MESSAGE}")
end
end.call
end
|
ruby
|
def data
@fauxhai_data ||= lambda do
# If a path option was specified, use it
if @options[:path]
filepath = File.expand_path(@options[:path])
unless File.exist?(filepath)
raise Fauxhai::Exception::InvalidPlatform.new("You specified a path to a JSON file on the local system that does not exist: '#{filepath}'")
end
else
filepath = File.join(platform_path, "#{version}.json")
end
if File.exist?(filepath)
parse_and_validate(File.read(filepath))
elsif @options[:github_fetching]
# Try loading from github (in case someone submitted a PR with a new file, but we haven't
# yet updated the gem version). Cache the response locally so it's faster next time.
begin
response = open("#{RAW_BASE}/lib/fauxhai/platforms/#{platform}/#{version}.json")
rescue OpenURI::HTTPError
raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and an HTTP error was encountered when fetching from Github. #{PLATFORM_LIST_MESSAGE}")
end
if response.status.first.to_i == 200
response_body = response.read
path = Pathname.new(filepath)
FileUtils.mkdir_p(path.dirname)
begin
File.open(filepath, 'w') { |f| f.write(response_body) }
rescue Errno::EACCES # a pretty common problem in CI systems
puts "Fetched '#{platform}/#{version}' from GitHub, but could not write to the local path: #{filepath}. Fix the local file permissions to avoid downloading this file every run."
end
return parse_and_validate(response_body)
else
raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and an Github fetching returned http error code #{response.status.first.to_i}! #{PLATFORM_LIST_MESSAGE}")
end
else
raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and Github fetching is disabled! #{PLATFORM_LIST_MESSAGE}")
end
end.call
end
|
[
"def",
"data",
"@fauxhai_data",
"||=",
"lambda",
"do",
"# If a path option was specified, use it",
"if",
"@options",
"[",
":path",
"]",
"filepath",
"=",
"File",
".",
"expand_path",
"(",
"@options",
"[",
":path",
"]",
")",
"unless",
"File",
".",
"exist?",
"(",
"filepath",
")",
"raise",
"Fauxhai",
"::",
"Exception",
"::",
"InvalidPlatform",
".",
"new",
"(",
"\"You specified a path to a JSON file on the local system that does not exist: '#{filepath}'\"",
")",
"end",
"else",
"filepath",
"=",
"File",
".",
"join",
"(",
"platform_path",
",",
"\"#{version}.json\"",
")",
"end",
"if",
"File",
".",
"exist?",
"(",
"filepath",
")",
"parse_and_validate",
"(",
"File",
".",
"read",
"(",
"filepath",
")",
")",
"elsif",
"@options",
"[",
":github_fetching",
"]",
"# Try loading from github (in case someone submitted a PR with a new file, but we haven't",
"# yet updated the gem version). Cache the response locally so it's faster next time.",
"begin",
"response",
"=",
"open",
"(",
"\"#{RAW_BASE}/lib/fauxhai/platforms/#{platform}/#{version}.json\"",
")",
"rescue",
"OpenURI",
"::",
"HTTPError",
"raise",
"Fauxhai",
"::",
"Exception",
"::",
"InvalidPlatform",
".",
"new",
"(",
"\"Could not find platform '#{platform}/#{version}' on the local disk and an HTTP error was encountered when fetching from Github. #{PLATFORM_LIST_MESSAGE}\"",
")",
"end",
"if",
"response",
".",
"status",
".",
"first",
".",
"to_i",
"==",
"200",
"response_body",
"=",
"response",
".",
"read",
"path",
"=",
"Pathname",
".",
"new",
"(",
"filepath",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"path",
".",
"dirname",
")",
"begin",
"File",
".",
"open",
"(",
"filepath",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"response_body",
")",
"}",
"rescue",
"Errno",
"::",
"EACCES",
"# a pretty common problem in CI systems",
"puts",
"\"Fetched '#{platform}/#{version}' from GitHub, but could not write to the local path: #{filepath}. Fix the local file permissions to avoid downloading this file every run.\"",
"end",
"return",
"parse_and_validate",
"(",
"response_body",
")",
"else",
"raise",
"Fauxhai",
"::",
"Exception",
"::",
"InvalidPlatform",
".",
"new",
"(",
"\"Could not find platform '#{platform}/#{version}' on the local disk and an Github fetching returned http error code #{response.status.first.to_i}! #{PLATFORM_LIST_MESSAGE}\"",
")",
"end",
"else",
"raise",
"Fauxhai",
"::",
"Exception",
"::",
"InvalidPlatform",
".",
"new",
"(",
"\"Could not find platform '#{platform}/#{version}' on the local disk and Github fetching is disabled! #{PLATFORM_LIST_MESSAGE}\"",
")",
"end",
"end",
".",
"call",
"end"
] |
Create a new Ohai Mock with fauxhai.
@param [Hash] options
the options for the mocker
@option options [String] :platform
the platform to mock
@option options [String] :version
the version of the platform to mock
@option options [String] :path
the path to a local JSON file
@option options [Bool] :github_fetching
whether to try loading from Github
|
[
"Create",
"a",
"new",
"Ohai",
"Mock",
"with",
"fauxhai",
"."
] |
c73522490738f254920a4c344822524fef1ee7d0
|
https://github.com/chefspec/fauxhai/blob/c73522490738f254920a4c344822524fef1ee7d0/lib/fauxhai/mocker.rb#L31-L73
|
21,476 |
chefspec/fauxhai
|
lib/fauxhai/mocker.rb
|
Fauxhai.Mocker.parse_and_validate
|
def parse_and_validate(unparsed_data)
parsed_data = JSON.parse(unparsed_data)
if parsed_data['deprecated']
STDERR.puts "WARNING: Fauxhai platform data for #{parsed_data['platform']} #{parsed_data['platform_version']} is deprecated and will be removed in the 7.0 release 3/2019. #{PLATFORM_LIST_MESSAGE}"
end
parsed_data
end
|
ruby
|
def parse_and_validate(unparsed_data)
parsed_data = JSON.parse(unparsed_data)
if parsed_data['deprecated']
STDERR.puts "WARNING: Fauxhai platform data for #{parsed_data['platform']} #{parsed_data['platform_version']} is deprecated and will be removed in the 7.0 release 3/2019. #{PLATFORM_LIST_MESSAGE}"
end
parsed_data
end
|
[
"def",
"parse_and_validate",
"(",
"unparsed_data",
")",
"parsed_data",
"=",
"JSON",
".",
"parse",
"(",
"unparsed_data",
")",
"if",
"parsed_data",
"[",
"'deprecated'",
"]",
"STDERR",
".",
"puts",
"\"WARNING: Fauxhai platform data for #{parsed_data['platform']} #{parsed_data['platform_version']} is deprecated and will be removed in the 7.0 release 3/2019. #{PLATFORM_LIST_MESSAGE}\"",
"end",
"parsed_data",
"end"
] |
As major releases of Ohai ship it's difficult and sometimes impossible
to regenerate all fauxhai data. This allows us to deprecate old releases
and eventually remove them while giving end users ample warning.
|
[
"As",
"major",
"releases",
"of",
"Ohai",
"ship",
"it",
"s",
"difficult",
"and",
"sometimes",
"impossible",
"to",
"regenerate",
"all",
"fauxhai",
"data",
".",
"This",
"allows",
"us",
"to",
"deprecate",
"old",
"releases",
"and",
"eventually",
"remove",
"them",
"while",
"giving",
"end",
"users",
"ample",
"warning",
"."
] |
c73522490738f254920a4c344822524fef1ee7d0
|
https://github.com/chefspec/fauxhai/blob/c73522490738f254920a4c344822524fef1ee7d0/lib/fauxhai/mocker.rb#L80-L86
|
21,477 |
jwilger/the_help
|
lib/the_help/service_caller.rb
|
TheHelp.ServiceCaller.call_service
|
def call_service(service, **args, &block)
service_args = {
context: service_context,
logger: service_logger
}.merge(args)
service_logger.debug("#{self.class.name}/#{__id__} called service " \
"#{service.name}")
service.call(**service_args, &block)
end
|
ruby
|
def call_service(service, **args, &block)
service_args = {
context: service_context,
logger: service_logger
}.merge(args)
service_logger.debug("#{self.class.name}/#{__id__} called service " \
"#{service.name}")
service.call(**service_args, &block)
end
|
[
"def",
"call_service",
"(",
"service",
",",
"**",
"args",
",",
"&",
"block",
")",
"service_args",
"=",
"{",
"context",
":",
"service_context",
",",
"logger",
":",
"service_logger",
"}",
".",
"merge",
"(",
"args",
")",
"service_logger",
".",
"debug",
"(",
"\"#{self.class.name}/#{__id__} called service \"",
"\"#{service.name}\"",
")",
"service",
".",
"call",
"(",
"**",
"service_args",
",",
"block",
")",
"end"
] |
Calls the specified service
@param service [Class<TheHelp::Service>]
@param args [Hash<Symbol, Object>] Any additional keyword arguments are
passed directly to the service.
@return [self]
|
[
"Calls",
"the",
"specified",
"service"
] |
4ca6dff0f1960a096657ac421a8b4e384c92deb8
|
https://github.com/jwilger/the_help/blob/4ca6dff0f1960a096657ac421a8b4e384c92deb8/lib/the_help/service_caller.rb#L35-L43
|
21,478 |
ManageIQ/awesome_spawn
|
lib/awesome_spawn/command_line_builder.rb
|
AwesomeSpawn.CommandLineBuilder.build
|
def build(command, params = nil)
params = assemble_params(sanitize(params))
params.empty? ? command.to_s : "#{command} #{params}"
end
|
ruby
|
def build(command, params = nil)
params = assemble_params(sanitize(params))
params.empty? ? command.to_s : "#{command} #{params}"
end
|
[
"def",
"build",
"(",
"command",
",",
"params",
"=",
"nil",
")",
"params",
"=",
"assemble_params",
"(",
"sanitize",
"(",
"params",
")",
")",
"params",
".",
"empty?",
"?",
"command",
".",
"to_s",
":",
"\"#{command} #{params}\"",
"end"
] |
Build the full command line.
@param [String] command The command to run
@param [Hash,Array] params Optional command line parameters. They can
be passed as a Hash or associative Array. The values are sanitized to
prevent command line injection. Keys as Symbols are prefixed with `--`,
and `_` is replaced with `-`.
- `{:k => "value"}` generates `-k value`
- `[[:k, "value"]]` generates `-k value`
- `{:k= => "value"}` generates `-k=value`
- `[[:k=, "value"]]` generates `-k=value` <br /><br />
- `{:key => "value"}` generates `--key value`
- `[[:key, "value"]]` generates `--key value`
- `{:key= => "value"}` generates `--key=value`
- `[[:key=, "value"]]` generates `--key=value` <br /><br />
- `{"--key" => "value"}` generates `--key value`
- `[["--key", "value"]]` generates `--key value`
- `{"--key=" => "value"}` generates `--key=value`
- `[["--key=", "value"]]` generates `--key=value` <br /><br />
- `{:key_name => "value"}` generates `--key-name value`
- `[[:key_name, "value"]]` generates `--key-name value`
- `{:key_name= => "value"}` generates `--key-name=value`
- `[[:key_name=, "value"]]` generates `--key-name=value` <br /><br />
- `{"-f" => ["file1", "file2"]}` generates `-f file1 file2`
- `[["-f", "file1", "file2"]]` generates `-f file1 file2` <br /><br />
- `{:key => nil}` generates `--key`
- `[[:key, nil]]` generates `--key`
- `[[:key]]` generates `--key` <br /><br />
- `{nil => ["file1", "file2"]}` generates `file1 file2`
- `[[nil, ["file1", "file2"]]]` generates `file1 file2`
- `[[nil, "file1", "file2"]]` generates `file1 file2`
- `[["file1", "file2"]]` generates `file1 file2`
@return [String] The full command line
|
[
"Build",
"the",
"full",
"command",
"line",
"."
] |
7cbf922be564271ce958a75a4e8660d9eef93823
|
https://github.com/ManageIQ/awesome_spawn/blob/7cbf922be564271ce958a75a4e8660d9eef93823/lib/awesome_spawn/command_line_builder.rb#L46-L49
|
21,479 |
lancejpollard/authlogic-connect
|
lib/authlogic_connect/common/user.rb
|
AuthlogicConnect::Common::User.InstanceMethods.save
|
def save(options = {}, &block)
self.errors.clear
# log_state
options = {} if options == false
options[:validate] = true unless options.has_key?(:validate)
save_options = ActiveRecord::VERSION::MAJOR < 3 ? options[:validate] : options
# kill the block if we're starting authentication
authenticate_via_protocol(block_given?, options) do |start_authentication|
block = nil if start_authentication # redirecting
# forces you to validate, only if a block is given
result = super(save_options) # validate!
unless block.nil?
cleanup_authentication_session(options)
yield(result)
end
result
end
end
|
ruby
|
def save(options = {}, &block)
self.errors.clear
# log_state
options = {} if options == false
options[:validate] = true unless options.has_key?(:validate)
save_options = ActiveRecord::VERSION::MAJOR < 3 ? options[:validate] : options
# kill the block if we're starting authentication
authenticate_via_protocol(block_given?, options) do |start_authentication|
block = nil if start_authentication # redirecting
# forces you to validate, only if a block is given
result = super(save_options) # validate!
unless block.nil?
cleanup_authentication_session(options)
yield(result)
end
result
end
end
|
[
"def",
"save",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"self",
".",
"errors",
".",
"clear",
"# log_state",
"options",
"=",
"{",
"}",
"if",
"options",
"==",
"false",
"options",
"[",
":validate",
"]",
"=",
"true",
"unless",
"options",
".",
"has_key?",
"(",
":validate",
")",
"save_options",
"=",
"ActiveRecord",
"::",
"VERSION",
"::",
"MAJOR",
"<",
"3",
"?",
"options",
"[",
":validate",
"]",
":",
"options",
"# kill the block if we're starting authentication",
"authenticate_via_protocol",
"(",
"block_given?",
",",
"options",
")",
"do",
"|",
"start_authentication",
"|",
"block",
"=",
"nil",
"if",
"start_authentication",
"# redirecting",
"# forces you to validate, only if a block is given",
"result",
"=",
"super",
"(",
"save_options",
")",
"# validate!",
"unless",
"block",
".",
"nil?",
"cleanup_authentication_session",
"(",
"options",
")",
"yield",
"(",
"result",
")",
"end",
"result",
"end",
"end"
] |
core save method coordinating how to save the user.
we dont' want to ru validations based on the
authentication mission we are trying to accomplish.
instead, we just return save as false.
the next time around, when we recieve the callback,
we will run the validations.
when you call 'current_user_session' in ApplicationController,
it leads to calling 'save' on this User object via "session.record.save",
from the 'persisting?' method. So we don't want any of this to occur
when that save is called, and the only way to check currently is
to check if there is a block_given?
|
[
"core",
"save",
"method",
"coordinating",
"how",
"to",
"save",
"the",
"user",
".",
"we",
"dont",
"want",
"to",
"ru",
"validations",
"based",
"on",
"the",
"authentication",
"mission",
"we",
"are",
"trying",
"to",
"accomplish",
".",
"instead",
"we",
"just",
"return",
"save",
"as",
"false",
".",
"the",
"next",
"time",
"around",
"when",
"we",
"recieve",
"the",
"callback",
"we",
"will",
"run",
"the",
"validations",
".",
"when",
"you",
"call",
"current_user_session",
"in",
"ApplicationController",
"it",
"leads",
"to",
"calling",
"save",
"on",
"this",
"User",
"object",
"via",
"session",
".",
"record",
".",
"save",
"from",
"the",
"persisting?",
"method",
".",
"So",
"we",
"don",
"t",
"want",
"any",
"of",
"this",
"to",
"occur",
"when",
"that",
"save",
"is",
"called",
"and",
"the",
"only",
"way",
"to",
"check",
"currently",
"is",
"to",
"check",
"if",
"there",
"is",
"a",
"block_given?"
] |
3b1959ec07f1a9c4164753fea5a5cb1079b88257
|
https://github.com/lancejpollard/authlogic-connect/blob/3b1959ec07f1a9c4164753fea5a5cb1079b88257/lib/authlogic_connect/common/user.rb#L55-L73
|
21,480 |
lancejpollard/authlogic-connect
|
lib/authlogic_connect/oauth/user.rb
|
AuthlogicConnect::Oauth::User.InstanceMethods.save_oauth_session
|
def save_oauth_session
super
auth_session[:auth_attributes] = attributes.reject!{|k, v| v.blank? || !self.respond_to?(k)} unless is_auth_session?
end
|
ruby
|
def save_oauth_session
super
auth_session[:auth_attributes] = attributes.reject!{|k, v| v.blank? || !self.respond_to?(k)} unless is_auth_session?
end
|
[
"def",
"save_oauth_session",
"super",
"auth_session",
"[",
":auth_attributes",
"]",
"=",
"attributes",
".",
"reject!",
"{",
"|",
"k",
",",
"v",
"|",
"v",
".",
"blank?",
"||",
"!",
"self",
".",
"respond_to?",
"(",
"k",
")",
"}",
"unless",
"is_auth_session?",
"end"
] |
user adds a few extra things to this method from Process
modules work like inheritance
|
[
"user",
"adds",
"a",
"few",
"extra",
"things",
"to",
"this",
"method",
"from",
"Process",
"modules",
"work",
"like",
"inheritance"
] |
3b1959ec07f1a9c4164753fea5a5cb1079b88257
|
https://github.com/lancejpollard/authlogic-connect/blob/3b1959ec07f1a9c4164753fea5a5cb1079b88257/lib/authlogic_connect/oauth/user.rb#L33-L36
|
21,481 |
lancejpollard/authlogic-connect
|
lib/authlogic_connect/oauth/user.rb
|
AuthlogicConnect::Oauth::User.InstanceMethods.complete_oauth_transaction
|
def complete_oauth_transaction
token = token_class.new(oauth_token_and_secret)
old_token = token_class.find_by_key_or_token(token.key, token.token)
token = old_token if old_token
if has_token?(oauth_provider)
self.errors.add(:tokens, "you have already created an account using your #{token_class.service_name} account, so it")
else
self.access_tokens << token
end
end
|
ruby
|
def complete_oauth_transaction
token = token_class.new(oauth_token_and_secret)
old_token = token_class.find_by_key_or_token(token.key, token.token)
token = old_token if old_token
if has_token?(oauth_provider)
self.errors.add(:tokens, "you have already created an account using your #{token_class.service_name} account, so it")
else
self.access_tokens << token
end
end
|
[
"def",
"complete_oauth_transaction",
"token",
"=",
"token_class",
".",
"new",
"(",
"oauth_token_and_secret",
")",
"old_token",
"=",
"token_class",
".",
"find_by_key_or_token",
"(",
"token",
".",
"key",
",",
"token",
".",
"token",
")",
"token",
"=",
"old_token",
"if",
"old_token",
"if",
"has_token?",
"(",
"oauth_provider",
")",
"self",
".",
"errors",
".",
"add",
"(",
":tokens",
",",
"\"you have already created an account using your #{token_class.service_name} account, so it\"",
")",
"else",
"self",
".",
"access_tokens",
"<<",
"token",
"end",
"end"
] |
single implementation method for oauth.
this is called after we get the callback url and we are saving the user
to the database.
it is called by the validation chain.
|
[
"single",
"implementation",
"method",
"for",
"oauth",
".",
"this",
"is",
"called",
"after",
"we",
"get",
"the",
"callback",
"url",
"and",
"we",
"are",
"saving",
"the",
"user",
"to",
"the",
"database",
".",
"it",
"is",
"called",
"by",
"the",
"validation",
"chain",
"."
] |
3b1959ec07f1a9c4164753fea5a5cb1079b88257
|
https://github.com/lancejpollard/authlogic-connect/blob/3b1959ec07f1a9c4164753fea5a5cb1079b88257/lib/authlogic_connect/oauth/user.rb#L51-L61
|
21,482 |
ondra-m/ruby-spark
|
lib/spark/command_builder.rb
|
Spark.CommandBuilder.serialize_function
|
def serialize_function(func)
case func
when String
serialize_function_from_string(func)
when Symbol
serialize_function_from_symbol(func)
when Proc
serialize_function_from_proc(func)
when Method
serialize_function_from_method(func)
else
raise Spark::CommandError, 'You must enter String, Symbol, Proc or Method.'
end
end
|
ruby
|
def serialize_function(func)
case func
when String
serialize_function_from_string(func)
when Symbol
serialize_function_from_symbol(func)
when Proc
serialize_function_from_proc(func)
when Method
serialize_function_from_method(func)
else
raise Spark::CommandError, 'You must enter String, Symbol, Proc or Method.'
end
end
|
[
"def",
"serialize_function",
"(",
"func",
")",
"case",
"func",
"when",
"String",
"serialize_function_from_string",
"(",
"func",
")",
"when",
"Symbol",
"serialize_function_from_symbol",
"(",
"func",
")",
"when",
"Proc",
"serialize_function_from_proc",
"(",
"func",
")",
"when",
"Method",
"serialize_function_from_method",
"(",
"func",
")",
"else",
"raise",
"Spark",
"::",
"CommandError",
",",
"'You must enter String, Symbol, Proc or Method.'",
"end",
"end"
] |
Serialized can be Proc and Method
=== Func
* *string:* already serialized proc
* *proc:* proc
* *symbol:* name of method
* *method:* Method class
|
[
"Serialized",
"can",
"be",
"Proc",
"and",
"Method"
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/command_builder.rb#L87-L100
|
21,483 |
ondra-m/ruby-spark
|
lib/spark/command_builder.rb
|
Spark.CommandBuilder.serialize_function_from_method
|
def serialize_function_from_method(meth)
if pry?
meth = Pry::Method.new(meth)
end
{type: 'method', name: meth.name, content: meth.source}
rescue
raise Spark::SerializeError, 'Method can not be serialized. Use full path or Proc.'
end
|
ruby
|
def serialize_function_from_method(meth)
if pry?
meth = Pry::Method.new(meth)
end
{type: 'method', name: meth.name, content: meth.source}
rescue
raise Spark::SerializeError, 'Method can not be serialized. Use full path or Proc.'
end
|
[
"def",
"serialize_function_from_method",
"(",
"meth",
")",
"if",
"pry?",
"meth",
"=",
"Pry",
"::",
"Method",
".",
"new",
"(",
"meth",
")",
"end",
"{",
"type",
":",
"'method'",
",",
"name",
":",
"meth",
".",
"name",
",",
"content",
":",
"meth",
".",
"source",
"}",
"rescue",
"raise",
"Spark",
"::",
"SerializeError",
",",
"'Method can not be serialized. Use full path or Proc.'",
"end"
] |
Serialize method as string
def test(x)
x*x
end
serialize_function_from_method(method(:test))
# => "def test(x)\n x*x\nend\n"
|
[
"Serialize",
"method",
"as",
"string"
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/command_builder.rb#L130-L138
|
21,484 |
ondra-m/ruby-spark
|
lib/spark/config.rb
|
Spark.Config.from_file
|
def from_file(file)
check_read_only
if file && File.exist?(file)
file = File.expand_path(file)
RubyUtils.loadPropertiesFile(spark_conf, file)
end
end
|
ruby
|
def from_file(file)
check_read_only
if file && File.exist?(file)
file = File.expand_path(file)
RubyUtils.loadPropertiesFile(spark_conf, file)
end
end
|
[
"def",
"from_file",
"(",
"file",
")",
"check_read_only",
"if",
"file",
"&&",
"File",
".",
"exist?",
"(",
"file",
")",
"file",
"=",
"File",
".",
"expand_path",
"(",
"file",
")",
"RubyUtils",
".",
"loadPropertiesFile",
"(",
"spark_conf",
",",
"file",
")",
"end",
"end"
] |
Initialize java SparkConf and load default configuration.
|
[
"Initialize",
"java",
"SparkConf",
"and",
"load",
"default",
"configuration",
"."
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/config.rb#L22-L29
|
21,485 |
ondra-m/ruby-spark
|
lib/spark/config.rb
|
Spark.Config.get
|
def get(key)
value = spark_conf.get(key.to_s)
case TYPES[key]
when :boolean
parse_boolean(value)
when :integer
parse_integer(value)
else
value
end
rescue
nil
end
|
ruby
|
def get(key)
value = spark_conf.get(key.to_s)
case TYPES[key]
when :boolean
parse_boolean(value)
when :integer
parse_integer(value)
else
value
end
rescue
nil
end
|
[
"def",
"get",
"(",
"key",
")",
"value",
"=",
"spark_conf",
".",
"get",
"(",
"key",
".",
"to_s",
")",
"case",
"TYPES",
"[",
"key",
"]",
"when",
":boolean",
"parse_boolean",
"(",
"value",
")",
"when",
":integer",
"parse_integer",
"(",
"value",
")",
"else",
"value",
"end",
"rescue",
"nil",
"end"
] |
Rescue from NoSuchElementException
|
[
"Rescue",
"from",
"NoSuchElementException"
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/config.rb#L85-L98
|
21,486 |
ondra-m/ruby-spark
|
lib/spark/config.rb
|
Spark.Config.load_executor_envs
|
def load_executor_envs
prefix = 'SPARK_RUBY_EXECUTOR_ENV_'
envs = ENV.select{|key, _| key.start_with?(prefix)}
envs.each do |key, value|
key = key.dup # ENV keys are frozen
key.slice!(0, prefix.size)
set("spark.ruby.executor.env.#{key}", value)
end
end
|
ruby
|
def load_executor_envs
prefix = 'SPARK_RUBY_EXECUTOR_ENV_'
envs = ENV.select{|key, _| key.start_with?(prefix)}
envs.each do |key, value|
key = key.dup # ENV keys are frozen
key.slice!(0, prefix.size)
set("spark.ruby.executor.env.#{key}", value)
end
end
|
[
"def",
"load_executor_envs",
"prefix",
"=",
"'SPARK_RUBY_EXECUTOR_ENV_'",
"envs",
"=",
"ENV",
".",
"select",
"{",
"|",
"key",
",",
"_",
"|",
"key",
".",
"start_with?",
"(",
"prefix",
")",
"}",
"envs",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"key",
"=",
"key",
".",
"dup",
"# ENV keys are frozen",
"key",
".",
"slice!",
"(",
"0",
",",
"prefix",
".",
"size",
")",
"set",
"(",
"\"spark.ruby.executor.env.#{key}\"",
",",
"value",
")",
"end",
"end"
] |
Load environment variables for executor from ENV.
== Examples:
SPARK_RUBY_EXECUTOR_ENV_KEY1="1"
SPARK_RUBY_EXECUTOR_ENV_KEY2="2"
|
[
"Load",
"environment",
"variables",
"for",
"executor",
"from",
"ENV",
"."
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/config.rb#L208-L218
|
21,487 |
ondra-m/ruby-spark
|
lib/spark/worker/worker.rb
|
Worker.Base.compute
|
def compute
before_start
# Load split index
@split_index = socket.read_int
# Load files
SparkFiles.root_directory = socket.read_string
# Load broadcast
count = socket.read_int
count.times do
Spark::Broadcast.register(socket.read_long, socket.read_string)
end
# Load command
@command = socket.read_data
# Load iterator
@iterator = @command.deserializer.load_from_io(socket).lazy
# Compute
@iterator = @command.execute(@iterator, @split_index)
# Result is not iterable
@iterator = [@iterator] unless @iterator.respond_to?(:each)
# Send result
@command.serializer.dump_to_io(@iterator, socket)
end
|
ruby
|
def compute
before_start
# Load split index
@split_index = socket.read_int
# Load files
SparkFiles.root_directory = socket.read_string
# Load broadcast
count = socket.read_int
count.times do
Spark::Broadcast.register(socket.read_long, socket.read_string)
end
# Load command
@command = socket.read_data
# Load iterator
@iterator = @command.deserializer.load_from_io(socket).lazy
# Compute
@iterator = @command.execute(@iterator, @split_index)
# Result is not iterable
@iterator = [@iterator] unless @iterator.respond_to?(:each)
# Send result
@command.serializer.dump_to_io(@iterator, socket)
end
|
[
"def",
"compute",
"before_start",
"# Load split index",
"@split_index",
"=",
"socket",
".",
"read_int",
"# Load files",
"SparkFiles",
".",
"root_directory",
"=",
"socket",
".",
"read_string",
"# Load broadcast",
"count",
"=",
"socket",
".",
"read_int",
"count",
".",
"times",
"do",
"Spark",
"::",
"Broadcast",
".",
"register",
"(",
"socket",
".",
"read_long",
",",
"socket",
".",
"read_string",
")",
"end",
"# Load command",
"@command",
"=",
"socket",
".",
"read_data",
"# Load iterator",
"@iterator",
"=",
"@command",
".",
"deserializer",
".",
"load_from_io",
"(",
"socket",
")",
".",
"lazy",
"# Compute",
"@iterator",
"=",
"@command",
".",
"execute",
"(",
"@iterator",
",",
"@split_index",
")",
"# Result is not iterable",
"@iterator",
"=",
"[",
"@iterator",
"]",
"unless",
"@iterator",
".",
"respond_to?",
"(",
":each",
")",
"# Send result",
"@command",
".",
"serializer",
".",
"dump_to_io",
"(",
"@iterator",
",",
"socket",
")",
"end"
] |
These methods must be on one method because iterator is Lazy
which mean that exception can be raised at `serializer` or `compute`
|
[
"These",
"methods",
"must",
"be",
"on",
"one",
"method",
"because",
"iterator",
"is",
"Lazy",
"which",
"mean",
"that",
"exception",
"can",
"be",
"raised",
"at",
"serializer",
"or",
"compute"
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/worker/worker.rb#L57-L86
|
21,488 |
ondra-m/ruby-spark
|
lib/spark/rdd.rb
|
Spark.RDD.inspect
|
def inspect
comms = @command.commands.join(' -> ')
result = %{#<#{self.class.name}:0x#{object_id}}
result << %{ (#{comms})} unless comms.empty?
result << %{ (cached)} if cached?
result << %{\n}
result << %{ Serializer: "#{serializer}"\n}
result << %{Deserializer: "#{deserializer}"}
result << %{>}
result
end
|
ruby
|
def inspect
comms = @command.commands.join(' -> ')
result = %{#<#{self.class.name}:0x#{object_id}}
result << %{ (#{comms})} unless comms.empty?
result << %{ (cached)} if cached?
result << %{\n}
result << %{ Serializer: "#{serializer}"\n}
result << %{Deserializer: "#{deserializer}"}
result << %{>}
result
end
|
[
"def",
"inspect",
"comms",
"=",
"@command",
".",
"commands",
".",
"join",
"(",
"' -> '",
")",
"result",
"=",
"%{#<#{self.class.name}:0x#{object_id}}",
"result",
"<<",
"%{ (#{comms})}",
"unless",
"comms",
".",
"empty?",
"result",
"<<",
"%{ (cached)}",
"if",
"cached?",
"result",
"<<",
"%{\\n}",
"result",
"<<",
"%{ Serializer: \"#{serializer}\"\\n}",
"result",
"<<",
"%{Deserializer: \"#{deserializer}\"}",
"result",
"<<",
"%{>}",
"result",
"end"
] |
Initializing RDD, this method is root of all Pipelined RDD - its unique
If you call some operations on this class it will be computed in Java
== Parameters:
jrdd:: org.apache.spark.api.java.JavaRDD
context:: {Spark::Context}
serializer:: {Spark::Serializer}
|
[
"Initializing",
"RDD",
"this",
"method",
"is",
"root",
"of",
"all",
"Pipelined",
"RDD",
"-",
"its",
"unique",
"If",
"you",
"call",
"some",
"operations",
"on",
"this",
"class",
"it",
"will",
"be",
"computed",
"in",
"Java"
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L37-L48
|
21,489 |
ondra-m/ruby-spark
|
lib/spark/rdd.rb
|
Spark.RDD.take
|
def take(count)
buffer = []
parts_count = self.partitions_size
# No parts was scanned, yet
last_scanned = -1
while buffer.empty?
last_scanned += 1
buffer += context.run_job_with_command(self, [last_scanned], true, Spark::Command::Take, 0, -1)
end
# Assumption. Depend on batch_size and how Spark divided data.
items_per_part = buffer.size
left = count - buffer.size
while left > 0 && last_scanned < parts_count
parts_to_take = (left.to_f/items_per_part).ceil
parts_for_scanned = Array.new(parts_to_take) do
last_scanned += 1
end
# We cannot take exact number of items because workers are isolated from each other.
# => once you take e.g. 50% from last part and left is still > 0 then its very
# difficult merge new items
items = context.run_job_with_command(self, parts_for_scanned, true, Spark::Command::Take, left, last_scanned)
buffer += items
left = count - buffer.size
# Average size of all parts
items_per_part = [items_per_part, items.size].reduce(0){|sum, x| sum + x.to_f/2}
end
buffer.slice!(0, count)
end
|
ruby
|
def take(count)
buffer = []
parts_count = self.partitions_size
# No parts was scanned, yet
last_scanned = -1
while buffer.empty?
last_scanned += 1
buffer += context.run_job_with_command(self, [last_scanned], true, Spark::Command::Take, 0, -1)
end
# Assumption. Depend on batch_size and how Spark divided data.
items_per_part = buffer.size
left = count - buffer.size
while left > 0 && last_scanned < parts_count
parts_to_take = (left.to_f/items_per_part).ceil
parts_for_scanned = Array.new(parts_to_take) do
last_scanned += 1
end
# We cannot take exact number of items because workers are isolated from each other.
# => once you take e.g. 50% from last part and left is still > 0 then its very
# difficult merge new items
items = context.run_job_with_command(self, parts_for_scanned, true, Spark::Command::Take, left, last_scanned)
buffer += items
left = count - buffer.size
# Average size of all parts
items_per_part = [items_per_part, items.size].reduce(0){|sum, x| sum + x.to_f/2}
end
buffer.slice!(0, count)
end
|
[
"def",
"take",
"(",
"count",
")",
"buffer",
"=",
"[",
"]",
"parts_count",
"=",
"self",
".",
"partitions_size",
"# No parts was scanned, yet",
"last_scanned",
"=",
"-",
"1",
"while",
"buffer",
".",
"empty?",
"last_scanned",
"+=",
"1",
"buffer",
"+=",
"context",
".",
"run_job_with_command",
"(",
"self",
",",
"[",
"last_scanned",
"]",
",",
"true",
",",
"Spark",
"::",
"Command",
"::",
"Take",
",",
"0",
",",
"-",
"1",
")",
"end",
"# Assumption. Depend on batch_size and how Spark divided data.",
"items_per_part",
"=",
"buffer",
".",
"size",
"left",
"=",
"count",
"-",
"buffer",
".",
"size",
"while",
"left",
">",
"0",
"&&",
"last_scanned",
"<",
"parts_count",
"parts_to_take",
"=",
"(",
"left",
".",
"to_f",
"/",
"items_per_part",
")",
".",
"ceil",
"parts_for_scanned",
"=",
"Array",
".",
"new",
"(",
"parts_to_take",
")",
"do",
"last_scanned",
"+=",
"1",
"end",
"# We cannot take exact number of items because workers are isolated from each other.",
"# => once you take e.g. 50% from last part and left is still > 0 then its very",
"# difficult merge new items",
"items",
"=",
"context",
".",
"run_job_with_command",
"(",
"self",
",",
"parts_for_scanned",
",",
"true",
",",
"Spark",
"::",
"Command",
"::",
"Take",
",",
"left",
",",
"last_scanned",
")",
"buffer",
"+=",
"items",
"left",
"=",
"count",
"-",
"buffer",
".",
"size",
"# Average size of all parts",
"items_per_part",
"=",
"[",
"items_per_part",
",",
"items",
".",
"size",
"]",
".",
"reduce",
"(",
"0",
")",
"{",
"|",
"sum",
",",
"x",
"|",
"sum",
"+",
"x",
".",
"to_f",
"/",
"2",
"}",
"end",
"buffer",
".",
"slice!",
"(",
"0",
",",
"count",
")",
"end"
] |
Take the first num elements of the RDD.
It works by first scanning one partition, and use the results from
that partition to estimate the number of additional partitions needed
to satisfy the limit.
== Example:
rdd = $sc.parallelize(0..100, 20)
rdd.take(5)
# => [0, 1, 2, 3, 4]
|
[
"Take",
"the",
"first",
"num",
"elements",
"of",
"the",
"RDD",
"."
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L247-L281
|
21,490 |
ondra-m/ruby-spark
|
lib/spark/rdd.rb
|
Spark.RDD.aggregate
|
def aggregate(zero_value, seq_op, comb_op)
_reduce(Spark::Command::Aggregate, seq_op, comb_op, zero_value)
end
|
ruby
|
def aggregate(zero_value, seq_op, comb_op)
_reduce(Spark::Command::Aggregate, seq_op, comb_op, zero_value)
end
|
[
"def",
"aggregate",
"(",
"zero_value",
",",
"seq_op",
",",
"comb_op",
")",
"_reduce",
"(",
"Spark",
"::",
"Command",
"::",
"Aggregate",
",",
"seq_op",
",",
"comb_op",
",",
"zero_value",
")",
"end"
] |
Aggregate the elements of each partition, and then the results for all the partitions, using
given combine functions and a neutral "zero value".
This function can return a different result type. We need one operation for merging.
Result must be an Array otherwise Serializer Array's zero value will be send
as multiple values and not just one.
== Example:
# 1 2 3 4 5 => 15 + 1 = 16
# 6 7 8 9 10 => 40 + 1 = 41
# 16 * 41 = 656
seq = lambda{|x,y| x+y}
com = lambda{|x,y| x*y}
rdd = $sc.parallelize(1..10, 2)
rdd.aggregate(1, seq, com)
# => 656
|
[
"Aggregate",
"the",
"elements",
"of",
"each",
"partition",
"and",
"then",
"the",
"results",
"for",
"all",
"the",
"partitions",
"using",
"given",
"combine",
"functions",
"and",
"a",
"neutral",
"zero",
"value",
"."
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L342-L344
|
21,491 |
ondra-m/ruby-spark
|
lib/spark/rdd.rb
|
Spark.RDD.coalesce
|
def coalesce(num_partitions)
if self.is_a?(PipelinedRDD)
deser = @command.serializer
else
deser = @command.deserializer
end
new_jrdd = jrdd.coalesce(num_partitions)
RDD.new(new_jrdd, context, @command.serializer, deser)
end
|
ruby
|
def coalesce(num_partitions)
if self.is_a?(PipelinedRDD)
deser = @command.serializer
else
deser = @command.deserializer
end
new_jrdd = jrdd.coalesce(num_partitions)
RDD.new(new_jrdd, context, @command.serializer, deser)
end
|
[
"def",
"coalesce",
"(",
"num_partitions",
")",
"if",
"self",
".",
"is_a?",
"(",
"PipelinedRDD",
")",
"deser",
"=",
"@command",
".",
"serializer",
"else",
"deser",
"=",
"@command",
".",
"deserializer",
"end",
"new_jrdd",
"=",
"jrdd",
".",
"coalesce",
"(",
"num_partitions",
")",
"RDD",
".",
"new",
"(",
"new_jrdd",
",",
"context",
",",
"@command",
".",
"serializer",
",",
"deser",
")",
"end"
] |
Return a new RDD that is reduced into num_partitions partitions.
== Example:
rdd = $sc.parallelize(0..10, 3)
rdd.coalesce(2).glom.collect
# => [[0, 1, 2], [3, 4, 5, 6, 7, 8, 9, 10]]
|
[
"Return",
"a",
"new",
"RDD",
"that",
"is",
"reduced",
"into",
"num_partitions",
"partitions",
"."
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L683-L692
|
21,492 |
ondra-m/ruby-spark
|
lib/spark/rdd.rb
|
Spark.RDD.shuffle
|
def shuffle(seed=nil)
seed ||= Random.new_seed
new_rdd_from_command(Spark::Command::Shuffle, seed)
end
|
ruby
|
def shuffle(seed=nil)
seed ||= Random.new_seed
new_rdd_from_command(Spark::Command::Shuffle, seed)
end
|
[
"def",
"shuffle",
"(",
"seed",
"=",
"nil",
")",
"seed",
"||=",
"Random",
".",
"new_seed",
"new_rdd_from_command",
"(",
"Spark",
"::",
"Command",
"::",
"Shuffle",
",",
"seed",
")",
"end"
] |
Return a shuffled RDD.
== Example:
rdd = $sc.parallelize(0..10)
rdd.shuffle.collect
# => [3, 10, 6, 7, 8, 0, 4, 2, 9, 1, 5]
|
[
"Return",
"a",
"shuffled",
"RDD",
"."
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L733-L737
|
21,493 |
ondra-m/ruby-spark
|
lib/spark/rdd.rb
|
Spark.RDD.reserialize
|
def reserialize(new_serializer)
if serializer == new_serializer
return self
end
new_command = @command.deep_copy
new_command.serializer = new_serializer
PipelinedRDD.new(self, new_command)
end
|
ruby
|
def reserialize(new_serializer)
if serializer == new_serializer
return self
end
new_command = @command.deep_copy
new_command.serializer = new_serializer
PipelinedRDD.new(self, new_command)
end
|
[
"def",
"reserialize",
"(",
"new_serializer",
")",
"if",
"serializer",
"==",
"new_serializer",
"return",
"self",
"end",
"new_command",
"=",
"@command",
".",
"deep_copy",
"new_command",
".",
"serializer",
"=",
"new_serializer",
"PipelinedRDD",
".",
"new",
"(",
"self",
",",
"new_command",
")",
"end"
] |
Return a new RDD with different serializer. This method is useful during union
and join operations.
== Example:
rdd = $sc.parallelize([1, 2, 3], nil, serializer: "marshal")
rdd = rdd.map(lambda{|x| x.to_s})
rdd.reserialize("oj").collect
# => ["1", "2", "3"]
|
[
"Return",
"a",
"new",
"RDD",
"with",
"different",
"serializer",
".",
"This",
"method",
"is",
"useful",
"during",
"union",
"and",
"join",
"operations",
"."
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L765-L774
|
21,494 |
ondra-m/ruby-spark
|
lib/spark/rdd.rb
|
Spark.RDD.intersection
|
def intersection(other)
mapping_function = 'lambda{|item| [item, nil]}'
filter_function = 'lambda{|(key, values)| values.size > 1}'
self.map(mapping_function)
.cogroup(other.map(mapping_function))
.filter(filter_function)
.keys
end
|
ruby
|
def intersection(other)
mapping_function = 'lambda{|item| [item, nil]}'
filter_function = 'lambda{|(key, values)| values.size > 1}'
self.map(mapping_function)
.cogroup(other.map(mapping_function))
.filter(filter_function)
.keys
end
|
[
"def",
"intersection",
"(",
"other",
")",
"mapping_function",
"=",
"'lambda{|item| [item, nil]}'",
"filter_function",
"=",
"'lambda{|(key, values)| values.size > 1}'",
"self",
".",
"map",
"(",
"mapping_function",
")",
".",
"cogroup",
"(",
"other",
".",
"map",
"(",
"mapping_function",
")",
")",
".",
"filter",
"(",
"filter_function",
")",
".",
"keys",
"end"
] |
Return the intersection of this RDD and another one. The output will not contain
any duplicate elements, even if the input RDDs did.
== Example:
rdd1 = $sc.parallelize([1,2,3,4,5])
rdd2 = $sc.parallelize([1,4,5,6,7])
rdd1.intersection(rdd2).collect
# => [1, 4, 5]
|
[
"Return",
"the",
"intersection",
"of",
"this",
"RDD",
"and",
"another",
"one",
".",
"The",
"output",
"will",
"not",
"contain",
"any",
"duplicate",
"elements",
"even",
"if",
"the",
"input",
"RDDs",
"did",
"."
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L785-L793
|
21,495 |
ondra-m/ruby-spark
|
lib/spark/rdd.rb
|
Spark.RDD.partition_by
|
def partition_by(num_partitions, partition_func=nil)
num_partitions ||= default_reduce_partitions
partition_func ||= 'lambda{|x| Spark::Digest.portable_hash(x.to_s)}'
_partition_by(num_partitions, Spark::Command::PartitionBy::Basic, partition_func)
end
|
ruby
|
def partition_by(num_partitions, partition_func=nil)
num_partitions ||= default_reduce_partitions
partition_func ||= 'lambda{|x| Spark::Digest.portable_hash(x.to_s)}'
_partition_by(num_partitions, Spark::Command::PartitionBy::Basic, partition_func)
end
|
[
"def",
"partition_by",
"(",
"num_partitions",
",",
"partition_func",
"=",
"nil",
")",
"num_partitions",
"||=",
"default_reduce_partitions",
"partition_func",
"||=",
"'lambda{|x| Spark::Digest.portable_hash(x.to_s)}'",
"_partition_by",
"(",
"num_partitions",
",",
"Spark",
"::",
"Command",
"::",
"PartitionBy",
"::",
"Basic",
",",
"partition_func",
")",
"end"
] |
Return a copy of the RDD partitioned using the specified partitioner.
== Example:
rdd = $sc.parallelize(["1","2","3","4","5"]).map(lambda {|x| [x, 1]})
rdd.partitionBy(2).glom.collect
# => [[["3", 1], ["4", 1]], [["1", 1], ["2", 1], ["5", 1]]]
|
[
"Return",
"a",
"copy",
"of",
"the",
"RDD",
"partitioned",
"using",
"the",
"specified",
"partitioner",
"."
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L802-L807
|
21,496 |
ondra-m/ruby-spark
|
lib/spark/rdd.rb
|
Spark.RDD.take_sample
|
def take_sample(with_replacement, num, seed=nil)
if num < 0
raise Spark::RDDError, 'Size have to be greater than 0'
elsif num == 0
return []
end
# Taken from scala
num_st_dev = 10.0
# Number of items
initial_count = self.count
return [] if initial_count == 0
# Create new generator
seed ||= Random.new_seed
rng = Random.new(seed)
# Shuffle elements if requested num if greater than array size
if !with_replacement && num >= initial_count
return self.shuffle(seed).collect
end
# Max num
max_sample_size = Integer::MAX - (num_st_dev * Math.sqrt(Integer::MAX)).to_i
if num > max_sample_size
raise Spark::RDDError, "Size can not be greate than #{max_sample_size}"
end
# Approximate fraction with tolerance
fraction = compute_fraction(num, initial_count, with_replacement)
# Compute first samled subset
samples = self.sample(with_replacement, fraction, seed).collect
# If the first sample didn't turn out large enough, keep trying to take samples;
# this shouldn't happen often because we use a big multiplier for their initial size.
index = 0
while samples.size < num
log_warning("Needed to re-sample due to insufficient sample size. Repeat #{index}")
samples = self.sample(with_replacement, fraction, rng.rand(0..Integer::MAX)).collect
index += 1
end
samples.shuffle!(random: rng)
samples[0, num]
end
|
ruby
|
def take_sample(with_replacement, num, seed=nil)
if num < 0
raise Spark::RDDError, 'Size have to be greater than 0'
elsif num == 0
return []
end
# Taken from scala
num_st_dev = 10.0
# Number of items
initial_count = self.count
return [] if initial_count == 0
# Create new generator
seed ||= Random.new_seed
rng = Random.new(seed)
# Shuffle elements if requested num if greater than array size
if !with_replacement && num >= initial_count
return self.shuffle(seed).collect
end
# Max num
max_sample_size = Integer::MAX - (num_st_dev * Math.sqrt(Integer::MAX)).to_i
if num > max_sample_size
raise Spark::RDDError, "Size can not be greate than #{max_sample_size}"
end
# Approximate fraction with tolerance
fraction = compute_fraction(num, initial_count, with_replacement)
# Compute first samled subset
samples = self.sample(with_replacement, fraction, seed).collect
# If the first sample didn't turn out large enough, keep trying to take samples;
# this shouldn't happen often because we use a big multiplier for their initial size.
index = 0
while samples.size < num
log_warning("Needed to re-sample due to insufficient sample size. Repeat #{index}")
samples = self.sample(with_replacement, fraction, rng.rand(0..Integer::MAX)).collect
index += 1
end
samples.shuffle!(random: rng)
samples[0, num]
end
|
[
"def",
"take_sample",
"(",
"with_replacement",
",",
"num",
",",
"seed",
"=",
"nil",
")",
"if",
"num",
"<",
"0",
"raise",
"Spark",
"::",
"RDDError",
",",
"'Size have to be greater than 0'",
"elsif",
"num",
"==",
"0",
"return",
"[",
"]",
"end",
"# Taken from scala",
"num_st_dev",
"=",
"10.0",
"# Number of items",
"initial_count",
"=",
"self",
".",
"count",
"return",
"[",
"]",
"if",
"initial_count",
"==",
"0",
"# Create new generator",
"seed",
"||=",
"Random",
".",
"new_seed",
"rng",
"=",
"Random",
".",
"new",
"(",
"seed",
")",
"# Shuffle elements if requested num if greater than array size",
"if",
"!",
"with_replacement",
"&&",
"num",
">=",
"initial_count",
"return",
"self",
".",
"shuffle",
"(",
"seed",
")",
".",
"collect",
"end",
"# Max num",
"max_sample_size",
"=",
"Integer",
"::",
"MAX",
"-",
"(",
"num_st_dev",
"*",
"Math",
".",
"sqrt",
"(",
"Integer",
"::",
"MAX",
")",
")",
".",
"to_i",
"if",
"num",
">",
"max_sample_size",
"raise",
"Spark",
"::",
"RDDError",
",",
"\"Size can not be greate than #{max_sample_size}\"",
"end",
"# Approximate fraction with tolerance",
"fraction",
"=",
"compute_fraction",
"(",
"num",
",",
"initial_count",
",",
"with_replacement",
")",
"# Compute first samled subset",
"samples",
"=",
"self",
".",
"sample",
"(",
"with_replacement",
",",
"fraction",
",",
"seed",
")",
".",
"collect",
"# If the first sample didn't turn out large enough, keep trying to take samples;",
"# this shouldn't happen often because we use a big multiplier for their initial size.",
"index",
"=",
"0",
"while",
"samples",
".",
"size",
"<",
"num",
"log_warning",
"(",
"\"Needed to re-sample due to insufficient sample size. Repeat #{index}\"",
")",
"samples",
"=",
"self",
".",
"sample",
"(",
"with_replacement",
",",
"fraction",
",",
"rng",
".",
"rand",
"(",
"0",
"..",
"Integer",
"::",
"MAX",
")",
")",
".",
"collect",
"index",
"+=",
"1",
"end",
"samples",
".",
"shuffle!",
"(",
"random",
":",
"rng",
")",
"samples",
"[",
"0",
",",
"num",
"]",
"end"
] |
Return a fixed-size sampled subset of this RDD in an array
== Examples:
rdd = $sc.parallelize(0..100)
rdd.take_sample(true, 10)
# => [90, 84, 74, 44, 27, 22, 72, 96, 80, 54]
rdd.take_sample(false, 10)
# => [5, 35, 30, 48, 22, 33, 40, 75, 42, 32]
|
[
"Return",
"a",
"fixed",
"-",
"size",
"sampled",
"subset",
"of",
"this",
"RDD",
"in",
"an",
"array"
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L837-L884
|
21,497 |
ondra-m/ruby-spark
|
lib/spark/rdd.rb
|
Spark.RDD.group_by_key
|
def group_by_key(num_partitions=nil)
create_combiner = 'lambda{|item| [item]}'
merge_value = 'lambda{|combiner, item| combiner << item; combiner}'
merge_combiners = 'lambda{|combiner_1, combiner_2| combiner_1 += combiner_2; combiner_1}'
combine_by_key(create_combiner, merge_value, merge_combiners, num_partitions)
end
|
ruby
|
def group_by_key(num_partitions=nil)
create_combiner = 'lambda{|item| [item]}'
merge_value = 'lambda{|combiner, item| combiner << item; combiner}'
merge_combiners = 'lambda{|combiner_1, combiner_2| combiner_1 += combiner_2; combiner_1}'
combine_by_key(create_combiner, merge_value, merge_combiners, num_partitions)
end
|
[
"def",
"group_by_key",
"(",
"num_partitions",
"=",
"nil",
")",
"create_combiner",
"=",
"'lambda{|item| [item]}'",
"merge_value",
"=",
"'lambda{|combiner, item| combiner << item; combiner}'",
"merge_combiners",
"=",
"'lambda{|combiner_1, combiner_2| combiner_1 += combiner_2; combiner_1}'",
"combine_by_key",
"(",
"create_combiner",
",",
"merge_value",
",",
"merge_combiners",
",",
"num_partitions",
")",
"end"
] |
Group the values for each key in the RDD into a single sequence. Allows controlling the
partitioning of the resulting key-value pair RDD by passing a Partitioner.
Note: If you are grouping in order to perform an aggregation (such as a sum or average)
over each key, using reduce_by_key or combine_by_key will provide much better performance.
== Example:
rdd = $sc.parallelize([["a", 1], ["a", 2], ["b", 3]])
rdd.group_by_key.collect
# => [["a", [1, 2]], ["b", [3]]]
|
[
"Group",
"the",
"values",
"for",
"each",
"key",
"in",
"the",
"RDD",
"into",
"a",
"single",
"sequence",
".",
"Allows",
"controlling",
"the",
"partitioning",
"of",
"the",
"resulting",
"key",
"-",
"value",
"pair",
"RDD",
"by",
"passing",
"a",
"Partitioner",
"."
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L989-L995
|
21,498 |
ondra-m/ruby-spark
|
lib/spark/rdd.rb
|
Spark.RDD.aggregate_by_key
|
def aggregate_by_key(zero_value, seq_func, comb_func, num_partitions=nil)
_combine_by_key(
[Spark::Command::CombineByKey::CombineWithZero, zero_value, seq_func],
[Spark::Command::CombineByKey::Merge, comb_func],
num_partitions
)
end
|
ruby
|
def aggregate_by_key(zero_value, seq_func, comb_func, num_partitions=nil)
_combine_by_key(
[Spark::Command::CombineByKey::CombineWithZero, zero_value, seq_func],
[Spark::Command::CombineByKey::Merge, comb_func],
num_partitions
)
end
|
[
"def",
"aggregate_by_key",
"(",
"zero_value",
",",
"seq_func",
",",
"comb_func",
",",
"num_partitions",
"=",
"nil",
")",
"_combine_by_key",
"(",
"[",
"Spark",
"::",
"Command",
"::",
"CombineByKey",
"::",
"CombineWithZero",
",",
"zero_value",
",",
"seq_func",
"]",
",",
"[",
"Spark",
"::",
"Command",
"::",
"CombineByKey",
"::",
"Merge",
",",
"comb_func",
"]",
",",
"num_partitions",
")",
"end"
] |
Aggregate the values of each key, using given combine functions and a neutral zero value.
== Example:
def combine(x,y)
x+y
end
def merge(x,y)
x*y
end
rdd = $sc.parallelize([["a", 1], ["b", 2], ["a", 3], ["a", 4], ["c", 5]], 2)
rdd.aggregate_by_key(1, method(:combine), method(:merge))
# => [["b", 3], ["a", 16], ["c", 6]]
|
[
"Aggregate",
"the",
"values",
"of",
"each",
"key",
"using",
"given",
"combine",
"functions",
"and",
"a",
"neutral",
"zero",
"value",
"."
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L1026-L1032
|
21,499 |
ondra-m/ruby-spark
|
lib/spark/rdd.rb
|
Spark.RDD.cogroup
|
def cogroup(*others)
unioned = self
others.each do |other|
unioned = unioned.union(other)
end
unioned.group_by_key
end
|
ruby
|
def cogroup(*others)
unioned = self
others.each do |other|
unioned = unioned.union(other)
end
unioned.group_by_key
end
|
[
"def",
"cogroup",
"(",
"*",
"others",
")",
"unioned",
"=",
"self",
"others",
".",
"each",
"do",
"|",
"other",
"|",
"unioned",
"=",
"unioned",
".",
"union",
"(",
"other",
")",
"end",
"unioned",
".",
"group_by_key",
"end"
] |
For each key k in `this` or `other`, return a resulting RDD that contains a tuple with the
list of values for that key in `this` as well as `other`.
== Example:
rdd1 = $sc.parallelize([["a", 1], ["a", 2], ["b", 3]])
rdd2 = $sc.parallelize([["a", 4], ["a", 5], ["b", 6]])
rdd3 = $sc.parallelize([["a", 7], ["a", 8], ["b", 9]])
rdd1.cogroup(rdd2, rdd3).collect
# => [["a", [1, 2, 4, 5, 7, 8]], ["b", [3, 6, 9]]]
|
[
"For",
"each",
"key",
"k",
"in",
"this",
"or",
"other",
"return",
"a",
"resulting",
"RDD",
"that",
"contains",
"a",
"tuple",
"with",
"the",
"list",
"of",
"values",
"for",
"that",
"key",
"in",
"this",
"as",
"well",
"as",
"other",
"."
] |
d1b9787642fe582dee906de3c6bb9407ded27145
|
https://github.com/ondra-m/ruby-spark/blob/d1b9787642fe582dee906de3c6bb9407ded27145/lib/spark/rdd.rb#L1057-L1064
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.