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
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
|
---|---|---|---|---|---|---|---|---|---|---|---|
4,700 | samvera-labs/geo_works | lib/generators/geo_works/install_generator.rb | GeoWorks.Install.inject_solr_document_behavior | def inject_solr_document_behavior
file_path = 'app/models/solr_document.rb'
if File.exist?(file_path)
inject_into_file file_path, after: /include Blacklight::Solr::Document.*$/ do
"\n # Adds GeoWorks behaviors to the SolrDocument.\n" \
" include GeoWorks::SolrDocumentBehavior\n"
end
else
Rails.logger.info " \e[31mFailure\e[0m GeoWorks requires a SolrDocument object. This generators assumes that the model is defined in the file #{file_path}, which does not exist."
end
end | ruby | def inject_solr_document_behavior
file_path = 'app/models/solr_document.rb'
if File.exist?(file_path)
inject_into_file file_path, after: /include Blacklight::Solr::Document.*$/ do
"\n # Adds GeoWorks behaviors to the SolrDocument.\n" \
" include GeoWorks::SolrDocumentBehavior\n"
end
else
Rails.logger.info " \e[31mFailure\e[0m GeoWorks requires a SolrDocument object. This generators assumes that the model is defined in the file #{file_path}, which does not exist."
end
end | [
"def",
"inject_solr_document_behavior",
"file_path",
"=",
"'app/models/solr_document.rb'",
"if",
"File",
".",
"exist?",
"(",
"file_path",
")",
"inject_into_file",
"file_path",
",",
"after",
":",
"/",
"/",
"do",
"\"\\n # Adds GeoWorks behaviors to the SolrDocument.\\n\"",
"\" include GeoWorks::SolrDocumentBehavior\\n\"",
"end",
"else",
"Rails",
".",
"logger",
".",
"info",
"\" \\e[31mFailure\\e[0m GeoWorks requires a SolrDocument object. This generators assumes that the model is defined in the file #{file_path}, which does not exist.\"",
"end",
"end"
] | Add behaviors to the SolrDocument model | [
"Add",
"behaviors",
"to",
"the",
"SolrDocument",
"model"
] | df1eff35fd01469a623fafeb9d71b44fd6160ca8 | https://github.com/samvera-labs/geo_works/blob/df1eff35fd01469a623fafeb9d71b44fd6160ca8/lib/generators/geo_works/install_generator.rb#L96-L106 |
4,701 | AssemDeghady/questionpro_rails | lib/questionpro_rails/survey_response.rb | QuestionproRails.SurveyResponse.response_set | def response_set
extracted_sets = []
unless self.qp_response_set.nil?
self.qp_response_set.each do |set|
extracted_sets.push(ResponseSet.new(set))
end
end
return extracted_sets
end | ruby | def response_set
extracted_sets = []
unless self.qp_response_set.nil?
self.qp_response_set.each do |set|
extracted_sets.push(ResponseSet.new(set))
end
end
return extracted_sets
end | [
"def",
"response_set",
"extracted_sets",
"=",
"[",
"]",
"unless",
"self",
".",
"qp_response_set",
".",
"nil?",
"self",
".",
"qp_response_set",
".",
"each",
"do",
"|",
"set",
"|",
"extracted_sets",
".",
"push",
"(",
"ResponseSet",
".",
"new",
"(",
"set",
")",
")",
"end",
"end",
"return",
"extracted_sets",
"end"
] | Extract the Response Set from the hash stored
inside qp_response_set attribute.
@return [Array<QuestionproRails::ResponseSet>] Response Sets. | [
"Extract",
"the",
"Response",
"Set",
"from",
"the",
"hash",
"stored",
"inside",
"qp_response_set",
"attribute",
"."
] | 79f295f193b6ad593f4d56d8edfa3076a23d8e4f | https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/survey_response.rb#L31-L41 |
4,702 | phatworx/rails_paginate | lib/rails_paginate/renderers/base.rb | RailsPaginate::Renderers.Base.url_for_page | def url_for_page(page)
view.url_for(view.default_url_options.merge({page_param.to_sym => page}).merge(options[:params] || {}))
end | ruby | def url_for_page(page)
view.url_for(view.default_url_options.merge({page_param.to_sym => page}).merge(options[:params] || {}))
end | [
"def",
"url_for_page",
"(",
"page",
")",
"view",
".",
"url_for",
"(",
"view",
".",
"default_url_options",
".",
"merge",
"(",
"{",
"page_param",
".",
"to_sym",
"=>",
"page",
"}",
")",
".",
"merge",
"(",
"options",
"[",
":params",
"]",
"||",
"{",
"}",
")",
")",
"end"
] | setup rails_paginate collection
build url | [
"setup",
"rails_paginate",
"collection",
"build",
"url"
] | ae8cbc12030853b236dc2cbf6ede8700fb835771 | https://github.com/phatworx/rails_paginate/blob/ae8cbc12030853b236dc2cbf6ede8700fb835771/lib/rails_paginate/renderers/base.rb#L18-L20 |
4,703 | phatworx/rails_paginate | lib/rails_paginate/renderers/base.rb | RailsPaginate::Renderers.Base.link_to_page | def link_to_page(page, key, link_options = {})
css_class = "#{link_options[:class]} #{page == current_page ? 'current' : ''}"
if key.nil?
content_tag :span, "..", :class => "spacer"
elsif page.nil?
content_tag :span, t(key), :class => "#{css_class} unavailable"
else
link_to t(key, :page => page), url_for_page(page), :class => css_class, :alt => view.strip_tags(t(key, :page => page)), :remote => options[:remote], :method => options[:method]
end
end | ruby | def link_to_page(page, key, link_options = {})
css_class = "#{link_options[:class]} #{page == current_page ? 'current' : ''}"
if key.nil?
content_tag :span, "..", :class => "spacer"
elsif page.nil?
content_tag :span, t(key), :class => "#{css_class} unavailable"
else
link_to t(key, :page => page), url_for_page(page), :class => css_class, :alt => view.strip_tags(t(key, :page => page)), :remote => options[:remote], :method => options[:method]
end
end | [
"def",
"link_to_page",
"(",
"page",
",",
"key",
",",
"link_options",
"=",
"{",
"}",
")",
"css_class",
"=",
"\"#{link_options[:class]} #{page == current_page ? 'current' : ''}\"",
"if",
"key",
".",
"nil?",
"content_tag",
":span",
",",
"\"..\"",
",",
":class",
"=>",
"\"spacer\"",
"elsif",
"page",
".",
"nil?",
"content_tag",
":span",
",",
"t",
"(",
"key",
")",
",",
":class",
"=>",
"\"#{css_class} unavailable\"",
"else",
"link_to",
"t",
"(",
"key",
",",
":page",
"=>",
"page",
")",
",",
"url_for_page",
"(",
"page",
")",
",",
":class",
"=>",
"css_class",
",",
":alt",
"=>",
"view",
".",
"strip_tags",
"(",
"t",
"(",
"key",
",",
":page",
"=>",
"page",
")",
")",
",",
":remote",
"=>",
"options",
"[",
":remote",
"]",
",",
":method",
"=>",
"options",
"[",
":method",
"]",
"end",
"end"
] | link to page with i18n support | [
"link",
"to",
"page",
"with",
"i18n",
"support"
] | ae8cbc12030853b236dc2cbf6ede8700fb835771 | https://github.com/phatworx/rails_paginate/blob/ae8cbc12030853b236dc2cbf6ede8700fb835771/lib/rails_paginate/renderers/base.rb#L30-L39 |
4,704 | piotrmurach/communist | lib/communist/server.rb | Communist.Server.stop | def stop
server = Communist.servers.delete(app.object_id) { |s| NullServer.new }
if Communist.server.respond_to?(:shutdown)
server.shutdown
elsif Communist.server.respond_to?(:stop!)
server.stop!
else
server.stop
end
@server_thread.join
end | ruby | def stop
server = Communist.servers.delete(app.object_id) { |s| NullServer.new }
if Communist.server.respond_to?(:shutdown)
server.shutdown
elsif Communist.server.respond_to?(:stop!)
server.stop!
else
server.stop
end
@server_thread.join
end | [
"def",
"stop",
"server",
"=",
"Communist",
".",
"servers",
".",
"delete",
"(",
"app",
".",
"object_id",
")",
"{",
"|",
"s",
"|",
"NullServer",
".",
"new",
"}",
"if",
"Communist",
".",
"server",
".",
"respond_to?",
"(",
":shutdown",
")",
"server",
".",
"shutdown",
"elsif",
"Communist",
".",
"server",
".",
"respond_to?",
"(",
":stop!",
")",
"server",
".",
"stop!",
"else",
"server",
".",
"stop",
"end",
"@server_thread",
".",
"join",
"end"
] | Stops the server after handling the connection.
Attempts to stop the server gracefully, otherwise
shuts current connection right away. | [
"Stops",
"the",
"server",
"after",
"handling",
"the",
"connection",
".",
"Attempts",
"to",
"stop",
"the",
"server",
"gracefully",
"otherwise",
"shuts",
"current",
"connection",
"right",
"away",
"."
] | 1f660ee1f201a265a65842d348414c17fcc0810a | https://github.com/piotrmurach/communist/blob/1f660ee1f201a265a65842d348414c17fcc0810a/lib/communist/server.rb#L85-L95 |
4,705 | sinefunc/pagination | lib/pagination/collection.rb | Pagination.Collection.displayed_pages | def displayed_pages(limit = 10, left_offset = -5, right_offset = 4)
lower, upper = nil, nil
if page + left_offset < 1 || page + right_offset > pages.last
lower = [page, [pages.last - limit, 0].max + 1].min
upper = [page + limit - 1, pages.last].min
else
lower = page + left_offset
upper = page + right_offset
end
(lower..upper).to_a
end | ruby | def displayed_pages(limit = 10, left_offset = -5, right_offset = 4)
lower, upper = nil, nil
if page + left_offset < 1 || page + right_offset > pages.last
lower = [page, [pages.last - limit, 0].max + 1].min
upper = [page + limit - 1, pages.last].min
else
lower = page + left_offset
upper = page + right_offset
end
(lower..upper).to_a
end | [
"def",
"displayed_pages",
"(",
"limit",
"=",
"10",
",",
"left_offset",
"=",
"-",
"5",
",",
"right_offset",
"=",
"4",
")",
"lower",
",",
"upper",
"=",
"nil",
",",
"nil",
"if",
"page",
"+",
"left_offset",
"<",
"1",
"||",
"page",
"+",
"right_offset",
">",
"pages",
".",
"last",
"lower",
"=",
"[",
"page",
",",
"[",
"pages",
".",
"last",
"-",
"limit",
",",
"0",
"]",
".",
"max",
"+",
"1",
"]",
".",
"min",
"upper",
"=",
"[",
"page",
"+",
"limit",
"-",
"1",
",",
"pages",
".",
"last",
"]",
".",
"min",
"else",
"lower",
"=",
"page",
"+",
"left_offset",
"upper",
"=",
"page",
"+",
"right_offset",
"end",
"(",
"lower",
"..",
"upper",
")",
".",
"to_a",
"end"
] | Provides dirt-simple logic for spitting out page numbers
based on the current page.
If we have 100 pages for example and we're at page 50,
this would simply return
[45, 46, 47, 48, 49, 50, 51, 52, 53, 54]
When we're at page 1, it displays 1 to 10.
You can pass in a number to limit the total displayed pages. | [
"Provides",
"dirt",
"-",
"simple",
"logic",
"for",
"spitting",
"out",
"page",
"numbers",
"based",
"on",
"the",
"current",
"page",
"."
] | e4d8684676dab2d4d9755af334fd35958bbfc3c8 | https://github.com/sinefunc/pagination/blob/e4d8684676dab2d4d9755af334fd35958bbfc3c8/lib/pagination/collection.rb#L56-L68 |
4,706 | Vasfed/orangedata | lib/orange_data/transport.rb | OrangeData.Transport.ping | def ping
res = transport.get(''){|r| r.headers['Accept'] = 'text/plain' }
res.status == 200 && res.body == "Nebula.Api v2"
rescue StandardError => _e
return false
end | ruby | def ping
res = transport.get(''){|r| r.headers['Accept'] = 'text/plain' }
res.status == 200 && res.body == "Nebula.Api v2"
rescue StandardError => _e
return false
end | [
"def",
"ping",
"res",
"=",
"transport",
".",
"get",
"(",
"''",
")",
"{",
"|",
"r",
"|",
"r",
".",
"headers",
"[",
"'Accept'",
"]",
"=",
"'text/plain'",
"}",
"res",
".",
"status",
"==",
"200",
"&&",
"res",
".",
"body",
"==",
"\"Nebula.Api v2\"",
"rescue",
"StandardError",
"=>",
"_e",
"return",
"false",
"end"
] | Below actual methods from api | [
"Below",
"actual",
"methods",
"from",
"api"
] | 020c332b1d11855e6bd0e9ba3b40f42276d013b5 | https://github.com/Vasfed/orangedata/blob/020c332b1d11855e6bd0e9ba3b40f42276d013b5/lib/orange_data/transport.rb#L157-L162 |
4,707 | unipept/unipept-cli | lib/batch_order.rb | Unipept.BatchOrder.wait | def wait(i, &block)
@order[i] = block
return unless i == @current
while order[@current]
order.delete(@current).call
@current += 1
end
end | ruby | def wait(i, &block)
@order[i] = block
return unless i == @current
while order[@current]
order.delete(@current).call
@current += 1
end
end | [
"def",
"wait",
"(",
"i",
",",
"&",
"block",
")",
"@order",
"[",
"i",
"]",
"=",
"block",
"return",
"unless",
"i",
"==",
"@current",
"while",
"order",
"[",
"@current",
"]",
"order",
".",
"delete",
"(",
"@current",
")",
".",
"call",
"@current",
"+=",
"1",
"end",
"end"
] | Executes block if it's its turn, queues the block in the other case. | [
"Executes",
"block",
"if",
"it",
"s",
"its",
"turn",
"queues",
"the",
"block",
"in",
"the",
"other",
"case",
"."
] | 183779bd1dffcd01ed623685c789160153b78681 | https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/batch_order.rb#L11-L19 |
4,708 | restaurant-cheetah/take2 | lib/take2.rb | Take2.InstanceMethods.call_api_with_retry | def call_api_with_retry(options = {})
config = self.class.retriable_configuration
config.merge!(Take2.local_defaults(options)) unless options.empty?
tries ||= config[:retries]
begin
yield
rescue => e
if config[:retriable].map { |klass| e.class <= klass }.any?
unless tries.zero? || config[:retry_condition_proc]&.call(e)
config[:retry_proc]&.call(e, tries)
rest(config, tries)
tries -= 1
retry
end
end
raise e
end
end | ruby | def call_api_with_retry(options = {})
config = self.class.retriable_configuration
config.merge!(Take2.local_defaults(options)) unless options.empty?
tries ||= config[:retries]
begin
yield
rescue => e
if config[:retriable].map { |klass| e.class <= klass }.any?
unless tries.zero? || config[:retry_condition_proc]&.call(e)
config[:retry_proc]&.call(e, tries)
rest(config, tries)
tries -= 1
retry
end
end
raise e
end
end | [
"def",
"call_api_with_retry",
"(",
"options",
"=",
"{",
"}",
")",
"config",
"=",
"self",
".",
"class",
".",
"retriable_configuration",
"config",
".",
"merge!",
"(",
"Take2",
".",
"local_defaults",
"(",
"options",
")",
")",
"unless",
"options",
".",
"empty?",
"tries",
"||=",
"config",
"[",
":retries",
"]",
"begin",
"yield",
"rescue",
"=>",
"e",
"if",
"config",
"[",
":retriable",
"]",
".",
"map",
"{",
"|",
"klass",
"|",
"e",
".",
"class",
"<=",
"klass",
"}",
".",
"any?",
"unless",
"tries",
".",
"zero?",
"||",
"config",
"[",
":retry_condition_proc",
"]",
"&.",
"call",
"(",
"e",
")",
"config",
"[",
":retry_proc",
"]",
"&.",
"call",
"(",
"e",
",",
"tries",
")",
"rest",
"(",
"config",
",",
"tries",
")",
"tries",
"-=",
"1",
"retry",
"end",
"end",
"raise",
"e",
"end",
"end"
] | Yields a block and retries on retriable errors n times.
The raised error could be the defined retriable or it child.
Example:
class PizzaService
include Take2
number_of_retries 3
retriable_errors Net::HTTPRetriableError
retriable_condition proc { |error| response_status(error.response) < 500 }
on_retry proc { |error, tries|
puts "#{self.name} - Retrying.. #{tries} of #{self.retriable_configuration[:retries]} (#{error})"
}
backoff_strategy type: :exponential, start: 3
def give_me_food
call_api_with_retry do
# Some logic that might raise..
# If it will raise retriable, magic happens.
# If not the original error re raised
end
end
end | [
"Yields",
"a",
"block",
"and",
"retries",
"on",
"retriable",
"errors",
"n",
"times",
".",
"The",
"raised",
"error",
"could",
"be",
"the",
"defined",
"retriable",
"or",
"it",
"child",
"."
] | 21bf2c67dd4aaca63e2c13733deef09cde195661 | https://github.com/restaurant-cheetah/take2/blob/21bf2c67dd4aaca63e2c13733deef09cde195661/lib/take2.rb#L59-L76 |
4,709 | restaurant-cheetah/take2 | lib/take2.rb | Take2.ClassMethods.number_of_retries | def number_of_retries(num)
raise ArgumentError, 'Must be positive Integer' unless num.is_a?(Integer) && num.positive?
self.retries = num
end | ruby | def number_of_retries(num)
raise ArgumentError, 'Must be positive Integer' unless num.is_a?(Integer) && num.positive?
self.retries = num
end | [
"def",
"number_of_retries",
"(",
"num",
")",
"raise",
"ArgumentError",
",",
"'Must be positive Integer'",
"unless",
"num",
".",
"is_a?",
"(",
"Integer",
")",
"&&",
"num",
".",
"positive?",
"self",
".",
"retries",
"=",
"num",
"end"
] | Sets number of retries.
Example:
class PizzaService
include Take2
number_of_retries 3
end
Arguments:
num: integer | [
"Sets",
"number",
"of",
"retries",
"."
] | 21bf2c67dd4aaca63e2c13733deef09cde195661 | https://github.com/restaurant-cheetah/take2/blob/21bf2c67dd4aaca63e2c13733deef09cde195661/lib/take2.rb#L105-L108 |
4,710 | restaurant-cheetah/take2 | lib/take2.rb | Take2.ClassMethods.retriable_errors | def retriable_errors(*errors)
message = 'All retriable errors must be StandardError decendants'
raise ArgumentError, message unless errors.all? { |e| e <= StandardError }
self.retriable = errors
end | ruby | def retriable_errors(*errors)
message = 'All retriable errors must be StandardError decendants'
raise ArgumentError, message unless errors.all? { |e| e <= StandardError }
self.retriable = errors
end | [
"def",
"retriable_errors",
"(",
"*",
"errors",
")",
"message",
"=",
"'All retriable errors must be StandardError decendants'",
"raise",
"ArgumentError",
",",
"message",
"unless",
"errors",
".",
"all?",
"{",
"|",
"e",
"|",
"e",
"<=",
"StandardError",
"}",
"self",
".",
"retriable",
"=",
"errors",
"end"
] | Sets list of errors on which the block will retry.
Example:
class PizzaService
include Take2
retriable_errors Net::HTTPRetriableError, Errno::ECONNRESET
end
Arguments:
errors: List of retiable errors | [
"Sets",
"list",
"of",
"errors",
"on",
"which",
"the",
"block",
"will",
"retry",
"."
] | 21bf2c67dd4aaca63e2c13733deef09cde195661 | https://github.com/restaurant-cheetah/take2/blob/21bf2c67dd4aaca63e2c13733deef09cde195661/lib/take2.rb#L119-L123 |
4,711 | restaurant-cheetah/take2 | lib/take2.rb | Take2.ClassMethods.backoff_strategy | def backoff_strategy(options)
available_types = [:constant, :linear, :fibonacci, :exponential]
raise ArgumentError, 'Incorrect backoff type' unless available_types.include?(options[:type])
self.backoff_intervals = Backoff.new(options[:type], options[:start]).intervals
end | ruby | def backoff_strategy(options)
available_types = [:constant, :linear, :fibonacci, :exponential]
raise ArgumentError, 'Incorrect backoff type' unless available_types.include?(options[:type])
self.backoff_intervals = Backoff.new(options[:type], options[:start]).intervals
end | [
"def",
"backoff_strategy",
"(",
"options",
")",
"available_types",
"=",
"[",
":constant",
",",
":linear",
",",
":fibonacci",
",",
":exponential",
"]",
"raise",
"ArgumentError",
",",
"'Incorrect backoff type'",
"unless",
"available_types",
".",
"include?",
"(",
"options",
"[",
":type",
"]",
")",
"self",
".",
"backoff_intervals",
"=",
"Backoff",
".",
"new",
"(",
"options",
"[",
":type",
"]",
",",
"options",
"[",
":start",
"]",
")",
".",
"intervals",
"end"
] | Sets the backoff strategy
Example:
class PizzaService
include Take2
backoff_strategy type: :exponential, start: 3
end
Arguments:
hash: object | [
"Sets",
"the",
"backoff",
"strategy"
] | 21bf2c67dd4aaca63e2c13733deef09cde195661 | https://github.com/restaurant-cheetah/take2/blob/21bf2c67dd4aaca63e2c13733deef09cde195661/lib/take2.rb#L172-L176 |
4,712 | restaurant-cheetah/take2 | lib/take2.rb | Take2.ClassMethods.retriable_configuration | def retriable_configuration
Take2::Configuration::CONFIG_ATTRS.each_with_object({}) do |key, hash|
hash[key] = send(key)
end
end | ruby | def retriable_configuration
Take2::Configuration::CONFIG_ATTRS.each_with_object({}) do |key, hash|
hash[key] = send(key)
end
end | [
"def",
"retriable_configuration",
"Take2",
"::",
"Configuration",
"::",
"CONFIG_ATTRS",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"key",
",",
"hash",
"|",
"hash",
"[",
"key",
"]",
"=",
"send",
"(",
"key",
")",
"end",
"end"
] | Exposes current class configuration | [
"Exposes",
"current",
"class",
"configuration"
] | 21bf2c67dd4aaca63e2c13733deef09cde195661 | https://github.com/restaurant-cheetah/take2/blob/21bf2c67dd4aaca63e2c13733deef09cde195661/lib/take2.rb#L179-L183 |
4,713 | quirkey/jim | lib/jim/installer.rb | Jim.Installer.install | def install
fetch
parse_package_json
determine_name_and_version
if !name || name.to_s =~ /^\s*$/ # blank
raise(Jim::InstallError, "Could not determine name for #{@fetched_path}")
end
logger.info "Installing #{name} #{version}"
logger.debug "fetched_path #{@fetched_path}"
if options[:shallow]
shallow_filename = [name, (version == "0" ? nil : version)].compact.join('-')
final_path = install_path + "#{shallow_filename}#{fetched_path.extname}"
else
final_path = install_path + 'lib' + "#{name}-#{version}" + "#{name}.js"
end
if @fetched_path.directory?
# install every js file
installed_paths = []
sub_options = options.merge({
:name => nil,
:version => nil,
:parent_version => version,
:package_json => package_json.merge("name" => nil)
})
Jim.each_path_in_directories([@fetched_path], '.js', IGNORE_DIRS) do |subfile|
logger.debug "Found file #{subfile}"
installed_paths << Jim::Installer.new(subfile, install_path, sub_options).install
end
logger.debug "Extracted to #{install_path}, #{installed_paths.length} file(s)"
return installed_paths
end
logger.debug "Installing to #{final_path}"
if final_path.exist?
logger.debug "#{final_path} already exists"
if options[:force]
FileUtils.rm_rf(final_path)
elsif Digest::MD5.hexdigest(File.read(final_path)) == Digest::MD5.hexdigest(File.read(@fetched_path))
logger.warn "Duplicate file, skipping"
return final_path
else
logger.error "Trying to install to #{final_path}, but file already exists and is different."
return false
end
end
Downlow.extract(@fetched_path, :destination => final_path, :tmp_dir => tmp_root)
# install json
install_package_json(final_path.dirname + 'package.json') if !options[:shallow]
installed = final_path.directory? ? Dir.glob(final_path + '**/*').length : 1
logger.debug "Extracted to #{final_path}, #{installed} file(s)"
final_path
ensure
FileUtils.rm_rf(@fetched_path) if @fetched_path && @fetched_path.exist?
final_path
end | ruby | def install
fetch
parse_package_json
determine_name_and_version
if !name || name.to_s =~ /^\s*$/ # blank
raise(Jim::InstallError, "Could not determine name for #{@fetched_path}")
end
logger.info "Installing #{name} #{version}"
logger.debug "fetched_path #{@fetched_path}"
if options[:shallow]
shallow_filename = [name, (version == "0" ? nil : version)].compact.join('-')
final_path = install_path + "#{shallow_filename}#{fetched_path.extname}"
else
final_path = install_path + 'lib' + "#{name}-#{version}" + "#{name}.js"
end
if @fetched_path.directory?
# install every js file
installed_paths = []
sub_options = options.merge({
:name => nil,
:version => nil,
:parent_version => version,
:package_json => package_json.merge("name" => nil)
})
Jim.each_path_in_directories([@fetched_path], '.js', IGNORE_DIRS) do |subfile|
logger.debug "Found file #{subfile}"
installed_paths << Jim::Installer.new(subfile, install_path, sub_options).install
end
logger.debug "Extracted to #{install_path}, #{installed_paths.length} file(s)"
return installed_paths
end
logger.debug "Installing to #{final_path}"
if final_path.exist?
logger.debug "#{final_path} already exists"
if options[:force]
FileUtils.rm_rf(final_path)
elsif Digest::MD5.hexdigest(File.read(final_path)) == Digest::MD5.hexdigest(File.read(@fetched_path))
logger.warn "Duplicate file, skipping"
return final_path
else
logger.error "Trying to install to #{final_path}, but file already exists and is different."
return false
end
end
Downlow.extract(@fetched_path, :destination => final_path, :tmp_dir => tmp_root)
# install json
install_package_json(final_path.dirname + 'package.json') if !options[:shallow]
installed = final_path.directory? ? Dir.glob(final_path + '**/*').length : 1
logger.debug "Extracted to #{final_path}, #{installed} file(s)"
final_path
ensure
FileUtils.rm_rf(@fetched_path) if @fetched_path && @fetched_path.exist?
final_path
end | [
"def",
"install",
"fetch",
"parse_package_json",
"determine_name_and_version",
"if",
"!",
"name",
"||",
"name",
".",
"to_s",
"=~",
"/",
"\\s",
"/",
"# blank",
"raise",
"(",
"Jim",
"::",
"InstallError",
",",
"\"Could not determine name for #{@fetched_path}\"",
")",
"end",
"logger",
".",
"info",
"\"Installing #{name} #{version}\"",
"logger",
".",
"debug",
"\"fetched_path #{@fetched_path}\"",
"if",
"options",
"[",
":shallow",
"]",
"shallow_filename",
"=",
"[",
"name",
",",
"(",
"version",
"==",
"\"0\"",
"?",
"nil",
":",
"version",
")",
"]",
".",
"compact",
".",
"join",
"(",
"'-'",
")",
"final_path",
"=",
"install_path",
"+",
"\"#{shallow_filename}#{fetched_path.extname}\"",
"else",
"final_path",
"=",
"install_path",
"+",
"'lib'",
"+",
"\"#{name}-#{version}\"",
"+",
"\"#{name}.js\"",
"end",
"if",
"@fetched_path",
".",
"directory?",
"# install every js file",
"installed_paths",
"=",
"[",
"]",
"sub_options",
"=",
"options",
".",
"merge",
"(",
"{",
":name",
"=>",
"nil",
",",
":version",
"=>",
"nil",
",",
":parent_version",
"=>",
"version",
",",
":package_json",
"=>",
"package_json",
".",
"merge",
"(",
"\"name\"",
"=>",
"nil",
")",
"}",
")",
"Jim",
".",
"each_path_in_directories",
"(",
"[",
"@fetched_path",
"]",
",",
"'.js'",
",",
"IGNORE_DIRS",
")",
"do",
"|",
"subfile",
"|",
"logger",
".",
"debug",
"\"Found file #{subfile}\"",
"installed_paths",
"<<",
"Jim",
"::",
"Installer",
".",
"new",
"(",
"subfile",
",",
"install_path",
",",
"sub_options",
")",
".",
"install",
"end",
"logger",
".",
"debug",
"\"Extracted to #{install_path}, #{installed_paths.length} file(s)\"",
"return",
"installed_paths",
"end",
"logger",
".",
"debug",
"\"Installing to #{final_path}\"",
"if",
"final_path",
".",
"exist?",
"logger",
".",
"debug",
"\"#{final_path} already exists\"",
"if",
"options",
"[",
":force",
"]",
"FileUtils",
".",
"rm_rf",
"(",
"final_path",
")",
"elsif",
"Digest",
"::",
"MD5",
".",
"hexdigest",
"(",
"File",
".",
"read",
"(",
"final_path",
")",
")",
"==",
"Digest",
"::",
"MD5",
".",
"hexdigest",
"(",
"File",
".",
"read",
"(",
"@fetched_path",
")",
")",
"logger",
".",
"warn",
"\"Duplicate file, skipping\"",
"return",
"final_path",
"else",
"logger",
".",
"error",
"\"Trying to install to #{final_path}, but file already exists and is different.\"",
"return",
"false",
"end",
"end",
"Downlow",
".",
"extract",
"(",
"@fetched_path",
",",
":destination",
"=>",
"final_path",
",",
":tmp_dir",
"=>",
"tmp_root",
")",
"# install json",
"install_package_json",
"(",
"final_path",
".",
"dirname",
"+",
"'package.json'",
")",
"if",
"!",
"options",
"[",
":shallow",
"]",
"installed",
"=",
"final_path",
".",
"directory?",
"?",
"Dir",
".",
"glob",
"(",
"final_path",
"+",
"'**/*'",
")",
".",
"length",
":",
"1",
"logger",
".",
"debug",
"\"Extracted to #{final_path}, #{installed} file(s)\"",
"final_path",
"ensure",
"FileUtils",
".",
"rm_rf",
"(",
"@fetched_path",
")",
"if",
"@fetched_path",
"&&",
"@fetched_path",
".",
"exist?",
"final_path",
"end"
] | Fetch and install the files determining their name and version if not provided.
If the fetch_path contains a directory of files, it iterates over the directory
installing each file that isn't in IGNORE_DIRS and a name and version can be
determined for. It also installs a package.json file along side the JS file
that contains meta data including the name and version, also merging with the
original package.json if found.
If options[:shallow] == true it will just copy the single file without any leading
directories or a package.json. 'shallow' installation is used for Bundle#vendor | [
"Fetch",
"and",
"install",
"the",
"files",
"determining",
"their",
"name",
"and",
"version",
"if",
"not",
"provided",
".",
"If",
"the",
"fetch_path",
"contains",
"a",
"directory",
"of",
"files",
"it",
"iterates",
"over",
"the",
"directory",
"installing",
"each",
"file",
"that",
"isn",
"t",
"in",
"IGNORE_DIRS",
"and",
"a",
"name",
"and",
"version",
"can",
"be",
"determined",
"for",
".",
"It",
"also",
"installs",
"a",
"package",
".",
"json",
"file",
"along",
"side",
"the",
"JS",
"file",
"that",
"contains",
"meta",
"data",
"including",
"the",
"name",
"and",
"version",
"also",
"merging",
"with",
"the",
"original",
"package",
".",
"json",
"if",
"found",
"."
] | ad5dbf06527a1d0376055a02b58bb11b5a0ebc35 | https://github.com/quirkey/jim/blob/ad5dbf06527a1d0376055a02b58bb11b5a0ebc35/lib/jim/installer.rb#L61-L120 |
4,714 | couchrest/couchrest_extended_document | lib/couchrest/validation.rb | CouchRest.Validation.validate_casted_arrays | def validate_casted_arrays
result = true
array_casted_properties = self.class.properties.select { |property| property.casted && property.type.instance_of?(Array) }
array_casted_properties.each do |property|
casted_values = self.send(property.name)
next unless casted_values.is_a?(Array) && casted_values.first.respond_to?(:valid?)
casted_values.each do |value|
result = (result && value.valid?) if value.respond_to?(:valid?)
end
end
result
end | ruby | def validate_casted_arrays
result = true
array_casted_properties = self.class.properties.select { |property| property.casted && property.type.instance_of?(Array) }
array_casted_properties.each do |property|
casted_values = self.send(property.name)
next unless casted_values.is_a?(Array) && casted_values.first.respond_to?(:valid?)
casted_values.each do |value|
result = (result && value.valid?) if value.respond_to?(:valid?)
end
end
result
end | [
"def",
"validate_casted_arrays",
"result",
"=",
"true",
"array_casted_properties",
"=",
"self",
".",
"class",
".",
"properties",
".",
"select",
"{",
"|",
"property",
"|",
"property",
".",
"casted",
"&&",
"property",
".",
"type",
".",
"instance_of?",
"(",
"Array",
")",
"}",
"array_casted_properties",
".",
"each",
"do",
"|",
"property",
"|",
"casted_values",
"=",
"self",
".",
"send",
"(",
"property",
".",
"name",
")",
"next",
"unless",
"casted_values",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"casted_values",
".",
"first",
".",
"respond_to?",
"(",
":valid?",
")",
"casted_values",
".",
"each",
"do",
"|",
"value",
"|",
"result",
"=",
"(",
"result",
"&&",
"value",
".",
"valid?",
")",
"if",
"value",
".",
"respond_to?",
"(",
":valid?",
")",
"end",
"end",
"result",
"end"
] | checking on casted objects | [
"checking",
"on",
"casted",
"objects"
] | 71511202ae10d3010dcf7b98fcba017cb37c76da | https://github.com/couchrest/couchrest_extended_document/blob/71511202ae10d3010dcf7b98fcba017cb37c76da/lib/couchrest/validation.rb#L126-L137 |
4,715 | couchrest/couchrest_extended_document | lib/couchrest/validation.rb | CouchRest.Validation.recursive_valid? | def recursive_valid?(target, context, state)
valid = state
target.each do |key, prop|
if prop.is_a?(Array)
prop.each do |item|
if item.validatable?
valid = recursive_valid?(item, context, valid) && valid
end
end
elsif prop.validatable?
valid = recursive_valid?(prop, context, valid) && valid
end
end
target._run_validate_callbacks do
target.class.validators.execute(context, target) && valid
end
end | ruby | def recursive_valid?(target, context, state)
valid = state
target.each do |key, prop|
if prop.is_a?(Array)
prop.each do |item|
if item.validatable?
valid = recursive_valid?(item, context, valid) && valid
end
end
elsif prop.validatable?
valid = recursive_valid?(prop, context, valid) && valid
end
end
target._run_validate_callbacks do
target.class.validators.execute(context, target) && valid
end
end | [
"def",
"recursive_valid?",
"(",
"target",
",",
"context",
",",
"state",
")",
"valid",
"=",
"state",
"target",
".",
"each",
"do",
"|",
"key",
",",
"prop",
"|",
"if",
"prop",
".",
"is_a?",
"(",
"Array",
")",
"prop",
".",
"each",
"do",
"|",
"item",
"|",
"if",
"item",
".",
"validatable?",
"valid",
"=",
"recursive_valid?",
"(",
"item",
",",
"context",
",",
"valid",
")",
"&&",
"valid",
"end",
"end",
"elsif",
"prop",
".",
"validatable?",
"valid",
"=",
"recursive_valid?",
"(",
"prop",
",",
"context",
",",
"valid",
")",
"&&",
"valid",
"end",
"end",
"target",
".",
"_run_validate_callbacks",
"do",
"target",
".",
"class",
".",
"validators",
".",
"execute",
"(",
"context",
",",
"target",
")",
"&&",
"valid",
"end",
"end"
] | Do recursive validity checking | [
"Do",
"recursive",
"validity",
"checking"
] | 71511202ae10d3010dcf7b98fcba017cb37c76da | https://github.com/couchrest/couchrest_extended_document/blob/71511202ae10d3010dcf7b98fcba017cb37c76da/lib/couchrest/validation.rb#L141-L157 |
4,716 | buren/honey_format | lib/honey_format/registry.rb | HoneyFormat.Registry.call | def call(value, type)
return type.call(value) if type.respond_to?(:call)
self[type].call(value)
end | ruby | def call(value, type)
return type.call(value) if type.respond_to?(:call)
self[type].call(value)
end | [
"def",
"call",
"(",
"value",
",",
"type",
")",
"return",
"type",
".",
"call",
"(",
"value",
")",
"if",
"type",
".",
"respond_to?",
"(",
":call",
")",
"self",
"[",
"type",
"]",
".",
"call",
"(",
"value",
")",
"end"
] | Call value type
@param [Symbol, String, #call] type the name of the type
@param [Object] value to be converted | [
"Call",
"value",
"type"
] | 5c54fba5f5ba044721afeef460a069af2018452c | https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/registry.rb#L43-L47 |
4,717 | buren/honey_format | lib/honey_format/registry.rb | HoneyFormat.Registry.[]= | def []=(type, caller)
type = to_key(type)
if type?(type)
raise(Errors::TypeExistsError, "type '#{type}' already exists")
end
@callers[type] = caller
end | ruby | def []=(type, caller)
type = to_key(type)
if type?(type)
raise(Errors::TypeExistsError, "type '#{type}' already exists")
end
@callers[type] = caller
end | [
"def",
"[]=",
"(",
"type",
",",
"caller",
")",
"type",
"=",
"to_key",
"(",
"type",
")",
"if",
"type?",
"(",
"type",
")",
"raise",
"(",
"Errors",
"::",
"TypeExistsError",
",",
"\"type '#{type}' already exists\"",
")",
"end",
"@callers",
"[",
"type",
"]",
"=",
"caller",
"end"
] | Register a caller
@param [Symbol, String] type the name of the type
@param [#call] caller that responds to #call
@return [Object] returns the caller
@raise [TypeExistsError] if type is already registered | [
"Register",
"a",
"caller"
] | 5c54fba5f5ba044721afeef460a069af2018452c | https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/registry.rb#L54-L62 |
4,718 | benmanns/cleverbot | lib/cleverbot/client.rb | Cleverbot.Client.write | def write message=''
response = self.class.write message, @params
message = response['message']
response.keep_if { |key, value| DEFAULT_PARAMS.keys.include? key }
@params.merge! response
@params.delete_if { |key, value| DEFAULT_PARAMS[key] == value }
message
end | ruby | def write message=''
response = self.class.write message, @params
message = response['message']
response.keep_if { |key, value| DEFAULT_PARAMS.keys.include? key }
@params.merge! response
@params.delete_if { |key, value| DEFAULT_PARAMS[key] == value }
message
end | [
"def",
"write",
"message",
"=",
"''",
"response",
"=",
"self",
".",
"class",
".",
"write",
"message",
",",
"@params",
"message",
"=",
"response",
"[",
"'message'",
"]",
"response",
".",
"keep_if",
"{",
"|",
"key",
",",
"value",
"|",
"DEFAULT_PARAMS",
".",
"keys",
".",
"include?",
"key",
"}",
"@params",
".",
"merge!",
"response",
"@params",
".",
"delete_if",
"{",
"|",
"key",
",",
"value",
"|",
"DEFAULT_PARAMS",
"[",
"key",
"]",
"==",
"value",
"}",
"message",
"end"
] | Initializes a Client with given parameters.
==== Parameters
[<tt>params</tt>] Optional <tt>Hash</tt> holding the initial parameters. Defaults to <tt>{}</tt>.
Sends a message and returns a <tt>String</tt> with the message received. Updates #params to maintain state.
==== Parameters
[<tt>message</tt>] Optional <tt>String</tt> holding the message to be sent. Defaults to <tt>''</tt>. | [
"Initializes",
"a",
"Client",
"with",
"given",
"parameters",
"."
] | 9040073227d3b2a68792838a1f036f76b739998b | https://github.com/benmanns/cleverbot/blob/9040073227d3b2a68792838a1f036f76b739998b/lib/cleverbot/client.rb#L74-L81 |
4,719 | medcat/command-runner | lib/command/runner.rb | Command.Runner.pass! | def pass!(interops = {}, options = {}, &block)
options[:unsafe] = @unsafe
env = options.delete(:env) || {}
backend.call(*contents(interops), env, options, &block)
rescue Errno::ENOENT
raise NoCommandError, @command
end | ruby | def pass!(interops = {}, options = {}, &block)
options[:unsafe] = @unsafe
env = options.delete(:env) || {}
backend.call(*contents(interops), env, options, &block)
rescue Errno::ENOENT
raise NoCommandError, @command
end | [
"def",
"pass!",
"(",
"interops",
"=",
"{",
"}",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"options",
"[",
":unsafe",
"]",
"=",
"@unsafe",
"env",
"=",
"options",
".",
"delete",
"(",
":env",
")",
"||",
"{",
"}",
"backend",
".",
"call",
"(",
"contents",
"(",
"interops",
")",
",",
"env",
",",
"options",
",",
"block",
")",
"rescue",
"Errno",
"::",
"ENOENT",
"raise",
"NoCommandError",
",",
"@command",
"end"
] | Initialize the messenger.
@param command [String] the name of the command file to run.
@param arguments [String] the arguments to pass to the command.
may contain interpolated values, like +{key}+ or +{{key}}+.
@param options [Hash] the options for the messenger.
Runs the command and arguments with the given interpolations;
defaults to no interpolations.
@note This method may not raise a {NoCommandError} and instead
return a {Message} with the error code +127+, even if the
command doesn't exist.
@yield [Message] when the command finishes.
@raise [NoCommandError] on no command.
@param interops [Hash<Symbol, Object>] the interpolations to
make.
@param options [Hash<Symbol, Object>] the options for the
backend.
@return [Message, Object] message if no block was given, the
return value of the block otherwise. | [
"Initialize",
"the",
"messenger",
"."
] | a18f00ae4cf7633656e4715db73536ae8294ac51 | https://github.com/medcat/command-runner/blob/a18f00ae4cf7633656e4715db73536ae8294ac51/lib/command/runner.rb#L103-L110 |
4,720 | dwayne/xo | lib/xo/grid.rb | XO.Grid.each | def each
(1..ROWS).each do |r|
(1..COLS).each do |c|
yield(r, c, self[r, c])
end
end
end | ruby | def each
(1..ROWS).each do |r|
(1..COLS).each do |c|
yield(r, c, self[r, c])
end
end
end | [
"def",
"each",
"(",
"1",
"..",
"ROWS",
")",
".",
"each",
"do",
"|",
"r",
"|",
"(",
"1",
"..",
"COLS",
")",
".",
"each",
"do",
"|",
"c",
"|",
"yield",
"(",
"r",
",",
"c",
",",
"self",
"[",
"r",
",",
"c",
"]",
")",
"end",
"end",
"end"
] | Iterates over all the positions of this grid from left to right and top to bottom.
@example
g = Grid.new
g.each do |r, c, k|
puts "(#{r}, #{c}) -> #{k}"
end | [
"Iterates",
"over",
"all",
"the",
"positions",
"of",
"this",
"grid",
"from",
"left",
"to",
"right",
"and",
"top",
"to",
"bottom",
"."
] | bd6524cf8882585fd5cca940f1daa5fb5f75d2bb | https://github.com/dwayne/xo/blob/bd6524cf8882585fd5cca940f1daa5fb5f75d2bb/lib/xo/grid.rb#L86-L92 |
4,721 | dwayne/xo | lib/xo/grid.rb | XO.Grid.each_open | def each_open
self.each { |r, c, _| yield(r, c) if open?(r, c) }
end | ruby | def each_open
self.each { |r, c, _| yield(r, c) if open?(r, c) }
end | [
"def",
"each_open",
"self",
".",
"each",
"{",
"|",
"r",
",",
"c",
",",
"_",
"|",
"yield",
"(",
"r",
",",
"c",
")",
"if",
"open?",
"(",
"r",
",",
"c",
")",
"}",
"end"
] | Iterates over all the open positions of this grid from left to right and top to bottom.
@example
g = Grid.new
g[1, 1] = g[2, 1] = Grid::X
g[2, 2] = g[3, 1] = Grid::O
g.each_open do |r, c|
puts "(#{r}, #{c}) is open"
end | [
"Iterates",
"over",
"all",
"the",
"open",
"positions",
"of",
"this",
"grid",
"from",
"left",
"to",
"right",
"and",
"top",
"to",
"bottom",
"."
] | bd6524cf8882585fd5cca940f1daa5fb5f75d2bb | https://github.com/dwayne/xo/blob/bd6524cf8882585fd5cca940f1daa5fb5f75d2bb/lib/xo/grid.rb#L105-L107 |
4,722 | sauspiel/postamt | lib/postamt/connection_handler.rb | Postamt.ConnectionHandler.connected? | def connected?(klass)
return false if Process.pid != @process_pid.get
conn = self.retrieve_connection_pool(klass)
conn && conn.connected?
end | ruby | def connected?(klass)
return false if Process.pid != @process_pid.get
conn = self.retrieve_connection_pool(klass)
conn && conn.connected?
end | [
"def",
"connected?",
"(",
"klass",
")",
"return",
"false",
"if",
"Process",
".",
"pid",
"!=",
"@process_pid",
".",
"get",
"conn",
"=",
"self",
".",
"retrieve_connection_pool",
"(",
"klass",
")",
"conn",
"&&",
"conn",
".",
"connected?",
"end"
] | Returns true if a connection that's accessible to this class has
already been opened. | [
"Returns",
"true",
"if",
"a",
"connection",
"that",
"s",
"accessible",
"to",
"this",
"class",
"has",
"already",
"been",
"opened",
"."
] | bafbcbd6ab6ab00e45e4afab89f1ecadffe4341a | https://github.com/sauspiel/postamt/blob/bafbcbd6ab6ab00e45e4afab89f1ecadffe4341a/lib/postamt/connection_handler.rb#L57-L61 |
4,723 | ftomassetti/codemodels | lib/codemodels/navigation.rb | CodeModels.NavigationExtensions.all_children | def all_children(flag=nil)
also_foreign = (flag==:also_foreign)
arr = []
ecore = self.class.ecore
# Awful hack to forbid the same reference is visited twice when
# two references with the same name are found
already_used_references = []
ecore.eAllReferences.sort_by{|r| r.name}.select {|r| r.containment}.each do |ref|
unless already_used_references.include?(ref.name)
res = self.send(ref.name.to_sym)
if ref.many
d = arr.count
res.each do |el|
arr << el unless res==nil
end
elsif res!=nil
d = arr.count
arr << res
end
already_used_references << ref.name
end
end
if also_foreign
arr.concat(self.foreign_asts)
end
arr
end | ruby | def all_children(flag=nil)
also_foreign = (flag==:also_foreign)
arr = []
ecore = self.class.ecore
# Awful hack to forbid the same reference is visited twice when
# two references with the same name are found
already_used_references = []
ecore.eAllReferences.sort_by{|r| r.name}.select {|r| r.containment}.each do |ref|
unless already_used_references.include?(ref.name)
res = self.send(ref.name.to_sym)
if ref.many
d = arr.count
res.each do |el|
arr << el unless res==nil
end
elsif res!=nil
d = arr.count
arr << res
end
already_used_references << ref.name
end
end
if also_foreign
arr.concat(self.foreign_asts)
end
arr
end | [
"def",
"all_children",
"(",
"flag",
"=",
"nil",
")",
"also_foreign",
"=",
"(",
"flag",
"==",
":also_foreign",
")",
"arr",
"=",
"[",
"]",
"ecore",
"=",
"self",
".",
"class",
".",
"ecore",
"# Awful hack to forbid the same reference is visited twice when",
"# two references with the same name are found",
"already_used_references",
"=",
"[",
"]",
"ecore",
".",
"eAllReferences",
".",
"sort_by",
"{",
"|",
"r",
"|",
"r",
".",
"name",
"}",
".",
"select",
"{",
"|",
"r",
"|",
"r",
".",
"containment",
"}",
".",
"each",
"do",
"|",
"ref",
"|",
"unless",
"already_used_references",
".",
"include?",
"(",
"ref",
".",
"name",
")",
"res",
"=",
"self",
".",
"send",
"(",
"ref",
".",
"name",
".",
"to_sym",
")",
"if",
"ref",
".",
"many",
"d",
"=",
"arr",
".",
"count",
"res",
".",
"each",
"do",
"|",
"el",
"|",
"arr",
"<<",
"el",
"unless",
"res",
"==",
"nil",
"end",
"elsif",
"res!",
"=",
"nil",
"d",
"=",
"arr",
".",
"count",
"arr",
"<<",
"res",
"end",
"already_used_references",
"<<",
"ref",
".",
"name",
"end",
"end",
"if",
"also_foreign",
"arr",
".",
"concat",
"(",
"self",
".",
"foreign_asts",
")",
"end",
"arr",
"end"
] | All direct children | [
"All",
"direct",
"children"
] | fb08f1fe13dad5a20c32b59d88bc5e9f3faa60f2 | https://github.com/ftomassetti/codemodels/blob/fb08f1fe13dad5a20c32b59d88bc5e9f3faa60f2/lib/codemodels/navigation.rb#L9-L35 |
4,724 | ftomassetti/codemodels | lib/codemodels/navigation.rb | CodeModels.NavigationExtensions.all_children_deep | def all_children_deep(flag=nil)
arr = []
all_children(flag).each do |c|
arr << c
c.all_children_deep(flag).each do |cc|
arr << cc
end
end
arr
end | ruby | def all_children_deep(flag=nil)
arr = []
all_children(flag).each do |c|
arr << c
c.all_children_deep(flag).each do |cc|
arr << cc
end
end
arr
end | [
"def",
"all_children_deep",
"(",
"flag",
"=",
"nil",
")",
"arr",
"=",
"[",
"]",
"all_children",
"(",
"flag",
")",
".",
"each",
"do",
"|",
"c",
"|",
"arr",
"<<",
"c",
"c",
".",
"all_children_deep",
"(",
"flag",
")",
".",
"each",
"do",
"|",
"cc",
"|",
"arr",
"<<",
"cc",
"end",
"end",
"arr",
"end"
] | All direct and indirect children | [
"All",
"direct",
"and",
"indirect",
"children"
] | fb08f1fe13dad5a20c32b59d88bc5e9f3faa60f2 | https://github.com/ftomassetti/codemodels/blob/fb08f1fe13dad5a20c32b59d88bc5e9f3faa60f2/lib/codemodels/navigation.rb#L38-L47 |
4,725 | ftomassetti/codemodels | lib/codemodels/navigation.rb | CodeModels.NavigationExtensions.traverse | def traverse(flag=nil,&op)
op.call(self)
all_children_deep(flag).each do |c|
op.call(c)
end
end | ruby | def traverse(flag=nil,&op)
op.call(self)
all_children_deep(flag).each do |c|
op.call(c)
end
end | [
"def",
"traverse",
"(",
"flag",
"=",
"nil",
",",
"&",
"op",
")",
"op",
".",
"call",
"(",
"self",
")",
"all_children_deep",
"(",
"flag",
")",
".",
"each",
"do",
"|",
"c",
"|",
"op",
".",
"call",
"(",
"c",
")",
"end",
"end"
] | Execute an operation on the node itself and all children,
direct and indirect. | [
"Execute",
"an",
"operation",
"on",
"the",
"node",
"itself",
"and",
"all",
"children",
"direct",
"and",
"indirect",
"."
] | fb08f1fe13dad5a20c32b59d88bc5e9f3faa60f2 | https://github.com/ftomassetti/codemodels/blob/fb08f1fe13dad5a20c32b59d88bc5e9f3faa60f2/lib/codemodels/navigation.rb#L51-L56 |
4,726 | dropofwill/rtasklib | lib/rtasklib/execute.rb | Rtasklib.Execute.handle_response | def handle_response stdout, stderr, thread
unless thread.value.success?
dump = "#{thread.value} \n Stderr: #{stderr.read} \n Stdout: #{stdout.read} \n"
raise dump
end
end | ruby | def handle_response stdout, stderr, thread
unless thread.value.success?
dump = "#{thread.value} \n Stderr: #{stderr.read} \n Stdout: #{stdout.read} \n"
raise dump
end
end | [
"def",
"handle_response",
"stdout",
",",
"stderr",
",",
"thread",
"unless",
"thread",
".",
"value",
".",
"success?",
"dump",
"=",
"\"#{thread.value} \\n Stderr: #{stderr.read} \\n Stdout: #{stdout.read} \\n\"",
"raise",
"dump",
"end",
"end"
] | Default error handling called in every popen3 call. Only executes if
thread had a failing exit code
@raise [RuntimeError] if failing exit code | [
"Default",
"error",
"handling",
"called",
"in",
"every",
"popen3",
"call",
".",
"Only",
"executes",
"if",
"thread",
"had",
"a",
"failing",
"exit",
"code"
] | c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c | https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/execute.rb#L91-L96 |
4,727 | buren/honey_format | lib/honey_format/configuration.rb | HoneyFormat.Configuration.header_deduplicator= | def header_deduplicator=(strategy)
if header_deduplicator_registry.type?(strategy)
@header_deduplicator = header_deduplicator_registry[strategy]
elsif strategy.respond_to?(:call)
@header_deduplicator = strategy
else
message = "unknown deduplication strategy: '#{strategy}'"
raise(Errors::UnknownDeduplicationStrategyError, message)
end
end | ruby | def header_deduplicator=(strategy)
if header_deduplicator_registry.type?(strategy)
@header_deduplicator = header_deduplicator_registry[strategy]
elsif strategy.respond_to?(:call)
@header_deduplicator = strategy
else
message = "unknown deduplication strategy: '#{strategy}'"
raise(Errors::UnknownDeduplicationStrategyError, message)
end
end | [
"def",
"header_deduplicator",
"=",
"(",
"strategy",
")",
"if",
"header_deduplicator_registry",
".",
"type?",
"(",
"strategy",
")",
"@header_deduplicator",
"=",
"header_deduplicator_registry",
"[",
"strategy",
"]",
"elsif",
"strategy",
".",
"respond_to?",
"(",
":call",
")",
"@header_deduplicator",
"=",
"strategy",
"else",
"message",
"=",
"\"unknown deduplication strategy: '#{strategy}'\"",
"raise",
"(",
"Errors",
"::",
"UnknownDeduplicationStrategyError",
",",
"message",
")",
"end",
"end"
] | Set the deduplication header strategy
@param [Symbol, #call]
symbol with known strategy identifier or method that responds
to #call(colums, key_count)
@return [#call] the header deduplication strategy
@raise [UnknownDeduplicationStrategyError] | [
"Set",
"the",
"deduplication",
"header",
"strategy"
] | 5c54fba5f5ba044721afeef460a069af2018452c | https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/configuration.rb#L55-L64 |
4,728 | buren/honey_format | lib/honey_format/configuration.rb | HoneyFormat.Configuration.default_header_deduplicators | def default_header_deduplicators
@default_header_deduplicators ||= {
deduplicate: proc do |columns|
Helpers.key_count_to_deduplicated_array(columns)
end,
raise: proc do |columns|
duplicates = Helpers.duplicated_items(columns)
if duplicates.any?
message = "all columns must be unique, duplicates are: #{duplicates}"
raise(Errors::DuplicateHeaderColumnError, message)
end
columns
end,
none: proc { |columns| columns },
}.freeze
end | ruby | def default_header_deduplicators
@default_header_deduplicators ||= {
deduplicate: proc do |columns|
Helpers.key_count_to_deduplicated_array(columns)
end,
raise: proc do |columns|
duplicates = Helpers.duplicated_items(columns)
if duplicates.any?
message = "all columns must be unique, duplicates are: #{duplicates}"
raise(Errors::DuplicateHeaderColumnError, message)
end
columns
end,
none: proc { |columns| columns },
}.freeze
end | [
"def",
"default_header_deduplicators",
"@default_header_deduplicators",
"||=",
"{",
"deduplicate",
":",
"proc",
"do",
"|",
"columns",
"|",
"Helpers",
".",
"key_count_to_deduplicated_array",
"(",
"columns",
")",
"end",
",",
"raise",
":",
"proc",
"do",
"|",
"columns",
"|",
"duplicates",
"=",
"Helpers",
".",
"duplicated_items",
"(",
"columns",
")",
"if",
"duplicates",
".",
"any?",
"message",
"=",
"\"all columns must be unique, duplicates are: #{duplicates}\"",
"raise",
"(",
"Errors",
"::",
"DuplicateHeaderColumnError",
",",
"message",
")",
"end",
"columns",
"end",
",",
"none",
":",
"proc",
"{",
"|",
"columns",
"|",
"columns",
"}",
",",
"}",
".",
"freeze",
"end"
] | Default header deduplicate strategies
@return [Hash] the default header deduplicatation strategies | [
"Default",
"header",
"deduplicate",
"strategies"
] | 5c54fba5f5ba044721afeef460a069af2018452c | https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/configuration.rb#L68-L83 |
4,729 | buren/honey_format | lib/honey_format/configuration.rb | HoneyFormat.Configuration.default_converters | def default_converters
@default_converters ||= {
# strict variants
decimal!: StrictConvertDecimal,
integer!: StrictConvertInteger,
date!: StrictConvertDate,
datetime!: StrictConvertDatetime,
symbol!: StrictConvertSymbol,
downcase!: StrictConvertDowncase,
upcase!: StrictConvertUpcase,
boolean!: StrictConvertBoolean,
# safe variants
decimal: ConvertDecimal,
decimal_or_zero: ConvertDecimalOrZero,
integer: ConvertInteger,
integer_or_zero: ConvertIntegerOrZero,
date: ConvertDate,
datetime: ConvertDatetime,
symbol: ConvertSymbol,
downcase: ConvertDowncase,
upcase: ConvertUpcase,
boolean: ConvertBoolean,
md5: ConvertMD5,
hex: ConvertHex,
nil: ConvertNil,
blank: ConvertBlank,
header_column: ConvertHeaderColumn,
method_name: ConvertHeaderColumn,
}.freeze
end | ruby | def default_converters
@default_converters ||= {
# strict variants
decimal!: StrictConvertDecimal,
integer!: StrictConvertInteger,
date!: StrictConvertDate,
datetime!: StrictConvertDatetime,
symbol!: StrictConvertSymbol,
downcase!: StrictConvertDowncase,
upcase!: StrictConvertUpcase,
boolean!: StrictConvertBoolean,
# safe variants
decimal: ConvertDecimal,
decimal_or_zero: ConvertDecimalOrZero,
integer: ConvertInteger,
integer_or_zero: ConvertIntegerOrZero,
date: ConvertDate,
datetime: ConvertDatetime,
symbol: ConvertSymbol,
downcase: ConvertDowncase,
upcase: ConvertUpcase,
boolean: ConvertBoolean,
md5: ConvertMD5,
hex: ConvertHex,
nil: ConvertNil,
blank: ConvertBlank,
header_column: ConvertHeaderColumn,
method_name: ConvertHeaderColumn,
}.freeze
end | [
"def",
"default_converters",
"@default_converters",
"||=",
"{",
"# strict variants",
"decimal!",
":",
"StrictConvertDecimal",
",",
"integer!",
":",
"StrictConvertInteger",
",",
"date!",
":",
"StrictConvertDate",
",",
"datetime!",
":",
"StrictConvertDatetime",
",",
"symbol!",
":",
"StrictConvertSymbol",
",",
"downcase!",
":",
"StrictConvertDowncase",
",",
"upcase!",
":",
"StrictConvertUpcase",
",",
"boolean!",
":",
"StrictConvertBoolean",
",",
"# safe variants",
"decimal",
":",
"ConvertDecimal",
",",
"decimal_or_zero",
":",
"ConvertDecimalOrZero",
",",
"integer",
":",
"ConvertInteger",
",",
"integer_or_zero",
":",
"ConvertIntegerOrZero",
",",
"date",
":",
"ConvertDate",
",",
"datetime",
":",
"ConvertDatetime",
",",
"symbol",
":",
"ConvertSymbol",
",",
"downcase",
":",
"ConvertDowncase",
",",
"upcase",
":",
"ConvertUpcase",
",",
"boolean",
":",
"ConvertBoolean",
",",
"md5",
":",
"ConvertMD5",
",",
"hex",
":",
"ConvertHex",
",",
"nil",
":",
"ConvertNil",
",",
"blank",
":",
"ConvertBlank",
",",
"header_column",
":",
"ConvertHeaderColumn",
",",
"method_name",
":",
"ConvertHeaderColumn",
",",
"}",
".",
"freeze",
"end"
] | Default converter registry
@return [Hash] hash with default converters | [
"Default",
"converter",
"registry"
] | 5c54fba5f5ba044721afeef460a069af2018452c | https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/configuration.rb#L99-L128 |
4,730 | unipept/unipept-cli | lib/commands/unipept/api_runner.rb | Unipept.Commands::ApiRunner.host | def host
# find host in opts first
host = options[:host] || @configuration['host']
host = 'http://api.unipept.ugent.be' if host.nil? || host.empty?
# add http:// if needed
if host.start_with?('http://', 'https://')
host
else
"http://#{host}"
end
end | ruby | def host
# find host in opts first
host = options[:host] || @configuration['host']
host = 'http://api.unipept.ugent.be' if host.nil? || host.empty?
# add http:// if needed
if host.start_with?('http://', 'https://')
host
else
"http://#{host}"
end
end | [
"def",
"host",
"# find host in opts first",
"host",
"=",
"options",
"[",
":host",
"]",
"||",
"@configuration",
"[",
"'host'",
"]",
"host",
"=",
"'http://api.unipept.ugent.be'",
"if",
"host",
".",
"nil?",
"||",
"host",
".",
"empty?",
"# add http:// if needed",
"if",
"host",
".",
"start_with?",
"(",
"'http://'",
",",
"'https://'",
")",
"host",
"else",
"\"http://#{host}\"",
"end",
"end"
] | Returns the host. If a value is defined by both an option and the config
file, the value of the option is used. | [
"Returns",
"the",
"host",
".",
"If",
"a",
"value",
"is",
"defined",
"by",
"both",
"an",
"option",
"and",
"the",
"config",
"file",
"the",
"value",
"of",
"the",
"option",
"is",
"used",
"."
] | 183779bd1dffcd01ed623685c789160153b78681 | https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/commands/unipept/api_runner.rb#L23-L34 |
4,731 | unipept/unipept-cli | lib/commands/unipept/api_runner.rb | Unipept.Commands::ApiRunner.input_iterator | def input_iterator
return arguments.each unless arguments.empty?
return IO.foreach(options[:input]) if options[:input]
$stdin.each_line
end | ruby | def input_iterator
return arguments.each unless arguments.empty?
return IO.foreach(options[:input]) if options[:input]
$stdin.each_line
end | [
"def",
"input_iterator",
"return",
"arguments",
".",
"each",
"unless",
"arguments",
".",
"empty?",
"return",
"IO",
".",
"foreach",
"(",
"options",
"[",
":input",
"]",
")",
"if",
"options",
"[",
":input",
"]",
"$stdin",
".",
"each_line",
"end"
] | Returns an input iterator to use for the request.
- if arguments are given, uses arguments
- if the input file option is given, uses file input
- if none of the previous are given, uses stdin | [
"Returns",
"an",
"input",
"iterator",
"to",
"use",
"for",
"the",
"request",
".",
"-",
"if",
"arguments",
"are",
"given",
"uses",
"arguments",
"-",
"if",
"the",
"input",
"file",
"option",
"is",
"given",
"uses",
"file",
"input",
"-",
"if",
"none",
"of",
"the",
"previous",
"are",
"given",
"uses",
"stdin"
] | 183779bd1dffcd01ed623685c789160153b78681 | https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/commands/unipept/api_runner.rb#L40-L45 |
4,732 | unipept/unipept-cli | lib/commands/unipept/api_runner.rb | Unipept.Commands::ApiRunner.selected_fields | def selected_fields
return @selected_fields unless @selected_fields.nil?
fields = [*options[:select]].map { |f| f.split(',') }.flatten
fields.concat(required_fields) if @fasta && !fields.empty?
@selected_fields = fields.map { |f| glob_to_regex(f) }
end | ruby | def selected_fields
return @selected_fields unless @selected_fields.nil?
fields = [*options[:select]].map { |f| f.split(',') }.flatten
fields.concat(required_fields) if @fasta && !fields.empty?
@selected_fields = fields.map { |f| glob_to_regex(f) }
end | [
"def",
"selected_fields",
"return",
"@selected_fields",
"unless",
"@selected_fields",
".",
"nil?",
"fields",
"=",
"[",
"options",
"[",
":select",
"]",
"]",
".",
"map",
"{",
"|",
"f",
"|",
"f",
".",
"split",
"(",
"','",
")",
"}",
".",
"flatten",
"fields",
".",
"concat",
"(",
"required_fields",
")",
"if",
"@fasta",
"&&",
"!",
"fields",
".",
"empty?",
"@selected_fields",
"=",
"fields",
".",
"map",
"{",
"|",
"f",
"|",
"glob_to_regex",
"(",
"f",
")",
"}",
"end"
] | Returns an array of regular expressions containing all the selected fields | [
"Returns",
"an",
"array",
"of",
"regular",
"expressions",
"containing",
"all",
"the",
"selected",
"fields"
] | 183779bd1dffcd01ed623685c789160153b78681 | https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/commands/unipept/api_runner.rb#L88-L94 |
4,733 | unipept/unipept-cli | lib/commands/unipept/api_runner.rb | Unipept.Commands::ApiRunner.run | def run
ServerMessage.new(@host).print unless options[:quiet]
hydra = Typhoeus::Hydra.new(max_concurrency: concurrent_requests)
batch_order = Unipept::BatchOrder.new
last_id = 0
batch_iterator.iterate(input_iterator) do |input_slice, batch_id, fasta_mapper|
last_id = batch_id
@fasta = !fasta_mapper.nil?
request = ::RetryableTyphoeus::Request.new(
@url,
method: :post,
body: construct_request_body(input_slice),
accept_encoding: 'gzip',
headers: { 'User-Agent' => @user_agent }
)
request.on_complete do |resp|
block = handle_response(resp, batch_id, fasta_mapper)
batch_order.wait(batch_id, &block)
end
hydra.queue request
hydra.run if (batch_id % queue_size).zero?
end
hydra.run
batch_order.wait(last_id + 1) { output_writer.write_line formatter.footer }
end | ruby | def run
ServerMessage.new(@host).print unless options[:quiet]
hydra = Typhoeus::Hydra.new(max_concurrency: concurrent_requests)
batch_order = Unipept::BatchOrder.new
last_id = 0
batch_iterator.iterate(input_iterator) do |input_slice, batch_id, fasta_mapper|
last_id = batch_id
@fasta = !fasta_mapper.nil?
request = ::RetryableTyphoeus::Request.new(
@url,
method: :post,
body: construct_request_body(input_slice),
accept_encoding: 'gzip',
headers: { 'User-Agent' => @user_agent }
)
request.on_complete do |resp|
block = handle_response(resp, batch_id, fasta_mapper)
batch_order.wait(batch_id, &block)
end
hydra.queue request
hydra.run if (batch_id % queue_size).zero?
end
hydra.run
batch_order.wait(last_id + 1) { output_writer.write_line formatter.footer }
end | [
"def",
"run",
"ServerMessage",
".",
"new",
"(",
"@host",
")",
".",
"print",
"unless",
"options",
"[",
":quiet",
"]",
"hydra",
"=",
"Typhoeus",
"::",
"Hydra",
".",
"new",
"(",
"max_concurrency",
":",
"concurrent_requests",
")",
"batch_order",
"=",
"Unipept",
"::",
"BatchOrder",
".",
"new",
"last_id",
"=",
"0",
"batch_iterator",
".",
"iterate",
"(",
"input_iterator",
")",
"do",
"|",
"input_slice",
",",
"batch_id",
",",
"fasta_mapper",
"|",
"last_id",
"=",
"batch_id",
"@fasta",
"=",
"!",
"fasta_mapper",
".",
"nil?",
"request",
"=",
"::",
"RetryableTyphoeus",
"::",
"Request",
".",
"new",
"(",
"@url",
",",
"method",
":",
":post",
",",
"body",
":",
"construct_request_body",
"(",
"input_slice",
")",
",",
"accept_encoding",
":",
"'gzip'",
",",
"headers",
":",
"{",
"'User-Agent'",
"=>",
"@user_agent",
"}",
")",
"request",
".",
"on_complete",
"do",
"|",
"resp",
"|",
"block",
"=",
"handle_response",
"(",
"resp",
",",
"batch_id",
",",
"fasta_mapper",
")",
"batch_order",
".",
"wait",
"(",
"batch_id",
",",
"block",
")",
"end",
"hydra",
".",
"queue",
"request",
"hydra",
".",
"run",
"if",
"(",
"batch_id",
"%",
"queue_size",
")",
".",
"zero?",
"end",
"hydra",
".",
"run",
"batch_order",
".",
"wait",
"(",
"last_id",
"+",
"1",
")",
"{",
"output_writer",
".",
"write_line",
"formatter",
".",
"footer",
"}",
"end"
] | Runs the command | [
"Runs",
"the",
"command"
] | 183779bd1dffcd01ed623685c789160153b78681 | https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/commands/unipept/api_runner.rb#L112-L140 |
4,734 | unipept/unipept-cli | lib/commands/unipept/api_runner.rb | Unipept.Commands::ApiRunner.save_error | def save_error(message)
path = error_file_path
FileUtils.mkdir_p File.dirname(path)
File.open(path, 'w') { |f| f.write message }
warn "API request failed! log can be found in #{path}"
end | ruby | def save_error(message)
path = error_file_path
FileUtils.mkdir_p File.dirname(path)
File.open(path, 'w') { |f| f.write message }
warn "API request failed! log can be found in #{path}"
end | [
"def",
"save_error",
"(",
"message",
")",
"path",
"=",
"error_file_path",
"FileUtils",
".",
"mkdir_p",
"File",
".",
"dirname",
"(",
"path",
")",
"File",
".",
"open",
"(",
"path",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"message",
"}",
"warn",
"\"API request failed! log can be found in #{path}\"",
"end"
] | Saves an error to a new file in the .unipept directory in the users home
directory. | [
"Saves",
"an",
"error",
"to",
"a",
"new",
"file",
"in",
"the",
".",
"unipept",
"directory",
"in",
"the",
"users",
"home",
"directory",
"."
] | 183779bd1dffcd01ed623685c789160153b78681 | https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/commands/unipept/api_runner.rb#L144-L149 |
4,735 | unipept/unipept-cli | lib/commands/unipept/api_runner.rb | Unipept.Commands::ApiRunner.handle_response | def handle_response(response, batch_id, fasta_mapper)
if response.success?
handle_success_response(response, batch_id, fasta_mapper)
else
handle_failed_response(response)
end
end | ruby | def handle_response(response, batch_id, fasta_mapper)
if response.success?
handle_success_response(response, batch_id, fasta_mapper)
else
handle_failed_response(response)
end
end | [
"def",
"handle_response",
"(",
"response",
",",
"batch_id",
",",
"fasta_mapper",
")",
"if",
"response",
".",
"success?",
"handle_success_response",
"(",
"response",
",",
"batch_id",
",",
"fasta_mapper",
")",
"else",
"handle_failed_response",
"(",
"response",
")",
"end",
"end"
] | Handles the response of an API request.
Returns a block to execute. | [
"Handles",
"the",
"response",
"of",
"an",
"API",
"request",
".",
"Returns",
"a",
"block",
"to",
"execute",
"."
] | 183779bd1dffcd01ed623685c789160153b78681 | https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/commands/unipept/api_runner.rb#L159-L165 |
4,736 | unipept/unipept-cli | lib/commands/unipept/api_runner.rb | Unipept.Commands::ApiRunner.filter_result | def filter_result(json_response)
result = JSON[json_response] rescue []
result = [result] unless result.is_a? Array
result.map! { |r| r.select! { |k, _v| selected_fields.any? { |f| f.match k } } } unless selected_fields.empty?
result
end | ruby | def filter_result(json_response)
result = JSON[json_response] rescue []
result = [result] unless result.is_a? Array
result.map! { |r| r.select! { |k, _v| selected_fields.any? { |f| f.match k } } } unless selected_fields.empty?
result
end | [
"def",
"filter_result",
"(",
"json_response",
")",
"result",
"=",
"JSON",
"[",
"json_response",
"]",
"rescue",
"[",
"]",
"result",
"=",
"[",
"result",
"]",
"unless",
"result",
".",
"is_a?",
"Array",
"result",
".",
"map!",
"{",
"|",
"r",
"|",
"r",
".",
"select!",
"{",
"|",
"k",
",",
"_v",
"|",
"selected_fields",
".",
"any?",
"{",
"|",
"f",
"|",
"f",
".",
"match",
"k",
"}",
"}",
"}",
"unless",
"selected_fields",
".",
"empty?",
"result",
"end"
] | Parses the json_response, wraps it in an array if needed and filters the
fields based on the selected_fields | [
"Parses",
"the",
"json_response",
"wraps",
"it",
"in",
"an",
"array",
"if",
"needed",
"and",
"filters",
"the",
"fields",
"based",
"on",
"the",
"selected_fields"
] | 183779bd1dffcd01ed623685c789160153b78681 | https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/commands/unipept/api_runner.rb#L190-L195 |
4,737 | wingrunr21/gitolite | lib/gitolite/gitolite_admin.rb | Gitolite.GitoliteAdmin.save | def save
Dir.chdir(@gl_admin.working_dir) do
#Process config file (if loaded, i.e. may be modified)
if @config
new_conf = @config.to_file(@confdir)
@gl_admin.add(new_conf)
end
#Process ssh keys (if loaded, i.e. may be modified)
if @ssh_keys
files = list_keys(@keydir).map{|f| File.basename f}
keys = @ssh_keys.values.map{|f| f.map {|t| t.filename}}.flatten
to_remove = (files - keys).map { |f| File.join(@keydir, f)}
@gl_admin.remove(to_remove)
@ssh_keys.each_value do |key|
#Write only keys from sets that has been modified
next if key.respond_to?(:dirty?) && !key.dirty?
key.each do |k|
@gl_admin.add(k.to_file(@keydir))
end
end
end
end
end | ruby | def save
Dir.chdir(@gl_admin.working_dir) do
#Process config file (if loaded, i.e. may be modified)
if @config
new_conf = @config.to_file(@confdir)
@gl_admin.add(new_conf)
end
#Process ssh keys (if loaded, i.e. may be modified)
if @ssh_keys
files = list_keys(@keydir).map{|f| File.basename f}
keys = @ssh_keys.values.map{|f| f.map {|t| t.filename}}.flatten
to_remove = (files - keys).map { |f| File.join(@keydir, f)}
@gl_admin.remove(to_remove)
@ssh_keys.each_value do |key|
#Write only keys from sets that has been modified
next if key.respond_to?(:dirty?) && !key.dirty?
key.each do |k|
@gl_admin.add(k.to_file(@keydir))
end
end
end
end
end | [
"def",
"save",
"Dir",
".",
"chdir",
"(",
"@gl_admin",
".",
"working_dir",
")",
"do",
"#Process config file (if loaded, i.e. may be modified)",
"if",
"@config",
"new_conf",
"=",
"@config",
".",
"to_file",
"(",
"@confdir",
")",
"@gl_admin",
".",
"add",
"(",
"new_conf",
")",
"end",
"#Process ssh keys (if loaded, i.e. may be modified)",
"if",
"@ssh_keys",
"files",
"=",
"list_keys",
"(",
"@keydir",
")",
".",
"map",
"{",
"|",
"f",
"|",
"File",
".",
"basename",
"f",
"}",
"keys",
"=",
"@ssh_keys",
".",
"values",
".",
"map",
"{",
"|",
"f",
"|",
"f",
".",
"map",
"{",
"|",
"t",
"|",
"t",
".",
"filename",
"}",
"}",
".",
"flatten",
"to_remove",
"=",
"(",
"files",
"-",
"keys",
")",
".",
"map",
"{",
"|",
"f",
"|",
"File",
".",
"join",
"(",
"@keydir",
",",
"f",
")",
"}",
"@gl_admin",
".",
"remove",
"(",
"to_remove",
")",
"@ssh_keys",
".",
"each_value",
"do",
"|",
"key",
"|",
"#Write only keys from sets that has been modified",
"next",
"if",
"key",
".",
"respond_to?",
"(",
":dirty?",
")",
"&&",
"!",
"key",
".",
"dirty?",
"key",
".",
"each",
"do",
"|",
"k",
"|",
"@gl_admin",
".",
"add",
"(",
"k",
".",
"to_file",
"(",
"@keydir",
")",
")",
"end",
"end",
"end",
"end",
"end"
] | Writes all changed aspects out to the file system
will also stage all changes | [
"Writes",
"all",
"changed",
"aspects",
"out",
"to",
"the",
"file",
"system",
"will",
"also",
"stage",
"all",
"changes"
] | f86ec83e0885734000432b9502ccaa2dc26f4376 | https://github.com/wingrunr21/gitolite/blob/f86ec83e0885734000432b9502ccaa2dc26f4376/lib/gitolite/gitolite_admin.rb#L65-L90 |
4,738 | wingrunr21/gitolite | lib/gitolite/gitolite_admin.rb | Gitolite.GitoliteAdmin.reset! | def reset!
Dir.chdir(@gl_admin.working_dir) do
@gl_admin.git.reset({:hard => true}, 'HEAD')
@gl_admin.git.clean({:d => true, :q => true, :f => true})
end
reload!
end | ruby | def reset!
Dir.chdir(@gl_admin.working_dir) do
@gl_admin.git.reset({:hard => true}, 'HEAD')
@gl_admin.git.clean({:d => true, :q => true, :f => true})
end
reload!
end | [
"def",
"reset!",
"Dir",
".",
"chdir",
"(",
"@gl_admin",
".",
"working_dir",
")",
"do",
"@gl_admin",
".",
"git",
".",
"reset",
"(",
"{",
":hard",
"=>",
"true",
"}",
",",
"'HEAD'",
")",
"@gl_admin",
".",
"git",
".",
"clean",
"(",
"{",
":d",
"=>",
"true",
",",
":q",
"=>",
"true",
",",
":f",
"=>",
"true",
"}",
")",
"end",
"reload!",
"end"
] | This method will destroy all local tracked changes, resetting the local gitolite
git repo to HEAD and reloading the entire repository
Note that this will also delete all untracked files | [
"This",
"method",
"will",
"destroy",
"all",
"local",
"tracked",
"changes",
"resetting",
"the",
"local",
"gitolite",
"git",
"repo",
"to",
"HEAD",
"and",
"reloading",
"the",
"entire",
"repository",
"Note",
"that",
"this",
"will",
"also",
"delete",
"all",
"untracked",
"files"
] | f86ec83e0885734000432b9502ccaa2dc26f4376 | https://github.com/wingrunr21/gitolite/blob/f86ec83e0885734000432b9502ccaa2dc26f4376/lib/gitolite/gitolite_admin.rb#L95-L101 |
4,739 | wingrunr21/gitolite | lib/gitolite/gitolite_admin.rb | Gitolite.GitoliteAdmin.update | def update(options = {})
options = {:reset => true, :rebase => false }.merge(options)
reset! if options[:reset]
Dir.chdir(@gl_admin.working_dir) do
@gl_admin.git.pull({:rebase => options[:rebase]}, "origin", "master")
end
reload!
end | ruby | def update(options = {})
options = {:reset => true, :rebase => false }.merge(options)
reset! if options[:reset]
Dir.chdir(@gl_admin.working_dir) do
@gl_admin.git.pull({:rebase => options[:rebase]}, "origin", "master")
end
reload!
end | [
"def",
"update",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":reset",
"=>",
"true",
",",
":rebase",
"=>",
"false",
"}",
".",
"merge",
"(",
"options",
")",
"reset!",
"if",
"options",
"[",
":reset",
"]",
"Dir",
".",
"chdir",
"(",
"@gl_admin",
".",
"working_dir",
")",
"do",
"@gl_admin",
".",
"git",
".",
"pull",
"(",
"{",
":rebase",
"=>",
"options",
"[",
":rebase",
"]",
"}",
",",
"\"origin\"",
",",
"\"master\"",
")",
"end",
"reload!",
"end"
] | Updates the repo with changes from remote master | [
"Updates",
"the",
"repo",
"with",
"changes",
"from",
"remote",
"master"
] | f86ec83e0885734000432b9502ccaa2dc26f4376 | https://github.com/wingrunr21/gitolite/blob/f86ec83e0885734000432b9502ccaa2dc26f4376/lib/gitolite/gitolite_admin.rb#L127-L137 |
4,740 | wingrunr21/gitolite | lib/gitolite/gitolite_admin.rb | Gitolite.GitoliteAdmin.load_keys | def load_keys(path = nil)
path ||= File.join(@path, @keydir)
keys = Hash.new {|k,v| k[v] = DirtyProxy.new([])}
list_keys(path).each do |key|
new_key = SSHKey.from_file(File.join(path, key))
owner = new_key.owner
keys[owner] << new_key
end
#Mark key sets as unmodified (for dirty checking)
keys.values.each{|set| set.clean_up!}
keys
end | ruby | def load_keys(path = nil)
path ||= File.join(@path, @keydir)
keys = Hash.new {|k,v| k[v] = DirtyProxy.new([])}
list_keys(path).each do |key|
new_key = SSHKey.from_file(File.join(path, key))
owner = new_key.owner
keys[owner] << new_key
end
#Mark key sets as unmodified (for dirty checking)
keys.values.each{|set| set.clean_up!}
keys
end | [
"def",
"load_keys",
"(",
"path",
"=",
"nil",
")",
"path",
"||=",
"File",
".",
"join",
"(",
"@path",
",",
"@keydir",
")",
"keys",
"=",
"Hash",
".",
"new",
"{",
"|",
"k",
",",
"v",
"|",
"k",
"[",
"v",
"]",
"=",
"DirtyProxy",
".",
"new",
"(",
"[",
"]",
")",
"}",
"list_keys",
"(",
"path",
")",
".",
"each",
"do",
"|",
"key",
"|",
"new_key",
"=",
"SSHKey",
".",
"from_file",
"(",
"File",
".",
"join",
"(",
"path",
",",
"key",
")",
")",
"owner",
"=",
"new_key",
".",
"owner",
"keys",
"[",
"owner",
"]",
"<<",
"new_key",
"end",
"#Mark key sets as unmodified (for dirty checking)",
"keys",
".",
"values",
".",
"each",
"{",
"|",
"set",
"|",
"set",
".",
"clean_up!",
"}",
"keys",
"end"
] | Loads all .pub files in the gitolite-admin
keydir directory | [
"Loads",
"all",
".",
"pub",
"files",
"in",
"the",
"gitolite",
"-",
"admin",
"keydir",
"directory"
] | f86ec83e0885734000432b9502ccaa2dc26f4376 | https://github.com/wingrunr21/gitolite/blob/f86ec83e0885734000432b9502ccaa2dc26f4376/lib/gitolite/gitolite_admin.rb#L178-L192 |
4,741 | dailycred/dailycred | lib/dailycred/client.rb | Dailycred.Client.event | def event(user_id, key, val="")
opts = {
:key => key,
:valuestring => val,
:user_id => user_id
}
post "/admin/api/customevent.json", opts
end | ruby | def event(user_id, key, val="")
opts = {
:key => key,
:valuestring => val,
:user_id => user_id
}
post "/admin/api/customevent.json", opts
end | [
"def",
"event",
"(",
"user_id",
",",
"key",
",",
"val",
"=",
"\"\"",
")",
"opts",
"=",
"{",
":key",
"=>",
"key",
",",
":valuestring",
"=>",
"val",
",",
":user_id",
"=>",
"user_id",
"}",
"post",
"\"/admin/api/customevent.json\"",
",",
"opts",
"end"
] | Initializes a dailycred object
- @param [String] client\_id the client's daiycred client id
- @param [String] secret\_key the clients secret key
- @param [Hash] opts a hash of options
Generates a Dailycred event
- @param [String] user_id the user's dailycred user id
- @param [String] key the name of the event type
- @param [String] val the value of the event (optional) | [
"Initializes",
"a",
"dailycred",
"object"
] | e4c504e26b2f56de819b5828bb5ca93d1f583e0d | https://github.com/dailycred/dailycred/blob/e4c504e26b2f56de819b5828bb5ca93d1f583e0d/lib/dailycred/client.rb#L31-L38 |
4,742 | Mik-die/mongoid_globalize | lib/mongoid_globalize/adapter.rb | Mongoid::Globalize.Adapter.prepare_translations! | def prepare_translations!
stash.each do |locale, attrs|
if attrs.any?
translation = record.translations.find_by_locale(locale)
translation ||= record.translations.build(:locale => locale)
attrs.each{ |name, value| translation[name] = value }
end
end
reset
end | ruby | def prepare_translations!
stash.each do |locale, attrs|
if attrs.any?
translation = record.translations.find_by_locale(locale)
translation ||= record.translations.build(:locale => locale)
attrs.each{ |name, value| translation[name] = value }
end
end
reset
end | [
"def",
"prepare_translations!",
"stash",
".",
"each",
"do",
"|",
"locale",
",",
"attrs",
"|",
"if",
"attrs",
".",
"any?",
"translation",
"=",
"record",
".",
"translations",
".",
"find_by_locale",
"(",
"locale",
")",
"translation",
"||=",
"record",
".",
"translations",
".",
"build",
"(",
":locale",
"=>",
"locale",
")",
"attrs",
".",
"each",
"{",
"|",
"name",
",",
"value",
"|",
"translation",
"[",
"name",
"]",
"=",
"value",
"}",
"end",
"end",
"reset",
"end"
] | Prepares data from stash for persisting in embeded Translation documents.
Also clears stash for further operations. | [
"Prepares",
"data",
"from",
"stash",
"for",
"persisting",
"in",
"embeded",
"Translation",
"documents",
".",
"Also",
"clears",
"stash",
"for",
"further",
"operations",
"."
] | 458105154574950aed98119fd54ffaae4e1a55ee | https://github.com/Mik-die/mongoid_globalize/blob/458105154574950aed98119fd54ffaae4e1a55ee/lib/mongoid_globalize/adapter.rb#L48-L57 |
4,743 | Mik-die/mongoid_globalize | lib/mongoid_globalize/adapter.rb | Mongoid::Globalize.Adapter.fetch_attribute | def fetch_attribute(locale, name)
translation = record.translation_for(locale)
return translation && translation.send(name)
end | ruby | def fetch_attribute(locale, name)
translation = record.translation_for(locale)
return translation && translation.send(name)
end | [
"def",
"fetch_attribute",
"(",
"locale",
",",
"name",
")",
"translation",
"=",
"record",
".",
"translation_for",
"(",
"locale",
")",
"return",
"translation",
"&&",
"translation",
".",
"send",
"(",
"name",
")",
"end"
] | Returns persisted value of attribute for given locale or nil. | [
"Returns",
"persisted",
"value",
"of",
"attribute",
"for",
"given",
"locale",
"or",
"nil",
"."
] | 458105154574950aed98119fd54ffaae4e1a55ee | https://github.com/Mik-die/mongoid_globalize/blob/458105154574950aed98119fd54ffaae4e1a55ee/lib/mongoid_globalize/adapter.rb#L66-L69 |
4,744 | blinkist/grantinee | lib/grantinee/configuration.rb | Grantinee.Configuration.url= | def url=(url)
uri = URI.parse url
case uri.scheme
when /^mysql/
default_port = 3306
@engine = :mysql
when /^postgres/
default_port = 5432
@engine = :postgres
end
raise 'Invalid database url' unless uri.user && uri.host && uri.path
@username = uri.user
@password = uri.password
@hostname = uri.host
@port = uri.port || default_port
@database = (uri.path || '').split('/').last
end | ruby | def url=(url)
uri = URI.parse url
case uri.scheme
when /^mysql/
default_port = 3306
@engine = :mysql
when /^postgres/
default_port = 5432
@engine = :postgres
end
raise 'Invalid database url' unless uri.user && uri.host && uri.path
@username = uri.user
@password = uri.password
@hostname = uri.host
@port = uri.port || default_port
@database = (uri.path || '').split('/').last
end | [
"def",
"url",
"=",
"(",
"url",
")",
"uri",
"=",
"URI",
".",
"parse",
"url",
"case",
"uri",
".",
"scheme",
"when",
"/",
"/",
"default_port",
"=",
"3306",
"@engine",
"=",
":mysql",
"when",
"/",
"/",
"default_port",
"=",
"5432",
"@engine",
"=",
":postgres",
"end",
"raise",
"'Invalid database url'",
"unless",
"uri",
".",
"user",
"&&",
"uri",
".",
"host",
"&&",
"uri",
".",
"path",
"@username",
"=",
"uri",
".",
"user",
"@password",
"=",
"uri",
".",
"password",
"@hostname",
"=",
"uri",
".",
"host",
"@port",
"=",
"uri",
".",
"port",
"||",
"default_port",
"@database",
"=",
"(",
"uri",
".",
"path",
"||",
"''",
")",
".",
"split",
"(",
"'/'",
")",
".",
"last",
"end"
] | Handle url -> fields conversion | [
"Handle",
"url",
"-",
">",
"fields",
"conversion"
] | ba0c9a8ccaf377c2484c814d39359f01f7e56ded | https://github.com/blinkist/grantinee/blob/ba0c9a8ccaf377c2484c814d39359f01f7e56ded/lib/grantinee/configuration.rb#L32-L51 |
4,745 | quirkey/jim | lib/jim/bundler.rb | Jim.Bundler.bundle_dir= | def bundle_dir=(new_dir)
if new_dir
new_dir = Pathname.new(new_dir)
new_dir.mkpath
end
@bundle_dir = new_dir
end | ruby | def bundle_dir=(new_dir)
if new_dir
new_dir = Pathname.new(new_dir)
new_dir.mkpath
end
@bundle_dir = new_dir
end | [
"def",
"bundle_dir",
"=",
"(",
"new_dir",
")",
"if",
"new_dir",
"new_dir",
"=",
"Pathname",
".",
"new",
"(",
"new_dir",
")",
"new_dir",
".",
"mkpath",
"end",
"@bundle_dir",
"=",
"new_dir",
"end"
] | Set the `bundle_dir` where bundles will be written. If `bundle_dir` is set
to nil, all bundles will be written to STDOUT | [
"Set",
"the",
"bundle_dir",
"where",
"bundles",
"will",
"be",
"written",
".",
"If",
"bundle_dir",
"is",
"set",
"to",
"nil",
"all",
"bundles",
"will",
"be",
"written",
"to",
"STDOUT"
] | ad5dbf06527a1d0376055a02b58bb11b5a0ebc35 | https://github.com/quirkey/jim/blob/ad5dbf06527a1d0376055a02b58bb11b5a0ebc35/lib/jim/bundler.rb#L70-L76 |
4,746 | quirkey/jim | lib/jim/bundler.rb | Jim.Bundler.jimfile_to_json | def jimfile_to_json
h = {
"bundle_dir" => bundle_dir
}.merge(options)
h['bundles'] = {}
self.bundles.each do |bundle_name, requirements|
h['bundles'][bundle_name] = []
requirements.each do |name, version|
h['bundles'][bundle_name] << if version.nil? || version.strip == ''
name
else
[name, version]
end
end
end
Yajl::Encoder.encode(h, :pretty => true)
end | ruby | def jimfile_to_json
h = {
"bundle_dir" => bundle_dir
}.merge(options)
h['bundles'] = {}
self.bundles.each do |bundle_name, requirements|
h['bundles'][bundle_name] = []
requirements.each do |name, version|
h['bundles'][bundle_name] << if version.nil? || version.strip == ''
name
else
[name, version]
end
end
end
Yajl::Encoder.encode(h, :pretty => true)
end | [
"def",
"jimfile_to_json",
"h",
"=",
"{",
"\"bundle_dir\"",
"=>",
"bundle_dir",
"}",
".",
"merge",
"(",
"options",
")",
"h",
"[",
"'bundles'",
"]",
"=",
"{",
"}",
"self",
".",
"bundles",
".",
"each",
"do",
"|",
"bundle_name",
",",
"requirements",
"|",
"h",
"[",
"'bundles'",
"]",
"[",
"bundle_name",
"]",
"=",
"[",
"]",
"requirements",
".",
"each",
"do",
"|",
"name",
",",
"version",
"|",
"h",
"[",
"'bundles'",
"]",
"[",
"bundle_name",
"]",
"<<",
"if",
"version",
".",
"nil?",
"||",
"version",
".",
"strip",
"==",
"''",
"name",
"else",
"[",
"name",
",",
"version",
"]",
"end",
"end",
"end",
"Yajl",
"::",
"Encoder",
".",
"encode",
"(",
"h",
",",
":pretty",
"=>",
"true",
")",
"end"
] | Output the parse Jimfile requirements and options as a Jimfile-ready
JSON-encoded string | [
"Output",
"the",
"parse",
"Jimfile",
"requirements",
"and",
"options",
"as",
"a",
"Jimfile",
"-",
"ready",
"JSON",
"-",
"encoded",
"string"
] | ad5dbf06527a1d0376055a02b58bb11b5a0ebc35 | https://github.com/quirkey/jim/blob/ad5dbf06527a1d0376055a02b58bb11b5a0ebc35/lib/jim/bundler.rb#L80-L96 |
4,747 | quirkey/jim | lib/jim/bundler.rb | Jim.Bundler.resolve! | def resolve!
self.bundles.each do |bundle_name, requirements|
self.paths[bundle_name] = []
requirements.each do |name, version|
path = self.index.find(name, version)
if !path
raise(MissingFile,
"Could not find #{name} #{version} in any of these paths #{index.directories.join(':')}")
end
self.paths[bundle_name] << [path, name, version]
end
end
paths
end | ruby | def resolve!
self.bundles.each do |bundle_name, requirements|
self.paths[bundle_name] = []
requirements.each do |name, version|
path = self.index.find(name, version)
if !path
raise(MissingFile,
"Could not find #{name} #{version} in any of these paths #{index.directories.join(':')}")
end
self.paths[bundle_name] << [path, name, version]
end
end
paths
end | [
"def",
"resolve!",
"self",
".",
"bundles",
".",
"each",
"do",
"|",
"bundle_name",
",",
"requirements",
"|",
"self",
".",
"paths",
"[",
"bundle_name",
"]",
"=",
"[",
"]",
"requirements",
".",
"each",
"do",
"|",
"name",
",",
"version",
"|",
"path",
"=",
"self",
".",
"index",
".",
"find",
"(",
"name",
",",
"version",
")",
"if",
"!",
"path",
"raise",
"(",
"MissingFile",
",",
"\"Could not find #{name} #{version} in any of these paths #{index.directories.join(':')}\"",
")",
"end",
"self",
".",
"paths",
"[",
"bundle_name",
"]",
"<<",
"[",
"path",
",",
"name",
",",
"version",
"]",
"end",
"end",
"paths",
"end"
] | Resolve the requirements specified in the Jimfile for each bundle to `paths`
Raises MissingFile error | [
"Resolve",
"the",
"requirements",
"specified",
"in",
"the",
"Jimfile",
"for",
"each",
"bundle",
"to",
"paths",
"Raises",
"MissingFile",
"error"
] | ad5dbf06527a1d0376055a02b58bb11b5a0ebc35 | https://github.com/quirkey/jim/blob/ad5dbf06527a1d0376055a02b58bb11b5a0ebc35/lib/jim/bundler.rb#L100-L113 |
4,748 | samvera-labs/geo_works | app/models/concerns/geo_works/vector_file_behavior.rb | GeoWorks.VectorFileBehavior.vector_work | def vector_work
parents.select do |parent|
parent.class.included_modules.include?(::GeoWorks::VectorWorkBehavior)
end.to_a
end | ruby | def vector_work
parents.select do |parent|
parent.class.included_modules.include?(::GeoWorks::VectorWorkBehavior)
end.to_a
end | [
"def",
"vector_work",
"parents",
".",
"select",
"do",
"|",
"parent",
"|",
"parent",
".",
"class",
".",
"included_modules",
".",
"include?",
"(",
"::",
"GeoWorks",
"::",
"VectorWorkBehavior",
")",
"end",
".",
"to_a",
"end"
] | Retrieve the Vector Work of which this Object is a member
@return [GeoWorks::VectorWork] | [
"Retrieve",
"the",
"Vector",
"Work",
"of",
"which",
"this",
"Object",
"is",
"a",
"member"
] | df1eff35fd01469a623fafeb9d71b44fd6160ca8 | https://github.com/samvera-labs/geo_works/blob/df1eff35fd01469a623fafeb9d71b44fd6160ca8/app/models/concerns/geo_works/vector_file_behavior.rb#L8-L12 |
4,749 | usmu/usmu | lib/usmu/plugin.rb | Usmu.Plugin.invoke | def invoke(method, *args)
@log.debug("Invoking plugin API #{method}")
plugins.map do |p|
if p.respond_to? method
@log.debug("Sending message to #{p.class.name}")
p.public_send method, *args
else
nil
end
end.select {|i| i}
end | ruby | def invoke(method, *args)
@log.debug("Invoking plugin API #{method}")
plugins.map do |p|
if p.respond_to? method
@log.debug("Sending message to #{p.class.name}")
p.public_send method, *args
else
nil
end
end.select {|i| i}
end | [
"def",
"invoke",
"(",
"method",
",",
"*",
"args",
")",
"@log",
".",
"debug",
"(",
"\"Invoking plugin API #{method}\"",
")",
"plugins",
".",
"map",
"do",
"|",
"p",
"|",
"if",
"p",
".",
"respond_to?",
"method",
"@log",
".",
"debug",
"(",
"\"Sending message to #{p.class.name}\"",
")",
"p",
".",
"public_send",
"method",
",",
"args",
"else",
"nil",
"end",
"end",
".",
"select",
"{",
"|",
"i",
"|",
"i",
"}",
"end"
] | Call all plugins and collate any data returned.
nil can be returned explicitly to say this plugin has nothing to return.
@param [Symbol] method The name of the method to call. This should be namespaced somehow. For example, a plugin
called `usmu-s3` could use the method namespace `s3` and have a hook called `:s3_upload`
@param [Array] args The arguments to pass through to plugins. Can be empty.
@return [Array] An array of non-nil values returned from plugins | [
"Call",
"all",
"plugins",
"and",
"collate",
"any",
"data",
"returned",
"."
] | 037bfe0daa995477c29662931236d7a60ca29730 | https://github.com/usmu/usmu/blob/037bfe0daa995477c29662931236d7a60ca29730/lib/usmu/plugin.rb#L42-L52 |
4,750 | usmu/usmu | lib/usmu/plugin.rb | Usmu.Plugin.alter | def alter(method, value, *context)
@log.debug("Invoking plugin alter API #{method}")
plugins.each do |p|
if p.respond_to? "#{method}_alter"
@log.debug("Sending message to #{p.class.name}")
value = p.public_send "#{method}_alter", value, *context
end
end
value
end | ruby | def alter(method, value, *context)
@log.debug("Invoking plugin alter API #{method}")
plugins.each do |p|
if p.respond_to? "#{method}_alter"
@log.debug("Sending message to #{p.class.name}")
value = p.public_send "#{method}_alter", value, *context
end
end
value
end | [
"def",
"alter",
"(",
"method",
",",
"value",
",",
"*",
"context",
")",
"@log",
".",
"debug",
"(",
"\"Invoking plugin alter API #{method}\"",
")",
"plugins",
".",
"each",
"do",
"|",
"p",
"|",
"if",
"p",
".",
"respond_to?",
"\"#{method}_alter\"",
"@log",
".",
"debug",
"(",
"\"Sending message to #{p.class.name}\"",
")",
"value",
"=",
"p",
".",
"public_send",
"\"#{method}_alter\"",
",",
"value",
",",
"context",
"end",
"end",
"value",
"end"
] | Call all plugins and allow for altering a value.
The return value of each hook is passed into the next alter function, hence all implementations must always
return a value. If the hook doesn't wish to modify data this call then it should return the original value.
@param [Symbol] method The name of the method to call. This should be namespaced somehow. For example, a plugin
called `usmu-s3` could use the method namespace `s3` and have a hook called `:s3_upload`
@param [Object] value The value to modify.
@param [Array] context Optional extra parameters to provide.
@return [Object] The modified value. | [
"Call",
"all",
"plugins",
"and",
"allow",
"for",
"altering",
"a",
"value",
"."
] | 037bfe0daa995477c29662931236d7a60ca29730 | https://github.com/usmu/usmu/blob/037bfe0daa995477c29662931236d7a60ca29730/lib/usmu/plugin.rb#L64-L73 |
4,751 | usmu/usmu | lib/usmu/plugin.rb | Usmu.Plugin.load_gem | def load_gem(spec)
load_path = spec.name.gsub('-', '/')
require load_path
unless @loaded.include? load_path
@loaded << load_path
klass = path_to_class(load_path)
@log.debug("Loading plugin #{klass} from '#{load_path}'")
plugins.push plugin_get(klass)
end
nil
end | ruby | def load_gem(spec)
load_path = spec.name.gsub('-', '/')
require load_path
unless @loaded.include? load_path
@loaded << load_path
klass = path_to_class(load_path)
@log.debug("Loading plugin #{klass} from '#{load_path}'")
plugins.push plugin_get(klass)
end
nil
end | [
"def",
"load_gem",
"(",
"spec",
")",
"load_path",
"=",
"spec",
".",
"name",
".",
"gsub",
"(",
"'-'",
",",
"'/'",
")",
"require",
"load_path",
"unless",
"@loaded",
".",
"include?",
"load_path",
"@loaded",
"<<",
"load_path",
"klass",
"=",
"path_to_class",
"(",
"load_path",
")",
"@log",
".",
"debug",
"(",
"\"Loading plugin #{klass} from '#{load_path}'\"",
")",
"plugins",
".",
"push",
"plugin_get",
"(",
"klass",
")",
"end",
"nil",
"end"
] | Helper function to load a plugin from a gem specification
@param [Gem::Specification] spec | [
"Helper",
"function",
"to",
"load",
"a",
"plugin",
"from",
"a",
"gem",
"specification"
] | 037bfe0daa995477c29662931236d7a60ca29730 | https://github.com/usmu/usmu/blob/037bfe0daa995477c29662931236d7a60ca29730/lib/usmu/plugin.rb#L88-L99 |
4,752 | buren/honey_format | lib/honey_format/cli/benchmark_cli.rb | HoneyFormat.BenchmarkCLI.expected_runtime_seconds | def expected_runtime_seconds(report_count:)
runs = report_count * options[:lines_multipliers].length
warmup_time_seconds = runs * options[:benchmark_warmup]
bench_time_seconds = runs * options[:benchmark_time]
warmup_time_seconds + bench_time_seconds
end | ruby | def expected_runtime_seconds(report_count:)
runs = report_count * options[:lines_multipliers].length
warmup_time_seconds = runs * options[:benchmark_warmup]
bench_time_seconds = runs * options[:benchmark_time]
warmup_time_seconds + bench_time_seconds
end | [
"def",
"expected_runtime_seconds",
"(",
"report_count",
":",
")",
"runs",
"=",
"report_count",
"*",
"options",
"[",
":lines_multipliers",
"]",
".",
"length",
"warmup_time_seconds",
"=",
"runs",
"*",
"options",
"[",
":benchmark_warmup",
"]",
"bench_time_seconds",
"=",
"runs",
"*",
"options",
"[",
":benchmark_time",
"]",
"warmup_time_seconds",
"+",
"bench_time_seconds",
"end"
] | Instantiate the CLI
@param writer [CLIResultWriter] the result writer to use
Returns the expected runtime in seconds
@param report_count [Integer] number of reports in benchmark
@return [Integer] expected runtime in seconds | [
"Instantiate",
"the",
"CLI"
] | 5c54fba5f5ba044721afeef460a069af2018452c | https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/cli/benchmark_cli.rb#L30-L36 |
4,753 | buren/honey_format | lib/honey_format/cli/benchmark_cli.rb | HoneyFormat.BenchmarkCLI.fetch_default_benchmark_csv | def fetch_default_benchmark_csv
cache_path = CSV_TEST_DATA_CACHE_PATH
if File.exist?(cache_path)
writer.puts "Cache file found at #{cache_path}.", verbose: true
@used_input_path = cache_path
return File.read(cache_path)
end
writer.print 'Downloading test data file from GitHub..', verbose: true
require 'open-uri'
open(CSV_TEST_DATA_URL).read.tap do |csv| # rubocop:disable Security/Open
@used_input_path = CSV_TEST_DATA_URL
writer.puts 'done!', verbose: true
File.write(cache_path, csv)
writer.puts "Wrote cache file to #{cache_path}..", verbose: true
end
end | ruby | def fetch_default_benchmark_csv
cache_path = CSV_TEST_DATA_CACHE_PATH
if File.exist?(cache_path)
writer.puts "Cache file found at #{cache_path}.", verbose: true
@used_input_path = cache_path
return File.read(cache_path)
end
writer.print 'Downloading test data file from GitHub..', verbose: true
require 'open-uri'
open(CSV_TEST_DATA_URL).read.tap do |csv| # rubocop:disable Security/Open
@used_input_path = CSV_TEST_DATA_URL
writer.puts 'done!', verbose: true
File.write(cache_path, csv)
writer.puts "Wrote cache file to #{cache_path}..", verbose: true
end
end | [
"def",
"fetch_default_benchmark_csv",
"cache_path",
"=",
"CSV_TEST_DATA_CACHE_PATH",
"if",
"File",
".",
"exist?",
"(",
"cache_path",
")",
"writer",
".",
"puts",
"\"Cache file found at #{cache_path}.\"",
",",
"verbose",
":",
"true",
"@used_input_path",
"=",
"cache_path",
"return",
"File",
".",
"read",
"(",
"cache_path",
")",
"end",
"writer",
".",
"print",
"'Downloading test data file from GitHub..'",
",",
"verbose",
":",
"true",
"require",
"'open-uri'",
"open",
"(",
"CSV_TEST_DATA_URL",
")",
".",
"read",
".",
"tap",
"do",
"|",
"csv",
"|",
"# rubocop:disable Security/Open",
"@used_input_path",
"=",
"CSV_TEST_DATA_URL",
"writer",
".",
"puts",
"'done!'",
",",
"verbose",
":",
"true",
"File",
".",
"write",
"(",
"cache_path",
",",
"csv",
")",
"writer",
".",
"puts",
"\"Wrote cache file to #{cache_path}..\"",
",",
"verbose",
":",
"true",
"end",
"end"
] | Download or fetch the default benchmark file from cache
@return [String] CSV file as a string | [
"Download",
"or",
"fetch",
"the",
"default",
"benchmark",
"file",
"from",
"cache"
] | 5c54fba5f5ba044721afeef460a069af2018452c | https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/cli/benchmark_cli.rb#L46-L63 |
4,754 | culturecode/stagehand | lib/stagehand/auditor.rb | Stagehand.Auditor.incomplete_end_operations | def incomplete_end_operations
last_entry_per_session = Staging::CommitEntry.group(:session).select('MAX(id) AS id')
return Staging::CommitEntry.uncontained.end_operations.where.not(:id => last_entry_per_session)
end | ruby | def incomplete_end_operations
last_entry_per_session = Staging::CommitEntry.group(:session).select('MAX(id) AS id')
return Staging::CommitEntry.uncontained.end_operations.where.not(:id => last_entry_per_session)
end | [
"def",
"incomplete_end_operations",
"last_entry_per_session",
"=",
"Staging",
"::",
"CommitEntry",
".",
"group",
"(",
":session",
")",
".",
"select",
"(",
"'MAX(id) AS id'",
")",
"return",
"Staging",
"::",
"CommitEntry",
".",
"uncontained",
".",
"end_operations",
".",
"where",
".",
"not",
"(",
":id",
"=>",
"last_entry_per_session",
")",
"end"
] | Incomplete End Operation that are not the last entry in their session | [
"Incomplete",
"End",
"Operation",
"that",
"are",
"not",
"the",
"last",
"entry",
"in",
"their",
"session"
] | af627f1948b9dfc39ec13aefe77a47c21b4456a5 | https://github.com/culturecode/stagehand/blob/af627f1948b9dfc39ec13aefe77a47c21b4456a5/lib/stagehand/auditor.rb#L92-L95 |
4,755 | culturecode/stagehand | lib/stagehand/auditor.rb | Stagehand.Auditor.incomplete_start_operations | def incomplete_start_operations
last_start_entry_per_session = Staging::CommitEntry.start_operations.group(:session).select('MAX(id) AS id')
return Staging::CommitEntry.uncontained.start_operations.where.not(:id => last_start_entry_per_session)
end | ruby | def incomplete_start_operations
last_start_entry_per_session = Staging::CommitEntry.start_operations.group(:session).select('MAX(id) AS id')
return Staging::CommitEntry.uncontained.start_operations.where.not(:id => last_start_entry_per_session)
end | [
"def",
"incomplete_start_operations",
"last_start_entry_per_session",
"=",
"Staging",
"::",
"CommitEntry",
".",
"start_operations",
".",
"group",
"(",
":session",
")",
".",
"select",
"(",
"'MAX(id) AS id'",
")",
"return",
"Staging",
"::",
"CommitEntry",
".",
"uncontained",
".",
"start_operations",
".",
"where",
".",
"not",
"(",
":id",
"=>",
"last_start_entry_per_session",
")",
"end"
] | Incomplete Start on the same session as a subsequent start operation | [
"Incomplete",
"Start",
"on",
"the",
"same",
"session",
"as",
"a",
"subsequent",
"start",
"operation"
] | af627f1948b9dfc39ec13aefe77a47c21b4456a5 | https://github.com/culturecode/stagehand/blob/af627f1948b9dfc39ec13aefe77a47c21b4456a5/lib/stagehand/auditor.rb#L98-L101 |
4,756 | samvera-labs/geo_works | app/models/concerns/geo_works/metadata_extraction_helper.rb | GeoWorks.MetadataExtractionHelper.populate_metadata | def populate_metadata(id)
extract_metadata(id).each do |k, v|
send("#{k}=".to_sym, v) # set each property
end
end | ruby | def populate_metadata(id)
extract_metadata(id).each do |k, v|
send("#{k}=".to_sym, v) # set each property
end
end | [
"def",
"populate_metadata",
"(",
"id",
")",
"extract_metadata",
"(",
"id",
")",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"send",
"(",
"\"#{k}=\"",
".",
"to_sym",
",",
"v",
")",
"# set each property",
"end",
"end"
] | Sets properties from the constitutent external metadata file | [
"Sets",
"properties",
"from",
"the",
"constitutent",
"external",
"metadata",
"file"
] | df1eff35fd01469a623fafeb9d71b44fd6160ca8 | https://github.com/samvera-labs/geo_works/blob/df1eff35fd01469a623fafeb9d71b44fd6160ca8/app/models/concerns/geo_works/metadata_extraction_helper.rb#L12-L16 |
4,757 | usmu/usmu | lib/usmu/site_generator.rb | Usmu.SiteGenerator.generate_page | def generate_page(page)
output_filename = page.output_filename
@log.success("creating #{output_filename}...")
@log.debug("Rendering #{output_filename} from #{page.name}")
file = File.join(@configuration.destination_path, output_filename)
directory = File.dirname(file)
unless File.directory?(directory)
FileUtils.mkdir_p(directory)
end
File.write file, page.render
FileUtils.touch file, mtime: page.mtime
nil
end | ruby | def generate_page(page)
output_filename = page.output_filename
@log.success("creating #{output_filename}...")
@log.debug("Rendering #{output_filename} from #{page.name}")
file = File.join(@configuration.destination_path, output_filename)
directory = File.dirname(file)
unless File.directory?(directory)
FileUtils.mkdir_p(directory)
end
File.write file, page.render
FileUtils.touch file, mtime: page.mtime
nil
end | [
"def",
"generate_page",
"(",
"page",
")",
"output_filename",
"=",
"page",
".",
"output_filename",
"@log",
".",
"success",
"(",
"\"creating #{output_filename}...\"",
")",
"@log",
".",
"debug",
"(",
"\"Rendering #{output_filename} from #{page.name}\"",
")",
"file",
"=",
"File",
".",
"join",
"(",
"@configuration",
".",
"destination_path",
",",
"output_filename",
")",
"directory",
"=",
"File",
".",
"dirname",
"(",
"file",
")",
"unless",
"File",
".",
"directory?",
"(",
"directory",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"directory",
")",
"end",
"File",
".",
"write",
"file",
",",
"page",
".",
"render",
"FileUtils",
".",
"touch",
"file",
",",
"mtime",
":",
"page",
".",
"mtime",
"nil",
"end"
] | Helper function to generate a page
@param [Usmu::Template::Page] page | [
"Helper",
"function",
"to",
"generate",
"a",
"page"
] | 037bfe0daa995477c29662931236d7a60ca29730 | https://github.com/usmu/usmu/blob/037bfe0daa995477c29662931236d7a60ca29730/lib/usmu/site_generator.rb#L76-L91 |
4,758 | printercu/gemfile_locker | lib/gemfile_locker/gem_entry.rb | GemfileLocker.GemEntry.replace_string_node | def replace_string_node(target, value)
quote = target.loc.begin.source
rewriter.replace(target.loc.expression, "#{quote}#{value}#{quote}")
end | ruby | def replace_string_node(target, value)
quote = target.loc.begin.source
rewriter.replace(target.loc.expression, "#{quote}#{value}#{quote}")
end | [
"def",
"replace_string_node",
"(",
"target",
",",
"value",
")",
"quote",
"=",
"target",
".",
"loc",
".",
"begin",
".",
"source",
"rewriter",
".",
"replace",
"(",
"target",
".",
"loc",
".",
"expression",
",",
"\"#{quote}#{value}#{quote}\"",
")",
"end"
] | Change content of string, keeping quoting style. | [
"Change",
"content",
"of",
"string",
"keeping",
"quoting",
"style",
"."
] | 886852a3d000eade8511efee91cac6a8cc927cdf | https://github.com/printercu/gemfile_locker/blob/886852a3d000eade8511efee91cac6a8cc927cdf/lib/gemfile_locker/gem_entry.rb#L37-L40 |
4,759 | printercu/gemfile_locker | lib/gemfile_locker/gem_entry.rb | GemfileLocker.GemEntry.remove_node_with_comma | def remove_node_with_comma(target)
expression = target.loc.expression
comma_pos = expression.source_buffer.source.rindex(',', expression.begin_pos)
rewriter.remove(expression.with(begin_pos: comma_pos))
end | ruby | def remove_node_with_comma(target)
expression = target.loc.expression
comma_pos = expression.source_buffer.source.rindex(',', expression.begin_pos)
rewriter.remove(expression.with(begin_pos: comma_pos))
end | [
"def",
"remove_node_with_comma",
"(",
"target",
")",
"expression",
"=",
"target",
".",
"loc",
".",
"expression",
"comma_pos",
"=",
"expression",
".",
"source_buffer",
".",
"source",
".",
"rindex",
"(",
"','",
",",
"expression",
".",
"begin_pos",
")",
"rewriter",
".",
"remove",
"(",
"expression",
".",
"with",
"(",
"begin_pos",
":",
"comma_pos",
")",
")",
"end"
] | Remove node with preceding comma. | [
"Remove",
"node",
"with",
"preceding",
"comma",
"."
] | 886852a3d000eade8511efee91cac6a8cc927cdf | https://github.com/printercu/gemfile_locker/blob/886852a3d000eade8511efee91cac6a8cc927cdf/lib/gemfile_locker/gem_entry.rb#L43-L47 |
4,760 | phatworx/rails_paginate | lib/rails_paginate/helpers/action_view.rb | RailsPaginate::Helpers.ActionView.paginate | def paginate(*args)
options = args.extract_options!
raise ArgumentError, "first argument must be a RailsPaginate::Collection" unless args.first.is_a? RailsPaginate::Collection
collection = args.first
# p @controller
# p url_for(:action => :index, :controller => :dummy)
# renderer
renderer = options[:renderer] || RailsPaginate.default_renderer
pager = options[:pager] || RailsPaginate.default_pager
attributes = {}
attributes[:class] = "pagination #{options[:class]}".strip
attributes[:id] = options[:id] unless options[:id].blank?
# load classes
renderer = RailsPaginate.renderer(renderer)
pager = RailsPaginate.pager(pager)
content_tag :div, attributes do
renderer.new(self, collection, pager.new(collection), options).render
end
end | ruby | def paginate(*args)
options = args.extract_options!
raise ArgumentError, "first argument must be a RailsPaginate::Collection" unless args.first.is_a? RailsPaginate::Collection
collection = args.first
# p @controller
# p url_for(:action => :index, :controller => :dummy)
# renderer
renderer = options[:renderer] || RailsPaginate.default_renderer
pager = options[:pager] || RailsPaginate.default_pager
attributes = {}
attributes[:class] = "pagination #{options[:class]}".strip
attributes[:id] = options[:id] unless options[:id].blank?
# load classes
renderer = RailsPaginate.renderer(renderer)
pager = RailsPaginate.pager(pager)
content_tag :div, attributes do
renderer.new(self, collection, pager.new(collection), options).render
end
end | [
"def",
"paginate",
"(",
"*",
"args",
")",
"options",
"=",
"args",
".",
"extract_options!",
"raise",
"ArgumentError",
",",
"\"first argument must be a RailsPaginate::Collection\"",
"unless",
"args",
".",
"first",
".",
"is_a?",
"RailsPaginate",
"::",
"Collection",
"collection",
"=",
"args",
".",
"first",
"# p @controller",
"# p url_for(:action => :index, :controller => :dummy)",
"# renderer",
"renderer",
"=",
"options",
"[",
":renderer",
"]",
"||",
"RailsPaginate",
".",
"default_renderer",
"pager",
"=",
"options",
"[",
":pager",
"]",
"||",
"RailsPaginate",
".",
"default_pager",
"attributes",
"=",
"{",
"}",
"attributes",
"[",
":class",
"]",
"=",
"\"pagination #{options[:class]}\"",
".",
"strip",
"attributes",
"[",
":id",
"]",
"=",
"options",
"[",
":id",
"]",
"unless",
"options",
"[",
":id",
"]",
".",
"blank?",
"# load classes",
"renderer",
"=",
"RailsPaginate",
".",
"renderer",
"(",
"renderer",
")",
"pager",
"=",
"RailsPaginate",
".",
"pager",
"(",
"pager",
")",
"content_tag",
":div",
",",
"attributes",
"do",
"renderer",
".",
"new",
"(",
"self",
",",
"collection",
",",
"pager",
".",
"new",
"(",
"collection",
")",
",",
"options",
")",
".",
"render",
"end",
"end"
] | view_helper for paginate
== Options
:id
:class | [
"view_helper",
"for",
"paginate"
] | ae8cbc12030853b236dc2cbf6ede8700fb835771 | https://github.com/phatworx/rails_paginate/blob/ae8cbc12030853b236dc2cbf6ede8700fb835771/lib/rails_paginate/helpers/action_view.rb#L9-L33 |
4,761 | topfunky/google-checkout | lib/google-checkout/notification.rb | GoogleCheckout.Notification.acknowledgment_xml | def acknowledgment_xml
xml = Builder::XmlMarkup.new
xml.instruct!
@xml = xml.tag!('notification-acknowledgment', {
:xmlns => "http://checkout.google.com/schema/2",
'serial-number' => serial_number
})
@xml
end | ruby | def acknowledgment_xml
xml = Builder::XmlMarkup.new
xml.instruct!
@xml = xml.tag!('notification-acknowledgment', {
:xmlns => "http://checkout.google.com/schema/2",
'serial-number' => serial_number
})
@xml
end | [
"def",
"acknowledgment_xml",
"xml",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"xml",
".",
"instruct!",
"@xml",
"=",
"xml",
".",
"tag!",
"(",
"'notification-acknowledgment'",
",",
"{",
":xmlns",
"=>",
"\"http://checkout.google.com/schema/2\"",
",",
"'serial-number'",
"=>",
"serial_number",
"}",
")",
"@xml",
"end"
] | Returns an XML string that can be sent back to Google to
communicate successful receipt of the notification. | [
"Returns",
"an",
"XML",
"string",
"that",
"can",
"be",
"sent",
"back",
"to",
"Google",
"to",
"communicate",
"successful",
"receipt",
"of",
"the",
"notification",
"."
] | 66089cef799bd40f3ba4370f01f1b8dc10f92115 | https://github.com/topfunky/google-checkout/blob/66089cef799bd40f3ba4370f01f1b8dc10f92115/lib/google-checkout/notification.rb#L103-L111 |
4,762 | topfunky/google-checkout | lib/google-checkout/notification.rb | GoogleCheckout.Notification.method_missing | def method_missing(method_name, *args)
element_name = method_name.to_s.gsub(/_/, '-')
if element = (@doc.at element_name)
if element.respond_to?(:inner_html)
return element.inner_html
end
end
super
end | ruby | def method_missing(method_name, *args)
element_name = method_name.to_s.gsub(/_/, '-')
if element = (@doc.at element_name)
if element.respond_to?(:inner_html)
return element.inner_html
end
end
super
end | [
"def",
"method_missing",
"(",
"method_name",
",",
"*",
"args",
")",
"element_name",
"=",
"method_name",
".",
"to_s",
".",
"gsub",
"(",
"/",
"/",
",",
"'-'",
")",
"if",
"element",
"=",
"(",
"@doc",
".",
"at",
"element_name",
")",
"if",
"element",
".",
"respond_to?",
"(",
":inner_html",
")",
"return",
"element",
".",
"inner_html",
"end",
"end",
"super",
"end"
] | Take requests for an XML element and returns its value.
notification.google_order_number
=> Returns value of '<google-order-number>'
Because of how Nokogiri#at works, it will even dig into subtags
and return the value of the first matching tag. For example,
there is an +email+ field in +buyer-shipping-address+ and also
in +buyer-billing-address+, but only the first will be returned.
If you want to get at a value explicitly, use +notification.doc+
and search the Nokogiri document manually. | [
"Take",
"requests",
"for",
"an",
"XML",
"element",
"and",
"returns",
"its",
"value",
"."
] | 66089cef799bd40f3ba4370f01f1b8dc10f92115 | https://github.com/topfunky/google-checkout/blob/66089cef799bd40f3ba4370f01f1b8dc10f92115/lib/google-checkout/notification.rb#L134-L142 |
4,763 | buren/honey_format | lib/honey_format/matrix/matrix.rb | HoneyFormat.Matrix.to_csv | def to_csv(columns: nil, &block)
columns = columns&.map(&:to_sym)
@header.to_csv(columns: columns) + @rows.to_csv(columns: columns, &block)
end | ruby | def to_csv(columns: nil, &block)
columns = columns&.map(&:to_sym)
@header.to_csv(columns: columns) + @rows.to_csv(columns: columns, &block)
end | [
"def",
"to_csv",
"(",
"columns",
":",
"nil",
",",
"&",
"block",
")",
"columns",
"=",
"columns",
"&.",
"map",
"(",
":to_sym",
")",
"@header",
".",
"to_csv",
"(",
"columns",
":",
"columns",
")",
"+",
"@rows",
".",
"to_csv",
"(",
"columns",
":",
"columns",
",",
"block",
")",
"end"
] | Convert matrix to CSV-string.
@param columns [Array<Symbol>, Set<Symbol>, NilClass]
the columns to output, nil means all columns (default: nil)
@yield [row]
The given block will be passed for every row - return truthy if you want the
row to be included in the output
@yieldparam [Row] row
@return [String] CSV-string representation.
@example with selected columns
matrix.to_csv(columns: [:id, :country])
@example with selected rows
matrix.to_csv { |row| row.country == 'Sweden' }
@example with both selected columns and rows
matrix.to_csv(columns: [:id, :country]) { |row| row.country == 'Sweden' } | [
"Convert",
"matrix",
"to",
"CSV",
"-",
"string",
"."
] | 5c54fba5f5ba044721afeef460a069af2018452c | https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/matrix/matrix.rb#L99-L102 |
4,764 | dropofwill/rtasklib | lib/rtasklib/controller.rb | Rtasklib.Controller.some | def some ids: nil, tags: nil, dom: nil, active: true
some = []
f = Helpers.filter(ids: ids, tags: tags, dom: dom)
a = Helpers.pending_or_waiting(active)
Execute.task_popen3(*@override_a, f, a, "export") do |i, o, e, t|
some = MultiJson.load(o.read).map do |x|
Rtasklib::Models::TaskModel.new(x)
end
end
return some
end | ruby | def some ids: nil, tags: nil, dom: nil, active: true
some = []
f = Helpers.filter(ids: ids, tags: tags, dom: dom)
a = Helpers.pending_or_waiting(active)
Execute.task_popen3(*@override_a, f, a, "export") do |i, o, e, t|
some = MultiJson.load(o.read).map do |x|
Rtasklib::Models::TaskModel.new(x)
end
end
return some
end | [
"def",
"some",
"ids",
":",
"nil",
",",
"tags",
":",
"nil",
",",
"dom",
":",
"nil",
",",
"active",
":",
"true",
"some",
"=",
"[",
"]",
"f",
"=",
"Helpers",
".",
"filter",
"(",
"ids",
":",
"ids",
",",
"tags",
":",
"tags",
",",
"dom",
":",
"dom",
")",
"a",
"=",
"Helpers",
".",
"pending_or_waiting",
"(",
"active",
")",
"Execute",
".",
"task_popen3",
"(",
"@override_a",
",",
"f",
",",
"a",
",",
"\"export\"",
")",
"do",
"|",
"i",
",",
"o",
",",
"e",
",",
"t",
"|",
"some",
"=",
"MultiJson",
".",
"load",
"(",
"o",
".",
"read",
")",
".",
"map",
"do",
"|",
"x",
"|",
"Rtasklib",
"::",
"Models",
"::",
"TaskModel",
".",
"new",
"(",
"x",
")",
"end",
"end",
"return",
"some",
"end"
] | Retrieves the current task list filtered by id, tag, or a dom query
@example filter by an array of ids
tw.some(ids: [1..2, 5])
@example filter by tags
tw.some(tags: ["+school", "or", "-work"]
# You can also pass in a TW style string if you prefer
tw.some(tags: "+school or -work"]
@example filter by a dom query
require "date"
today = DateTime.now
# note that queries with dots need to be Strings, as they would be
# invalid Symbols
tw.some(dom: {project: "Work", "due.before" => today})
# You can also pass in a TW style string if you prefer
tw.some(dom: "project:Work due.before:#{today}")
@param ids [Array<Range, Fixnum, String>, String, Range, Fixnum]
@param tags [Array<String>, String]
@param dom [Array<String>, String]
@param active [Boolean] return only pending & waiting tasks
@return [Array<Models::TaskModel>]
@api public | [
"Retrieves",
"the",
"current",
"task",
"list",
"filtered",
"by",
"id",
"tag",
"or",
"a",
"dom",
"query"
] | c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c | https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L104-L114 |
4,765 | dropofwill/rtasklib | lib/rtasklib/controller.rb | Rtasklib.Controller.get_rc | def get_rc
res = []
Execute.task_popen3(*@override_a, "_show") do |i, o, e, t|
res = o.read.each_line.map { |l| l.chomp }
end
Taskrc.new(res, :array)
end | ruby | def get_rc
res = []
Execute.task_popen3(*@override_a, "_show") do |i, o, e, t|
res = o.read.each_line.map { |l| l.chomp }
end
Taskrc.new(res, :array)
end | [
"def",
"get_rc",
"res",
"=",
"[",
"]",
"Execute",
".",
"task_popen3",
"(",
"@override_a",
",",
"\"_show\"",
")",
"do",
"|",
"i",
",",
"o",
",",
"e",
",",
"t",
"|",
"res",
"=",
"o",
".",
"read",
".",
"each_line",
".",
"map",
"{",
"|",
"l",
"|",
"l",
".",
"chomp",
"}",
"end",
"Taskrc",
".",
"new",
"(",
"res",
",",
":array",
")",
"end"
] | Calls `task _show` with initial overrides returns a Taskrc object of the
result
@return [Rtasklib::Taskrc]
@api public | [
"Calls",
"task",
"_show",
"with",
"initial",
"overrides",
"returns",
"a",
"Taskrc",
"object",
"of",
"the",
"result"
] | c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c | https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L139-L145 |
4,766 | dropofwill/rtasklib | lib/rtasklib/controller.rb | Rtasklib.Controller.get_version | def get_version
version = nil
Execute.task_popen3("_version") do |i, o, e, t|
version = Helpers.to_gem_version(o.read.chomp)
end
version
end | ruby | def get_version
version = nil
Execute.task_popen3("_version") do |i, o, e, t|
version = Helpers.to_gem_version(o.read.chomp)
end
version
end | [
"def",
"get_version",
"version",
"=",
"nil",
"Execute",
".",
"task_popen3",
"(",
"\"_version\"",
")",
"do",
"|",
"i",
",",
"o",
",",
"e",
",",
"t",
"|",
"version",
"=",
"Helpers",
".",
"to_gem_version",
"(",
"o",
".",
"read",
".",
"chomp",
")",
"end",
"version",
"end"
] | Calls `task _version` and returns the result
@return [String]
@api public | [
"Calls",
"task",
"_version",
"and",
"returns",
"the",
"result"
] | c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c | https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L151-L157 |
4,767 | dropofwill/rtasklib | lib/rtasklib/controller.rb | Rtasklib.Controller.get_udas | def get_udas
udas = {}
taskrc.config.attributes
.select { |attr, val| Helpers.uda_attr? attr }
.sort
.chunk { |attr, val| Helpers.arbitrary_attr attr }
.each do |attr, arr|
uda = arr.map do |pair|
[Helpers.deep_attr(pair[0]), pair[1]]
end
udas[attr.to_sym] = Hash[uda]
end
return udas
end | ruby | def get_udas
udas = {}
taskrc.config.attributes
.select { |attr, val| Helpers.uda_attr? attr }
.sort
.chunk { |attr, val| Helpers.arbitrary_attr attr }
.each do |attr, arr|
uda = arr.map do |pair|
[Helpers.deep_attr(pair[0]), pair[1]]
end
udas[attr.to_sym] = Hash[uda]
end
return udas
end | [
"def",
"get_udas",
"udas",
"=",
"{",
"}",
"taskrc",
".",
"config",
".",
"attributes",
".",
"select",
"{",
"|",
"attr",
",",
"val",
"|",
"Helpers",
".",
"uda_attr?",
"attr",
"}",
".",
"sort",
".",
"chunk",
"{",
"|",
"attr",
",",
"val",
"|",
"Helpers",
".",
"arbitrary_attr",
"attr",
"}",
".",
"each",
"do",
"|",
"attr",
",",
"arr",
"|",
"uda",
"=",
"arr",
".",
"map",
"do",
"|",
"pair",
"|",
"[",
"Helpers",
".",
"deep_attr",
"(",
"pair",
"[",
"0",
"]",
")",
",",
"pair",
"[",
"1",
"]",
"]",
"end",
"udas",
"[",
"attr",
".",
"to_sym",
"]",
"=",
"Hash",
"[",
"uda",
"]",
"end",
"return",
"udas",
"end"
] | Retrieves a hash of hashes with info about the UDAs currently available
@return [Hash{Symbol=>Hash}]
@api public | [
"Retrieves",
"a",
"hash",
"of",
"hashes",
"with",
"info",
"about",
"the",
"UDAs",
"currently",
"available"
] | c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c | https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L292-L305 |
4,768 | dropofwill/rtasklib | lib/rtasklib/controller.rb | Rtasklib.Controller.update_config! | def update_config! attr, val
Execute.task_popen3(*override_a, "config #{attr} #{val}") do |i, o, e, t|
return t.value
end
end | ruby | def update_config! attr, val
Execute.task_popen3(*override_a, "config #{attr} #{val}") do |i, o, e, t|
return t.value
end
end | [
"def",
"update_config!",
"attr",
",",
"val",
"Execute",
".",
"task_popen3",
"(",
"override_a",
",",
"\"config #{attr} #{val}\"",
")",
"do",
"|",
"i",
",",
"o",
",",
"e",
",",
"t",
"|",
"return",
"t",
".",
"value",
"end",
"end"
] | Update a configuration variable in the .taskrc
@param attr [String]
@param val [String]
@return [Process::Status] the exit status of the thread
@api public | [
"Update",
"a",
"configuration",
"variable",
"in",
"the",
".",
"taskrc"
] | c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c | https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L313-L317 |
4,769 | dropofwill/rtasklib | lib/rtasklib/controller.rb | Rtasklib.Controller.add_udas_to_model! | def add_udas_to_model! uda_hash, type=nil, model=Models::TaskModel
uda_hash.each do |attr, val|
val.each do |k, v|
type = Helpers.determine_type(v) if type.nil?
model.attribute attr, type
end
end
end | ruby | def add_udas_to_model! uda_hash, type=nil, model=Models::TaskModel
uda_hash.each do |attr, val|
val.each do |k, v|
type = Helpers.determine_type(v) if type.nil?
model.attribute attr, type
end
end
end | [
"def",
"add_udas_to_model!",
"uda_hash",
",",
"type",
"=",
"nil",
",",
"model",
"=",
"Models",
"::",
"TaskModel",
"uda_hash",
".",
"each",
"do",
"|",
"attr",
",",
"val",
"|",
"val",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"type",
"=",
"Helpers",
".",
"determine_type",
"(",
"v",
")",
"if",
"type",
".",
"nil?",
"model",
".",
"attribute",
"attr",
",",
"type",
"end",
"end",
"end"
] | Add new found udas to our internal TaskModel
@param uda_hash [Hash{Symbol=>Hash}]
@param type [Class, nil]
@param model [Models::TaskModel, Class]
@api protected | [
"Add",
"new",
"found",
"udas",
"to",
"our",
"internal",
"TaskModel"
] | c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c | https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L325-L332 |
4,770 | dropofwill/rtasklib | lib/rtasklib/controller.rb | Rtasklib.Controller.get_uda_names | def get_uda_names
Execute.task_popen3(*@override_a, "_udas") do |i, o, e, t|
return o.read.each_line.map { |l| l.chomp }
end
end | ruby | def get_uda_names
Execute.task_popen3(*@override_a, "_udas") do |i, o, e, t|
return o.read.each_line.map { |l| l.chomp }
end
end | [
"def",
"get_uda_names",
"Execute",
".",
"task_popen3",
"(",
"@override_a",
",",
"\"_udas\"",
")",
"do",
"|",
"i",
",",
"o",
",",
"e",
",",
"t",
"|",
"return",
"o",
".",
"read",
".",
"each_line",
".",
"map",
"{",
"|",
"l",
"|",
"l",
".",
"chomp",
"}",
"end",
"end"
] | Retrieve an array of the uda names
@return [Array<String>]
@api public | [
"Retrieve",
"an",
"array",
"of",
"the",
"uda",
"names"
] | c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c | https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L339-L343 |
4,771 | dropofwill/rtasklib | lib/rtasklib/controller.rb | Rtasklib.Controller.sync! | def sync!
Execute.task_popen3(*override_a, "sync") do |i, o, e, t|
return t.value
end
end | ruby | def sync!
Execute.task_popen3(*override_a, "sync") do |i, o, e, t|
return t.value
end
end | [
"def",
"sync!",
"Execute",
".",
"task_popen3",
"(",
"override_a",
",",
"\"sync\"",
")",
"do",
"|",
"i",
",",
"o",
",",
"e",
",",
"t",
"|",
"return",
"t",
".",
"value",
"end",
"end"
] | Sync the local TaskWarrior database changes to the remote databases.
Remotes need to be configured in the .taskrc.
@example
# make some local changes with add!, modify!, or the like
tw.sync!
@return [Process::Status] the exit status of the thread
@api public | [
"Sync",
"the",
"local",
"TaskWarrior",
"database",
"changes",
"to",
"the",
"remote",
"databases",
".",
"Remotes",
"need",
"to",
"be",
"configured",
"in",
"the",
".",
"taskrc",
"."
] | c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c | https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L388-L392 |
4,772 | isabanin/mercurial-ruby | lib/mercurial-ruby/manifest.rb | Mercurial.Manifest.contents | def contents(revision=nil, cmd_options={})
revision ||= 'tip'
hg(manifest_cmd(revision), cmd_options).tap do |res|
if RUBY_VERSION >= '1.9.1'
res.force_encoding('utf-8')
end
end
end | ruby | def contents(revision=nil, cmd_options={})
revision ||= 'tip'
hg(manifest_cmd(revision), cmd_options).tap do |res|
if RUBY_VERSION >= '1.9.1'
res.force_encoding('utf-8')
end
end
end | [
"def",
"contents",
"(",
"revision",
"=",
"nil",
",",
"cmd_options",
"=",
"{",
"}",
")",
"revision",
"||=",
"'tip'",
"hg",
"(",
"manifest_cmd",
"(",
"revision",
")",
",",
"cmd_options",
")",
".",
"tap",
"do",
"|",
"res",
"|",
"if",
"RUBY_VERSION",
">=",
"'1.9.1'",
"res",
".",
"force_encoding",
"(",
"'utf-8'",
")",
"end",
"end",
"end"
] | Returns contents of the manifest as a String at a specified revision.
Latest version of the manifest is used if +revision+ is ommitted.
=== Example:
repository.manifest.contents | [
"Returns",
"contents",
"of",
"the",
"manifest",
"as",
"a",
"String",
"at",
"a",
"specified",
"revision",
".",
"Latest",
"version",
"of",
"the",
"manifest",
"is",
"used",
"if",
"+",
"revision",
"+",
"is",
"ommitted",
"."
] | d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a | https://github.com/isabanin/mercurial-ruby/blob/d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a/lib/mercurial-ruby/manifest.rb#L27-L34 |
4,773 | imanel/odt2html | lib/odt2html/analyze_styles.rb | ODT2HTML.AnalyzeStyles.process_normal_style_attr | def process_normal_style_attr( selector, property, value )
if (@style_info[selector] == nil) then
@style_info[selector] = DeclarationBlock.new( )
@style_info[selector].push Declaration.new(property, value)
else
found = @style_info[selector].find { |obj|
obj.property == property }
if (found != nil) then
found.value = value
else
@style_info[selector].push Declaration.new(property, value)
end
end
end | ruby | def process_normal_style_attr( selector, property, value )
if (@style_info[selector] == nil) then
@style_info[selector] = DeclarationBlock.new( )
@style_info[selector].push Declaration.new(property, value)
else
found = @style_info[selector].find { |obj|
obj.property == property }
if (found != nil) then
found.value = value
else
@style_info[selector].push Declaration.new(property, value)
end
end
end | [
"def",
"process_normal_style_attr",
"(",
"selector",
",",
"property",
",",
"value",
")",
"if",
"(",
"@style_info",
"[",
"selector",
"]",
"==",
"nil",
")",
"then",
"@style_info",
"[",
"selector",
"]",
"=",
"DeclarationBlock",
".",
"new",
"(",
")",
"@style_info",
"[",
"selector",
"]",
".",
"push",
"Declaration",
".",
"new",
"(",
"property",
",",
"value",
")",
"else",
"found",
"=",
"@style_info",
"[",
"selector",
"]",
".",
"find",
"{",
"|",
"obj",
"|",
"obj",
".",
"property",
"==",
"property",
"}",
"if",
"(",
"found",
"!=",
"nil",
")",
"then",
"found",
".",
"value",
"=",
"value",
"else",
"@style_info",
"[",
"selector",
"]",
".",
"push",
"Declaration",
".",
"new",
"(",
"property",
",",
"value",
")",
"end",
"end",
"end"
] | If the style hasn't been registered yet, create a new array
with the style property and value.
If the style has been registered, and the property name is a duplicate,
supplant the old property value with the new one.
If the style has been registered, and the property is a new one,
push the property and value onto the array. | [
"If",
"the",
"style",
"hasn",
"t",
"been",
"registered",
"yet",
"create",
"a",
"new",
"array",
"with",
"the",
"style",
"property",
"and",
"value",
"."
] | ae155289a9290adef55a5eddfa7c9bfe8eeb7a34 | https://github.com/imanel/odt2html/blob/ae155289a9290adef55a5eddfa7c9bfe8eeb7a34/lib/odt2html/analyze_styles.rb#L142-L155 |
4,774 | joelanders/r6502 | lib/r6502/assembler.rb | R6502.Assembler.asm_instr | def asm_instr(instr)
command = extract_command(instr)
param = extract_param(instr)
# Branch instructions always in relative
# mode. No other instructions use this mode.
# Relative mode and zero-page mode look the
# same to addr_mode(), so we need to handle
# this here.
if [:bpl, :bmi, :bvc, :bvs,
:bcc, :bcs, :bne, :beq].
include?(command)
mode = :rel
else
mode = addr_mode(param)
end
bytes = []
bytes << opcode(command, mode)
# If implied mode, it's a 1-byte instruction.
if [:imp].include?(mode)
return bytes
end
# Handle label or address / immediate value
if param =~ /\$/ # non-labels always have a $
# Extract hex number from param string.
number = /[0-9a-f]{1,4}/.match(param)[0].to_i(16)
else
# Store a dummy value and record this location
# to be updated in 2nd pass.
defer_value(@pc + 1, param)
number = mode == :rel ? 0xff : 0xffff
end
# These instructions take 1 byte.
if [:imm, :zp, :zpx, :zpy,
:indx, :indy, :rel].include?(mode)
(number <= 0xff) || (raise "#{command}'s number too big")
return bytes << number
# These instructions take 2 bytes.
elsif [:abs, :absx, :absy, :ind].include?(mode)
(number <= 0xffff) || (raise 'number too big')
bytes << (number & 0xff) # least-sig. byte
bytes << (number >> 8) # most-sig. byte
end
end | ruby | def asm_instr(instr)
command = extract_command(instr)
param = extract_param(instr)
# Branch instructions always in relative
# mode. No other instructions use this mode.
# Relative mode and zero-page mode look the
# same to addr_mode(), so we need to handle
# this here.
if [:bpl, :bmi, :bvc, :bvs,
:bcc, :bcs, :bne, :beq].
include?(command)
mode = :rel
else
mode = addr_mode(param)
end
bytes = []
bytes << opcode(command, mode)
# If implied mode, it's a 1-byte instruction.
if [:imp].include?(mode)
return bytes
end
# Handle label or address / immediate value
if param =~ /\$/ # non-labels always have a $
# Extract hex number from param string.
number = /[0-9a-f]{1,4}/.match(param)[0].to_i(16)
else
# Store a dummy value and record this location
# to be updated in 2nd pass.
defer_value(@pc + 1, param)
number = mode == :rel ? 0xff : 0xffff
end
# These instructions take 1 byte.
if [:imm, :zp, :zpx, :zpy,
:indx, :indy, :rel].include?(mode)
(number <= 0xff) || (raise "#{command}'s number too big")
return bytes << number
# These instructions take 2 bytes.
elsif [:abs, :absx, :absy, :ind].include?(mode)
(number <= 0xffff) || (raise 'number too big')
bytes << (number & 0xff) # least-sig. byte
bytes << (number >> 8) # most-sig. byte
end
end | [
"def",
"asm_instr",
"(",
"instr",
")",
"command",
"=",
"extract_command",
"(",
"instr",
")",
"param",
"=",
"extract_param",
"(",
"instr",
")",
"# Branch instructions always in relative",
"# mode. No other instructions use this mode.",
"# Relative mode and zero-page mode look the",
"# same to addr_mode(), so we need to handle",
"# this here.",
"if",
"[",
":bpl",
",",
":bmi",
",",
":bvc",
",",
":bvs",
",",
":bcc",
",",
":bcs",
",",
":bne",
",",
":beq",
"]",
".",
"include?",
"(",
"command",
")",
"mode",
"=",
":rel",
"else",
"mode",
"=",
"addr_mode",
"(",
"param",
")",
"end",
"bytes",
"=",
"[",
"]",
"bytes",
"<<",
"opcode",
"(",
"command",
",",
"mode",
")",
"# If implied mode, it's a 1-byte instruction.",
"if",
"[",
":imp",
"]",
".",
"include?",
"(",
"mode",
")",
"return",
"bytes",
"end",
"# Handle label or address / immediate value",
"if",
"param",
"=~",
"/",
"\\$",
"/",
"# non-labels always have a $",
"# Extract hex number from param string.",
"number",
"=",
"/",
"/",
".",
"match",
"(",
"param",
")",
"[",
"0",
"]",
".",
"to_i",
"(",
"16",
")",
"else",
"# Store a dummy value and record this location",
"# to be updated in 2nd pass.",
"defer_value",
"(",
"@pc",
"+",
"1",
",",
"param",
")",
"number",
"=",
"mode",
"==",
":rel",
"?",
"0xff",
":",
"0xffff",
"end",
"# These instructions take 1 byte.",
"if",
"[",
":imm",
",",
":zp",
",",
":zpx",
",",
":zpy",
",",
":indx",
",",
":indy",
",",
":rel",
"]",
".",
"include?",
"(",
"mode",
")",
"(",
"number",
"<=",
"0xff",
")",
"||",
"(",
"raise",
"\"#{command}'s number too big\"",
")",
"return",
"bytes",
"<<",
"number",
"# These instructions take 2 bytes.",
"elsif",
"[",
":abs",
",",
":absx",
",",
":absy",
",",
":ind",
"]",
".",
"include?",
"(",
"mode",
")",
"(",
"number",
"<=",
"0xffff",
")",
"||",
"(",
"raise",
"'number too big'",
")",
"bytes",
"<<",
"(",
"number",
"&",
"0xff",
")",
"# least-sig. byte",
"bytes",
"<<",
"(",
"number",
">>",
"8",
")",
"# most-sig. byte",
"end",
"end"
] | This method got nasty. | [
"This",
"method",
"got",
"nasty",
"."
] | 1b3a73b439edc3a0742976ada7d987c041e126b5 | https://github.com/joelanders/r6502/blob/1b3a73b439edc3a0742976ada7d987c041e126b5/lib/r6502/assembler.rb#L75-L122 |
4,775 | cotag/em-promise | lib/em-promise/q.rb | EventMachine.Q.all | def all(*promises)
deferred = Q.defer
counter = promises.length
results = []
if counter > 0
promises.each_index do |index|
ref(promises[index]).then(proc {|result|
if results[index].nil?
results[index] = result
counter -= 1
deferred.resolve(results) if counter <= 0
end
result
}, proc {|reason|
if results[index].nil?
deferred.reject(reason)
end
reason
})
end
else
deferred.resolve(results)
end
return deferred.promise
end | ruby | def all(*promises)
deferred = Q.defer
counter = promises.length
results = []
if counter > 0
promises.each_index do |index|
ref(promises[index]).then(proc {|result|
if results[index].nil?
results[index] = result
counter -= 1
deferred.resolve(results) if counter <= 0
end
result
}, proc {|reason|
if results[index].nil?
deferred.reject(reason)
end
reason
})
end
else
deferred.resolve(results)
end
return deferred.promise
end | [
"def",
"all",
"(",
"*",
"promises",
")",
"deferred",
"=",
"Q",
".",
"defer",
"counter",
"=",
"promises",
".",
"length",
"results",
"=",
"[",
"]",
"if",
"counter",
">",
"0",
"promises",
".",
"each_index",
"do",
"|",
"index",
"|",
"ref",
"(",
"promises",
"[",
"index",
"]",
")",
".",
"then",
"(",
"proc",
"{",
"|",
"result",
"|",
"if",
"results",
"[",
"index",
"]",
".",
"nil?",
"results",
"[",
"index",
"]",
"=",
"result",
"counter",
"-=",
"1",
"deferred",
".",
"resolve",
"(",
"results",
")",
"if",
"counter",
"<=",
"0",
"end",
"result",
"}",
",",
"proc",
"{",
"|",
"reason",
"|",
"if",
"results",
"[",
"index",
"]",
".",
"nil?",
"deferred",
".",
"reject",
"(",
"reason",
")",
"end",
"reason",
"}",
")",
"end",
"else",
"deferred",
".",
"resolve",
"(",
"results",
")",
"end",
"return",
"deferred",
".",
"promise",
"end"
] | Combines multiple promises into a single promise that is resolved when all of the input
promises are resolved.
@param [*Promise] Promises a number of promises that will be combined into a single promise
@return [Promise] Returns a single promise that will be resolved with an array of values,
each value corresponding to the promise at the same index in the `promises` array. If any of
the promises is resolved with a rejection, this resulting promise will be resolved with the
same rejection. | [
"Combines",
"multiple",
"promises",
"into",
"a",
"single",
"promise",
"that",
"is",
"resolved",
"when",
"all",
"of",
"the",
"input",
"promises",
"are",
"resolved",
"."
] | b2a7bcb97f085a4271b2b79ade02f8f3442bbdf9 | https://github.com/cotag/em-promise/blob/b2a7bcb97f085a4271b2b79ade02f8f3442bbdf9/lib/em-promise/q.rb#L230-L256 |
4,776 | topfunky/google-checkout | lib/google-checkout/cart.rb | GoogleCheckout.Cart.shipping_cost_xml | def shipping_cost_xml
xml = Builder::XmlMarkup.new
if @flat_rate_shipping
xml.price(:currency => currency) {
xml.text! @flat_rate_shipping[:price].to_s
}
else
xml.price(:currency => @currency) {
xml.text! shipping_cost.to_s
}
end
end | ruby | def shipping_cost_xml
xml = Builder::XmlMarkup.new
if @flat_rate_shipping
xml.price(:currency => currency) {
xml.text! @flat_rate_shipping[:price].to_s
}
else
xml.price(:currency => @currency) {
xml.text! shipping_cost.to_s
}
end
end | [
"def",
"shipping_cost_xml",
"xml",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"if",
"@flat_rate_shipping",
"xml",
".",
"price",
"(",
":currency",
"=>",
"currency",
")",
"{",
"xml",
".",
"text!",
"@flat_rate_shipping",
"[",
":price",
"]",
".",
"to_s",
"}",
"else",
"xml",
".",
"price",
"(",
":currency",
"=>",
"@currency",
")",
"{",
"xml",
".",
"text!",
"shipping_cost",
".",
"to_s",
"}",
"end",
"end"
] | Generates the XML for the shipping cost, conditional on
@flat_rate_shipping being set. | [
"Generates",
"the",
"XML",
"for",
"the",
"shipping",
"cost",
"conditional",
"on"
] | 66089cef799bd40f3ba4370f01f1b8dc10f92115 | https://github.com/topfunky/google-checkout/blob/66089cef799bd40f3ba4370f01f1b8dc10f92115/lib/google-checkout/cart.rb#L267-L278 |
4,777 | topfunky/google-checkout | lib/google-checkout/cart.rb | GoogleCheckout.Cart.shipping_cost | def shipping_cost
currency = 'USD'
shipping = @contents.inject(0) { |total,item|
total + item[:regular_shipping].to_i
}.to_s
end | ruby | def shipping_cost
currency = 'USD'
shipping = @contents.inject(0) { |total,item|
total + item[:regular_shipping].to_i
}.to_s
end | [
"def",
"shipping_cost",
"currency",
"=",
"'USD'",
"shipping",
"=",
"@contents",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"total",
",",
"item",
"|",
"total",
"+",
"item",
"[",
":regular_shipping",
"]",
".",
"to_i",
"}",
".",
"to_s",
"end"
] | Returns the shipping cost for the contents of the cart. | [
"Returns",
"the",
"shipping",
"cost",
"for",
"the",
"contents",
"of",
"the",
"cart",
"."
] | 66089cef799bd40f3ba4370f01f1b8dc10f92115 | https://github.com/topfunky/google-checkout/blob/66089cef799bd40f3ba4370f01f1b8dc10f92115/lib/google-checkout/cart.rb#L281-L286 |
4,778 | topfunky/google-checkout | lib/google-checkout/cart.rb | GoogleCheckout.Cart.currency | def currency
# Mixing currency not allowed; this
# library can't convert between
# currencies.
currencies = @contents.map { |item| item[:currency] }.uniq || "USD"
case currencies.count
when 0
"USD"
when 1
currencies.first
else
raise RuntimeError.new("Mixing currency not allowed")
end
end | ruby | def currency
# Mixing currency not allowed; this
# library can't convert between
# currencies.
currencies = @contents.map { |item| item[:currency] }.uniq || "USD"
case currencies.count
when 0
"USD"
when 1
currencies.first
else
raise RuntimeError.new("Mixing currency not allowed")
end
end | [
"def",
"currency",
"# Mixing currency not allowed; this",
"# library can't convert between",
"# currencies.",
"currencies",
"=",
"@contents",
".",
"map",
"{",
"|",
"item",
"|",
"item",
"[",
":currency",
"]",
"}",
".",
"uniq",
"||",
"\"USD\"",
"case",
"currencies",
".",
"count",
"when",
"0",
"\"USD\"",
"when",
"1",
"currencies",
".",
"first",
"else",
"raise",
"RuntimeError",
".",
"new",
"(",
"\"Mixing currency not allowed\"",
")",
"end",
"end"
] | Returns the currency for the cart. Mixing currency not allowed; this
library can't convert between currencies. | [
"Returns",
"the",
"currency",
"for",
"the",
"cart",
".",
"Mixing",
"currency",
"not",
"allowed",
";",
"this",
"library",
"can",
"t",
"convert",
"between",
"currencies",
"."
] | 66089cef799bd40f3ba4370f01f1b8dc10f92115 | https://github.com/topfunky/google-checkout/blob/66089cef799bd40f3ba4370f01f1b8dc10f92115/lib/google-checkout/cart.rb#L290-L305 |
4,779 | topfunky/google-checkout | lib/google-checkout/cart.rb | GoogleCheckout.Cart.signature | def signature
@xml or to_xml
digest = OpenSSL::Digest::Digest.new('sha1')
OpenSSL::HMAC.digest(digest, @merchant_key, @xml)
end | ruby | def signature
@xml or to_xml
digest = OpenSSL::Digest::Digest.new('sha1')
OpenSSL::HMAC.digest(digest, @merchant_key, @xml)
end | [
"def",
"signature",
"@xml",
"or",
"to_xml",
"digest",
"=",
"OpenSSL",
"::",
"Digest",
"::",
"Digest",
".",
"new",
"(",
"'sha1'",
")",
"OpenSSL",
"::",
"HMAC",
".",
"digest",
"(",
"digest",
",",
"@merchant_key",
",",
"@xml",
")",
"end"
] | Returns the signature for the cart XML. | [
"Returns",
"the",
"signature",
"for",
"the",
"cart",
"XML",
"."
] | 66089cef799bd40f3ba4370f01f1b8dc10f92115 | https://github.com/topfunky/google-checkout/blob/66089cef799bd40f3ba4370f01f1b8dc10f92115/lib/google-checkout/cart.rb#L308-L313 |
4,780 | topfunky/google-checkout | lib/google-checkout/cart.rb | GoogleCheckout.Cart.checkout_button | def checkout_button(button_opts = {})
@xml or to_xml
burl = button_url(button_opts)
html = Builder::XmlMarkup.new(:indent => 2)
html.form({
:action => submit_url,
:style => 'border: 0;',
:id => 'BB_BuyButtonForm',
:method => 'post',
:name => 'BB_BuyButtonForm'
}) do
html.input({
:name => 'cart',
:type => 'hidden',
:value => Base64.encode64(@xml).gsub("\n", '')
})
html.input({
:name => 'signature',
:type => 'hidden',
:value => Base64.encode64(signature).gsub("\n", '')
})
html.input({
:alt => 'Google Checkout',
:style => "width: auto;",
:src => button_url(button_opts),
:type => 'image'
})
end
end | ruby | def checkout_button(button_opts = {})
@xml or to_xml
burl = button_url(button_opts)
html = Builder::XmlMarkup.new(:indent => 2)
html.form({
:action => submit_url,
:style => 'border: 0;',
:id => 'BB_BuyButtonForm',
:method => 'post',
:name => 'BB_BuyButtonForm'
}) do
html.input({
:name => 'cart',
:type => 'hidden',
:value => Base64.encode64(@xml).gsub("\n", '')
})
html.input({
:name => 'signature',
:type => 'hidden',
:value => Base64.encode64(signature).gsub("\n", '')
})
html.input({
:alt => 'Google Checkout',
:style => "width: auto;",
:src => button_url(button_opts),
:type => 'image'
})
end
end | [
"def",
"checkout_button",
"(",
"button_opts",
"=",
"{",
"}",
")",
"@xml",
"or",
"to_xml",
"burl",
"=",
"button_url",
"(",
"button_opts",
")",
"html",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"(",
":indent",
"=>",
"2",
")",
"html",
".",
"form",
"(",
"{",
":action",
"=>",
"submit_url",
",",
":style",
"=>",
"'border: 0;'",
",",
":id",
"=>",
"'BB_BuyButtonForm'",
",",
":method",
"=>",
"'post'",
",",
":name",
"=>",
"'BB_BuyButtonForm'",
"}",
")",
"do",
"html",
".",
"input",
"(",
"{",
":name",
"=>",
"'cart'",
",",
":type",
"=>",
"'hidden'",
",",
":value",
"=>",
"Base64",
".",
"encode64",
"(",
"@xml",
")",
".",
"gsub",
"(",
"\"\\n\"",
",",
"''",
")",
"}",
")",
"html",
".",
"input",
"(",
"{",
":name",
"=>",
"'signature'",
",",
":type",
"=>",
"'hidden'",
",",
":value",
"=>",
"Base64",
".",
"encode64",
"(",
"signature",
")",
".",
"gsub",
"(",
"\"\\n\"",
",",
"''",
")",
"}",
")",
"html",
".",
"input",
"(",
"{",
":alt",
"=>",
"'Google Checkout'",
",",
":style",
"=>",
"\"width: auto;\"",
",",
":src",
"=>",
"button_url",
"(",
"button_opts",
")",
",",
":type",
"=>",
"'image'",
"}",
")",
"end",
"end"
] | Returns HTML for a checkout form for buying all the items in the
cart. | [
"Returns",
"HTML",
"for",
"a",
"checkout",
"form",
"for",
"buying",
"all",
"the",
"items",
"in",
"the",
"cart",
"."
] | 66089cef799bd40f3ba4370f01f1b8dc10f92115 | https://github.com/topfunky/google-checkout/blob/66089cef799bd40f3ba4370f01f1b8dc10f92115/lib/google-checkout/cart.rb#L317-L345 |
4,781 | drKreso/cube | lib/cube/cube.rb | XMLA.Cube.table | def table
if (header.size == 1 && y_size == 0)
cell_data[0]
else
(0...y_axe.size).reduce(header) do |result, j|
result << ( y_axe[j] + (0...x_size).map { |i| "#{cell_data[i + j]}" })
end
end
end | ruby | def table
if (header.size == 1 && y_size == 0)
cell_data[0]
else
(0...y_axe.size).reduce(header) do |result, j|
result << ( y_axe[j] + (0...x_size).map { |i| "#{cell_data[i + j]}" })
end
end
end | [
"def",
"table",
"if",
"(",
"header",
".",
"size",
"==",
"1",
"&&",
"y_size",
"==",
"0",
")",
"cell_data",
"[",
"0",
"]",
"else",
"(",
"0",
"...",
"y_axe",
".",
"size",
")",
".",
"reduce",
"(",
"header",
")",
"do",
"|",
"result",
",",
"j",
"|",
"result",
"<<",
"(",
"y_axe",
"[",
"j",
"]",
"+",
"(",
"0",
"...",
"x_size",
")",
".",
"map",
"{",
"|",
"i",
"|",
"\"#{cell_data[i + j]}\"",
"}",
")",
"end",
"end",
"end"
] | header and rows | [
"header",
"and",
"rows"
] | 9955eac4fd21a69771bc74525ba17acf81b996e8 | https://github.com/drKreso/cube/blob/9955eac4fd21a69771bc74525ba17acf81b996e8/lib/cube/cube.rb#L33-L41 |
4,782 | phatworx/rails_paginate | lib/rails_paginate/collection.rb | RailsPaginate.Collection.load_result | def load_result
if array_or_relation.is_a? Array
result = array_or_relation[offset..(offset + per_page - 1)]
else
result = array_or_relation.limit(per_page).offset(offset).all
end
self.replace result.nil? ? [] : result
end | ruby | def load_result
if array_or_relation.is_a? Array
result = array_or_relation[offset..(offset + per_page - 1)]
else
result = array_or_relation.limit(per_page).offset(offset).all
end
self.replace result.nil? ? [] : result
end | [
"def",
"load_result",
"if",
"array_or_relation",
".",
"is_a?",
"Array",
"result",
"=",
"array_or_relation",
"[",
"offset",
"..",
"(",
"offset",
"+",
"per_page",
"-",
"1",
")",
"]",
"else",
"result",
"=",
"array_or_relation",
".",
"limit",
"(",
"per_page",
")",
".",
"offset",
"(",
"offset",
")",
".",
"all",
"end",
"self",
".",
"replace",
"result",
".",
"nil?",
"?",
"[",
"]",
":",
"result",
"end"
] | load result from input array_or_relation to internal array | [
"load",
"result",
"from",
"input",
"array_or_relation",
"to",
"internal",
"array"
] | ae8cbc12030853b236dc2cbf6ede8700fb835771 | https://github.com/phatworx/rails_paginate/blob/ae8cbc12030853b236dc2cbf6ede8700fb835771/lib/rails_paginate/collection.rb#L43-L51 |
4,783 | sosedoff/munin-ruby | lib/munin-ruby/connection.rb | Munin.Connection.open | def open
begin
begin
with_timeout do
@socket = TCPSocket.new(@host, @port)
@socket.sync = true
welcome = @socket.gets
unless welcome =~ /^# munin node at/
raise Munin::AccessDenied
end
@connected = true
end
rescue Timeout::Error
raise Munin::ConnectionError, "Timed out talking to #{@host}"
end
rescue Errno::ETIMEDOUT, Errno::ECONNREFUSED, Errno::ECONNRESET => ex
raise Munin::ConnectionError, ex.message
rescue EOFError
raise Munin::AccessDenied
rescue Exception => ex
raise Munin::ConnectionError, ex.message
end
end | ruby | def open
begin
begin
with_timeout do
@socket = TCPSocket.new(@host, @port)
@socket.sync = true
welcome = @socket.gets
unless welcome =~ /^# munin node at/
raise Munin::AccessDenied
end
@connected = true
end
rescue Timeout::Error
raise Munin::ConnectionError, "Timed out talking to #{@host}"
end
rescue Errno::ETIMEDOUT, Errno::ECONNREFUSED, Errno::ECONNRESET => ex
raise Munin::ConnectionError, ex.message
rescue EOFError
raise Munin::AccessDenied
rescue Exception => ex
raise Munin::ConnectionError, ex.message
end
end | [
"def",
"open",
"begin",
"begin",
"with_timeout",
"do",
"@socket",
"=",
"TCPSocket",
".",
"new",
"(",
"@host",
",",
"@port",
")",
"@socket",
".",
"sync",
"=",
"true",
"welcome",
"=",
"@socket",
".",
"gets",
"unless",
"welcome",
"=~",
"/",
"/",
"raise",
"Munin",
"::",
"AccessDenied",
"end",
"@connected",
"=",
"true",
"end",
"rescue",
"Timeout",
"::",
"Error",
"raise",
"Munin",
"::",
"ConnectionError",
",",
"\"Timed out talking to #{@host}\"",
"end",
"rescue",
"Errno",
"::",
"ETIMEDOUT",
",",
"Errno",
"::",
"ECONNREFUSED",
",",
"Errno",
"::",
"ECONNRESET",
"=>",
"ex",
"raise",
"Munin",
"::",
"ConnectionError",
",",
"ex",
".",
"message",
"rescue",
"EOFError",
"raise",
"Munin",
"::",
"AccessDenied",
"rescue",
"Exception",
"=>",
"ex",
"raise",
"Munin",
"::",
"ConnectionError",
",",
"ex",
".",
"message",
"end",
"end"
] | Establish connection to the server | [
"Establish",
"connection",
"to",
"the",
"server"
] | 28f65b0abb88fc40e234b6af327094992504be6a | https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/connection.rb#L33-L55 |
4,784 | sosedoff/munin-ruby | lib/munin-ruby/connection.rb | Munin.Connection.send_data | def send_data(str)
if !connected?
if [email protected]? && @reconnect == false
raise Munin::ConnectionError, "Not connected."
else
open
end
end
begin
with_timeout { @socket.puts("#{str.strip}\n") }
rescue Timeout::Error
raise Munin::ConnectionError, "Timed out on #{@host} trying to send."
end
end | ruby | def send_data(str)
if !connected?
if [email protected]? && @reconnect == false
raise Munin::ConnectionError, "Not connected."
else
open
end
end
begin
with_timeout { @socket.puts("#{str.strip}\n") }
rescue Timeout::Error
raise Munin::ConnectionError, "Timed out on #{@host} trying to send."
end
end | [
"def",
"send_data",
"(",
"str",
")",
"if",
"!",
"connected?",
"if",
"!",
"@socket",
".",
"nil?",
"&&",
"@reconnect",
"==",
"false",
"raise",
"Munin",
"::",
"ConnectionError",
",",
"\"Not connected.\"",
"else",
"open",
"end",
"end",
"begin",
"with_timeout",
"{",
"@socket",
".",
"puts",
"(",
"\"#{str.strip}\\n\"",
")",
"}",
"rescue",
"Timeout",
"::",
"Error",
"raise",
"Munin",
"::",
"ConnectionError",
",",
"\"Timed out on #{@host} trying to send.\"",
"end",
"end"
] | Send a string of data followed by a newline symbol | [
"Send",
"a",
"string",
"of",
"data",
"followed",
"by",
"a",
"newline",
"symbol"
] | 28f65b0abb88fc40e234b6af327094992504be6a | https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/connection.rb#L70-L84 |
4,785 | sosedoff/munin-ruby | lib/munin-ruby/connection.rb | Munin.Connection.read_line | def read_line
begin
with_timeout { @socket.gets.to_s.strip }
rescue Errno::ETIMEDOUT, Errno::ECONNREFUSED, Errno::ECONNRESET, EOFError => ex
raise Munin::ConnectionError, ex.message
rescue Timeout::Error
raise Munin::ConnectionError, "Timed out reading from #{@host}."
end
end | ruby | def read_line
begin
with_timeout { @socket.gets.to_s.strip }
rescue Errno::ETIMEDOUT, Errno::ECONNREFUSED, Errno::ECONNRESET, EOFError => ex
raise Munin::ConnectionError, ex.message
rescue Timeout::Error
raise Munin::ConnectionError, "Timed out reading from #{@host}."
end
end | [
"def",
"read_line",
"begin",
"with_timeout",
"{",
"@socket",
".",
"gets",
".",
"to_s",
".",
"strip",
"}",
"rescue",
"Errno",
"::",
"ETIMEDOUT",
",",
"Errno",
"::",
"ECONNREFUSED",
",",
"Errno",
"::",
"ECONNRESET",
",",
"EOFError",
"=>",
"ex",
"raise",
"Munin",
"::",
"ConnectionError",
",",
"ex",
".",
"message",
"rescue",
"Timeout",
"::",
"Error",
"raise",
"Munin",
"::",
"ConnectionError",
",",
"\"Timed out reading from #{@host}.\"",
"end",
"end"
] | Reads a single line from socket | [
"Reads",
"a",
"single",
"line",
"from",
"socket"
] | 28f65b0abb88fc40e234b6af327094992504be6a | https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/connection.rb#L88-L96 |
4,786 | sosedoff/munin-ruby | lib/munin-ruby/connection.rb | Munin.Connection.read_packet | def read_packet
begin
with_timeout do
lines = []
while(str = @socket.readline.to_s) do
break if str.strip == '.'
lines << str.strip
end
parse_error(lines)
lines
end
rescue Errno::ETIMEDOUT, Errno::ECONNREFUSED, Errno::ECONNRESET, EOFError => ex
raise Munin::ConnectionError, ex.message
rescue Timeout::Error
raise Munin::ConnectionError, "Timed out reading from #{@host}."
end
end | ruby | def read_packet
begin
with_timeout do
lines = []
while(str = @socket.readline.to_s) do
break if str.strip == '.'
lines << str.strip
end
parse_error(lines)
lines
end
rescue Errno::ETIMEDOUT, Errno::ECONNREFUSED, Errno::ECONNRESET, EOFError => ex
raise Munin::ConnectionError, ex.message
rescue Timeout::Error
raise Munin::ConnectionError, "Timed out reading from #{@host}."
end
end | [
"def",
"read_packet",
"begin",
"with_timeout",
"do",
"lines",
"=",
"[",
"]",
"while",
"(",
"str",
"=",
"@socket",
".",
"readline",
".",
"to_s",
")",
"do",
"break",
"if",
"str",
".",
"strip",
"==",
"'.'",
"lines",
"<<",
"str",
".",
"strip",
"end",
"parse_error",
"(",
"lines",
")",
"lines",
"end",
"rescue",
"Errno",
"::",
"ETIMEDOUT",
",",
"Errno",
"::",
"ECONNREFUSED",
",",
"Errno",
"::",
"ECONNRESET",
",",
"EOFError",
"=>",
"ex",
"raise",
"Munin",
"::",
"ConnectionError",
",",
"ex",
".",
"message",
"rescue",
"Timeout",
"::",
"Error",
"raise",
"Munin",
"::",
"ConnectionError",
",",
"\"Timed out reading from #{@host}.\"",
"end",
"end"
] | Reads a packet of data until '.' reached | [
"Reads",
"a",
"packet",
"of",
"data",
"until",
".",
"reached"
] | 28f65b0abb88fc40e234b6af327094992504be6a | https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/connection.rb#L100-L116 |
4,787 | sosedoff/munin-ruby | lib/munin-ruby/connection.rb | Munin.Connection.with_timeout | def with_timeout(time=@options[:timeout])
raise ArgumentError, "Block required" if !block_given?
if Munin::TIMEOUT_CLASS.respond_to?(:timeout_after)
Munin::TIMEOUT_CLASS.timeout_after(time) { yield }
else
Munin::TIMEOUT_CLASS.timeout(time) { yield }
end
end | ruby | def with_timeout(time=@options[:timeout])
raise ArgumentError, "Block required" if !block_given?
if Munin::TIMEOUT_CLASS.respond_to?(:timeout_after)
Munin::TIMEOUT_CLASS.timeout_after(time) { yield }
else
Munin::TIMEOUT_CLASS.timeout(time) { yield }
end
end | [
"def",
"with_timeout",
"(",
"time",
"=",
"@options",
"[",
":timeout",
"]",
")",
"raise",
"ArgumentError",
",",
"\"Block required\"",
"if",
"!",
"block_given?",
"if",
"Munin",
"::",
"TIMEOUT_CLASS",
".",
"respond_to?",
"(",
":timeout_after",
")",
"Munin",
"::",
"TIMEOUT_CLASS",
".",
"timeout_after",
"(",
"time",
")",
"{",
"yield",
"}",
"else",
"Munin",
"::",
"TIMEOUT_CLASS",
".",
"timeout",
"(",
"time",
")",
"{",
"yield",
"}",
"end",
"end"
] | Execute operation with timeout
@param [Block] block Block to execute | [
"Execute",
"operation",
"with",
"timeout"
] | 28f65b0abb88fc40e234b6af327094992504be6a | https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/connection.rb#L122-L129 |
4,788 | davesloan/restful_api_authentication | lib/restful_api_authentication/checker.rb | RestfulApiAuthentication.Checker.authorized? | def authorized?(options = {})
raise "Configuration values not found. Please run rails g restful_api_authentication:install to generate a config file." if @@header_timestamp.nil? || @@header_signature.nil? || @@header_api_key.nil? || @@time_window.nil? || @@disabled_message.nil?
return_val = false
if headers_have_values?
if in_time_window?
if test_hash.downcase == @http_headers[@@header_signature].downcase
if is_disabled?
@errors << @@disabled_message
return false
end
if options[:require_master] == true
if is_master?
return_val = true
else
@errors << "client does not have the required permissions"
end
else
return_val = true
end
else
@errors << "signature is invalid"
end
else
@errors << "request is outside the required time window of #{@@time_window.to_s} minutes"
end
else
@errors << "one or more required headers is missing"
end
if return_val == false && @errors.count == 0
@errors << "authentication failed"
end
return_val
end | ruby | def authorized?(options = {})
raise "Configuration values not found. Please run rails g restful_api_authentication:install to generate a config file." if @@header_timestamp.nil? || @@header_signature.nil? || @@header_api_key.nil? || @@time_window.nil? || @@disabled_message.nil?
return_val = false
if headers_have_values?
if in_time_window?
if test_hash.downcase == @http_headers[@@header_signature].downcase
if is_disabled?
@errors << @@disabled_message
return false
end
if options[:require_master] == true
if is_master?
return_val = true
else
@errors << "client does not have the required permissions"
end
else
return_val = true
end
else
@errors << "signature is invalid"
end
else
@errors << "request is outside the required time window of #{@@time_window.to_s} minutes"
end
else
@errors << "one or more required headers is missing"
end
if return_val == false && @errors.count == 0
@errors << "authentication failed"
end
return_val
end | [
"def",
"authorized?",
"(",
"options",
"=",
"{",
"}",
")",
"raise",
"\"Configuration values not found. Please run rails g restful_api_authentication:install to generate a config file.\"",
"if",
"@@header_timestamp",
".",
"nil?",
"||",
"@@header_signature",
".",
"nil?",
"||",
"@@header_api_key",
".",
"nil?",
"||",
"@@time_window",
".",
"nil?",
"||",
"@@disabled_message",
".",
"nil?",
"return_val",
"=",
"false",
"if",
"headers_have_values?",
"if",
"in_time_window?",
"if",
"test_hash",
".",
"downcase",
"==",
"@http_headers",
"[",
"@@header_signature",
"]",
".",
"downcase",
"if",
"is_disabled?",
"@errors",
"<<",
"@@disabled_message",
"return",
"false",
"end",
"if",
"options",
"[",
":require_master",
"]",
"==",
"true",
"if",
"is_master?",
"return_val",
"=",
"true",
"else",
"@errors",
"<<",
"\"client does not have the required permissions\"",
"end",
"else",
"return_val",
"=",
"true",
"end",
"else",
"@errors",
"<<",
"\"signature is invalid\"",
"end",
"else",
"@errors",
"<<",
"\"request is outside the required time window of #{@@time_window.to_s} minutes\"",
"end",
"else",
"@errors",
"<<",
"\"one or more required headers is missing\"",
"end",
"if",
"return_val",
"==",
"false",
"&&",
"@errors",
".",
"count",
"==",
"0",
"@errors",
"<<",
"\"authentication failed\"",
"end",
"return_val",
"end"
] | Checks if the current request passes authorization | [
"Checks",
"if",
"the",
"current",
"request",
"passes",
"authorization"
] | 1612e3adf815fd54502f2b08c2f222c11dbbf432 | https://github.com/davesloan/restful_api_authentication/blob/1612e3adf815fd54502f2b08c2f222c11dbbf432/lib/restful_api_authentication/checker.rb#L37-L69 |
4,789 | davesloan/restful_api_authentication | lib/restful_api_authentication/checker.rb | RestfulApiAuthentication.Checker.is_disabled? | def is_disabled?
client = RestClient.where(:api_key => @http_headers[@@header_api_key]).first
return true if client.nil?
return false if client.is_disabled.nil?
client.is_disabled
end | ruby | def is_disabled?
client = RestClient.where(:api_key => @http_headers[@@header_api_key]).first
return true if client.nil?
return false if client.is_disabled.nil?
client.is_disabled
end | [
"def",
"is_disabled?",
"client",
"=",
"RestClient",
".",
"where",
"(",
":api_key",
"=>",
"@http_headers",
"[",
"@@header_api_key",
"]",
")",
".",
"first",
"return",
"true",
"if",
"client",
".",
"nil?",
"return",
"false",
"if",
"client",
".",
"is_disabled",
".",
"nil?",
"client",
".",
"is_disabled",
"end"
] | determines if a RestClient is disabled or not | [
"determines",
"if",
"a",
"RestClient",
"is",
"disabled",
"or",
"not"
] | 1612e3adf815fd54502f2b08c2f222c11dbbf432 | https://github.com/davesloan/restful_api_authentication/blob/1612e3adf815fd54502f2b08c2f222c11dbbf432/lib/restful_api_authentication/checker.rb#L74-L79 |
4,790 | davesloan/restful_api_authentication | lib/restful_api_authentication/checker.rb | RestfulApiAuthentication.Checker.in_time_window? | def in_time_window?
@@time_window = 4 if @@time_window < 4
minutes = (@@time_window / 2).floor
ts = Chronic.parse @http_headers[@@header_timestamp]
before = Time.now.utc - 60*minutes
after = Time.now.utc + 60*minutes
if ts.nil?
@errors << "timestamp was in an invalid format; should be YYYY-MM-DD HH:MM:SS UTC"
return false
end
ts > before && ts < after
end | ruby | def in_time_window?
@@time_window = 4 if @@time_window < 4
minutes = (@@time_window / 2).floor
ts = Chronic.parse @http_headers[@@header_timestamp]
before = Time.now.utc - 60*minutes
after = Time.now.utc + 60*minutes
if ts.nil?
@errors << "timestamp was in an invalid format; should be YYYY-MM-DD HH:MM:SS UTC"
return false
end
ts > before && ts < after
end | [
"def",
"in_time_window?",
"@@time_window",
"=",
"4",
"if",
"@@time_window",
"<",
"4",
"minutes",
"=",
"(",
"@@time_window",
"/",
"2",
")",
".",
"floor",
"ts",
"=",
"Chronic",
".",
"parse",
"@http_headers",
"[",
"@@header_timestamp",
"]",
"before",
"=",
"Time",
".",
"now",
".",
"utc",
"-",
"60",
"*",
"minutes",
"after",
"=",
"Time",
".",
"now",
".",
"utc",
"+",
"60",
"*",
"minutes",
"if",
"ts",
".",
"nil?",
"@errors",
"<<",
"\"timestamp was in an invalid format; should be YYYY-MM-DD HH:MM:SS UTC\"",
"return",
"false",
"end",
"ts",
">",
"before",
"&&",
"ts",
"<",
"after",
"end"
] | determines if given timestamp is within a specific window of minutes | [
"determines",
"if",
"given",
"timestamp",
"is",
"within",
"a",
"specific",
"window",
"of",
"minutes"
] | 1612e3adf815fd54502f2b08c2f222c11dbbf432 | https://github.com/davesloan/restful_api_authentication/blob/1612e3adf815fd54502f2b08c2f222c11dbbf432/lib/restful_api_authentication/checker.rb#L88-L99 |
4,791 | davesloan/restful_api_authentication | lib/restful_api_authentication/checker.rb | RestfulApiAuthentication.Checker.str_to_hash | def str_to_hash
client = RestClient.where(:api_key => @http_headers[@@header_api_key]).first
if client.nil?
@errors << "client is not registered"
end
client.nil? ? "" : client.secret + @request_uri.gsub( /\?.*/, "" ) + @http_headers[@@header_timestamp]
end | ruby | def str_to_hash
client = RestClient.where(:api_key => @http_headers[@@header_api_key]).first
if client.nil?
@errors << "client is not registered"
end
client.nil? ? "" : client.secret + @request_uri.gsub( /\?.*/, "" ) + @http_headers[@@header_timestamp]
end | [
"def",
"str_to_hash",
"client",
"=",
"RestClient",
".",
"where",
"(",
":api_key",
"=>",
"@http_headers",
"[",
"@@header_api_key",
"]",
")",
".",
"first",
"if",
"client",
".",
"nil?",
"@errors",
"<<",
"\"client is not registered\"",
"end",
"client",
".",
"nil?",
"?",
"\"\"",
":",
"client",
".",
"secret",
"+",
"@request_uri",
".",
"gsub",
"(",
"/",
"\\?",
"/",
",",
"\"\"",
")",
"+",
"@http_headers",
"[",
"@@header_timestamp",
"]",
"end"
] | generates the string that is hashed to produce the signature | [
"generates",
"the",
"string",
"that",
"is",
"hashed",
"to",
"produce",
"the",
"signature"
] | 1612e3adf815fd54502f2b08c2f222c11dbbf432 | https://github.com/davesloan/restful_api_authentication/blob/1612e3adf815fd54502f2b08c2f222c11dbbf432/lib/restful_api_authentication/checker.rb#L107-L113 |
4,792 | unipept/unipept-cli | lib/formatters.rb | Unipept.Formatter.format | def format(data, fasta_mapper, first)
data = integrate_fasta_headers(data, fasta_mapper) if fasta_mapper
convert(data, first)
end | ruby | def format(data, fasta_mapper, first)
data = integrate_fasta_headers(data, fasta_mapper) if fasta_mapper
convert(data, first)
end | [
"def",
"format",
"(",
"data",
",",
"fasta_mapper",
",",
"first",
")",
"data",
"=",
"integrate_fasta_headers",
"(",
"data",
",",
"fasta_mapper",
")",
"if",
"fasta_mapper",
"convert",
"(",
"data",
",",
"first",
")",
"end"
] | Converts the given input data and corresponding fasta headers to another
format.
@param [Array] data The data we wish to convert
@param [Array<Array<String>>] fasta_mapper Optional mapping between input
data and corresponding fasta header. The data is represented as a list
containing tuples where the first element is the fasta header and second
element is the input data
@param [Boolean] Is this the first output batch?
@return [String] The converted input data | [
"Converts",
"the",
"given",
"input",
"data",
"and",
"corresponding",
"fasta",
"headers",
"to",
"another",
"format",
"."
] | 183779bd1dffcd01ed623685c789160153b78681 | https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/formatters.rb#L89-L92 |
4,793 | unipept/unipept-cli | lib/formatters.rb | Unipept.Formatter.integrate_fasta_headers | def integrate_fasta_headers(data, fasta_mapper)
data_dict = group_by_first_key(data)
data = fasta_mapper.map do |header, key|
result = data_dict[key]
unless result.nil?
result = result.map do |row|
copy = { fasta_header: header }
copy.merge(row)
end
end
result
end
data.compact.flatten(1)
end | ruby | def integrate_fasta_headers(data, fasta_mapper)
data_dict = group_by_first_key(data)
data = fasta_mapper.map do |header, key|
result = data_dict[key]
unless result.nil?
result = result.map do |row|
copy = { fasta_header: header }
copy.merge(row)
end
end
result
end
data.compact.flatten(1)
end | [
"def",
"integrate_fasta_headers",
"(",
"data",
",",
"fasta_mapper",
")",
"data_dict",
"=",
"group_by_first_key",
"(",
"data",
")",
"data",
"=",
"fasta_mapper",
".",
"map",
"do",
"|",
"header",
",",
"key",
"|",
"result",
"=",
"data_dict",
"[",
"key",
"]",
"unless",
"result",
".",
"nil?",
"result",
"=",
"result",
".",
"map",
"do",
"|",
"row",
"|",
"copy",
"=",
"{",
"fasta_header",
":",
"header",
"}",
"copy",
".",
"merge",
"(",
"row",
")",
"end",
"end",
"result",
"end",
"data",
".",
"compact",
".",
"flatten",
"(",
"1",
")",
"end"
] | Integrates the fasta headers into the data object | [
"Integrates",
"the",
"fasta",
"headers",
"into",
"the",
"data",
"object"
] | 183779bd1dffcd01ed623685c789160153b78681 | https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/formatters.rb#L106-L119 |
4,794 | unipept/unipept-cli | lib/formatters.rb | Unipept.JSONFormatter.convert | def convert(data, first)
output = data.map(&:to_json).join(',')
first ? output : ',' + output
end | ruby | def convert(data, first)
output = data.map(&:to_json).join(',')
first ? output : ',' + output
end | [
"def",
"convert",
"(",
"data",
",",
"first",
")",
"output",
"=",
"data",
".",
"map",
"(",
":to_json",
")",
".",
"join",
"(",
"','",
")",
"first",
"?",
"output",
":",
"','",
"+",
"output",
"end"
] | Converts the given input data to the JSON format.
@param [Array] data The data we wish to convert
@param [Boolean] Is this the first output batch?
@return [String] The converted input data in the JSON format | [
"Converts",
"the",
"given",
"input",
"data",
"to",
"the",
"JSON",
"format",
"."
] | 183779bd1dffcd01ed623685c789160153b78681 | https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/formatters.rb#L157-L160 |
4,795 | unipept/unipept-cli | lib/formatters.rb | Unipept.CSVFormatter.header | def header(data, fasta_mapper = nil)
CSV.generate do |csv|
first = data.first
keys = fasta_mapper ? ['fasta_header'] : []
csv << (keys + first.keys).map(&:to_s) if first
end
end | ruby | def header(data, fasta_mapper = nil)
CSV.generate do |csv|
first = data.first
keys = fasta_mapper ? ['fasta_header'] : []
csv << (keys + first.keys).map(&:to_s) if first
end
end | [
"def",
"header",
"(",
"data",
",",
"fasta_mapper",
"=",
"nil",
")",
"CSV",
".",
"generate",
"do",
"|",
"csv",
"|",
"first",
"=",
"data",
".",
"first",
"keys",
"=",
"fasta_mapper",
"?",
"[",
"'fasta_header'",
"]",
":",
"[",
"]",
"csv",
"<<",
"(",
"keys",
"+",
"first",
".",
"keys",
")",
".",
"map",
"(",
":to_s",
")",
"if",
"first",
"end",
"end"
] | Returns the header row for the given data and fasta_mapper. This row
contains all the keys of the first element of the data, preceded by
'fasta_header' if a fasta_mapper is given.
@param [Array] data The data that we will use to extract the keys from.
@param [Array<Array<String>>] fasta_mapper Optional mapping between input
data and corresponding fasta header. The data is represented as a list
containing tuples where the first element is the fasta header and second
element is the input data If a fasta_mapper is given, the output will be
preceded with 'fasta_header'.
@return [String] The header row | [
"Returns",
"the",
"header",
"row",
"for",
"the",
"given",
"data",
"and",
"fasta_mapper",
".",
"This",
"row",
"contains",
"all",
"the",
"keys",
"of",
"the",
"first",
"element",
"of",
"the",
"data",
"preceded",
"by",
"fasta_header",
"if",
"a",
"fasta_mapper",
"is",
"given",
"."
] | 183779bd1dffcd01ed623685c789160153b78681 | https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/formatters.rb#L185-L191 |
4,796 | unipept/unipept-cli | lib/formatters.rb | Unipept.CSVFormatter.convert | def convert(data, _first)
CSV.generate do |csv|
data.each do |o|
csv << o.values.map { |v| v == '' ? nil : v }
end
end
end | ruby | def convert(data, _first)
CSV.generate do |csv|
data.each do |o|
csv << o.values.map { |v| v == '' ? nil : v }
end
end
end | [
"def",
"convert",
"(",
"data",
",",
"_first",
")",
"CSV",
".",
"generate",
"do",
"|",
"csv",
"|",
"data",
".",
"each",
"do",
"|",
"o",
"|",
"csv",
"<<",
"o",
".",
"values",
".",
"map",
"{",
"|",
"v",
"|",
"v",
"==",
"''",
"?",
"nil",
":",
"v",
"}",
"end",
"end",
"end"
] | Converts the given input data to the CSV format.
@param [Array] data The data we wish to convert
@param [Boolean] Is this the first output batch?
@return [String] The converted input data in the CSV format | [
"Converts",
"the",
"given",
"input",
"data",
"to",
"the",
"CSV",
"format",
"."
] | 183779bd1dffcd01ed623685c789160153b78681 | https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/formatters.rb#L204-L210 |
4,797 | unipept/unipept-cli | lib/formatters.rb | Unipept.BlastFormatter.convert | def convert(data, _first)
data
.reject { |o| o['refseq_protein_ids'].empty? }
.map do |o|
"#{o['peptide']}\tref|#{o['refseq_protein_ids']}|\t100\t10\t0\t0\t0\t10\t0\t10\t1e-100\t100\n"
end
.join
end | ruby | def convert(data, _first)
data
.reject { |o| o['refseq_protein_ids'].empty? }
.map do |o|
"#{o['peptide']}\tref|#{o['refseq_protein_ids']}|\t100\t10\t0\t0\t0\t10\t0\t10\t1e-100\t100\n"
end
.join
end | [
"def",
"convert",
"(",
"data",
",",
"_first",
")",
"data",
".",
"reject",
"{",
"|",
"o",
"|",
"o",
"[",
"'refseq_protein_ids'",
"]",
".",
"empty?",
"}",
".",
"map",
"do",
"|",
"o",
"|",
"\"#{o['peptide']}\\tref|#{o['refseq_protein_ids']}|\\t100\\t10\\t0\\t0\\t0\\t10\\t0\\t10\\t1e-100\\t100\\n\"",
"end",
".",
"join",
"end"
] | Converts the given input data to the Blast format.
@param [Array] data The data we wish to convert
@param [Boolean] Is this the first output batch?
@return [String] The converted input data in the Blast format | [
"Converts",
"the",
"given",
"input",
"data",
"to",
"the",
"Blast",
"format",
"."
] | 183779bd1dffcd01ed623685c789160153b78681 | https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/formatters.rb#L289-L296 |
4,798 | code-and-effect/effective_roles | app/models/concerns/acts_as_role_restricted.rb | ActsAsRoleRestricted.ClassMethods.for_role | def for_role(*roles)
sql = with_role_sql(roles) || ''
sql += ' OR ' if sql.present?
sql += "(#{self.table_name}.roles_mask = 0) OR (#{self.table_name}.roles_mask IS NULL)"
where(sql)
end | ruby | def for_role(*roles)
sql = with_role_sql(roles) || ''
sql += ' OR ' if sql.present?
sql += "(#{self.table_name}.roles_mask = 0) OR (#{self.table_name}.roles_mask IS NULL)"
where(sql)
end | [
"def",
"for_role",
"(",
"*",
"roles",
")",
"sql",
"=",
"with_role_sql",
"(",
"roles",
")",
"||",
"''",
"sql",
"+=",
"' OR '",
"if",
"sql",
".",
"present?",
"sql",
"+=",
"\"(#{self.table_name}.roles_mask = 0) OR (#{self.table_name}.roles_mask IS NULL)\"",
"where",
"(",
"sql",
")",
"end"
] | Returns all records which have been assigned any of the given roles, as well as any record with no role assigned | [
"Returns",
"all",
"records",
"which",
"have",
"been",
"assigned",
"any",
"of",
"the",
"given",
"roles",
"as",
"well",
"as",
"any",
"record",
"with",
"no",
"role",
"assigned"
] | 334605ae4573f742bedc3e29b0eb4d4245a4cff9 | https://github.com/code-and-effect/effective_roles/blob/334605ae4573f742bedc3e29b0eb4d4245a4cff9/app/models/concerns/acts_as_role_restricted.rb#L39-L44 |
4,799 | zertico/softlayer | lib/softlayer/client.rb | Softlayer.Client.auth_params | def auth_params
return {} unless Softlayer.configuration
auth_hash = {
authenticate: {
'username' => Softlayer.configuration.username,
'apiKey' => Softlayer.configuration.api_key
}
}
auth_hash.merge!({
"clientLegacySession" =>
{
"userId" => Softlayer.configuration.impersonate_user,
"authToken" => Softlayer.configuration.impersonate_token
}
}) if Softlayer.impersonating?
auth_hash
end | ruby | def auth_params
return {} unless Softlayer.configuration
auth_hash = {
authenticate: {
'username' => Softlayer.configuration.username,
'apiKey' => Softlayer.configuration.api_key
}
}
auth_hash.merge!({
"clientLegacySession" =>
{
"userId" => Softlayer.configuration.impersonate_user,
"authToken" => Softlayer.configuration.impersonate_token
}
}) if Softlayer.impersonating?
auth_hash
end | [
"def",
"auth_params",
"return",
"{",
"}",
"unless",
"Softlayer",
".",
"configuration",
"auth_hash",
"=",
"{",
"authenticate",
":",
"{",
"'username'",
"=>",
"Softlayer",
".",
"configuration",
".",
"username",
",",
"'apiKey'",
"=>",
"Softlayer",
".",
"configuration",
".",
"api_key",
"}",
"}",
"auth_hash",
".",
"merge!",
"(",
"{",
"\"clientLegacySession\"",
"=>",
"{",
"\"userId\"",
"=>",
"Softlayer",
".",
"configuration",
".",
"impersonate_user",
",",
"\"authToken\"",
"=>",
"Softlayer",
".",
"configuration",
".",
"impersonate_token",
"}",
"}",
")",
"if",
"Softlayer",
".",
"impersonating?",
"auth_hash",
"end"
] | Authorization hash to use with all SOAP requests | [
"Authorization",
"hash",
"to",
"use",
"with",
"all",
"SOAP",
"requests"
] | 77c2e73f22cebd73359ff108342ed1927a063428 | https://github.com/zertico/softlayer/blob/77c2e73f22cebd73359ff108342ed1927a063428/lib/softlayer/client.rb#L23-L39 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.