id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
|
|---|---|---|---|---|---|---|---|---|---|---|---|
8,200
|
byu/optser
|
lib/optser/opt_set.rb
|
Optser.OptSet.get!
|
def get!(key, default=nil, &block)
value = get key, default, &block
raise "Nil value found for option: #{key}, #{default}" if value.nil?
return value
end
|
ruby
|
def get!(key, default=nil, &block)
value = get key, default, &block
raise "Nil value found for option: #{key}, #{default}" if value.nil?
return value
end
|
[
"def",
"get!",
"(",
"key",
",",
"default",
"=",
"nil",
",",
"&",
"block",
")",
"value",
"=",
"get",
"key",
",",
"default",
",",
"block",
"raise",
"\"Nil value found for option: #{key}, #{default}\"",
"if",
"value",
".",
"nil?",
"return",
"value",
"end"
] |
Use this the option is mandatory.
There are cases where an option may have a default value for a feature,
but the caller may just want to disable said feature. To do so,
users of this module should allow for the caller to pass in 'false'
as an option value instead of nil to disable said feature. The
implementer will have to do a boolean check of the returned option value
and disable accordingly.
Examples:
# Has a default logger, but we can disable logging by passing false.
# If caller had passed in nil for :logger, it would have
# defaulted to ::Log4r['my_logger'].
logger = opt_set.get! :logger, ::Log4r['my_logger']
# Here we force the end user to pass in a Non-nil option as a
# mandatory parameter.
max_threads = opt_set.get! :max_threads
Raises error when `get` returns a nil.
|
[
"Use",
"this",
"the",
"option",
"is",
"mandatory",
"."
] |
c88c19f15ca31874ad46fb6f15b20485635a5ffb
|
https://github.com/byu/optser/blob/c88c19f15ca31874ad46fb6f15b20485635a5ffb/lib/optser/opt_set.rb#L62-L66
|
8,201
|
samvera-deprecated/solrizer-fedora
|
lib/solrizer/fedora/indexer.rb
|
Solrizer::Fedora.Indexer.connect
|
def connect
if defined?(Blacklight)
solr_config = Blacklight.solr_config
elsif defined?(Rails.root.to_s)
solr_config = load_rails_config
else
solr_config = load_fallback_config
end
if index_full_text == true && solr_config.has_key?(:fulltext) && solr_config[:fulltext].has_key?('url')
solr_config[:url] = solr_config[:fulltext]['url']
elsif solr_config.has_key?(:default) && solr_config[:default].has_key?('url')
solr_config[:url] = solr_config[:default]['url']
elsif !solr_config.has_key?(:url)
raise "Unable to find a solr url in the config file"
end
@solr = RSolr.connect solr_config
rescue RuntimeError => e
logger.debug "Unable to establish SOLR Connection with #{solr_config.inspect}. Failed with #{e.message}"
raise URI::InvalidURIError
end
|
ruby
|
def connect
if defined?(Blacklight)
solr_config = Blacklight.solr_config
elsif defined?(Rails.root.to_s)
solr_config = load_rails_config
else
solr_config = load_fallback_config
end
if index_full_text == true && solr_config.has_key?(:fulltext) && solr_config[:fulltext].has_key?('url')
solr_config[:url] = solr_config[:fulltext]['url']
elsif solr_config.has_key?(:default) && solr_config[:default].has_key?('url')
solr_config[:url] = solr_config[:default]['url']
elsif !solr_config.has_key?(:url)
raise "Unable to find a solr url in the config file"
end
@solr = RSolr.connect solr_config
rescue RuntimeError => e
logger.debug "Unable to establish SOLR Connection with #{solr_config.inspect}. Failed with #{e.message}"
raise URI::InvalidURIError
end
|
[
"def",
"connect",
"if",
"defined?",
"(",
"Blacklight",
")",
"solr_config",
"=",
"Blacklight",
".",
"solr_config",
"elsif",
"defined?",
"(",
"Rails",
".",
"root",
".",
"to_s",
")",
"solr_config",
"=",
"load_rails_config",
"else",
"solr_config",
"=",
"load_fallback_config",
"end",
"if",
"index_full_text",
"==",
"true",
"&&",
"solr_config",
".",
"has_key?",
"(",
":fulltext",
")",
"&&",
"solr_config",
"[",
":fulltext",
"]",
".",
"has_key?",
"(",
"'url'",
")",
"solr_config",
"[",
":url",
"]",
"=",
"solr_config",
"[",
":fulltext",
"]",
"[",
"'url'",
"]",
"elsif",
"solr_config",
".",
"has_key?",
"(",
":default",
")",
"&&",
"solr_config",
"[",
":default",
"]",
".",
"has_key?",
"(",
"'url'",
")",
"solr_config",
"[",
":url",
"]",
"=",
"solr_config",
"[",
":default",
"]",
"[",
"'url'",
"]",
"elsif",
"!",
"solr_config",
".",
"has_key?",
"(",
":url",
")",
"raise",
"\"Unable to find a solr url in the config file\"",
"end",
"@solr",
"=",
"RSolr",
".",
"connect",
"solr_config",
"rescue",
"RuntimeError",
"=>",
"e",
"logger",
".",
"debug",
"\"Unable to establish SOLR Connection with #{solr_config.inspect}. Failed with #{e.message}\"",
"raise",
"URI",
"::",
"InvalidURIError",
"end"
] |
This method performs initialization tasks
This method connects to the Solr instance. It looks to see if Blacklight is loaded first for the
Blacklight.solr_config. If not loaded, it then looks for the Rails.root.to_s/config/solr.yaml file and loads
it to get the solr url. The configuration strucuture can take both the
{ "development" => {"default" => { "url" => "http://localhost"}, "fulltext" => { "url" => "http://localhost"} }}
or { "development"=>{"url"=>"http://localhost" }}
Can also take Blacklight.solr_config["url"] and Blacklight.solr_config[:url]
If you want to specify a timeout for solr, provide these keys:
:read_timeout=>120, :open_timeout => 120
|
[
"This",
"method",
"performs",
"initialization",
"tasks"
] |
277fab50a93a761fbccd07e2cfa01b22736d5cff
|
https://github.com/samvera-deprecated/solrizer-fedora/blob/277fab50a93a761fbccd07e2cfa01b22736d5cff/lib/solrizer/fedora/indexer.rb#L44-L66
|
8,202
|
samvera-deprecated/solrizer-fedora
|
lib/solrizer/fedora/indexer.rb
|
Solrizer::Fedora.Indexer.generate_dates
|
def generate_dates(solr_doc)
# This will check for valid dates, but it seems most of the dates are currently invalid....
#date_check = /^(19|20)\d\d([- \/.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])/
#if there is not date_t, add on with easy-to-find value
if solr_doc[:date_t].nil?
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :date_t, "9999-99-99")
end #if
# Grab the date value from date_t regardless of wheter it is inside of an array
# then convert it to a Date object
date_value = solr_doc[:date_t]
if date_value.kind_of? Array
date_value = date_value.first
end
date_obj = Date._parse(date_value)
if date_obj[:mon].nil?
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :month_facet, "99")
elsif 0 < date_obj[:mon] && date_obj[:mon] < 13
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :month_facet, date_obj[:mon].to_s.rjust(2, '0'))
else
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :month_facet, "99")
end
if date_obj[:mday].nil?
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :day_facet, "99")
elsif 0 < date_obj[:mday] && date_obj[:mday] < 32
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :day_facet, date_obj[:mday].to_s.rjust(2, '0'))
else
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :day_facet, "99")
end
return solr_doc
end
|
ruby
|
def generate_dates(solr_doc)
# This will check for valid dates, but it seems most of the dates are currently invalid....
#date_check = /^(19|20)\d\d([- \/.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])/
#if there is not date_t, add on with easy-to-find value
if solr_doc[:date_t].nil?
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :date_t, "9999-99-99")
end #if
# Grab the date value from date_t regardless of wheter it is inside of an array
# then convert it to a Date object
date_value = solr_doc[:date_t]
if date_value.kind_of? Array
date_value = date_value.first
end
date_obj = Date._parse(date_value)
if date_obj[:mon].nil?
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :month_facet, "99")
elsif 0 < date_obj[:mon] && date_obj[:mon] < 13
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :month_facet, date_obj[:mon].to_s.rjust(2, '0'))
else
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :month_facet, "99")
end
if date_obj[:mday].nil?
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :day_facet, "99")
elsif 0 < date_obj[:mday] && date_obj[:mday] < 32
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :day_facet, date_obj[:mday].to_s.rjust(2, '0'))
else
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :day_facet, "99")
end
return solr_doc
end
|
[
"def",
"generate_dates",
"(",
"solr_doc",
")",
"# This will check for valid dates, but it seems most of the dates are currently invalid....",
"#date_check = /^(19|20)\\d\\d([- \\/.])(0[1-9]|1[012])\\2(0[1-9]|[12][0-9]|3[01])/",
"#if there is not date_t, add on with easy-to-find value",
"if",
"solr_doc",
"[",
":date_t",
"]",
".",
"nil?",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":date_t",
",",
"\"9999-99-99\"",
")",
"end",
"#if",
"# Grab the date value from date_t regardless of wheter it is inside of an array",
"# then convert it to a Date object",
"date_value",
"=",
"solr_doc",
"[",
":date_t",
"]",
"if",
"date_value",
".",
"kind_of?",
"Array",
"date_value",
"=",
"date_value",
".",
"first",
"end",
"date_obj",
"=",
"Date",
".",
"_parse",
"(",
"date_value",
")",
"if",
"date_obj",
"[",
":mon",
"]",
".",
"nil?",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":month_facet",
",",
"\"99\"",
")",
"elsif",
"0",
"<",
"date_obj",
"[",
":mon",
"]",
"&&",
"date_obj",
"[",
":mon",
"]",
"<",
"13",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":month_facet",
",",
"date_obj",
"[",
":mon",
"]",
".",
"to_s",
".",
"rjust",
"(",
"2",
",",
"'0'",
")",
")",
"else",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":month_facet",
",",
"\"99\"",
")",
"end",
"if",
"date_obj",
"[",
":mday",
"]",
".",
"nil?",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":day_facet",
",",
"\"99\"",
")",
"elsif",
"0",
"<",
"date_obj",
"[",
":mday",
"]",
"&&",
"date_obj",
"[",
":mday",
"]",
"<",
"32",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":day_facet",
",",
"date_obj",
"[",
":mday",
"]",
".",
"to_s",
".",
"rjust",
"(",
"2",
",",
"'0'",
")",
")",
"else",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":day_facet",
",",
"\"99\"",
")",
"end",
"return",
"solr_doc",
"end"
] |
This method generates the month and day facets from the date_t in solr_doc
|
[
"This",
"method",
"generates",
"the",
"month",
"and",
"day",
"facets",
"from",
"the",
"date_t",
"in",
"solr_doc"
] |
277fab50a93a761fbccd07e2cfa01b22736d5cff
|
https://github.com/samvera-deprecated/solrizer-fedora/blob/277fab50a93a761fbccd07e2cfa01b22736d5cff/lib/solrizer/fedora/indexer.rb#L100-L136
|
8,203
|
samvera-deprecated/solrizer-fedora
|
lib/solrizer/fedora/indexer.rb
|
Solrizer::Fedora.Indexer.create_document
|
def create_document( obj )
solr_doc = Hash.new
model_klazz_array = ActiveFedora::ContentModel.known_models_for( obj )
model_klazz_array.delete(ActiveFedora::Base)
# If the object was passed in as an ActiveFedora::Base, call to_solr in order to get the base field entries from ActiveFedora::Base
# Otherwise, the object was passed in as a model instance other than ActiveFedora::Base,so call its to_solr method & allow it to insert the fields from ActiveFedora::Base
if obj.class == ActiveFedora::Base
solr_doc = obj.to_solr(solr_doc)
logger.debug " added base fields from #{obj.class.to_s}"
else
solr_doc = obj.to_solr(solr_doc)
model_klazz_array.delete(obj.class)
logger.debug " added base fields from #{obj.class.to_s} and model fields from #{obj.class.to_s}"
end
# Load the object as an instance of each of its other models and get the corresponding solr fields
# Include :model_only=>true in the options in order to avoid adding the metadata from ActiveFedora::Base every time.
model_klazz_array.each do |klazz|
instance = obj.adapt_to(klazz)
solr_doc = instance.to_solr(solr_doc, :model_only=>true)
logger.debug " added solr fields from #{klazz.to_s}"
end
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :id_t, "#{obj.pid}" )
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :id, "#{obj.pid}" ) unless solr_doc[:id]
return solr_doc
end
|
ruby
|
def create_document( obj )
solr_doc = Hash.new
model_klazz_array = ActiveFedora::ContentModel.known_models_for( obj )
model_klazz_array.delete(ActiveFedora::Base)
# If the object was passed in as an ActiveFedora::Base, call to_solr in order to get the base field entries from ActiveFedora::Base
# Otherwise, the object was passed in as a model instance other than ActiveFedora::Base,so call its to_solr method & allow it to insert the fields from ActiveFedora::Base
if obj.class == ActiveFedora::Base
solr_doc = obj.to_solr(solr_doc)
logger.debug " added base fields from #{obj.class.to_s}"
else
solr_doc = obj.to_solr(solr_doc)
model_klazz_array.delete(obj.class)
logger.debug " added base fields from #{obj.class.to_s} and model fields from #{obj.class.to_s}"
end
# Load the object as an instance of each of its other models and get the corresponding solr fields
# Include :model_only=>true in the options in order to avoid adding the metadata from ActiveFedora::Base every time.
model_klazz_array.each do |klazz|
instance = obj.adapt_to(klazz)
solr_doc = instance.to_solr(solr_doc, :model_only=>true)
logger.debug " added solr fields from #{klazz.to_s}"
end
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :id_t, "#{obj.pid}" )
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :id, "#{obj.pid}" ) unless solr_doc[:id]
return solr_doc
end
|
[
"def",
"create_document",
"(",
"obj",
")",
"solr_doc",
"=",
"Hash",
".",
"new",
"model_klazz_array",
"=",
"ActiveFedora",
"::",
"ContentModel",
".",
"known_models_for",
"(",
"obj",
")",
"model_klazz_array",
".",
"delete",
"(",
"ActiveFedora",
"::",
"Base",
")",
"# If the object was passed in as an ActiveFedora::Base, call to_solr in order to get the base field entries from ActiveFedora::Base",
"# Otherwise, the object was passed in as a model instance other than ActiveFedora::Base,so call its to_solr method & allow it to insert the fields from ActiveFedora::Base",
"if",
"obj",
".",
"class",
"==",
"ActiveFedora",
"::",
"Base",
"solr_doc",
"=",
"obj",
".",
"to_solr",
"(",
"solr_doc",
")",
"logger",
".",
"debug",
"\" added base fields from #{obj.class.to_s}\"",
"else",
"solr_doc",
"=",
"obj",
".",
"to_solr",
"(",
"solr_doc",
")",
"model_klazz_array",
".",
"delete",
"(",
"obj",
".",
"class",
")",
"logger",
".",
"debug",
"\" added base fields from #{obj.class.to_s} and model fields from #{obj.class.to_s}\"",
"end",
"# Load the object as an instance of each of its other models and get the corresponding solr fields",
"# Include :model_only=>true in the options in order to avoid adding the metadata from ActiveFedora::Base every time.",
"model_klazz_array",
".",
"each",
"do",
"|",
"klazz",
"|",
"instance",
"=",
"obj",
".",
"adapt_to",
"(",
"klazz",
")",
"solr_doc",
"=",
"instance",
".",
"to_solr",
"(",
"solr_doc",
",",
":model_only",
"=>",
"true",
")",
"logger",
".",
"debug",
"\" added solr fields from #{klazz.to_s}\"",
"end",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":id_t",
",",
"\"#{obj.pid}\"",
")",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":id",
",",
"\"#{obj.pid}\"",
")",
"unless",
"solr_doc",
"[",
":id",
"]",
"return",
"solr_doc",
"end"
] |
This method creates a Solr-formatted XML document
|
[
"This",
"method",
"creates",
"a",
"Solr",
"-",
"formatted",
"XML",
"document"
] |
277fab50a93a761fbccd07e2cfa01b22736d5cff
|
https://github.com/samvera-deprecated/solrizer-fedora/blob/277fab50a93a761fbccd07e2cfa01b22736d5cff/lib/solrizer/fedora/indexer.rb#L141-L171
|
8,204
|
megamsys/megam_api
|
lib/megam/api/accounts.rb
|
Megam.API.post_accounts
|
def post_accounts(new_account)
@options = {path: '/accounts/content',
body: Megam::JSONCompat.to_json(new_account)}.merge(@options)
request(
:expects => 201,
:method => :post,
:body => @options[:body]
)
end
|
ruby
|
def post_accounts(new_account)
@options = {path: '/accounts/content',
body: Megam::JSONCompat.to_json(new_account)}.merge(@options)
request(
:expects => 201,
:method => :post,
:body => @options[:body]
)
end
|
[
"def",
"post_accounts",
"(",
"new_account",
")",
"@options",
"=",
"{",
"path",
":",
"'/accounts/content'",
",",
"body",
":",
"Megam",
"::",
"JSONCompat",
".",
"to_json",
"(",
"new_account",
")",
"}",
".",
"merge",
"(",
"@options",
")",
"request",
"(",
":expects",
"=>",
"201",
",",
":method",
"=>",
":post",
",",
":body",
"=>",
"@options",
"[",
":body",
"]",
")",
"end"
] |
The body content needs to be a json.
|
[
"The",
"body",
"content",
"needs",
"to",
"be",
"a",
"json",
"."
] |
c28e743311706dfef9c7745ae64058a468f5b1a4
|
https://github.com/megamsys/megam_api/blob/c28e743311706dfef9c7745ae64058a468f5b1a4/lib/megam/api/accounts.rb#L28-L37
|
8,205
|
michaelmior/mipper
|
lib/mipper/lp_solve/model.rb
|
MIPPeR.LPSolveModel.store_constraint_matrix
|
def store_constraint_matrix(constr, type)
# Initialize arrays used to hold the coefficients for each variable
row = []
colno = []
constr.expression.terms.each do |var, coeff|
row << coeff * 1.0
colno << var.index
end
row_buffer = build_pointer_array row, :double
colno_buffer = build_pointer_array colno, :int
ret = LPSolve.add_constraintex(@ptr, constr.expression.terms.length,
row_buffer, colno_buffer,
type, constr.rhs)
fail if ret != 1
end
|
ruby
|
def store_constraint_matrix(constr, type)
# Initialize arrays used to hold the coefficients for each variable
row = []
colno = []
constr.expression.terms.each do |var, coeff|
row << coeff * 1.0
colno << var.index
end
row_buffer = build_pointer_array row, :double
colno_buffer = build_pointer_array colno, :int
ret = LPSolve.add_constraintex(@ptr, constr.expression.terms.length,
row_buffer, colno_buffer,
type, constr.rhs)
fail if ret != 1
end
|
[
"def",
"store_constraint_matrix",
"(",
"constr",
",",
"type",
")",
"# Initialize arrays used to hold the coefficients for each variable",
"row",
"=",
"[",
"]",
"colno",
"=",
"[",
"]",
"constr",
".",
"expression",
".",
"terms",
".",
"each",
"do",
"|",
"var",
",",
"coeff",
"|",
"row",
"<<",
"coeff",
"*",
"1.0",
"colno",
"<<",
"var",
".",
"index",
"end",
"row_buffer",
"=",
"build_pointer_array",
"row",
",",
":double",
"colno_buffer",
"=",
"build_pointer_array",
"colno",
",",
":int",
"ret",
"=",
"LPSolve",
".",
"add_constraintex",
"(",
"@ptr",
",",
"constr",
".",
"expression",
".",
"terms",
".",
"length",
",",
"row_buffer",
",",
"colno_buffer",
",",
"type",
",",
"constr",
".",
"rhs",
")",
"fail",
"if",
"ret",
"!=",
"1",
"end"
] |
Build the constraint matrix and add it to the model
|
[
"Build",
"the",
"constraint",
"matrix",
"and",
"add",
"it",
"to",
"the",
"model"
] |
4ab7f8b32c27f33fc5121756554a0a28d2077e06
|
https://github.com/michaelmior/mipper/blob/4ab7f8b32c27f33fc5121756554a0a28d2077e06/lib/mipper/lp_solve/model.rb#L70-L86
|
8,206
|
oniram88/imdb-scan
|
lib/imdb/person.rb
|
IMDB.Person.birthdate
|
def birthdate
month_data_element = bio_document.at("td.label[text()*='Date of Birth']").
next_element.first_element_child
date_month = month_data_element.inner_text.strip rescue ""
year = month_data_element.next_element.inner_text.strip rescue ""
Date.parse("#{date_month} #{year}") rescue nil
end
|
ruby
|
def birthdate
month_data_element = bio_document.at("td.label[text()*='Date of Birth']").
next_element.first_element_child
date_month = month_data_element.inner_text.strip rescue ""
year = month_data_element.next_element.inner_text.strip rescue ""
Date.parse("#{date_month} #{year}") rescue nil
end
|
[
"def",
"birthdate",
"month_data_element",
"=",
"bio_document",
".",
"at",
"(",
"\"td.label[text()*='Date of Birth']\"",
")",
".",
"next_element",
".",
"first_element_child",
"date_month",
"=",
"month_data_element",
".",
"inner_text",
".",
"strip",
"rescue",
"\"\"",
"year",
"=",
"month_data_element",
".",
"next_element",
".",
"inner_text",
".",
"strip",
"rescue",
"\"\"",
"Date",
".",
"parse",
"(",
"\"#{date_month} #{year}\"",
")",
"rescue",
"nil",
"end"
] |
Get The Birth Date
@return [Date]
|
[
"Get",
"The",
"Birth",
"Date"
] |
e358adaba3db178df42c711c79c894f14d83c742
|
https://github.com/oniram88/imdb-scan/blob/e358adaba3db178df42c711c79c894f14d83c742/lib/imdb/person.rb#L50-L56
|
8,207
|
oniram88/imdb-scan
|
lib/imdb/person.rb
|
IMDB.Person.deathdate
|
def deathdate
date_month = bio_document.at("h5[text()*='Date of Death']").next_element.inner_text.strip rescue ""
year = bio_document.at("a[@href*='death_date']").inner_text.strip rescue ""
Date.parse("#{date_month} #{year}") rescue nil
end
|
ruby
|
def deathdate
date_month = bio_document.at("h5[text()*='Date of Death']").next_element.inner_text.strip rescue ""
year = bio_document.at("a[@href*='death_date']").inner_text.strip rescue ""
Date.parse("#{date_month} #{year}") rescue nil
end
|
[
"def",
"deathdate",
"date_month",
"=",
"bio_document",
".",
"at",
"(",
"\"h5[text()*='Date of Death']\"",
")",
".",
"next_element",
".",
"inner_text",
".",
"strip",
"rescue",
"\"\"",
"year",
"=",
"bio_document",
".",
"at",
"(",
"\"a[@href*='death_date']\"",
")",
".",
"inner_text",
".",
"strip",
"rescue",
"\"\"",
"Date",
".",
"parse",
"(",
"\"#{date_month} #{year}\"",
")",
"rescue",
"nil",
"end"
] |
Get The death date else nil
@return [Date]
|
[
"Get",
"The",
"death",
"date",
"else",
"nil"
] |
e358adaba3db178df42c711c79c894f14d83c742
|
https://github.com/oniram88/imdb-scan/blob/e358adaba3db178df42c711c79c894f14d83c742/lib/imdb/person.rb#L60-L64
|
8,208
|
oniram88/imdb-scan
|
lib/imdb/person.rb
|
IMDB.Person.filmography
|
def filmography
#@return [Hash]
# writer: [Movie]
# actor: [Movie]
# director: [Movie]
# composer: [Movie]
#as_writer = main_document.at("#filmo-head-Writer").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
#as_actor = main_document.at("#filmo-head-Actor").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
#as_director = main_document.at("#filmo-head-Director").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
#as_composer = main_document.at("#filmo-head-Composer").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
#{ writer: as_writer.map { |m| Movie.new(m) }, actor: as_actor.map { |m| Movie.new(m) }, director: as_director.map { |m| Movie.new(m) }, composer: as_composer.map { |m| Movie.new(m) } }
films=main_document.css(".filmo-row b a").map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
films.map { |f| Movie.new(f.to_i) }
end
|
ruby
|
def filmography
#@return [Hash]
# writer: [Movie]
# actor: [Movie]
# director: [Movie]
# composer: [Movie]
#as_writer = main_document.at("#filmo-head-Writer").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
#as_actor = main_document.at("#filmo-head-Actor").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
#as_director = main_document.at("#filmo-head-Director").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
#as_composer = main_document.at("#filmo-head-Composer").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
#{ writer: as_writer.map { |m| Movie.new(m) }, actor: as_actor.map { |m| Movie.new(m) }, director: as_director.map { |m| Movie.new(m) }, composer: as_composer.map { |m| Movie.new(m) } }
films=main_document.css(".filmo-row b a").map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
films.map { |f| Movie.new(f.to_i) }
end
|
[
"def",
"filmography",
"#@return [Hash]\r",
"# writer: [Movie]\r",
"# actor: [Movie]\r",
"# director: [Movie]\r",
"# composer: [Movie]\r",
"#as_writer = main_document.at(\"#filmo-head-Writer\").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\\d+)/, 1] } rescue []\r",
"#as_actor = main_document.at(\"#filmo-head-Actor\").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\\d+)/, 1] } rescue []\r",
"#as_director = main_document.at(\"#filmo-head-Director\").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\\d+)/, 1] } rescue []\r",
"#as_composer = main_document.at(\"#filmo-head-Composer\").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\\d+)/, 1] } rescue []\r",
"#{ writer: as_writer.map { |m| Movie.new(m) }, actor: as_actor.map { |m| Movie.new(m) }, director: as_director.map { |m| Movie.new(m) }, composer: as_composer.map { |m| Movie.new(m) } }\r",
"films",
"=",
"main_document",
".",
"css",
"(",
"\".filmo-row b a\"",
")",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"get_attribute",
"(",
"'href'",
")",
"[",
"/",
"\\d",
"/",
",",
"1",
"]",
"}",
"rescue",
"[",
"]",
"films",
".",
"map",
"{",
"|",
"f",
"|",
"Movie",
".",
"new",
"(",
"f",
".",
"to_i",
")",
"}",
"end"
] |
Return the Filmography
for the moment I can't make subdivision of this, then i take all in an array
@return [Movie]
|
[
"Return",
"the",
"Filmography",
"for",
"the",
"moment",
"I",
"can",
"t",
"make",
"subdivision",
"of",
"this",
"then",
"i",
"take",
"all",
"in",
"an",
"array"
] |
e358adaba3db178df42c711c79c894f14d83c742
|
https://github.com/oniram88/imdb-scan/blob/e358adaba3db178df42c711c79c894f14d83c742/lib/imdb/person.rb#L93-L106
|
8,209
|
rixth/tay
|
lib/tay/specification.rb
|
Tay.Specification.all_javascript_paths
|
def all_javascript_paths
all_paths = []
all_paths += @javascripts
all_paths += @background_scripts
all_paths += @content_scripts.map { |cs| cs.javascripts }.compact
all_paths.flatten.uniq
end
|
ruby
|
def all_javascript_paths
all_paths = []
all_paths += @javascripts
all_paths += @background_scripts
all_paths += @content_scripts.map { |cs| cs.javascripts }.compact
all_paths.flatten.uniq
end
|
[
"def",
"all_javascript_paths",
"all_paths",
"=",
"[",
"]",
"all_paths",
"+=",
"@javascripts",
"all_paths",
"+=",
"@background_scripts",
"all_paths",
"+=",
"@content_scripts",
".",
"map",
"{",
"|",
"cs",
"|",
"cs",
".",
"javascripts",
"}",
".",
"compact",
"all_paths",
".",
"flatten",
".",
"uniq",
"end"
] |
Return all the javascript paths in the spec, included those nested
inside other objects
|
[
"Return",
"all",
"the",
"javascript",
"paths",
"in",
"the",
"spec",
"included",
"those",
"nested",
"inside",
"other",
"objects"
] |
60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5
|
https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/specification.rb#L261-L267
|
8,210
|
rixth/tay
|
lib/tay/specification.rb
|
Tay.Specification.all_stylesheet_paths
|
def all_stylesheet_paths
all_paths = []
all_paths += @stylesheets
all_paths += @content_scripts.map { |cs| cs.stylesheets }.compact
all_paths.flatten.uniq
end
|
ruby
|
def all_stylesheet_paths
all_paths = []
all_paths += @stylesheets
all_paths += @content_scripts.map { |cs| cs.stylesheets }.compact
all_paths.flatten.uniq
end
|
[
"def",
"all_stylesheet_paths",
"all_paths",
"=",
"[",
"]",
"all_paths",
"+=",
"@stylesheets",
"all_paths",
"+=",
"@content_scripts",
".",
"map",
"{",
"|",
"cs",
"|",
"cs",
".",
"stylesheets",
"}",
".",
"compact",
"all_paths",
".",
"flatten",
".",
"uniq",
"end"
] |
Return all the stylesheet paths in the spec, included those nested
inside other objects
|
[
"Return",
"all",
"the",
"stylesheet",
"paths",
"in",
"the",
"spec",
"included",
"those",
"nested",
"inside",
"other",
"objects"
] |
60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5
|
https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/specification.rb#L272-L277
|
8,211
|
ideonetwork/lato-blog
|
app/models/lato_blog/category/serializer_helpers.rb
|
LatoBlog.Category::SerializerHelpers.serialize
|
def serialize
serialized = {}
# set basic info
serialized[:id] = id
serialized[:title] = title
serialized[:meta_language] = meta_language
serialized[:meta_permalink] = meta_permalink
# add category father informations
serialized[:category_father] = category_father ? category_father.serialize_base : nil
# add category children informations
serialized[:category_children] = serialize_category_children
# add category parent informations
serialized[:other_informations] = serialize_other_informations
# return serialized post
serialized
end
|
ruby
|
def serialize
serialized = {}
# set basic info
serialized[:id] = id
serialized[:title] = title
serialized[:meta_language] = meta_language
serialized[:meta_permalink] = meta_permalink
# add category father informations
serialized[:category_father] = category_father ? category_father.serialize_base : nil
# add category children informations
serialized[:category_children] = serialize_category_children
# add category parent informations
serialized[:other_informations] = serialize_other_informations
# return serialized post
serialized
end
|
[
"def",
"serialize",
"serialized",
"=",
"{",
"}",
"# set basic info",
"serialized",
"[",
":id",
"]",
"=",
"id",
"serialized",
"[",
":title",
"]",
"=",
"title",
"serialized",
"[",
":meta_language",
"]",
"=",
"meta_language",
"serialized",
"[",
":meta_permalink",
"]",
"=",
"meta_permalink",
"# add category father informations",
"serialized",
"[",
":category_father",
"]",
"=",
"category_father",
"?",
"category_father",
".",
"serialize_base",
":",
"nil",
"# add category children informations",
"serialized",
"[",
":category_children",
"]",
"=",
"serialize_category_children",
"# add category parent informations",
"serialized",
"[",
":other_informations",
"]",
"=",
"serialize_other_informations",
"# return serialized post",
"serialized",
"end"
] |
This function serializes a complete version of the category.
|
[
"This",
"function",
"serializes",
"a",
"complete",
"version",
"of",
"the",
"category",
"."
] |
a0d92de299a0e285851743b9d4a902f611187cba
|
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/category/serializer_helpers.rb#L5-L25
|
8,212
|
ideonetwork/lato-blog
|
app/models/lato_blog/category/serializer_helpers.rb
|
LatoBlog.Category::SerializerHelpers.serialize_base
|
def serialize_base
serialized = {}
# set basic info
serialized[:id] = id
serialized[:title] = title
serialized[:meta_language] = meta_language
serialized[:meta_permalink] = meta_permalink
# return serialized category
serialized
end
|
ruby
|
def serialize_base
serialized = {}
# set basic info
serialized[:id] = id
serialized[:title] = title
serialized[:meta_language] = meta_language
serialized[:meta_permalink] = meta_permalink
# return serialized category
serialized
end
|
[
"def",
"serialize_base",
"serialized",
"=",
"{",
"}",
"# set basic info",
"serialized",
"[",
":id",
"]",
"=",
"id",
"serialized",
"[",
":title",
"]",
"=",
"title",
"serialized",
"[",
":meta_language",
"]",
"=",
"meta_language",
"serialized",
"[",
":meta_permalink",
"]",
"=",
"meta_permalink",
"# return serialized category",
"serialized",
"end"
] |
This function serializes a basic version of the category.
|
[
"This",
"function",
"serializes",
"a",
"basic",
"version",
"of",
"the",
"category",
"."
] |
a0d92de299a0e285851743b9d4a902f611187cba
|
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/category/serializer_helpers.rb#L28-L39
|
8,213
|
paxtonhare/marklogic-ruby-driver
|
lib/marklogic/collection.rb
|
MarkLogic.Collection.from_criteria
|
def from_criteria(criteria)
queries = []
criteria.each do |k, v|
name, operator, index_type, value = nil
query_options = {}
if (v.is_a?(Hash))
name = k.to_s
query_options.merge!(v.delete(:options) || {})
sub_queries = []
v.each do |kk, vv|
operator = kk.to_s.gsub('$', '').upcase || "EQ"
if @operators.include?(operator)
value = vv
value = value.to_s if value.is_a?(MarkLogic::ObjectId)
sub_queries << build_query(name, operator, value, query_options)
elsif value.is_a?(Hash)
child_queries = value.map do |kk, vv|
build_query(kk, vv, query_options)
end
sub_queries << Queries::ContainerQuery.new(name, Queries::AndQuery.new(child_queries))
end
end
if sub_queries.length > 1
queries << Queries::AndQuery.new(sub_queries)
elsif sub_queries.length == 1
queries << sub_queries[0]
end
else
name = k.to_s
value = v
operator = "EQ"
queries << build_query(name, operator, value, query_options)
end
end
if queries.length > 1
MarkLogic::Queries::AndQuery.new(*queries)
elsif queries.length == 1
queries[0]
end
end
|
ruby
|
def from_criteria(criteria)
queries = []
criteria.each do |k, v|
name, operator, index_type, value = nil
query_options = {}
if (v.is_a?(Hash))
name = k.to_s
query_options.merge!(v.delete(:options) || {})
sub_queries = []
v.each do |kk, vv|
operator = kk.to_s.gsub('$', '').upcase || "EQ"
if @operators.include?(operator)
value = vv
value = value.to_s if value.is_a?(MarkLogic::ObjectId)
sub_queries << build_query(name, operator, value, query_options)
elsif value.is_a?(Hash)
child_queries = value.map do |kk, vv|
build_query(kk, vv, query_options)
end
sub_queries << Queries::ContainerQuery.new(name, Queries::AndQuery.new(child_queries))
end
end
if sub_queries.length > 1
queries << Queries::AndQuery.new(sub_queries)
elsif sub_queries.length == 1
queries << sub_queries[0]
end
else
name = k.to_s
value = v
operator = "EQ"
queries << build_query(name, operator, value, query_options)
end
end
if queries.length > 1
MarkLogic::Queries::AndQuery.new(*queries)
elsif queries.length == 1
queries[0]
end
end
|
[
"def",
"from_criteria",
"(",
"criteria",
")",
"queries",
"=",
"[",
"]",
"criteria",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"name",
",",
"operator",
",",
"index_type",
",",
"value",
"=",
"nil",
"query_options",
"=",
"{",
"}",
"if",
"(",
"v",
".",
"is_a?",
"(",
"Hash",
")",
")",
"name",
"=",
"k",
".",
"to_s",
"query_options",
".",
"merge!",
"(",
"v",
".",
"delete",
"(",
":options",
")",
"||",
"{",
"}",
")",
"sub_queries",
"=",
"[",
"]",
"v",
".",
"each",
"do",
"|",
"kk",
",",
"vv",
"|",
"operator",
"=",
"kk",
".",
"to_s",
".",
"gsub",
"(",
"'$'",
",",
"''",
")",
".",
"upcase",
"||",
"\"EQ\"",
"if",
"@operators",
".",
"include?",
"(",
"operator",
")",
"value",
"=",
"vv",
"value",
"=",
"value",
".",
"to_s",
"if",
"value",
".",
"is_a?",
"(",
"MarkLogic",
"::",
"ObjectId",
")",
"sub_queries",
"<<",
"build_query",
"(",
"name",
",",
"operator",
",",
"value",
",",
"query_options",
")",
"elsif",
"value",
".",
"is_a?",
"(",
"Hash",
")",
"child_queries",
"=",
"value",
".",
"map",
"do",
"|",
"kk",
",",
"vv",
"|",
"build_query",
"(",
"kk",
",",
"vv",
",",
"query_options",
")",
"end",
"sub_queries",
"<<",
"Queries",
"::",
"ContainerQuery",
".",
"new",
"(",
"name",
",",
"Queries",
"::",
"AndQuery",
".",
"new",
"(",
"child_queries",
")",
")",
"end",
"end",
"if",
"sub_queries",
".",
"length",
">",
"1",
"queries",
"<<",
"Queries",
"::",
"AndQuery",
".",
"new",
"(",
"sub_queries",
")",
"elsif",
"sub_queries",
".",
"length",
"==",
"1",
"queries",
"<<",
"sub_queries",
"[",
"0",
"]",
"end",
"else",
"name",
"=",
"k",
".",
"to_s",
"value",
"=",
"v",
"operator",
"=",
"\"EQ\"",
"queries",
"<<",
"build_query",
"(",
"name",
",",
"operator",
",",
"value",
",",
"query_options",
")",
"end",
"end",
"if",
"queries",
".",
"length",
">",
"1",
"MarkLogic",
"::",
"Queries",
"::",
"AndQuery",
".",
"new",
"(",
"queries",
")",
"elsif",
"queries",
".",
"length",
"==",
"1",
"queries",
"[",
"0",
"]",
"end",
"end"
] |
Builds a MarkLogic Query from Mongo Style Criteria
@param [Hash] criteria The Criteria to use when searching
@example Build a query from criteria
# Query on age == 3
collection.from_criteria({ 'age' => { '$eq' => 3 } })
# Query on age < 3
collection.from_criteria({ 'age' => { '$lt' => 3 } })
# Query on age <= 3
collection.from_criteria({ 'age' => { '$le' => 3 } })
# Query on age > 3
collection.from_criteria({ 'age' => { '$gt' => 3 } })
# Query on age >= 3
collection.from_criteria({ 'age' => { '$ge' => 3 } })
# Query on age != 3
collection.from_criteria({ 'age' => { '$ne' => 3 } })
@since 0.0.1
|
[
"Builds",
"a",
"MarkLogic",
"Query",
"from",
"Mongo",
"Style",
"Criteria"
] |
76c3f2c2da7b8266cdbe786b7f3e910e0983eb9b
|
https://github.com/paxtonhare/marklogic-ruby-driver/blob/76c3f2c2da7b8266cdbe786b7f3e910e0983eb9b/lib/marklogic/collection.rb#L174-L218
|
8,214
|
cjfuller/rimageanalysistools
|
lib/rimageanalysistools/drawing.rb
|
RImageAnalysisTools.Drawing.draw
|
def draw(im, draw_value = 255.0)
im.each do |ic|
if (yield ic) then
im.setValue(ic, draw_value)
end
end
end
|
ruby
|
def draw(im, draw_value = 255.0)
im.each do |ic|
if (yield ic) then
im.setValue(ic, draw_value)
end
end
end
|
[
"def",
"draw",
"(",
"im",
",",
"draw_value",
"=",
"255.0",
")",
"im",
".",
"each",
"do",
"|",
"ic",
"|",
"if",
"(",
"yield",
"ic",
")",
"then",
"im",
".",
"setValue",
"(",
"ic",
",",
"draw_value",
")",
"end",
"end",
"end"
] |
A basic drawing method that iterates through an entire image. At each coordinate,
an attached block is evaluated for a boolean response that determines whether that
coordinate is overwritten with a specified value. The attached block will be given
a single parameter, which is the current ImageCoordinate.
@param [WritableImage] im the image being drawn on
@param [Numeric] draw_value the value to which a pixel will be set if the block
evaluates to a true value at that coordinate
@return [void]
|
[
"A",
"basic",
"drawing",
"method",
"that",
"iterates",
"through",
"an",
"entire",
"image",
".",
"At",
"each",
"coordinate",
"an",
"attached",
"block",
"is",
"evaluated",
"for",
"a",
"boolean",
"response",
"that",
"determines",
"whether",
"that",
"coordinate",
"is",
"overwritten",
"with",
"a",
"specified",
"value",
".",
"The",
"attached",
"block",
"will",
"be",
"given",
"a",
"single",
"parameter",
"which",
"is",
"the",
"current",
"ImageCoordinate",
"."
] |
991aa7a61a8ad7bd902a31d99a19ce135e3cc485
|
https://github.com/cjfuller/rimageanalysistools/blob/991aa7a61a8ad7bd902a31d99a19ce135e3cc485/lib/rimageanalysistools/drawing.rb#L96-L108
|
8,215
|
cjfuller/rimageanalysistools
|
lib/rimageanalysistools/drawing.rb
|
RImageAnalysisTools.Drawing.draw_shape
|
def draw_shape(im, location, shape_name=:circle, shape_parameters= 10)
if self.respond_to?(shape_name) then
self.send(shape_name, im, location, shape_parameters)
end
end
|
ruby
|
def draw_shape(im, location, shape_name=:circle, shape_parameters= 10)
if self.respond_to?(shape_name) then
self.send(shape_name, im, location, shape_parameters)
end
end
|
[
"def",
"draw_shape",
"(",
"im",
",",
"location",
",",
"shape_name",
"=",
":circle",
",",
"shape_parameters",
"=",
"10",
")",
"if",
"self",
".",
"respond_to?",
"(",
"shape_name",
")",
"then",
"self",
".",
"send",
"(",
"shape_name",
",",
"im",
",",
"location",
",",
"shape_parameters",
")",
"end",
"end"
] |
Draws a specified shape into an image.
@param [WritableImage] im the image into which to draw
@param [Array] location an array containing the coordinates of the shape to draw.
The exact meaning of this parameter depends on which shape is being drawn.
@param [Symbol] shape_name the name of the shape to draw. This should correspond
to one of the methods of this class.
@param shape_parameters the parameters for drawing the specified shape;
the meaning of this parameter depends on the shape.
@return [void]
|
[
"Draws",
"a",
"specified",
"shape",
"into",
"an",
"image",
"."
] |
991aa7a61a8ad7bd902a31d99a19ce135e3cc485
|
https://github.com/cjfuller/rimageanalysistools/blob/991aa7a61a8ad7bd902a31d99a19ce135e3cc485/lib/rimageanalysistools/drawing.rb#L123-L131
|
8,216
|
cjfuller/rimageanalysistools
|
lib/rimageanalysistools/drawing.rb
|
RImageAnalysisTools.Drawing.circle
|
def circle(im, center, radius)
lower = ImageCoordinate[center[0]-radius-1, center[1]-radius-1, 0,0,0]
upper = ImageCoordinate[center[0]+radius+1, center[1]+radius+1, 0,0,0]
im.box_conservative(lower, upper, [:x, :y])
draw(im) do |ic|
xdiff = ic[:x] - center[0]
ydiff = ic[:y] - center[1]
if (Math.hypot(xdiff, ydiff) - radius).abs <= Math.sqrt(2) then
true
else
false
end
end
lower.recycle
upper.recycle
end
|
ruby
|
def circle(im, center, radius)
lower = ImageCoordinate[center[0]-radius-1, center[1]-radius-1, 0,0,0]
upper = ImageCoordinate[center[0]+radius+1, center[1]+radius+1, 0,0,0]
im.box_conservative(lower, upper, [:x, :y])
draw(im) do |ic|
xdiff = ic[:x] - center[0]
ydiff = ic[:y] - center[1]
if (Math.hypot(xdiff, ydiff) - radius).abs <= Math.sqrt(2) then
true
else
false
end
end
lower.recycle
upper.recycle
end
|
[
"def",
"circle",
"(",
"im",
",",
"center",
",",
"radius",
")",
"lower",
"=",
"ImageCoordinate",
"[",
"center",
"[",
"0",
"]",
"-",
"radius",
"-",
"1",
",",
"center",
"[",
"1",
"]",
"-",
"radius",
"-",
"1",
",",
"0",
",",
"0",
",",
"0",
"]",
"upper",
"=",
"ImageCoordinate",
"[",
"center",
"[",
"0",
"]",
"+",
"radius",
"+",
"1",
",",
"center",
"[",
"1",
"]",
"+",
"radius",
"+",
"1",
",",
"0",
",",
"0",
",",
"0",
"]",
"im",
".",
"box_conservative",
"(",
"lower",
",",
"upper",
",",
"[",
":x",
",",
":y",
"]",
")",
"draw",
"(",
"im",
")",
"do",
"|",
"ic",
"|",
"xdiff",
"=",
"ic",
"[",
":x",
"]",
"-",
"center",
"[",
"0",
"]",
"ydiff",
"=",
"ic",
"[",
":y",
"]",
"-",
"center",
"[",
"1",
"]",
"if",
"(",
"Math",
".",
"hypot",
"(",
"xdiff",
",",
"ydiff",
")",
"-",
"radius",
")",
".",
"abs",
"<=",
"Math",
".",
"sqrt",
"(",
"2",
")",
"then",
"true",
"else",
"false",
"end",
"end",
"lower",
".",
"recycle",
"upper",
".",
"recycle",
"end"
] |
Draws a circle into an image.
@param [WritableImage] im the image into which to draw
@param [Array] center an array containing the x,y coordinates of the circle's center
@param [Numeric] radius the radius of the circle in pixels
@return [void]
|
[
"Draws",
"a",
"circle",
"into",
"an",
"image",
"."
] |
991aa7a61a8ad7bd902a31d99a19ce135e3cc485
|
https://github.com/cjfuller/rimageanalysistools/blob/991aa7a61a8ad7bd902a31d99a19ce135e3cc485/lib/rimageanalysistools/drawing.rb#L142-L165
|
8,217
|
cjfuller/rimageanalysistools
|
lib/rimageanalysistools/drawing.rb
|
RImageAnalysisTools.Drawing.ellipse
|
def ellipse(im, foci, radius_inc)
min_x = foci[0][0]
max_x = foci[1][0]
min_y = foci[0][1]
max_y = foci[1][1]
if foci[1][0] < min_x then
min_x = foci[1][0]
max_x = foci[0][0]
end
if foci[1][1] < min_y then
min_y = foci[1][1]
max_y = foci[0][1]
end
radius = radius_inc + Math.hypot(max_x-min_x, max_y-min_y)
lower = ImageCoordinate[min_x-radius-1, min_y-radius-1, 0,0,0]
upper = ImageCoordinate[max_x+radius+1, max_y+radius+1, 0,0,0]
im.box_conservative(lower, upper, [:x, :y])
draw(im) do |ic|
xdiff0 = ic[:x] - foci[0][0]
ydiff0 = ic[:y] - foci[0][1]
xdiff1 = ic[:x] - foci[1][0]
ydiff1 = ic[:y] - foci[1][1]
if (Math.hypot(xdiff0, ydiff0) + Math.hypot(xdiff1, ydiff1) - radius).abs <= Math.sqrt(2) then
true
else
false
end
end
end
|
ruby
|
def ellipse(im, foci, radius_inc)
min_x = foci[0][0]
max_x = foci[1][0]
min_y = foci[0][1]
max_y = foci[1][1]
if foci[1][0] < min_x then
min_x = foci[1][0]
max_x = foci[0][0]
end
if foci[1][1] < min_y then
min_y = foci[1][1]
max_y = foci[0][1]
end
radius = radius_inc + Math.hypot(max_x-min_x, max_y-min_y)
lower = ImageCoordinate[min_x-radius-1, min_y-radius-1, 0,0,0]
upper = ImageCoordinate[max_x+radius+1, max_y+radius+1, 0,0,0]
im.box_conservative(lower, upper, [:x, :y])
draw(im) do |ic|
xdiff0 = ic[:x] - foci[0][0]
ydiff0 = ic[:y] - foci[0][1]
xdiff1 = ic[:x] - foci[1][0]
ydiff1 = ic[:y] - foci[1][1]
if (Math.hypot(xdiff0, ydiff0) + Math.hypot(xdiff1, ydiff1) - radius).abs <= Math.sqrt(2) then
true
else
false
end
end
end
|
[
"def",
"ellipse",
"(",
"im",
",",
"foci",
",",
"radius_inc",
")",
"min_x",
"=",
"foci",
"[",
"0",
"]",
"[",
"0",
"]",
"max_x",
"=",
"foci",
"[",
"1",
"]",
"[",
"0",
"]",
"min_y",
"=",
"foci",
"[",
"0",
"]",
"[",
"1",
"]",
"max_y",
"=",
"foci",
"[",
"1",
"]",
"[",
"1",
"]",
"if",
"foci",
"[",
"1",
"]",
"[",
"0",
"]",
"<",
"min_x",
"then",
"min_x",
"=",
"foci",
"[",
"1",
"]",
"[",
"0",
"]",
"max_x",
"=",
"foci",
"[",
"0",
"]",
"[",
"0",
"]",
"end",
"if",
"foci",
"[",
"1",
"]",
"[",
"1",
"]",
"<",
"min_y",
"then",
"min_y",
"=",
"foci",
"[",
"1",
"]",
"[",
"1",
"]",
"max_y",
"=",
"foci",
"[",
"0",
"]",
"[",
"1",
"]",
"end",
"radius",
"=",
"radius_inc",
"+",
"Math",
".",
"hypot",
"(",
"max_x",
"-",
"min_x",
",",
"max_y",
"-",
"min_y",
")",
"lower",
"=",
"ImageCoordinate",
"[",
"min_x",
"-",
"radius",
"-",
"1",
",",
"min_y",
"-",
"radius",
"-",
"1",
",",
"0",
",",
"0",
",",
"0",
"]",
"upper",
"=",
"ImageCoordinate",
"[",
"max_x",
"+",
"radius",
"+",
"1",
",",
"max_y",
"+",
"radius",
"+",
"1",
",",
"0",
",",
"0",
",",
"0",
"]",
"im",
".",
"box_conservative",
"(",
"lower",
",",
"upper",
",",
"[",
":x",
",",
":y",
"]",
")",
"draw",
"(",
"im",
")",
"do",
"|",
"ic",
"|",
"xdiff0",
"=",
"ic",
"[",
":x",
"]",
"-",
"foci",
"[",
"0",
"]",
"[",
"0",
"]",
"ydiff0",
"=",
"ic",
"[",
":y",
"]",
"-",
"foci",
"[",
"0",
"]",
"[",
"1",
"]",
"xdiff1",
"=",
"ic",
"[",
":x",
"]",
"-",
"foci",
"[",
"1",
"]",
"[",
"0",
"]",
"ydiff1",
"=",
"ic",
"[",
":y",
"]",
"-",
"foci",
"[",
"1",
"]",
"[",
"1",
"]",
"if",
"(",
"Math",
".",
"hypot",
"(",
"xdiff0",
",",
"ydiff0",
")",
"+",
"Math",
".",
"hypot",
"(",
"xdiff1",
",",
"ydiff1",
")",
"-",
"radius",
")",
".",
"abs",
"<=",
"Math",
".",
"sqrt",
"(",
"2",
")",
"then",
"true",
"else",
"false",
"end",
"end",
"end"
] |
Draws an ellipse into an image.
@param [WritableImage] im the image into which to draw
@param [Array] foci an array containing two arrays, each of which contains the x,y
coordinates of one focus of the ellipse
@param [Numeric] radius_inc the extra amount of distance (in pixels) beyond the
distance between the foci that the ellipse should be drawn. (2*radius_inc + dist
between foci = major axis length)
@return [void]
|
[
"Draws",
"an",
"ellipse",
"into",
"an",
"image",
"."
] |
991aa7a61a8ad7bd902a31d99a19ce135e3cc485
|
https://github.com/cjfuller/rimageanalysistools/blob/991aa7a61a8ad7bd902a31d99a19ce135e3cc485/lib/rimageanalysistools/drawing.rb#L179-L219
|
8,218
|
assaf/css-annotate
|
lib/css/annotate.rb
|
CSS.Annotate.annotate
|
def annotate(filename)
engine = Sass::Engine.new(IO.read(filename), options.merge(:syntax=>guess_syntax(filename)))
tree = engine.to_tree
tree.perform!(Sass::Environment.new)
resolve_rules tree
@rows = to_rows(tree)
end
|
ruby
|
def annotate(filename)
engine = Sass::Engine.new(IO.read(filename), options.merge(:syntax=>guess_syntax(filename)))
tree = engine.to_tree
tree.perform!(Sass::Environment.new)
resolve_rules tree
@rows = to_rows(tree)
end
|
[
"def",
"annotate",
"(",
"filename",
")",
"engine",
"=",
"Sass",
"::",
"Engine",
".",
"new",
"(",
"IO",
".",
"read",
"(",
"filename",
")",
",",
"options",
".",
"merge",
"(",
":syntax",
"=>",
"guess_syntax",
"(",
"filename",
")",
")",
")",
"tree",
"=",
"engine",
".",
"to_tree",
"tree",
".",
"perform!",
"(",
"Sass",
"::",
"Environment",
".",
"new",
")",
"resolve_rules",
"tree",
"@rows",
"=",
"to_rows",
"(",
"tree",
")",
"end"
] |
Annotate the named file. Sets and returns rows.
|
[
"Annotate",
"the",
"named",
"file",
".",
"Sets",
"and",
"returns",
"rows",
"."
] |
5368d8f15e70b2f3cc6b38872a4685383b119d02
|
https://github.com/assaf/css-annotate/blob/5368d8f15e70b2f3cc6b38872a4685383b119d02/lib/css/annotate.rb#L29-L35
|
8,219
|
assaf/css-annotate
|
lib/css/annotate.rb
|
CSS.Annotate.to_html
|
def to_html(filename)
rows = annotate(filename)
ERB.new(IO.read(File.dirname(__FILE__) + "/annotate/template.erb")).result(binding)
rescue Sass::SyntaxError=>error
error = Sass::SyntaxError.exception_to_css error, @options.merge(:full_exception=>true)
ERB.new(IO.read(File.dirname(__FILE__) + "/annotate/template.erb")).result(binding)
end
|
ruby
|
def to_html(filename)
rows = annotate(filename)
ERB.new(IO.read(File.dirname(__FILE__) + "/annotate/template.erb")).result(binding)
rescue Sass::SyntaxError=>error
error = Sass::SyntaxError.exception_to_css error, @options.merge(:full_exception=>true)
ERB.new(IO.read(File.dirname(__FILE__) + "/annotate/template.erb")).result(binding)
end
|
[
"def",
"to_html",
"(",
"filename",
")",
"rows",
"=",
"annotate",
"(",
"filename",
")",
"ERB",
".",
"new",
"(",
"IO",
".",
"read",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
"+",
"\"/annotate/template.erb\"",
")",
")",
".",
"result",
"(",
"binding",
")",
"rescue",
"Sass",
"::",
"SyntaxError",
"=>",
"error",
"error",
"=",
"Sass",
"::",
"SyntaxError",
".",
"exception_to_css",
"error",
",",
"@options",
".",
"merge",
"(",
":full_exception",
"=>",
"true",
")",
"ERB",
".",
"new",
"(",
"IO",
".",
"read",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
"+",
"\"/annotate/template.erb\"",
")",
")",
".",
"result",
"(",
"binding",
")",
"end"
] |
Annotate the named file, returns HTML document.
|
[
"Annotate",
"the",
"named",
"file",
"returns",
"HTML",
"document",
"."
] |
5368d8f15e70b2f3cc6b38872a4685383b119d02
|
https://github.com/assaf/css-annotate/blob/5368d8f15e70b2f3cc6b38872a4685383b119d02/lib/css/annotate.rb#L38-L44
|
8,220
|
assaf/css-annotate
|
lib/css/annotate.rb
|
CSS.Annotate.styles
|
def styles
Sass::Engine.new(IO.read(File.dirname(__FILE__) + "/annotate/style.scss"), :syntax=>:scss).render
end
|
ruby
|
def styles
Sass::Engine.new(IO.read(File.dirname(__FILE__) + "/annotate/style.scss"), :syntax=>:scss).render
end
|
[
"def",
"styles",
"Sass",
"::",
"Engine",
".",
"new",
"(",
"IO",
".",
"read",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
"+",
"\"/annotate/style.scss\"",
")",
",",
":syntax",
"=>",
":scss",
")",
".",
"render",
"end"
] |
ERB template uses this to obtain our own stylesheet.
|
[
"ERB",
"template",
"uses",
"this",
"to",
"obtain",
"our",
"own",
"stylesheet",
"."
] |
5368d8f15e70b2f3cc6b38872a4685383b119d02
|
https://github.com/assaf/css-annotate/blob/5368d8f15e70b2f3cc6b38872a4685383b119d02/lib/css/annotate.rb#L52-L54
|
8,221
|
wapcaplet/kelp
|
lib/kelp/visibility.rb
|
Kelp.Visibility.page_contains?
|
def page_contains?(text_or_regexp)
if text_or_regexp.class == String
return page.has_content?(text_or_regexp)
elsif text_or_regexp.class == Regexp
return page.has_xpath?('.//*', :text => text_or_regexp)
else
raise ArgumentError, "Expected String or Regexp, got #{text_or_regexp.class}"
end
end
|
ruby
|
def page_contains?(text_or_regexp)
if text_or_regexp.class == String
return page.has_content?(text_or_regexp)
elsif text_or_regexp.class == Regexp
return page.has_xpath?('.//*', :text => text_or_regexp)
else
raise ArgumentError, "Expected String or Regexp, got #{text_or_regexp.class}"
end
end
|
[
"def",
"page_contains?",
"(",
"text_or_regexp",
")",
"if",
"text_or_regexp",
".",
"class",
"==",
"String",
"return",
"page",
".",
"has_content?",
"(",
"text_or_regexp",
")",
"elsif",
"text_or_regexp",
".",
"class",
"==",
"Regexp",
"return",
"page",
".",
"has_xpath?",
"(",
"'.//*'",
",",
":text",
"=>",
"text_or_regexp",
")",
"else",
"raise",
"ArgumentError",
",",
"\"Expected String or Regexp, got #{text_or_regexp.class}\"",
"end",
"end"
] |
Return `true` if the current page contains the given text or regular expression,
or `false` if it does not.
@param [String, Regexp] text_or_regexp
Text or regular expression to look for
@raise [ArgumentError]
If the given argument isn't a String or Regexp
@since 0.2.0
|
[
"Return",
"true",
"if",
"the",
"current",
"page",
"contains",
"the",
"given",
"text",
"or",
"regular",
"expression",
"or",
"false",
"if",
"it",
"does",
"not",
"."
] |
592fe188db5a3d05e6120ed2157ad8d781601b7a
|
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/visibility.rb#L26-L34
|
8,222
|
wapcaplet/kelp
|
lib/kelp/visibility.rb
|
Kelp.Visibility.should_see
|
def should_see(texts, scope={})
in_scope(scope) do
texts = [texts] if (texts.class == String || texts.class == Regexp)
# Select all expected values that don't appear on the page
unexpected = texts.select do |text|
!page_contains?(text)
end
if !unexpected.empty?
raise Kelp::Unexpected,
"Expected to see: #{texts.inspect}\nDid not see: #{unexpected.inspect}"
end
end
end
|
ruby
|
def should_see(texts, scope={})
in_scope(scope) do
texts = [texts] if (texts.class == String || texts.class == Regexp)
# Select all expected values that don't appear on the page
unexpected = texts.select do |text|
!page_contains?(text)
end
if !unexpected.empty?
raise Kelp::Unexpected,
"Expected to see: #{texts.inspect}\nDid not see: #{unexpected.inspect}"
end
end
end
|
[
"def",
"should_see",
"(",
"texts",
",",
"scope",
"=",
"{",
"}",
")",
"in_scope",
"(",
"scope",
")",
"do",
"texts",
"=",
"[",
"texts",
"]",
"if",
"(",
"texts",
".",
"class",
"==",
"String",
"||",
"texts",
".",
"class",
"==",
"Regexp",
")",
"# Select all expected values that don't appear on the page",
"unexpected",
"=",
"texts",
".",
"select",
"do",
"|",
"text",
"|",
"!",
"page_contains?",
"(",
"text",
")",
"end",
"if",
"!",
"unexpected",
".",
"empty?",
"raise",
"Kelp",
"::",
"Unexpected",
",",
"\"Expected to see: #{texts.inspect}\\nDid not see: #{unexpected.inspect}\"",
"end",
"end",
"end"
] |
Verify the presence of content on the page. Passes when all the given items
are found on the page, and fails if any of them are not found.
@example
should_see "Animaniacs"
should_see ["Yakko", "Wakko", "Dot"]
should_see "Baloney", :within => "#slacks"
should_see /(Animaney|Totally Insaney|Pinky and the Brainy)/
@param [String, Regexp, Array] texts
Text(s) or regexp(s) to look for
@param [Hash] scope
Scoping keywords as understood by {#in_scope}
@raise [Kelp::Unexpected]
If any of the expected text strings are not seen in the given scope
|
[
"Verify",
"the",
"presence",
"of",
"content",
"on",
"the",
"page",
".",
"Passes",
"when",
"all",
"the",
"given",
"items",
"are",
"found",
"on",
"the",
"page",
"and",
"fails",
"if",
"any",
"of",
"them",
"are",
"not",
"found",
"."
] |
592fe188db5a3d05e6120ed2157ad8d781601b7a
|
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/visibility.rb#L54-L66
|
8,223
|
wapcaplet/kelp
|
lib/kelp/visibility.rb
|
Kelp.Visibility.should_see_in_same_row
|
def should_see_in_same_row(texts, scope={})
in_scope(scope) do
if !page.has_xpath?(xpath_row_containing(texts))
raise Kelp::Unexpected, "Expected, but did not see: #{texts.inspect} in the same row"
end
end
end
|
ruby
|
def should_see_in_same_row(texts, scope={})
in_scope(scope) do
if !page.has_xpath?(xpath_row_containing(texts))
raise Kelp::Unexpected, "Expected, but did not see: #{texts.inspect} in the same row"
end
end
end
|
[
"def",
"should_see_in_same_row",
"(",
"texts",
",",
"scope",
"=",
"{",
"}",
")",
"in_scope",
"(",
"scope",
")",
"do",
"if",
"!",
"page",
".",
"has_xpath?",
"(",
"xpath_row_containing",
"(",
"texts",
")",
")",
"raise",
"Kelp",
"::",
"Unexpected",
",",
"\"Expected, but did not see: #{texts.inspect} in the same row\"",
"end",
"end",
"end"
] |
Verify that all items appear in the same table row. Passes if a `tr`
element exists containing all the given `texts`, and fails if no such
`tr` exists. The texts may be in any order in the row.
@example
should_see_in_same_row ["Yakko", "Rob Paulsen"]
should_see_in_same_row ["Wakko", "Jess Harnell"]
should_see_in_same_row ["Dot", "Tress MacNeille"]
@param [Array] texts
Array of Strings that should appear in the same row
@param [Hash] scope
Scoping keywords as understood by {#in_scope}
@raise [Kelp::Unexpected]
If no row is found containing all strings in `texts`
|
[
"Verify",
"that",
"all",
"items",
"appear",
"in",
"the",
"same",
"table",
"row",
".",
"Passes",
"if",
"a",
"tr",
"element",
"exists",
"containing",
"all",
"the",
"given",
"texts",
"and",
"fails",
"if",
"no",
"such",
"tr",
"exists",
".",
"The",
"texts",
"may",
"be",
"in",
"any",
"order",
"in",
"the",
"row",
"."
] |
592fe188db5a3d05e6120ed2157ad8d781601b7a
|
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/visibility.rb#L112-L118
|
8,224
|
jeremyd/virtualmonkey
|
lib/virtualmonkey/ebs.rb
|
VirtualMonkey.EBS.wait_for_snapshots
|
def wait_for_snapshots
timeout=1500
step=10
while timeout > 0
puts "Checking for snapshot completed"
snapshots = behavior(:find_snapshots)
status= snapshots.map { |x| x.aws_status }
break unless status.include?("pending")
sleep step
timeout -= step
end
raise "FATAL: timed out waiting for all snapshots in lineage #{@lineage} to complete" if timeout == 0
end
|
ruby
|
def wait_for_snapshots
timeout=1500
step=10
while timeout > 0
puts "Checking for snapshot completed"
snapshots = behavior(:find_snapshots)
status= snapshots.map { |x| x.aws_status }
break unless status.include?("pending")
sleep step
timeout -= step
end
raise "FATAL: timed out waiting for all snapshots in lineage #{@lineage} to complete" if timeout == 0
end
|
[
"def",
"wait_for_snapshots",
"timeout",
"=",
"1500",
"step",
"=",
"10",
"while",
"timeout",
">",
"0",
"puts",
"\"Checking for snapshot completed\"",
"snapshots",
"=",
"behavior",
"(",
":find_snapshots",
")",
"status",
"=",
"snapshots",
".",
"map",
"{",
"|",
"x",
"|",
"x",
".",
"aws_status",
"}",
"break",
"unless",
"status",
".",
"include?",
"(",
"\"pending\"",
")",
"sleep",
"step",
"timeout",
"-=",
"step",
"end",
"raise",
"\"FATAL: timed out waiting for all snapshots in lineage #{@lineage} to complete\"",
"if",
"timeout",
"==",
"0",
"end"
] |
take the lineage name, find all snapshots and sleep until none are in the pending state.
|
[
"take",
"the",
"lineage",
"name",
"find",
"all",
"snapshots",
"and",
"sleep",
"until",
"none",
"are",
"in",
"the",
"pending",
"state",
"."
] |
b2c7255f20ac5ec881eb90afbb5e712160db0dcb
|
https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/ebs.rb#L45-L57
|
8,225
|
jeremyd/virtualmonkey
|
lib/virtualmonkey/ebs.rb
|
VirtualMonkey.EBS.find_snapshot_timestamp
|
def find_snapshot_timestamp
last_snap = behavior(:find_snapshots).last
last_snap.tags.detect { |t| t["name"] =~ /timestamp=(\d+)$/ }
timestamp = $1
end
|
ruby
|
def find_snapshot_timestamp
last_snap = behavior(:find_snapshots).last
last_snap.tags.detect { |t| t["name"] =~ /timestamp=(\d+)$/ }
timestamp = $1
end
|
[
"def",
"find_snapshot_timestamp",
"last_snap",
"=",
"behavior",
"(",
":find_snapshots",
")",
".",
"last",
"last_snap",
".",
"tags",
".",
"detect",
"{",
"|",
"t",
"|",
"t",
"[",
"\"name\"",
"]",
"=~",
"/",
"\\d",
"/",
"}",
"timestamp",
"=",
"$1",
"end"
] |
Returns the timestamp of the latest snapshot for testing OPT_DB_RESTORE_TIMESTAMP_OVERRIDE
|
[
"Returns",
"the",
"timestamp",
"of",
"the",
"latest",
"snapshot",
"for",
"testing",
"OPT_DB_RESTORE_TIMESTAMP_OVERRIDE"
] |
b2c7255f20ac5ec881eb90afbb5e712160db0dcb
|
https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/ebs.rb#L70-L74
|
8,226
|
postmodern/open_namespace
|
lib/open_namespace/class_methods.rb
|
OpenNamespace.ClassMethods.require_file
|
def require_file(name)
name = name.to_s
path = File.join(namespace_root,File.expand_path(File.join('',name)))
begin
require path
rescue Gem::LoadError => e
raise(e)
rescue ::LoadError
return nil
end
return true
end
|
ruby
|
def require_file(name)
name = name.to_s
path = File.join(namespace_root,File.expand_path(File.join('',name)))
begin
require path
rescue Gem::LoadError => e
raise(e)
rescue ::LoadError
return nil
end
return true
end
|
[
"def",
"require_file",
"(",
"name",
")",
"name",
"=",
"name",
".",
"to_s",
"path",
"=",
"File",
".",
"join",
"(",
"namespace_root",
",",
"File",
".",
"expand_path",
"(",
"File",
".",
"join",
"(",
"''",
",",
"name",
")",
")",
")",
"begin",
"require",
"path",
"rescue",
"Gem",
"::",
"LoadError",
"=>",
"e",
"raise",
"(",
"e",
")",
"rescue",
"::",
"LoadError",
"return",
"nil",
"end",
"return",
"true",
"end"
] |
Requires the file with the given name, within the namespace root
directory.
@param [Symbol, String] name
The name of the file to require.
@return [true, nil]
Returns `true` if the file was successfully loaded, returns `nil`
on a `LoadError` exception.
@raise [Gem::LoadError]
A dependency needed by the file could not be satisfied by RubyGems.
@since 0.3.0
|
[
"Requires",
"the",
"file",
"with",
"the",
"given",
"name",
"within",
"the",
"namespace",
"root",
"directory",
"."
] |
305e3a794fda6a290faa935098fe528048ffed77
|
https://github.com/postmodern/open_namespace/blob/305e3a794fda6a290faa935098fe528048ffed77/lib/open_namespace/class_methods.rb#L67-L80
|
8,227
|
postmodern/open_namespace
|
lib/open_namespace/class_methods.rb
|
OpenNamespace.ClassMethods.const_defined?
|
def const_defined?(name,*inherit)
if super(name,*inherit)
true
else
# attempt to load the file that might have the constant
require_file(OpenNamespace.const_path(name))
# check for the constant again
return super(name,*inherit)
end
end
|
ruby
|
def const_defined?(name,*inherit)
if super(name,*inherit)
true
else
# attempt to load the file that might have the constant
require_file(OpenNamespace.const_path(name))
# check for the constant again
return super(name,*inherit)
end
end
|
[
"def",
"const_defined?",
"(",
"name",
",",
"*",
"inherit",
")",
"if",
"super",
"(",
"name",
",",
"inherit",
")",
"true",
"else",
"# attempt to load the file that might have the constant",
"require_file",
"(",
"OpenNamespace",
".",
"const_path",
"(",
"name",
")",
")",
"# check for the constant again",
"return",
"super",
"(",
"name",
",",
"inherit",
")",
"end",
"end"
] |
Checks if a constant is defined or attempts loading the constant.
@param [String] name
The name of the constant.
@param [Boolean] inherit
Specifies whether to search the ancestors for the constant.
@return [Boolean]
Specifies whether the constant is defined.
|
[
"Checks",
"if",
"a",
"constant",
"is",
"defined",
"or",
"attempts",
"loading",
"the",
"constant",
"."
] |
305e3a794fda6a290faa935098fe528048ffed77
|
https://github.com/postmodern/open_namespace/blob/305e3a794fda6a290faa935098fe528048ffed77/lib/open_namespace/class_methods.rb#L94-L104
|
8,228
|
maxjacobson/todo_lint
|
lib/todo_lint/todo.rb
|
TodoLint.Todo.relative_path
|
def relative_path
current_dir = Pathname.new(File.expand_path("./"))
Pathname.new(path).relative_path_from(current_dir).to_s
end
|
ruby
|
def relative_path
current_dir = Pathname.new(File.expand_path("./"))
Pathname.new(path).relative_path_from(current_dir).to_s
end
|
[
"def",
"relative_path",
"current_dir",
"=",
"Pathname",
".",
"new",
"(",
"File",
".",
"expand_path",
"(",
"\"./\"",
")",
")",
"Pathname",
".",
"new",
"(",
"path",
")",
".",
"relative_path_from",
"(",
"current_dir",
")",
".",
"to_s",
"end"
] |
Which todo is due sooner?
@example
[todo_one, todo_two].sort # this implicitly calls <=>
@return [Fixnum]
@api public
The relative path to the file where this todo was found
@example
todo.relative #=> "spec/spec_helper.rb"
@return [String]
@api public
|
[
"Which",
"todo",
"is",
"due",
"sooner?"
] |
0d1061383ea205ef4c74edc64568e308ac1af990
|
https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/todo.rb#L179-L182
|
8,229
|
maxjacobson/todo_lint
|
lib/todo_lint/todo.rb
|
TodoLint.Todo.lookup_tag_due_date
|
def lookup_tag_due_date
config.fetch(:tags).fetch(match[:tag])
rescue KeyError
msg = "#{match[:tag]} tag not defined in config file"
raise KeyError, msg
end
|
ruby
|
def lookup_tag_due_date
config.fetch(:tags).fetch(match[:tag])
rescue KeyError
msg = "#{match[:tag]} tag not defined in config file"
raise KeyError, msg
end
|
[
"def",
"lookup_tag_due_date",
"config",
".",
"fetch",
"(",
":tags",
")",
".",
"fetch",
"(",
"match",
"[",
":tag",
"]",
")",
"rescue",
"KeyError",
"msg",
"=",
"\"#{match[:tag]} tag not defined in config file\"",
"raise",
"KeyError",
",",
"msg",
"end"
] |
A tag was referenced, so let's see when that's due
@return [DueDate]
@raise [KeyError] if the tag does not reference a due date in the config
@api private
|
[
"A",
"tag",
"was",
"referenced",
"so",
"let",
"s",
"see",
"when",
"that",
"s",
"due"
] |
0d1061383ea205ef4c74edc64568e308ac1af990
|
https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/todo.rb#L224-L229
|
8,230
|
Deradon/Rdcpu16
|
lib/dcpu16/support/debug.rb
|
DCPU16.Debug.debug
|
def debug(msg = nil, &block)
return unless debug?
puts "\n[DEBUG] - #{caller.first}"
msg.each { |m| puts(m) } if msg.is_a?(Array)
if msg.is_a?(Hash)
msg.each do |k, v|
puts "[#{k.to_s}]"
if v.is_a?(Array)
v.each {|m| puts(m) }
else
puts v
end
end
elsif (msg.is_a?(String) || msg.is_a?(Symbol))
puts msg.to_s
end
yield if block_given?
puts "\n"
end
|
ruby
|
def debug(msg = nil, &block)
return unless debug?
puts "\n[DEBUG] - #{caller.first}"
msg.each { |m| puts(m) } if msg.is_a?(Array)
if msg.is_a?(Hash)
msg.each do |k, v|
puts "[#{k.to_s}]"
if v.is_a?(Array)
v.each {|m| puts(m) }
else
puts v
end
end
elsif (msg.is_a?(String) || msg.is_a?(Symbol))
puts msg.to_s
end
yield if block_given?
puts "\n"
end
|
[
"def",
"debug",
"(",
"msg",
"=",
"nil",
",",
"&",
"block",
")",
"return",
"unless",
"debug?",
"puts",
"\"\\n[DEBUG] - #{caller.first}\"",
"msg",
".",
"each",
"{",
"|",
"m",
"|",
"puts",
"(",
"m",
")",
"}",
"if",
"msg",
".",
"is_a?",
"(",
"Array",
")",
"if",
"msg",
".",
"is_a?",
"(",
"Hash",
")",
"msg",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"puts",
"\"[#{k.to_s}]\"",
"if",
"v",
".",
"is_a?",
"(",
"Array",
")",
"v",
".",
"each",
"{",
"|",
"m",
"|",
"puts",
"(",
"m",
")",
"}",
"else",
"puts",
"v",
"end",
"end",
"elsif",
"(",
"msg",
".",
"is_a?",
"(",
"String",
")",
"||",
"msg",
".",
"is_a?",
"(",
"Symbol",
")",
")",
"puts",
"msg",
".",
"to_s",
"end",
"yield",
"if",
"block_given?",
"puts",
"\"\\n\"",
"end"
] |
Debug-Wrapper
|
[
"Debug",
"-",
"Wrapper"
] |
a4460927aa64c2a514c57993e8ea13f5b48377e9
|
https://github.com/Deradon/Rdcpu16/blob/a4460927aa64c2a514c57993e8ea13f5b48377e9/lib/dcpu16/support/debug.rb#L11-L33
|
8,231
|
sanichi/icu_tournament
|
lib/icu_tournament/result.rb
|
ICU.Result.rateable=
|
def rateable=(rateable)
if opponent.nil?
@rateable = false
return
end
@rateable = case rateable
when nil then true # default is true
when false then false # this is the only way to turn it off
else true
end
end
|
ruby
|
def rateable=(rateable)
if opponent.nil?
@rateable = false
return
end
@rateable = case rateable
when nil then true # default is true
when false then false # this is the only way to turn it off
else true
end
end
|
[
"def",
"rateable",
"=",
"(",
"rateable",
")",
"if",
"opponent",
".",
"nil?",
"@rateable",
"=",
"false",
"return",
"end",
"@rateable",
"=",
"case",
"rateable",
"when",
"nil",
"then",
"true",
"# default is true",
"when",
"false",
"then",
"false",
"# this is the only way to turn it off",
"else",
"true",
"end",
"end"
] |
Rateable flag. If false, result is not rateable. Can only be true if there is an opponent.
|
[
"Rateable",
"flag",
".",
"If",
"false",
"result",
"is",
"not",
"rateable",
".",
"Can",
"only",
"be",
"true",
"if",
"there",
"is",
"an",
"opponent",
"."
] |
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
|
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/result.rb#L142-L152
|
8,232
|
groupdocs-storage-cloud/groupdocs-storage-cloud-ruby
|
lib/GroupDocs/Storage/configuration.rb
|
GroupDocsStorageCloud.Configuration.auth_settings
|
def auth_settings
{
'appsid' =>
{
type: 'api_key',
in: 'query',
key: 'appsid',
value: api_key_with_prefix('appsid')
},
'oauth' =>
{
type: 'oauth2',
in: 'header',
key: 'Authorization',
value: "Bearer #{access_token}"
},
'signature' =>
{
type: 'api_key',
in: 'query',
key: 'signature',
value: api_key_with_prefix('signature')
},
}
end
|
ruby
|
def auth_settings
{
'appsid' =>
{
type: 'api_key',
in: 'query',
key: 'appsid',
value: api_key_with_prefix('appsid')
},
'oauth' =>
{
type: 'oauth2',
in: 'header',
key: 'Authorization',
value: "Bearer #{access_token}"
},
'signature' =>
{
type: 'api_key',
in: 'query',
key: 'signature',
value: api_key_with_prefix('signature')
},
}
end
|
[
"def",
"auth_settings",
"{",
"'appsid'",
"=>",
"{",
"type",
":",
"'api_key'",
",",
"in",
":",
"'query'",
",",
"key",
":",
"'appsid'",
",",
"value",
":",
"api_key_with_prefix",
"(",
"'appsid'",
")",
"}",
",",
"'oauth'",
"=>",
"{",
"type",
":",
"'oauth2'",
",",
"in",
":",
"'header'",
",",
"key",
":",
"'Authorization'",
",",
"value",
":",
"\"Bearer #{access_token}\"",
"}",
",",
"'signature'",
"=>",
"{",
"type",
":",
"'api_key'",
",",
"in",
":",
"'query'",
",",
"key",
":",
"'signature'",
",",
"value",
":",
"api_key_with_prefix",
"(",
"'signature'",
")",
"}",
",",
"}",
"end"
] |
Returns Auth Settings hash for api client.
|
[
"Returns",
"Auth",
"Settings",
"hash",
"for",
"api",
"client",
"."
] |
0820b8b5582ea2a6bc0f5e7f694eb80aad5e67ce
|
https://github.com/groupdocs-storage-cloud/groupdocs-storage-cloud-ruby/blob/0820b8b5582ea2a6bc0f5e7f694eb80aad5e67ce/lib/GroupDocs/Storage/configuration.rb#L177-L201
|
8,233
|
chetan/bixby-common
|
lib/bixby-common/api/http_channel.rb
|
Bixby.HttpChannel.execute_internal
|
def execute_internal(json_request, &block)
if json_request.respond_to?(:headers) then
# always required for posting to API
json_request.headers["Content-Type"] = "application/json"
end
req = HTTPI::Request.new(:url => @uri, :body => json_request.to_wire)
# add in extra headers if we have a SignedJsonRequest (or anything which has additional headers)
if json_request.respond_to? :headers then
req.headers.merge!(json_request.headers)
end
if block then
# execute request with block
req.on_body(&block)
HTTPI.post(req)
return JsonResponse.new("success")
else
# execute normal req, and return parsed response
res = HTTPI.post(req).body
return JsonResponse.from_json(res)
end
end
|
ruby
|
def execute_internal(json_request, &block)
if json_request.respond_to?(:headers) then
# always required for posting to API
json_request.headers["Content-Type"] = "application/json"
end
req = HTTPI::Request.new(:url => @uri, :body => json_request.to_wire)
# add in extra headers if we have a SignedJsonRequest (or anything which has additional headers)
if json_request.respond_to? :headers then
req.headers.merge!(json_request.headers)
end
if block then
# execute request with block
req.on_body(&block)
HTTPI.post(req)
return JsonResponse.new("success")
else
# execute normal req, and return parsed response
res = HTTPI.post(req).body
return JsonResponse.from_json(res)
end
end
|
[
"def",
"execute_internal",
"(",
"json_request",
",",
"&",
"block",
")",
"if",
"json_request",
".",
"respond_to?",
"(",
":headers",
")",
"then",
"# always required for posting to API",
"json_request",
".",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"\"application/json\"",
"end",
"req",
"=",
"HTTPI",
"::",
"Request",
".",
"new",
"(",
":url",
"=>",
"@uri",
",",
":body",
"=>",
"json_request",
".",
"to_wire",
")",
"# add in extra headers if we have a SignedJsonRequest (or anything which has additional headers)",
"if",
"json_request",
".",
"respond_to?",
":headers",
"then",
"req",
".",
"headers",
".",
"merge!",
"(",
"json_request",
".",
"headers",
")",
"end",
"if",
"block",
"then",
"# execute request with block",
"req",
".",
"on_body",
"(",
"block",
")",
"HTTPI",
".",
"post",
"(",
"req",
")",
"return",
"JsonResponse",
".",
"new",
"(",
"\"success\"",
")",
"else",
"# execute normal req, and return parsed response",
"res",
"=",
"HTTPI",
".",
"post",
"(",
"req",
")",
".",
"body",
"return",
"JsonResponse",
".",
"from_json",
"(",
"res",
")",
"end",
"end"
] |
Execute the request, optionally passing a block to handle the response
@param [JsonRequest] json_request
@param [Block] block
@return [JsonResponse] response
|
[
"Execute",
"the",
"request",
"optionally",
"passing",
"a",
"block",
"to",
"handle",
"the",
"response"
] |
3fb8829987b115fc53ec820d97a20b4a8c49b4a2
|
https://github.com/chetan/bixby-common/blob/3fb8829987b115fc53ec820d97a20b4a8c49b4a2/lib/bixby-common/api/http_channel.rb#L40-L67
|
8,234
|
ajeychronus/chronuscop_client
|
lib/chronuscop_client/synchronizer.rb
|
ChronuscopClient.Synchronizer.write_last_update
|
def write_last_update(last_update_at)
# Check for the presence of the tmp directory.
if(! File::directory?("tmp")) then
Dir.mkdir("tmp")
end
f = File.new("tmp/chronuscop.tmp","w")
f.printf("%d",last_update_at.to_i)
f.close()
end
|
ruby
|
def write_last_update(last_update_at)
# Check for the presence of the tmp directory.
if(! File::directory?("tmp")) then
Dir.mkdir("tmp")
end
f = File.new("tmp/chronuscop.tmp","w")
f.printf("%d",last_update_at.to_i)
f.close()
end
|
[
"def",
"write_last_update",
"(",
"last_update_at",
")",
"# Check for the presence of the tmp directory.",
"if",
"(",
"!",
"File",
"::",
"directory?",
"(",
"\"tmp\"",
")",
")",
"then",
"Dir",
".",
"mkdir",
"(",
"\"tmp\"",
")",
"end",
"f",
"=",
"File",
".",
"new",
"(",
"\"tmp/chronuscop.tmp\"",
",",
"\"w\"",
")",
"f",
".",
"printf",
"(",
"\"%d\"",
",",
"last_update_at",
".",
"to_i",
")",
"f",
".",
"close",
"(",
")",
"end"
] |
Function to write the last update time to a temporary file.
|
[
"Function",
"to",
"write",
"the",
"last",
"update",
"time",
"to",
"a",
"temporary",
"file",
"."
] |
17834beba5215b122b399f145f8710da03ff7a0a
|
https://github.com/ajeychronus/chronuscop_client/blob/17834beba5215b122b399f145f8710da03ff7a0a/lib/chronuscop_client/synchronizer.rb#L19-L28
|
8,235
|
ajeychronus/chronuscop_client
|
lib/chronuscop_client/synchronizer.rb
|
ChronuscopClient.Synchronizer.xml_time_to_integer
|
def xml_time_to_integer(str)
arr = str.gsub(/T|Z|:/,"-").split(/-/)
year = arr[0]
month = arr[1]
day = arr[2]
hour = arr[3]
min = arr[4]
sec = arr[5]
Time.utc(year,month,day,hour,min,sec).to_i
end
|
ruby
|
def xml_time_to_integer(str)
arr = str.gsub(/T|Z|:/,"-").split(/-/)
year = arr[0]
month = arr[1]
day = arr[2]
hour = arr[3]
min = arr[4]
sec = arr[5]
Time.utc(year,month,day,hour,min,sec).to_i
end
|
[
"def",
"xml_time_to_integer",
"(",
"str",
")",
"arr",
"=",
"str",
".",
"gsub",
"(",
"/",
"/",
",",
"\"-\"",
")",
".",
"split",
"(",
"/",
"/",
")",
"year",
"=",
"arr",
"[",
"0",
"]",
"month",
"=",
"arr",
"[",
"1",
"]",
"day",
"=",
"arr",
"[",
"2",
"]",
"hour",
"=",
"arr",
"[",
"3",
"]",
"min",
"=",
"arr",
"[",
"4",
"]",
"sec",
"=",
"arr",
"[",
"5",
"]",
"Time",
".",
"utc",
"(",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"min",
",",
"sec",
")",
".",
"to_i",
"end"
] |
To convert xml_time received from the server to integer.
|
[
"To",
"convert",
"xml_time",
"received",
"from",
"the",
"server",
"to",
"integer",
"."
] |
17834beba5215b122b399f145f8710da03ff7a0a
|
https://github.com/ajeychronus/chronuscop_client/blob/17834beba5215b122b399f145f8710da03ff7a0a/lib/chronuscop_client/synchronizer.rb#L58-L67
|
8,236
|
ajeychronus/chronuscop_client
|
lib/chronuscop_client/synchronizer.rb
|
ChronuscopClient.Synchronizer.sync_it_now
|
def sync_it_now
puts "Attempt Sync"
# Getting the last sync value.
last_update_at = get_last_update_at
# querying the page.
page = @mechanize_agent.get("#{ChronuscopClient.configuration_object.chronuscop_server_address}/projects/#{ChronuscopClient.configuration_object.project_number}/translations.xml/?auth_token=#{ChronuscopClient.configuration_object.api_token}&last_update_at=#{last_update_at}")
# converting the returned xml page into a hash.
words_hash = XmlSimple.xml_in(page.body)
# catching the case when no-translations are returned.
if(!words_hash) then
puts "Nothing new added."
return
end
# collecting the translations array.
all_translations = words_hash["translation"]
# catching the case when no-translations are returned.
if(!all_translations) then
puts "Nothing new added."
return
end
all_translations.each do |t|
# Inserting into the redis store.
@redis_agent.set "#{t["key"]}","#{t["value"]}"
# Bad hack used here. Should fix this.
str = t["updated-at"][0]["content"]
key_updated_at = xml_time_to_integer(str)
# Updating the value last_update_at
if(key_updated_at > last_update_at) then
last_update_at = key_updated_at
end
end
# Writing the value of last_update_at to the file.
write_last_update(last_update_at.to_i)
puts "Finished synchronizing !!!"
end
|
ruby
|
def sync_it_now
puts "Attempt Sync"
# Getting the last sync value.
last_update_at = get_last_update_at
# querying the page.
page = @mechanize_agent.get("#{ChronuscopClient.configuration_object.chronuscop_server_address}/projects/#{ChronuscopClient.configuration_object.project_number}/translations.xml/?auth_token=#{ChronuscopClient.configuration_object.api_token}&last_update_at=#{last_update_at}")
# converting the returned xml page into a hash.
words_hash = XmlSimple.xml_in(page.body)
# catching the case when no-translations are returned.
if(!words_hash) then
puts "Nothing new added."
return
end
# collecting the translations array.
all_translations = words_hash["translation"]
# catching the case when no-translations are returned.
if(!all_translations) then
puts "Nothing new added."
return
end
all_translations.each do |t|
# Inserting into the redis store.
@redis_agent.set "#{t["key"]}","#{t["value"]}"
# Bad hack used here. Should fix this.
str = t["updated-at"][0]["content"]
key_updated_at = xml_time_to_integer(str)
# Updating the value last_update_at
if(key_updated_at > last_update_at) then
last_update_at = key_updated_at
end
end
# Writing the value of last_update_at to the file.
write_last_update(last_update_at.to_i)
puts "Finished synchronizing !!!"
end
|
[
"def",
"sync_it_now",
"puts",
"\"Attempt Sync\"",
"# Getting the last sync value.",
"last_update_at",
"=",
"get_last_update_at",
"# querying the page.",
"page",
"=",
"@mechanize_agent",
".",
"get",
"(",
"\"#{ChronuscopClient.configuration_object.chronuscop_server_address}/projects/#{ChronuscopClient.configuration_object.project_number}/translations.xml/?auth_token=#{ChronuscopClient.configuration_object.api_token}&last_update_at=#{last_update_at}\"",
")",
"# converting the returned xml page into a hash.",
"words_hash",
"=",
"XmlSimple",
".",
"xml_in",
"(",
"page",
".",
"body",
")",
"# catching the case when no-translations are returned.",
"if",
"(",
"!",
"words_hash",
")",
"then",
"puts",
"\"Nothing new added.\"",
"return",
"end",
"# collecting the translations array.",
"all_translations",
"=",
"words_hash",
"[",
"\"translation\"",
"]",
"# catching the case when no-translations are returned.",
"if",
"(",
"!",
"all_translations",
")",
"then",
"puts",
"\"Nothing new added.\"",
"return",
"end",
"all_translations",
".",
"each",
"do",
"|",
"t",
"|",
"# Inserting into the redis store.",
"@redis_agent",
".",
"set",
"\"#{t[\"key\"]}\"",
",",
"\"#{t[\"value\"]}\"",
"# Bad hack used here. Should fix this.",
"str",
"=",
"t",
"[",
"\"updated-at\"",
"]",
"[",
"0",
"]",
"[",
"\"content\"",
"]",
"key_updated_at",
"=",
"xml_time_to_integer",
"(",
"str",
")",
"# Updating the value last_update_at",
"if",
"(",
"key_updated_at",
">",
"last_update_at",
")",
"then",
"last_update_at",
"=",
"key_updated_at",
"end",
"end",
"# Writing the value of last_update_at to the file.",
"write_last_update",
"(",
"last_update_at",
".",
"to_i",
")",
"puts",
"\"Finished synchronizing !!!\"",
"end"
] |
This method keeps the remote-keys and the local-keys synchronized.
This method should be called only after initializing the configuration
object as it uses those configuration values.
|
[
"This",
"method",
"keeps",
"the",
"remote",
"-",
"keys",
"and",
"the",
"local",
"-",
"keys",
"synchronized",
".",
"This",
"method",
"should",
"be",
"called",
"only",
"after",
"initializing",
"the",
"configuration",
"object",
"as",
"it",
"uses",
"those",
"configuration",
"values",
"."
] |
17834beba5215b122b399f145f8710da03ff7a0a
|
https://github.com/ajeychronus/chronuscop_client/blob/17834beba5215b122b399f145f8710da03ff7a0a/lib/chronuscop_client/synchronizer.rb#L74-L120
|
8,237
|
agilecreativity/vim_printer
|
lib/vim_printer/cli.rb
|
VimPrinter.CLI.get_input_files
|
def get_input_files(args = {})
command = args.fetch(:command, nil)
if command.nil?
CodeLister.files(args)
else
# Note: base_dir must be the the same the directory where the command is executed from
CodeLister.files_from_shell(command, args.fetch(:base_dir, "."))
end
end
|
ruby
|
def get_input_files(args = {})
command = args.fetch(:command, nil)
if command.nil?
CodeLister.files(args)
else
# Note: base_dir must be the the same the directory where the command is executed from
CodeLister.files_from_shell(command, args.fetch(:base_dir, "."))
end
end
|
[
"def",
"get_input_files",
"(",
"args",
"=",
"{",
"}",
")",
"command",
"=",
"args",
".",
"fetch",
"(",
":command",
",",
"nil",
")",
"if",
"command",
".",
"nil?",
"CodeLister",
".",
"files",
"(",
"args",
")",
"else",
"# Note: base_dir must be the the same the directory where the command is executed from",
"CodeLister",
".",
"files_from_shell",
"(",
"command",
",",
"args",
".",
"fetch",
"(",
":base_dir",
",",
"\".\"",
")",
")",
"end",
"end"
] |
Get the list of input file
@param [Hash<Symbol, Object>] args the input options
@option args [String] :command the shell command to be used to get list of files
@return [Array<String>] list of files in the format
["./Gemfile", "./lib/vim_printer/cli.rb", ..]
|
[
"Get",
"the",
"list",
"of",
"input",
"file"
] |
4ac22ca6034da299ffd2f6f8fb6c1b6efbc59206
|
https://github.com/agilecreativity/vim_printer/blob/4ac22ca6034da299ffd2f6f8fb6c1b6efbc59206/lib/vim_printer/cli.rb#L84-L92
|
8,238
|
agilecreativity/vim_printer
|
lib/vim_printer/cli.rb
|
VimPrinter.CLI.execute
|
def execute(options = {})
input_files = get_input_files(options)
# we want to avoid printing the binary file
input_files.delete_if do |file|
File.binary?(file.gsub(/^\./, options[:base_dir]))
end
if input_files.empty?
puts "No file found for your option: #{options}"
return
end
to_htmls(input_files, options)
generated_files = input_files.map { |f| "#{f}.xhtml" }
index_file = "./index.html"
IndexHtml.htmlify generated_files, base_dir: options[:base_dir],
output: index_file,
drop_ext: true
generated_files << index_file if options[:index]
output_file = "vim_printer_#{File.basename(File.expand_path(options[:base_dir]))}.tar.gz"
AgileUtils::FileUtil.tar_gzip_files(generated_files, output_file)
AgileUtils::FileUtil.delete(generated_files)
FileUtils.rm_rf(index_file) if options[:index]
puts "Your output file is '#{File.absolute_path(output_file)}'"
end
|
ruby
|
def execute(options = {})
input_files = get_input_files(options)
# we want to avoid printing the binary file
input_files.delete_if do |file|
File.binary?(file.gsub(/^\./, options[:base_dir]))
end
if input_files.empty?
puts "No file found for your option: #{options}"
return
end
to_htmls(input_files, options)
generated_files = input_files.map { |f| "#{f}.xhtml" }
index_file = "./index.html"
IndexHtml.htmlify generated_files, base_dir: options[:base_dir],
output: index_file,
drop_ext: true
generated_files << index_file if options[:index]
output_file = "vim_printer_#{File.basename(File.expand_path(options[:base_dir]))}.tar.gz"
AgileUtils::FileUtil.tar_gzip_files(generated_files, output_file)
AgileUtils::FileUtil.delete(generated_files)
FileUtils.rm_rf(index_file) if options[:index]
puts "Your output file is '#{File.absolute_path(output_file)}'"
end
|
[
"def",
"execute",
"(",
"options",
"=",
"{",
"}",
")",
"input_files",
"=",
"get_input_files",
"(",
"options",
")",
"# we want to avoid printing the binary file",
"input_files",
".",
"delete_if",
"do",
"|",
"file",
"|",
"File",
".",
"binary?",
"(",
"file",
".",
"gsub",
"(",
"/",
"\\.",
"/",
",",
"options",
"[",
":base_dir",
"]",
")",
")",
"end",
"if",
"input_files",
".",
"empty?",
"puts",
"\"No file found for your option: #{options}\"",
"return",
"end",
"to_htmls",
"(",
"input_files",
",",
"options",
")",
"generated_files",
"=",
"input_files",
".",
"map",
"{",
"|",
"f",
"|",
"\"#{f}.xhtml\"",
"}",
"index_file",
"=",
"\"./index.html\"",
"IndexHtml",
".",
"htmlify",
"generated_files",
",",
"base_dir",
":",
"options",
"[",
":base_dir",
"]",
",",
"output",
":",
"index_file",
",",
"drop_ext",
":",
"true",
"generated_files",
"<<",
"index_file",
"if",
"options",
"[",
":index",
"]",
"output_file",
"=",
"\"vim_printer_#{File.basename(File.expand_path(options[:base_dir]))}.tar.gz\"",
"AgileUtils",
"::",
"FileUtil",
".",
"tar_gzip_files",
"(",
"generated_files",
",",
"output_file",
")",
"AgileUtils",
"::",
"FileUtil",
".",
"delete",
"(",
"generated_files",
")",
"FileUtils",
".",
"rm_rf",
"(",
"index_file",
")",
"if",
"options",
"[",
":index",
"]",
"puts",
"\"Your output file is '#{File.absolute_path(output_file)}'\"",
"end"
] |
Main entry point to export the code
@param [Hash<Symbol, Object>] options the options argument
|
[
"Main",
"entry",
"point",
"to",
"export",
"the",
"code"
] |
4ac22ca6034da299ffd2f6f8fb6c1b6efbc59206
|
https://github.com/agilecreativity/vim_printer/blob/4ac22ca6034da299ffd2f6f8fb6c1b6efbc59206/lib/vim_printer/cli.rb#L97-L121
|
8,239
|
agilecreativity/vim_printer
|
lib/vim_printer/cli.rb
|
VimPrinter.CLI.to_htmls
|
def to_htmls(files, options = {})
FileUtils.chdir(File.expand_path(options[:base_dir]))
files.each_with_index do |file, index|
puts "FYI: process file #{index + 1} of #{files.size} : #{file}"
to_html(file, options)
end
end
|
ruby
|
def to_htmls(files, options = {})
FileUtils.chdir(File.expand_path(options[:base_dir]))
files.each_with_index do |file, index|
puts "FYI: process file #{index + 1} of #{files.size} : #{file}"
to_html(file, options)
end
end
|
[
"def",
"to_htmls",
"(",
"files",
",",
"options",
"=",
"{",
"}",
")",
"FileUtils",
".",
"chdir",
"(",
"File",
".",
"expand_path",
"(",
"options",
"[",
":base_dir",
"]",
")",
")",
"files",
".",
"each_with_index",
"do",
"|",
"file",
",",
"index",
"|",
"puts",
"\"FYI: process file #{index + 1} of #{files.size} : #{file}\"",
"to_html",
"(",
"file",
",",
"options",
")",
"end",
"end"
] |
convert multiple files to html
|
[
"convert",
"multiple",
"files",
"to",
"html"
] |
4ac22ca6034da299ffd2f6f8fb6c1b6efbc59206
|
https://github.com/agilecreativity/vim_printer/blob/4ac22ca6034da299ffd2f6f8fb6c1b6efbc59206/lib/vim_printer/cli.rb#L124-L130
|
8,240
|
kylegrantlucas/takeout
|
lib/takeout/client.rb
|
Takeout.Client.substitute_template_values
|
def substitute_template_values(endpoint, request_type, options={})
# Gets the proper template for the give CUSTOM_SCHEMA string for this endpoint and substitutes value for it based on give options
endpoint_templates = @schemas.fetch(request_type.to_sym, nil)
template = endpoint_templates.fetch(endpoint.to_sym, nil) if endpoint_templates
if template
extracted_options, options = extract_template_options(options.merge({endpoint: endpoint}), template)
# Render out the template
rendered_template = Liquid::Template.parse(template).render(extracted_options)
end
return rendered_template, options
end
|
ruby
|
def substitute_template_values(endpoint, request_type, options={})
# Gets the proper template for the give CUSTOM_SCHEMA string for this endpoint and substitutes value for it based on give options
endpoint_templates = @schemas.fetch(request_type.to_sym, nil)
template = endpoint_templates.fetch(endpoint.to_sym, nil) if endpoint_templates
if template
extracted_options, options = extract_template_options(options.merge({endpoint: endpoint}), template)
# Render out the template
rendered_template = Liquid::Template.parse(template).render(extracted_options)
end
return rendered_template, options
end
|
[
"def",
"substitute_template_values",
"(",
"endpoint",
",",
"request_type",
",",
"options",
"=",
"{",
"}",
")",
"# Gets the proper template for the give CUSTOM_SCHEMA string for this endpoint and substitutes value for it based on give options",
"endpoint_templates",
"=",
"@schemas",
".",
"fetch",
"(",
"request_type",
".",
"to_sym",
",",
"nil",
")",
"template",
"=",
"endpoint_templates",
".",
"fetch",
"(",
"endpoint",
".",
"to_sym",
",",
"nil",
")",
"if",
"endpoint_templates",
"if",
"template",
"extracted_options",
",",
"options",
"=",
"extract_template_options",
"(",
"options",
".",
"merge",
"(",
"{",
"endpoint",
":",
"endpoint",
"}",
")",
",",
"template",
")",
"# Render out the template",
"rendered_template",
"=",
"Liquid",
"::",
"Template",
".",
"parse",
"(",
"template",
")",
".",
"render",
"(",
"extracted_options",
")",
"end",
"return",
"rendered_template",
",",
"options",
"end"
] |
Render out the template values and return the updated options hash
@param [String] endpoint
@param [String] request_type
@param [Hash] options
@return [String] rendered_template
@return [Hash] options
|
[
"Render",
"out",
"the",
"template",
"values",
"and",
"return",
"the",
"updated",
"options",
"hash"
] |
c6ac62e5c0bcd2a33be6a2657dfc2ae1c1e712df
|
https://github.com/kylegrantlucas/takeout/blob/c6ac62e5c0bcd2a33be6a2657dfc2ae1c1e712df/lib/takeout/client.rb#L90-L102
|
8,241
|
pdorrell/regenerate
|
lib/regenerate/site-regenerator.rb
|
Regenerate.SiteRegenerator.copySrcToOutputFile
|
def copySrcToOutputFile(srcFile, outFile, makeBackup)
if makeBackup
makeBackupFile(outFile)
end
FileUtils.cp(srcFile, outFile, :verbose => true)
end
|
ruby
|
def copySrcToOutputFile(srcFile, outFile, makeBackup)
if makeBackup
makeBackupFile(outFile)
end
FileUtils.cp(srcFile, outFile, :verbose => true)
end
|
[
"def",
"copySrcToOutputFile",
"(",
"srcFile",
",",
"outFile",
",",
"makeBackup",
")",
"if",
"makeBackup",
"makeBackupFile",
"(",
"outFile",
")",
"end",
"FileUtils",
".",
"cp",
"(",
"srcFile",
",",
"outFile",
",",
":verbose",
"=>",
"true",
")",
"end"
] |
Copy a source file directly to an output file
|
[
"Copy",
"a",
"source",
"file",
"directly",
"to",
"an",
"output",
"file"
] |
31f3beb3ff9b45384a90f20fed61be20f39da0d4
|
https://github.com/pdorrell/regenerate/blob/31f3beb3ff9b45384a90f20fed61be20f39da0d4/lib/regenerate/site-regenerator.rb#L87-L92
|
8,242
|
niyireth/brownpapertickets
|
lib/brownpapertickets/httpost.rb
|
BrownPaperTickets.Httpost.handle_deflation
|
def handle_deflation
case last_response["content-encoding"]
when "gzip"
body_io = StringIO.new(last_response.body)
last_response.body.replace Zlib::GzipReader.new(body_io).read
when "deflate"
last_response.body.replace Zlib::Inflate.inflate(last_response.body)
end
end
|
ruby
|
def handle_deflation
case last_response["content-encoding"]
when "gzip"
body_io = StringIO.new(last_response.body)
last_response.body.replace Zlib::GzipReader.new(body_io).read
when "deflate"
last_response.body.replace Zlib::Inflate.inflate(last_response.body)
end
end
|
[
"def",
"handle_deflation",
"case",
"last_response",
"[",
"\"content-encoding\"",
"]",
"when",
"\"gzip\"",
"body_io",
"=",
"StringIO",
".",
"new",
"(",
"last_response",
".",
"body",
")",
"last_response",
".",
"body",
".",
"replace",
"Zlib",
"::",
"GzipReader",
".",
"new",
"(",
"body_io",
")",
".",
"read",
"when",
"\"deflate\"",
"last_response",
".",
"body",
".",
"replace",
"Zlib",
"::",
"Inflate",
".",
"inflate",
"(",
"last_response",
".",
"body",
")",
"end",
"end"
] |
Inspired by Ruby 1.9
|
[
"Inspired",
"by",
"Ruby",
"1",
".",
"9"
] |
1eae1dc6f02b183c55090b79a62023e0f572fb57
|
https://github.com/niyireth/brownpapertickets/blob/1eae1dc6f02b183c55090b79a62023e0f572fb57/lib/brownpapertickets/httpost.rb#L169-L177
|
8,243
|
nragaz/timely
|
lib/timely/cell.rb
|
Timely.Cell.value_from_redis
|
def value_from_redis
if val = Timely.redis.hget(redis_hash_key, redis_value_key)
val = val.include?(".") ? val.to_f : val.to_i
else
val = value_without_caching
Timely.redis.hset(redis_hash_key, redis_value_key, val)
end
val
end
|
ruby
|
def value_from_redis
if val = Timely.redis.hget(redis_hash_key, redis_value_key)
val = val.include?(".") ? val.to_f : val.to_i
else
val = value_without_caching
Timely.redis.hset(redis_hash_key, redis_value_key, val)
end
val
end
|
[
"def",
"value_from_redis",
"if",
"val",
"=",
"Timely",
".",
"redis",
".",
"hget",
"(",
"redis_hash_key",
",",
"redis_value_key",
")",
"val",
"=",
"val",
".",
"include?",
"(",
"\".\"",
")",
"?",
"val",
".",
"to_f",
":",
"val",
".",
"to_i",
"else",
"val",
"=",
"value_without_caching",
"Timely",
".",
"redis",
".",
"hset",
"(",
"redis_hash_key",
",",
"redis_value_key",
",",
"val",
")",
"end",
"val",
"end"
] |
retrieve a cached value from a redis hash.
hashes are accessed using the report title and row title. values within
the hash are keyed using the column's start/end timestamps
|
[
"retrieve",
"a",
"cached",
"value",
"from",
"a",
"redis",
"hash",
"."
] |
768c15630b2d4b28a96d3f89307175f058b32374
|
https://github.com/nragaz/timely/blob/768c15630b2d4b28a96d3f89307175f058b32374/lib/timely/cell.rb#L59-L68
|
8,244
|
marcbowes/UsingYAML
|
lib/using_yaml.rb
|
UsingYAML.ClassMethods.using_yaml
|
def using_yaml(*args)
# Include the instance methods which provide accessors and
# mutators for reading/writing from/to the YAML objects.
include InstanceMethods
# Each argument is either a filename or a :path option
args.each do |arg|
case arg
when Symbol, String
# Define accessors for this file
using_yaml_file(arg.to_s)
when Hash
# Currently only accepts { :path => ... }
next unless arg.size == 1 && arg.keys.first == :path
# Take note of the path
UsingYAML.path = [self.inspect, arg.values.first]
end
end
end
|
ruby
|
def using_yaml(*args)
# Include the instance methods which provide accessors and
# mutators for reading/writing from/to the YAML objects.
include InstanceMethods
# Each argument is either a filename or a :path option
args.each do |arg|
case arg
when Symbol, String
# Define accessors for this file
using_yaml_file(arg.to_s)
when Hash
# Currently only accepts { :path => ... }
next unless arg.size == 1 && arg.keys.first == :path
# Take note of the path
UsingYAML.path = [self.inspect, arg.values.first]
end
end
end
|
[
"def",
"using_yaml",
"(",
"*",
"args",
")",
"# Include the instance methods which provide accessors and",
"# mutators for reading/writing from/to the YAML objects.",
"include",
"InstanceMethods",
"# Each argument is either a filename or a :path option",
"args",
".",
"each",
"do",
"|",
"arg",
"|",
"case",
"arg",
"when",
"Symbol",
",",
"String",
"# Define accessors for this file",
"using_yaml_file",
"(",
"arg",
".",
"to_s",
")",
"when",
"Hash",
"# Currently only accepts { :path => ... }",
"next",
"unless",
"arg",
".",
"size",
"==",
"1",
"&&",
"arg",
".",
"keys",
".",
"first",
"==",
":path",
"# Take note of the path",
"UsingYAML",
".",
"path",
"=",
"[",
"self",
".",
"inspect",
",",
"arg",
".",
"values",
".",
"first",
"]",
"end",
"end",
"end"
] |
Used to configure UsingYAML for a class by defining what files
should be loaded and from where.
include UsingYAML
using_yaml :foo, :bar, :path => "/some/where"
+args+ can contain either filenames or a hash which specifices a
path which contains the corresponding files.
The value of :path must either be a string or Proc (see
+using_yaml_path+ for more information on overriding paths).
|
[
"Used",
"to",
"configure",
"UsingYAML",
"for",
"a",
"class",
"by",
"defining",
"what",
"files",
"should",
"be",
"loaded",
"and",
"from",
"where",
"."
] |
4485476ad0ad14850d41c8ed61673f7b08b9f007
|
https://github.com/marcbowes/UsingYAML/blob/4485476ad0ad14850d41c8ed61673f7b08b9f007/lib/using_yaml.rb#L100-L119
|
8,245
|
device-independent/restless_router
|
lib/restless_router/route.rb
|
RestlessRouter.Route.url_for
|
def url_for(options={})
if templated?
template = Addressable::Template.new(base_path)
template = template.expand(options)
template.to_s
else
base_path
end
end
|
ruby
|
def url_for(options={})
if templated?
template = Addressable::Template.new(base_path)
template = template.expand(options)
template.to_s
else
base_path
end
end
|
[
"def",
"url_for",
"(",
"options",
"=",
"{",
"}",
")",
"if",
"templated?",
"template",
"=",
"Addressable",
"::",
"Template",
".",
"new",
"(",
"base_path",
")",
"template",
"=",
"template",
".",
"expand",
"(",
"options",
")",
"template",
".",
"to_s",
"else",
"base_path",
"end",
"end"
] |
Returns the URL for the route. If it's templated,
then we utilize the provided options hash to expand
the route. Otherwise we return the `path`
@return [String] The templated or base URI
|
[
"Returns",
"the",
"URL",
"for",
"the",
"route",
".",
"If",
"it",
"s",
"templated",
"then",
"we",
"utilize",
"the",
"provided",
"options",
"hash",
"to",
"expand",
"the",
"route",
".",
"Otherwise",
"we",
"return",
"the",
"path"
] |
c20ea03ec53b889d192393c7ab18bcacb0b5e46f
|
https://github.com/device-independent/restless_router/blob/c20ea03ec53b889d192393c7ab18bcacb0b5e46f/lib/restless_router/route.rb#L63-L71
|
8,246
|
mnipper/serket
|
lib/serket/field_decrypter.rb
|
Serket.FieldDecrypter.decrypt
|
def decrypt(field)
return if field !~ /\S/
iv, encrypted_aes_key, encrypted_text = parse(field)
private_key = OpenSSL::PKey::RSA.new(File.read(private_key_filepath))
decrypted_aes_key = private_key.private_decrypt(Base64.decode64(encrypted_aes_key))
decrypted_field = decrypt_data(iv, decrypted_aes_key, encrypted_text)
decrypted_field.force_encoding(encoding)
end
|
ruby
|
def decrypt(field)
return if field !~ /\S/
iv, encrypted_aes_key, encrypted_text = parse(field)
private_key = OpenSSL::PKey::RSA.new(File.read(private_key_filepath))
decrypted_aes_key = private_key.private_decrypt(Base64.decode64(encrypted_aes_key))
decrypted_field = decrypt_data(iv, decrypted_aes_key, encrypted_text)
decrypted_field.force_encoding(encoding)
end
|
[
"def",
"decrypt",
"(",
"field",
")",
"return",
"if",
"field",
"!~",
"/",
"\\S",
"/",
"iv",
",",
"encrypted_aes_key",
",",
"encrypted_text",
"=",
"parse",
"(",
"field",
")",
"private_key",
"=",
"OpenSSL",
"::",
"PKey",
"::",
"RSA",
".",
"new",
"(",
"File",
".",
"read",
"(",
"private_key_filepath",
")",
")",
"decrypted_aes_key",
"=",
"private_key",
".",
"private_decrypt",
"(",
"Base64",
".",
"decode64",
"(",
"encrypted_aes_key",
")",
")",
"decrypted_field",
"=",
"decrypt_data",
"(",
"iv",
",",
"decrypted_aes_key",
",",
"encrypted_text",
")",
"decrypted_field",
".",
"force_encoding",
"(",
"encoding",
")",
"end"
] |
Decrypt the provided cipher text, and return the plaintext
Return nil if whitespace
|
[
"Decrypt",
"the",
"provided",
"cipher",
"text",
"and",
"return",
"the",
"plaintext",
"Return",
"nil",
"if",
"whitespace"
] |
a4606071fde8982d794ff1f8fc09c399ac92ba17
|
https://github.com/mnipper/serket/blob/a4606071fde8982d794ff1f8fc09c399ac92ba17/lib/serket/field_decrypter.rb#L22-L29
|
8,247
|
mnipper/serket
|
lib/serket/field_decrypter.rb
|
Serket.FieldDecrypter.parse
|
def parse(field)
case @format
when :delimited
field.split(field_delimiter)
when :json
parsed = JSON.parse(field)
[parsed['iv'], parsed['key'], parsed['message']]
end
end
|
ruby
|
def parse(field)
case @format
when :delimited
field.split(field_delimiter)
when :json
parsed = JSON.parse(field)
[parsed['iv'], parsed['key'], parsed['message']]
end
end
|
[
"def",
"parse",
"(",
"field",
")",
"case",
"@format",
"when",
":delimited",
"field",
".",
"split",
"(",
"field_delimiter",
")",
"when",
":json",
"parsed",
"=",
"JSON",
".",
"parse",
"(",
"field",
")",
"[",
"parsed",
"[",
"'iv'",
"]",
",",
"parsed",
"[",
"'key'",
"]",
",",
"parsed",
"[",
"'message'",
"]",
"]",
"end",
"end"
] |
Extracts the initialization vector, encrypted key, and
cipher text according to the specified format.
delimited:
* Expected format: iv::encrypted-key::ciphertext
json:
* Expected keys: iv, key, message
|
[
"Extracts",
"the",
"initialization",
"vector",
"encrypted",
"key",
"and",
"cipher",
"text",
"according",
"to",
"the",
"specified",
"format",
"."
] |
a4606071fde8982d794ff1f8fc09c399ac92ba17
|
https://github.com/mnipper/serket/blob/a4606071fde8982d794ff1f8fc09c399ac92ba17/lib/serket/field_decrypter.rb#L59-L67
|
8,248
|
tonytonyjan/tj-bootstrap-helper
|
lib/tj_bootstrap_helper/helper.rb
|
TJBootstrapHelper.Helper.page_header
|
def page_header *args, &block
if block_given?
size = (1..6) === args.first ? args.first : 1
content_tag :div, :class => "page-header" do
content_tag "h#{size}" do
capture(&block)
end
end
else
title = args.first
size = (1..6) === args.second ? args.second : 1
content_tag :div, content_tag("h#{size}", title), :class => "page-header"
end
end
|
ruby
|
def page_header *args, &block
if block_given?
size = (1..6) === args.first ? args.first : 1
content_tag :div, :class => "page-header" do
content_tag "h#{size}" do
capture(&block)
end
end
else
title = args.first
size = (1..6) === args.second ? args.second : 1
content_tag :div, content_tag("h#{size}", title), :class => "page-header"
end
end
|
[
"def",
"page_header",
"*",
"args",
",",
"&",
"block",
"if",
"block_given?",
"size",
"=",
"(",
"1",
"..",
"6",
")",
"===",
"args",
".",
"first",
"?",
"args",
".",
"first",
":",
"1",
"content_tag",
":div",
",",
":class",
"=>",
"\"page-header\"",
"do",
"content_tag",
"\"h#{size}\"",
"do",
"capture",
"(",
"block",
")",
"end",
"end",
"else",
"title",
"=",
"args",
".",
"first",
"size",
"=",
"(",
"1",
"..",
"6",
")",
"===",
"args",
".",
"second",
"?",
"args",
".",
"second",
":",
"1",
"content_tag",
":div",
",",
"content_tag",
"(",
"\"h#{size}\"",
",",
"title",
")",
",",
":class",
"=>",
"\"page-header\"",
"end",
"end"
] |
title, size = 1
size = 1, &block
|
[
"title",
"size",
"=",
"1"
] |
a11c104b8caf582a28a0a903ae4ea9ee200aca75
|
https://github.com/tonytonyjan/tj-bootstrap-helper/blob/a11c104b8caf582a28a0a903ae4ea9ee200aca75/lib/tj_bootstrap_helper/helper.rb#L25-L38
|
8,249
|
tonytonyjan/tj-bootstrap-helper
|
lib/tj_bootstrap_helper/helper.rb
|
TJBootstrapHelper.Helper.nav_li
|
def nav_li *args, &block
options = (block_given? ? args.first : args.second) || {}
url = url_for(options)
active = "active" if url == request.path || url == request.url
content_tag :li, :class => active do
link_to *args, &block
end
end
|
ruby
|
def nav_li *args, &block
options = (block_given? ? args.first : args.second) || {}
url = url_for(options)
active = "active" if url == request.path || url == request.url
content_tag :li, :class => active do
link_to *args, &block
end
end
|
[
"def",
"nav_li",
"*",
"args",
",",
"&",
"block",
"options",
"=",
"(",
"block_given?",
"?",
"args",
".",
"first",
":",
"args",
".",
"second",
")",
"||",
"{",
"}",
"url",
"=",
"url_for",
"(",
"options",
")",
"active",
"=",
"\"active\"",
"if",
"url",
"==",
"request",
".",
"path",
"||",
"url",
"==",
"request",
".",
"url",
"content_tag",
":li",
",",
":class",
"=>",
"active",
"do",
"link_to",
"args",
",",
"block",
"end",
"end"
] |
Just like +link_to+, but wrap with li tag and set +class="active"+
to corresponding page.
|
[
"Just",
"like",
"+",
"link_to",
"+",
"but",
"wrap",
"with",
"li",
"tag",
"and",
"set",
"+",
"class",
"=",
"active",
"+",
"to",
"corresponding",
"page",
"."
] |
a11c104b8caf582a28a0a903ae4ea9ee200aca75
|
https://github.com/tonytonyjan/tj-bootstrap-helper/blob/a11c104b8caf582a28a0a903ae4ea9ee200aca75/lib/tj_bootstrap_helper/helper.rb#L42-L49
|
8,250
|
spheromak/services
|
lib/services/connection.rb
|
Services.Connection.find_servers
|
def find_servers
# need a run_context to find anything in
return nil unless run_context
# If there are already servers in attribs use those
return node[:etcd][:servers] if node.key?(:etcd) &&
node[:etcd].key?(:servers)
# if we have already searched in this run use those
return node.run_state[:etcd_servers] if node.run_state.key? :etcd_servers
# find nodes and build array of ip's
etcd_nodes = search(:node, search_query)
servers = etcd_nodes.map { |n| n[:ipaddress] }
# store that in the run_state
node.run_state[:etcd_servers] = servers
end
|
ruby
|
def find_servers
# need a run_context to find anything in
return nil unless run_context
# If there are already servers in attribs use those
return node[:etcd][:servers] if node.key?(:etcd) &&
node[:etcd].key?(:servers)
# if we have already searched in this run use those
return node.run_state[:etcd_servers] if node.run_state.key? :etcd_servers
# find nodes and build array of ip's
etcd_nodes = search(:node, search_query)
servers = etcd_nodes.map { |n| n[:ipaddress] }
# store that in the run_state
node.run_state[:etcd_servers] = servers
end
|
[
"def",
"find_servers",
"# need a run_context to find anything in",
"return",
"nil",
"unless",
"run_context",
"# If there are already servers in attribs use those",
"return",
"node",
"[",
":etcd",
"]",
"[",
":servers",
"]",
"if",
"node",
".",
"key?",
"(",
":etcd",
")",
"&&",
"node",
"[",
":etcd",
"]",
".",
"key?",
"(",
":servers",
")",
"# if we have already searched in this run use those",
"return",
"node",
".",
"run_state",
"[",
":etcd_servers",
"]",
"if",
"node",
".",
"run_state",
".",
"key?",
":etcd_servers",
"# find nodes and build array of ip's",
"etcd_nodes",
"=",
"search",
"(",
":node",
",",
"search_query",
")",
"servers",
"=",
"etcd_nodes",
".",
"map",
"{",
"|",
"n",
"|",
"n",
"[",
":ipaddress",
"]",
"}",
"# store that in the run_state",
"node",
".",
"run_state",
"[",
":etcd_servers",
"]",
"=",
"servers",
"end"
] |
Find other Etd Servers by looking at node attributes or via Chef Search
|
[
"Find",
"other",
"Etd",
"Servers",
"by",
"looking",
"at",
"node",
"attributes",
"or",
"via",
"Chef",
"Search"
] |
c14445954f4402f1ccdaf61d451e4d47b67de93b
|
https://github.com/spheromak/services/blob/c14445954f4402f1ccdaf61d451e4d47b67de93b/lib/services/connection.rb#L72-L88
|
8,251
|
spheromak/services
|
lib/services/connection.rb
|
Services.Connection.try_connect
|
def try_connect(server)
c = ::Etcd.client(host: server, port: port, allow_redirect: @redirect)
begin
c.get '/_etcd/machines'
return c
rescue
puts "ETCD: failed to connect to #{c.host}:#{c.port}"
return nil
end
end
|
ruby
|
def try_connect(server)
c = ::Etcd.client(host: server, port: port, allow_redirect: @redirect)
begin
c.get '/_etcd/machines'
return c
rescue
puts "ETCD: failed to connect to #{c.host}:#{c.port}"
return nil
end
end
|
[
"def",
"try_connect",
"(",
"server",
")",
"c",
"=",
"::",
"Etcd",
".",
"client",
"(",
"host",
":",
"server",
",",
"port",
":",
"port",
",",
"allow_redirect",
":",
"@redirect",
")",
"begin",
"c",
".",
"get",
"'/_etcd/machines'",
"return",
"c",
"rescue",
"puts",
"\"ETCD: failed to connect to #{c.host}:#{c.port}\"",
"return",
"nil",
"end",
"end"
] |
Try to grab an etcd connection
@param [String] server () The server to try to connect too
|
[
"Try",
"to",
"grab",
"an",
"etcd",
"connection"
] |
c14445954f4402f1ccdaf61d451e4d47b67de93b
|
https://github.com/spheromak/services/blob/c14445954f4402f1ccdaf61d451e4d47b67de93b/lib/services/connection.rb#L130-L139
|
8,252
|
danielbush/RubyCron
|
lib/CronR/Cron.rb
|
CronR.Cron.run
|
def run time=nil
puts "[cron] run called #{Time.now}" if @debug
time = self.time if time.nil?
self.each { |cron_job|
ok,details = cron_job.runnable?(time)
if ok then
@queue.enq(cron_job)
if cron_job.once? then
cron_job[:delete] = true
end
end
}
self.reject! { |cron_job|
cron_job[:delete]
}
end
|
ruby
|
def run time=nil
puts "[cron] run called #{Time.now}" if @debug
time = self.time if time.nil?
self.each { |cron_job|
ok,details = cron_job.runnable?(time)
if ok then
@queue.enq(cron_job)
if cron_job.once? then
cron_job[:delete] = true
end
end
}
self.reject! { |cron_job|
cron_job[:delete]
}
end
|
[
"def",
"run",
"time",
"=",
"nil",
"puts",
"\"[cron] run called #{Time.now}\"",
"if",
"@debug",
"time",
"=",
"self",
".",
"time",
"if",
"time",
".",
"nil?",
"self",
".",
"each",
"{",
"|",
"cron_job",
"|",
"ok",
",",
"details",
"=",
"cron_job",
".",
"runnable?",
"(",
"time",
")",
"if",
"ok",
"then",
"@queue",
".",
"enq",
"(",
"cron_job",
")",
"if",
"cron_job",
".",
"once?",
"then",
"cron_job",
"[",
":delete",
"]",
"=",
"true",
"end",
"end",
"}",
"self",
".",
"reject!",
"{",
"|",
"cron_job",
"|",
"cron_job",
"[",
":delete",
"]",
"}",
"end"
] |
Check each item in this array, if runnable push it on a queue.
We assume that this item is or simlar to CronJob. We don't call
cron_job#job. That is the work for another thread esp. if #job
is a Proc.
|
[
"Check",
"each",
"item",
"in",
"this",
"array",
"if",
"runnable",
"push",
"it",
"on",
"a",
"queue",
"."
] |
24a2f997b81663ded1ac1d01017e8d807d5caffd
|
https://github.com/danielbush/RubyCron/blob/24a2f997b81663ded1ac1d01017e8d807d5caffd/lib/CronR/Cron.rb#L124-L140
|
8,253
|
danielbush/RubyCron
|
lib/CronR/Cron.rb
|
CronR.Cron.start
|
def start debug=false,method=:every_minute,*args
@stopped = false
@suspended = false
@dead = Queue.new
@thread = CronR::Utils.send(method,debug,*args) {
time = self.time
@mutex.synchronize {
if @stopped then
# It's important we put something on this queue ONLY AFTER
# we've acquired the mutex...
@dead.enq(true)
true
elsif @suspended then
else
self.run(time)
end
}
}
end
|
ruby
|
def start debug=false,method=:every_minute,*args
@stopped = false
@suspended = false
@dead = Queue.new
@thread = CronR::Utils.send(method,debug,*args) {
time = self.time
@mutex.synchronize {
if @stopped then
# It's important we put something on this queue ONLY AFTER
# we've acquired the mutex...
@dead.enq(true)
true
elsif @suspended then
else
self.run(time)
end
}
}
end
|
[
"def",
"start",
"debug",
"=",
"false",
",",
"method",
"=",
":every_minute",
",",
"*",
"args",
"@stopped",
"=",
"false",
"@suspended",
"=",
"false",
"@dead",
"=",
"Queue",
".",
"new",
"@thread",
"=",
"CronR",
"::",
"Utils",
".",
"send",
"(",
"method",
",",
"debug",
",",
"args",
")",
"{",
"time",
"=",
"self",
".",
"time",
"@mutex",
".",
"synchronize",
"{",
"if",
"@stopped",
"then",
"# It's important we put something on this queue ONLY AFTER",
"# we've acquired the mutex...",
"@dead",
".",
"enq",
"(",
"true",
")",
"true",
"elsif",
"@suspended",
"then",
"else",
"self",
".",
"run",
"(",
"time",
")",
"end",
"}",
"}",
"end"
] |
Start cron.
Will wake up every minute and perform #run.
|
[
"Start",
"cron",
"."
] |
24a2f997b81663ded1ac1d01017e8d807d5caffd
|
https://github.com/danielbush/RubyCron/blob/24a2f997b81663ded1ac1d01017e8d807d5caffd/lib/CronR/Cron.rb#L146-L164
|
8,254
|
danielbush/RubyCron
|
lib/CronR/Cron.rb
|
CronR.Cron.stop
|
def stop &block
if block_given? then
@stopped = true
@suspended = false
# Wait till something is put on the dead queue...
# This stops us from acquiring the mutex until after @thread
# has processed @stopped set to true.
sig = @dead.deq
# The cron thread should be dead now, or wrapping up (with the
# acquired mutex)...
@mutex.synchronize {
while @thread.alive?
sleep 0.2
end
block.call(self)
}
end
end
|
ruby
|
def stop &block
if block_given? then
@stopped = true
@suspended = false
# Wait till something is put on the dead queue...
# This stops us from acquiring the mutex until after @thread
# has processed @stopped set to true.
sig = @dead.deq
# The cron thread should be dead now, or wrapping up (with the
# acquired mutex)...
@mutex.synchronize {
while @thread.alive?
sleep 0.2
end
block.call(self)
}
end
end
|
[
"def",
"stop",
"&",
"block",
"if",
"block_given?",
"then",
"@stopped",
"=",
"true",
"@suspended",
"=",
"false",
"# Wait till something is put on the dead queue...",
"# This stops us from acquiring the mutex until after @thread",
"# has processed @stopped set to true.",
"sig",
"=",
"@dead",
".",
"deq",
"# The cron thread should be dead now, or wrapping up (with the",
"# acquired mutex)... ",
"@mutex",
".",
"synchronize",
"{",
"while",
"@thread",
".",
"alive?",
"sleep",
"0.2",
"end",
"block",
".",
"call",
"(",
"self",
")",
"}",
"end",
"end"
] |
Gracefully stop the thread.
If block is given, it will be called once the thread has
stopped.
|
[
"Gracefully",
"stop",
"the",
"thread",
"."
] |
24a2f997b81663ded1ac1d01017e8d807d5caffd
|
https://github.com/danielbush/RubyCron/blob/24a2f997b81663ded1ac1d01017e8d807d5caffd/lib/CronR/Cron.rb#L190-L207
|
8,255
|
NUBIC/aker
|
lib/aker/form/middleware/login_renderer.rb
|
Aker::Form::Middleware.LoginRenderer.provide_login_html
|
def provide_login_html(env)
request = ::Rack::Request.new(env)
html = login_html(env, :url => request['url'], :session_expired => request['session_expired'])
html_response(html).finish
end
|
ruby
|
def provide_login_html(env)
request = ::Rack::Request.new(env)
html = login_html(env, :url => request['url'], :session_expired => request['session_expired'])
html_response(html).finish
end
|
[
"def",
"provide_login_html",
"(",
"env",
")",
"request",
"=",
"::",
"Rack",
"::",
"Request",
".",
"new",
"(",
"env",
")",
"html",
"=",
"login_html",
"(",
"env",
",",
":url",
"=>",
"request",
"[",
"'url'",
"]",
",",
":session_expired",
"=>",
"request",
"[",
"'session_expired'",
"]",
")",
"html_response",
"(",
"html",
")",
".",
"finish",
"end"
] |
An HTML form for logging in.
@param env the Rack environment
@return a finished Rack response
|
[
"An",
"HTML",
"form",
"for",
"logging",
"in",
"."
] |
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
|
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/form/middleware/login_renderer.rb#L55-L60
|
8,256
|
kvokka/active_admin_simple_life
|
lib/active_admin_simple_life/simple_elements.rb
|
ActiveAdminSimpleLife.SimpleElements.filter_for_main_fields
|
def filter_for_main_fields(klass, options ={})
klass.main_fields.each do |f|
if f == :gender
filter ExtensionedSymbol.new(f).cut_id, collection: genders
else
filter ExtensionedSymbol.new(f).cut_id
end
end
end
|
ruby
|
def filter_for_main_fields(klass, options ={})
klass.main_fields.each do |f|
if f == :gender
filter ExtensionedSymbol.new(f).cut_id, collection: genders
else
filter ExtensionedSymbol.new(f).cut_id
end
end
end
|
[
"def",
"filter_for_main_fields",
"(",
"klass",
",",
"options",
"=",
"{",
"}",
")",
"klass",
".",
"main_fields",
".",
"each",
"do",
"|",
"f",
"|",
"if",
"f",
"==",
":gender",
"filter",
"ExtensionedSymbol",
".",
"new",
"(",
"f",
")",
".",
"cut_id",
",",
"collection",
":",
"genders",
"else",
"filter",
"ExtensionedSymbol",
".",
"new",
"(",
"f",
")",
".",
"cut_id",
"end",
"end",
"end"
] |
it check only for gender field for now
|
[
"it",
"check",
"only",
"for",
"gender",
"field",
"for",
"now"
] |
050ac1a87462c2b57bd42bae43df3cb0c238c42b
|
https://github.com/kvokka/active_admin_simple_life/blob/050ac1a87462c2b57bd42bae43df3cb0c238c42b/lib/active_admin_simple_life/simple_elements.rb#L41-L49
|
8,257
|
kvokka/active_admin_simple_life
|
lib/active_admin_simple_life/simple_elements.rb
|
ActiveAdminSimpleLife.SimpleElements.nested_form_for_main_fields
|
def nested_form_for_main_fields(klass, nested_klass, options={})
form_for_main_fields(klass,options) do |form_field|
nested_table_name = nested_klass.to_s.underscore.pluralize.to_sym
main_model_name = klass.to_s.underscore.to_sym
form_field.has_many nested_table_name, allow_destroy: true do |form|
nested_klass.main_fields.map { |f| ExtensionedSymbol.new(f).cut_id }.each do |nested_field|
current_options = options.fetch(nested_table_name){{}}.fetch(nested_field){{}}
form.input(nested_field, current_options) unless nested_field == main_model_name
end
end
end
end
|
ruby
|
def nested_form_for_main_fields(klass, nested_klass, options={})
form_for_main_fields(klass,options) do |form_field|
nested_table_name = nested_klass.to_s.underscore.pluralize.to_sym
main_model_name = klass.to_s.underscore.to_sym
form_field.has_many nested_table_name, allow_destroy: true do |form|
nested_klass.main_fields.map { |f| ExtensionedSymbol.new(f).cut_id }.each do |nested_field|
current_options = options.fetch(nested_table_name){{}}.fetch(nested_field){{}}
form.input(nested_field, current_options) unless nested_field == main_model_name
end
end
end
end
|
[
"def",
"nested_form_for_main_fields",
"(",
"klass",
",",
"nested_klass",
",",
"options",
"=",
"{",
"}",
")",
"form_for_main_fields",
"(",
"klass",
",",
"options",
")",
"do",
"|",
"form_field",
"|",
"nested_table_name",
"=",
"nested_klass",
".",
"to_s",
".",
"underscore",
".",
"pluralize",
".",
"to_sym",
"main_model_name",
"=",
"klass",
".",
"to_s",
".",
"underscore",
".",
"to_sym",
"form_field",
".",
"has_many",
"nested_table_name",
",",
"allow_destroy",
":",
"true",
"do",
"|",
"form",
"|",
"nested_klass",
".",
"main_fields",
".",
"map",
"{",
"|",
"f",
"|",
"ExtensionedSymbol",
".",
"new",
"(",
"f",
")",
".",
"cut_id",
"}",
".",
"each",
"do",
"|",
"nested_field",
"|",
"current_options",
"=",
"options",
".",
"fetch",
"(",
"nested_table_name",
")",
"{",
"{",
"}",
"}",
".",
"fetch",
"(",
"nested_field",
")",
"{",
"{",
"}",
"}",
"form",
".",
"input",
"(",
"nested_field",
",",
"current_options",
")",
"unless",
"nested_field",
"==",
"main_model_name",
"end",
"end",
"end",
"end"
] |
simple nested set for 2 classes with defined main_fields
|
[
"simple",
"nested",
"set",
"for",
"2",
"classes",
"with",
"defined",
"main_fields"
] |
050ac1a87462c2b57bd42bae43df3cb0c238c42b
|
https://github.com/kvokka/active_admin_simple_life/blob/050ac1a87462c2b57bd42bae43df3cb0c238c42b/lib/active_admin_simple_life/simple_elements.rb#L71-L82
|
8,258
|
pwnall/authpwn_rails
|
lib/authpwn_rails/http_basic.rb
|
Authpwn.HttpBasicControllerInstanceMethods.authenticate_using_http_basic
|
def authenticate_using_http_basic
return if current_user
authenticate_with_http_basic do |email, password|
signin = Session.new email: email, password: password
auth = User.authenticate_signin signin
self.current_user = auth unless auth.kind_of? Symbol
end
end
|
ruby
|
def authenticate_using_http_basic
return if current_user
authenticate_with_http_basic do |email, password|
signin = Session.new email: email, password: password
auth = User.authenticate_signin signin
self.current_user = auth unless auth.kind_of? Symbol
end
end
|
[
"def",
"authenticate_using_http_basic",
"return",
"if",
"current_user",
"authenticate_with_http_basic",
"do",
"|",
"email",
",",
"password",
"|",
"signin",
"=",
"Session",
".",
"new",
"email",
":",
"email",
",",
"password",
":",
"password",
"auth",
"=",
"User",
".",
"authenticate_signin",
"signin",
"self",
".",
"current_user",
"=",
"auth",
"unless",
"auth",
".",
"kind_of?",
"Symbol",
"end",
"end"
] |
The before_action that implements authenticates_using_http_basic.
If your ApplicationController contains authenticates_using_http_basic, you
can opt out in individual controllers using skip_before_action.
skip_before_action :authenticate_using_http_basic
|
[
"The",
"before_action",
"that",
"implements",
"authenticates_using_http_basic",
"."
] |
de3bd612a00025e8dc8296a73abe3acba948db17
|
https://github.com/pwnall/authpwn_rails/blob/de3bd612a00025e8dc8296a73abe3acba948db17/lib/authpwn_rails/http_basic.rb#L29-L36
|
8,259
|
sideshowcoder/activerecord_translatable
|
lib/activerecord_translatable/extension.rb
|
ActiveRecordTranslatable.ClassMethods.translate
|
def translate(*attributes)
self._translatable ||= Hash.new { |h,k| h[k] = [] }
self._translatable[base_name] = translatable.concat(attributes).uniq
end
|
ruby
|
def translate(*attributes)
self._translatable ||= Hash.new { |h,k| h[k] = [] }
self._translatable[base_name] = translatable.concat(attributes).uniq
end
|
[
"def",
"translate",
"(",
"*",
"attributes",
")",
"self",
".",
"_translatable",
"||=",
"Hash",
".",
"new",
"{",
"|",
"h",
",",
"k",
"|",
"h",
"[",
"k",
"]",
"=",
"[",
"]",
"}",
"self",
".",
"_translatable",
"[",
"base_name",
"]",
"=",
"translatable",
".",
"concat",
"(",
"attributes",
")",
".",
"uniq",
"end"
] |
Define attribute as translatable
class Thing < ActiveRecord::Base
translate :name
end
|
[
"Define",
"attribute",
"as",
"translatable"
] |
42f9508530db39d0edaf2d7dc6c5d9ee1b0375fb
|
https://github.com/sideshowcoder/activerecord_translatable/blob/42f9508530db39d0edaf2d7dc6c5d9ee1b0375fb/lib/activerecord_translatable/extension.rb#L91-L94
|
8,260
|
leoc/em-systemcommand
|
lib/em-systemcommand.rb
|
EventMachine.SystemCommand.execute
|
def execute &block
raise 'Previous process still exists' unless pipes.empty?
# clear callbacks
@callbacks = []
@errbacks = []
pid, stdin, stdout, stderr = POSIX::Spawn.popen4 @command.to_s
@pid = pid
@stdin = attach_pipe_handler :stdin, stdin
@stdout = attach_pipe_handler :stdout, stdout
@stderr = attach_pipe_handler :stderr, stderr
if block
block.call self
elsif @execution_proc
@execution_proc.call self
end
self
end
|
ruby
|
def execute &block
raise 'Previous process still exists' unless pipes.empty?
# clear callbacks
@callbacks = []
@errbacks = []
pid, stdin, stdout, stderr = POSIX::Spawn.popen4 @command.to_s
@pid = pid
@stdin = attach_pipe_handler :stdin, stdin
@stdout = attach_pipe_handler :stdout, stdout
@stderr = attach_pipe_handler :stderr, stderr
if block
block.call self
elsif @execution_proc
@execution_proc.call self
end
self
end
|
[
"def",
"execute",
"&",
"block",
"raise",
"'Previous process still exists'",
"unless",
"pipes",
".",
"empty?",
"# clear callbacks",
"@callbacks",
"=",
"[",
"]",
"@errbacks",
"=",
"[",
"]",
"pid",
",",
"stdin",
",",
"stdout",
",",
"stderr",
"=",
"POSIX",
"::",
"Spawn",
".",
"popen4",
"@command",
".",
"to_s",
"@pid",
"=",
"pid",
"@stdin",
"=",
"attach_pipe_handler",
":stdin",
",",
"stdin",
"@stdout",
"=",
"attach_pipe_handler",
":stdout",
",",
"stdout",
"@stderr",
"=",
"attach_pipe_handler",
":stderr",
",",
"stderr",
"if",
"block",
"block",
".",
"call",
"self",
"elsif",
"@execution_proc",
"@execution_proc",
".",
"call",
"self",
"end",
"self",
"end"
] |
Executes the command from the `Builder` object.
If there had been given a block at instantiation it will be
called after the `popen3` call and after the pipes have been
attached.
|
[
"Executes",
"the",
"command",
"from",
"the",
"Builder",
"object",
".",
"If",
"there",
"had",
"been",
"given",
"a",
"block",
"at",
"instantiation",
"it",
"will",
"be",
"called",
"after",
"the",
"popen3",
"call",
"and",
"after",
"the",
"pipes",
"have",
"been",
"attached",
"."
] |
e1987253527c4b4dcc8ca7fe5ce6a16235f4810d
|
https://github.com/leoc/em-systemcommand/blob/e1987253527c4b4dcc8ca7fe5ce6a16235f4810d/lib/em-systemcommand.rb#L63-L83
|
8,261
|
leoc/em-systemcommand
|
lib/em-systemcommand.rb
|
EventMachine.SystemCommand.unbind
|
def unbind name
pipes.delete name
if pipes.empty?
exit_callbacks.each do |cb|
EM.next_tick do
cb.call status
end
end
if status.exitstatus == 0
EM.next_tick do
succeed self
end
else
EM.next_tick do
fail self
end
end
end
end
|
ruby
|
def unbind name
pipes.delete name
if pipes.empty?
exit_callbacks.each do |cb|
EM.next_tick do
cb.call status
end
end
if status.exitstatus == 0
EM.next_tick do
succeed self
end
else
EM.next_tick do
fail self
end
end
end
end
|
[
"def",
"unbind",
"name",
"pipes",
".",
"delete",
"name",
"if",
"pipes",
".",
"empty?",
"exit_callbacks",
".",
"each",
"do",
"|",
"cb",
"|",
"EM",
".",
"next_tick",
"do",
"cb",
".",
"call",
"status",
"end",
"end",
"if",
"status",
".",
"exitstatus",
"==",
"0",
"EM",
".",
"next_tick",
"do",
"succeed",
"self",
"end",
"else",
"EM",
".",
"next_tick",
"do",
"fail",
"self",
"end",
"end",
"end",
"end"
] |
Called by child pipes when they get unbound.
|
[
"Called",
"by",
"child",
"pipes",
"when",
"they",
"get",
"unbound",
"."
] |
e1987253527c4b4dcc8ca7fe5ce6a16235f4810d
|
https://github.com/leoc/em-systemcommand/blob/e1987253527c4b4dcc8ca7fe5ce6a16235f4810d/lib/em-systemcommand.rb#L108-L126
|
8,262
|
leoc/em-systemcommand
|
lib/em-systemcommand.rb
|
EventMachine.SystemCommand.kill
|
def kill signal = 'TERM', wait = false
Process.kill signal, self.pid
val = status if wait
@stdin.close
@stdout.close
@stderr.close
val
end
|
ruby
|
def kill signal = 'TERM', wait = false
Process.kill signal, self.pid
val = status if wait
@stdin.close
@stdout.close
@stderr.close
val
end
|
[
"def",
"kill",
"signal",
"=",
"'TERM'",
",",
"wait",
"=",
"false",
"Process",
".",
"kill",
"signal",
",",
"self",
".",
"pid",
"val",
"=",
"status",
"if",
"wait",
"@stdin",
".",
"close",
"@stdout",
".",
"close",
"@stderr",
".",
"close",
"val",
"end"
] |
Kills the child process.
|
[
"Kills",
"the",
"child",
"process",
"."
] |
e1987253527c4b4dcc8ca7fe5ce6a16235f4810d
|
https://github.com/leoc/em-systemcommand/blob/e1987253527c4b4dcc8ca7fe5ce6a16235f4810d/lib/em-systemcommand.rb#L130-L137
|
8,263
|
jdno/ai_games-parser
|
lib/ai_games/parser.rb
|
AiGames.Parser.run
|
def run
AiGames::Logger.info 'Parser.run : Starting loop'
loop do
command = read_from_engine
break if command.nil?
command.strip!
next if command.length == 0
response = parse split_line command
write_to_engine response unless response.nil? || response.length < 1
end
AiGames::Logger.info 'Parser.run : Stopping loop'
end
|
ruby
|
def run
AiGames::Logger.info 'Parser.run : Starting loop'
loop do
command = read_from_engine
break if command.nil?
command.strip!
next if command.length == 0
response = parse split_line command
write_to_engine response unless response.nil? || response.length < 1
end
AiGames::Logger.info 'Parser.run : Stopping loop'
end
|
[
"def",
"run",
"AiGames",
"::",
"Logger",
".",
"info",
"'Parser.run : Starting loop'",
"loop",
"do",
"command",
"=",
"read_from_engine",
"break",
"if",
"command",
".",
"nil?",
"command",
".",
"strip!",
"next",
"if",
"command",
".",
"length",
"==",
"0",
"response",
"=",
"parse",
"split_line",
"command",
"write_to_engine",
"response",
"unless",
"response",
".",
"nil?",
"||",
"response",
".",
"length",
"<",
"1",
"end",
"AiGames",
"::",
"Logger",
".",
"info",
"'Parser.run : Stopping loop'",
"end"
] |
Initializes the parser. Pass in options using a hash structure.
Starts the main loop. This loop runs until the game engine closes the
console line. During the loop, the parser reads from the game engine,
sanitizes the input a little bit, and then passes it to a method that
needs to be overwritten by parsers extending this interface.
|
[
"Initializes",
"the",
"parser",
".",
"Pass",
"in",
"options",
"using",
"a",
"hash",
"structure",
".",
"Starts",
"the",
"main",
"loop",
".",
"This",
"loop",
"runs",
"until",
"the",
"game",
"engine",
"closes",
"the",
"console",
"line",
".",
"During",
"the",
"loop",
"the",
"parser",
"reads",
"from",
"the",
"game",
"engine",
"sanitizes",
"the",
"input",
"a",
"little",
"bit",
"and",
"then",
"passes",
"it",
"to",
"a",
"method",
"that",
"needs",
"to",
"be",
"overwritten",
"by",
"parsers",
"extending",
"this",
"interface",
"."
] |
3bee81293ea8f0b3b1e89f98614d98a277365602
|
https://github.com/jdno/ai_games-parser/blob/3bee81293ea8f0b3b1e89f98614d98a277365602/lib/ai_games/parser.rb#L19-L34
|
8,264
|
Fire-Dragon-DoL/fried-typings
|
lib/fried/typings/enumerator_of.rb
|
Fried::Typings.EnumeratorOf.valid?
|
def valid?(enumerator)
return false unless Is[Enumerator].valid?(enumerator)
enumerator.all? { |obj| Is[type].valid?(obj) }
end
|
ruby
|
def valid?(enumerator)
return false unless Is[Enumerator].valid?(enumerator)
enumerator.all? { |obj| Is[type].valid?(obj) }
end
|
[
"def",
"valid?",
"(",
"enumerator",
")",
"return",
"false",
"unless",
"Is",
"[",
"Enumerator",
"]",
".",
"valid?",
"(",
"enumerator",
")",
"enumerator",
".",
"all?",
"{",
"|",
"obj",
"|",
"Is",
"[",
"type",
"]",
".",
"valid?",
"(",
"obj",
")",
"}",
"end"
] |
Notice that the method will actually iterate over the enumerator
@param enumerator [Enumerator]
|
[
"Notice",
"that",
"the",
"method",
"will",
"actually",
"iterate",
"over",
"the",
"enumerator"
] |
9c7d726c48003b008fd88c1b7ae51c0a3dbca892
|
https://github.com/Fire-Dragon-DoL/fried-typings/blob/9c7d726c48003b008fd88c1b7ae51c0a3dbca892/lib/fried/typings/enumerator_of.rb#L24-L28
|
8,265
|
fotonauts/activr
|
lib/activr/activity.rb
|
Activr.Activity.to_hash
|
def to_hash
result = { }
# id
result['_id'] = @_id if @_id
# timestamp
result['at'] = @at
# kind
result['kind'] = kind.to_s
# entities
@entities.each do |entity_name, entity|
result[entity_name.to_s] = entity.model_id
end
# meta
result['meta'] = @meta.stringify_keys unless @meta.blank?
result
end
|
ruby
|
def to_hash
result = { }
# id
result['_id'] = @_id if @_id
# timestamp
result['at'] = @at
# kind
result['kind'] = kind.to_s
# entities
@entities.each do |entity_name, entity|
result[entity_name.to_s] = entity.model_id
end
# meta
result['meta'] = @meta.stringify_keys unless @meta.blank?
result
end
|
[
"def",
"to_hash",
"result",
"=",
"{",
"}",
"# id",
"result",
"[",
"'_id'",
"]",
"=",
"@_id",
"if",
"@_id",
"# timestamp",
"result",
"[",
"'at'",
"]",
"=",
"@at",
"# kind",
"result",
"[",
"'kind'",
"]",
"=",
"kind",
".",
"to_s",
"# entities",
"@entities",
".",
"each",
"do",
"|",
"entity_name",
",",
"entity",
"|",
"result",
"[",
"entity_name",
".",
"to_s",
"]",
"=",
"entity",
".",
"model_id",
"end",
"# meta",
"result",
"[",
"'meta'",
"]",
"=",
"@meta",
".",
"stringify_keys",
"unless",
"@meta",
".",
"blank?",
"result",
"end"
] |
Serialize activity to a hash
@note All keys are stringified (ie. there is no Symbol)
@return [Hash] Activity hash
|
[
"Serialize",
"activity",
"to",
"a",
"hash"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/activity.rb#L317-L338
|
8,266
|
fotonauts/activr
|
lib/activr/activity.rb
|
Activr.Activity.humanization_bindings
|
def humanization_bindings(options = { })
result = { }
@entities.each do |entity_name, entity|
result[entity_name] = entity.humanize(options.merge(:activity => self))
result["#{entity_name}_model".to_sym] = entity.model
end
result.merge(@meta)
end
|
ruby
|
def humanization_bindings(options = { })
result = { }
@entities.each do |entity_name, entity|
result[entity_name] = entity.humanize(options.merge(:activity => self))
result["#{entity_name}_model".to_sym] = entity.model
end
result.merge(@meta)
end
|
[
"def",
"humanization_bindings",
"(",
"options",
"=",
"{",
"}",
")",
"result",
"=",
"{",
"}",
"@entities",
".",
"each",
"do",
"|",
"entity_name",
",",
"entity",
"|",
"result",
"[",
"entity_name",
"]",
"=",
"entity",
".",
"humanize",
"(",
"options",
".",
"merge",
"(",
":activity",
"=>",
"self",
")",
")",
"result",
"[",
"\"#{entity_name}_model\"",
".",
"to_sym",
"]",
"=",
"entity",
".",
"model",
"end",
"result",
".",
"merge",
"(",
"@meta",
")",
"end"
] |
Bindings for humanization sentence
For each entity, returned hash contains:
:<entity_name> => <entity humanization>
:<entity_name>_model => <entity model instance>
All `meta` are merged in returned hash too.
@param options [Hash] Humanization options
@return [Hash] Humanization bindings
|
[
"Bindings",
"for",
"humanization",
"sentence"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/activity.rb#L363-L372
|
8,267
|
fotonauts/activr
|
lib/activr/activity.rb
|
Activr.Activity.humanize
|
def humanize(options = { })
raise "No humanize_tpl defined" if self.humanize_tpl.blank?
Activr.sentence(self.humanize_tpl, self.humanization_bindings(options))
end
|
ruby
|
def humanize(options = { })
raise "No humanize_tpl defined" if self.humanize_tpl.blank?
Activr.sentence(self.humanize_tpl, self.humanization_bindings(options))
end
|
[
"def",
"humanize",
"(",
"options",
"=",
"{",
"}",
")",
"raise",
"\"No humanize_tpl defined\"",
"if",
"self",
".",
"humanize_tpl",
".",
"blank?",
"Activr",
".",
"sentence",
"(",
"self",
".",
"humanize_tpl",
",",
"self",
".",
"humanization_bindings",
"(",
"options",
")",
")",
"end"
] |
Humanize that activity
@param options [Hash] Options hash
@option options [true, false] :html Output HTML (default: `false`)
@return [String] Humanized activity
|
[
"Humanize",
"that",
"activity"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/activity.rb#L379-L383
|
8,268
|
fotonauts/activr
|
lib/activr/activity.rb
|
Activr.Activity.check!
|
def check!
# check mandatory entities
self.allowed_entities.each do |entity_name, entity_options|
if !entity_options[:optional] && @entities[entity_name].blank?
raise Activr::Activity::MissingEntityError, "Missing '#{entity_name}' entity in this '#{self.kind}' activity: #{self.inspect}"
end
end
end
|
ruby
|
def check!
# check mandatory entities
self.allowed_entities.each do |entity_name, entity_options|
if !entity_options[:optional] && @entities[entity_name].blank?
raise Activr::Activity::MissingEntityError, "Missing '#{entity_name}' entity in this '#{self.kind}' activity: #{self.inspect}"
end
end
end
|
[
"def",
"check!",
"# check mandatory entities",
"self",
".",
"allowed_entities",
".",
"each",
"do",
"|",
"entity_name",
",",
"entity_options",
"|",
"if",
"!",
"entity_options",
"[",
":optional",
"]",
"&&",
"@entities",
"[",
"entity_name",
"]",
".",
"blank?",
"raise",
"Activr",
"::",
"Activity",
"::",
"MissingEntityError",
",",
"\"Missing '#{entity_name}' entity in this '#{self.kind}' activity: #{self.inspect}\"",
"end",
"end",
"end"
] |
Check if activity is valid
@raise [MissingEntityError] if a mandatory entity is missing
@api private
|
[
"Check",
"if",
"activity",
"is",
"valid"
] |
92c071ad18a76d4130661da3ce47c1f0fb8ae913
|
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/activity.rb#L389-L396
|
8,269
|
kron4eg/confrider
|
lib/confrider/vault.rb
|
Confrider.Vault.deep_merge!
|
def deep_merge!(other_hash)
other_hash.each_pair do |k,v|
tv = self[k]
self[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? self.class.new(tv).deep_merge(v) : v
end
self
end
|
ruby
|
def deep_merge!(other_hash)
other_hash.each_pair do |k,v|
tv = self[k]
self[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? self.class.new(tv).deep_merge(v) : v
end
self
end
|
[
"def",
"deep_merge!",
"(",
"other_hash",
")",
"other_hash",
".",
"each_pair",
"do",
"|",
"k",
",",
"v",
"|",
"tv",
"=",
"self",
"[",
"k",
"]",
"self",
"[",
"k",
"]",
"=",
"tv",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"v",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"self",
".",
"class",
".",
"new",
"(",
"tv",
")",
".",
"deep_merge",
"(",
"v",
")",
":",
"v",
"end",
"self",
"end"
] |
Returns a new hash with +self+ and +other_hash+ merged recursively.
Modifies the receiver in place.
|
[
"Returns",
"a",
"new",
"hash",
"with",
"+",
"self",
"+",
"and",
"+",
"other_hash",
"+",
"merged",
"recursively",
".",
"Modifies",
"the",
"receiver",
"in",
"place",
"."
] |
97f381c71ed34dd0f9ee8943ac85f1813efcba22
|
https://github.com/kron4eg/confrider/blob/97f381c71ed34dd0f9ee8943ac85f1813efcba22/lib/confrider/vault.rb#L10-L16
|
8,270
|
fugroup/easymongo
|
lib/easymongo/query.rb
|
Easymongo.Query.ids
|
def ids(data)
# Just return if nothing to do
return data if data and data.empty?
# Support passing id as string
data = {'_id' => data} if !data or data.is_a?(String)
# Turn all keys to string
data = data.stringify_keys
# Convert id to _id for mongo
data['_id'] = data.delete('id') if data['id']
# Convert ids to BSON ObjectId
data.each do |k, v|
if v.is_a?(String) and v =~ /^[0-9a-fA-F]{24}$/
data[k] = oid(v)
end
end
# Return data
data
end
|
ruby
|
def ids(data)
# Just return if nothing to do
return data if data and data.empty?
# Support passing id as string
data = {'_id' => data} if !data or data.is_a?(String)
# Turn all keys to string
data = data.stringify_keys
# Convert id to _id for mongo
data['_id'] = data.delete('id') if data['id']
# Convert ids to BSON ObjectId
data.each do |k, v|
if v.is_a?(String) and v =~ /^[0-9a-fA-F]{24}$/
data[k] = oid(v)
end
end
# Return data
data
end
|
[
"def",
"ids",
"(",
"data",
")",
"# Just return if nothing to do",
"return",
"data",
"if",
"data",
"and",
"data",
".",
"empty?",
"# Support passing id as string",
"data",
"=",
"{",
"'_id'",
"=>",
"data",
"}",
"if",
"!",
"data",
"or",
"data",
".",
"is_a?",
"(",
"String",
")",
"# Turn all keys to string",
"data",
"=",
"data",
".",
"stringify_keys",
"# Convert id to _id for mongo",
"data",
"[",
"'_id'",
"]",
"=",
"data",
".",
"delete",
"(",
"'id'",
")",
"if",
"data",
"[",
"'id'",
"]",
"# Convert ids to BSON ObjectId",
"data",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"if",
"v",
".",
"is_a?",
"(",
"String",
")",
"and",
"v",
"=~",
"/",
"/",
"data",
"[",
"k",
"]",
"=",
"oid",
"(",
"v",
")",
"end",
"end",
"# Return data",
"data",
"end"
] |
Make sure data is optimal
|
[
"Make",
"sure",
"data",
"is",
"optimal"
] |
a48675248eafcd4885278d3196600c8ebda46240
|
https://github.com/fugroup/easymongo/blob/a48675248eafcd4885278d3196600c8ebda46240/lib/easymongo/query.rb#L108-L131
|
8,271
|
fugroup/easymongo
|
lib/easymongo/query.rb
|
Easymongo.Query.oid
|
def oid(v = nil)
return BSON::ObjectId.new if v.nil?; BSON::ObjectId.from_string(v) rescue v
end
|
ruby
|
def oid(v = nil)
return BSON::ObjectId.new if v.nil?; BSON::ObjectId.from_string(v) rescue v
end
|
[
"def",
"oid",
"(",
"v",
"=",
"nil",
")",
"return",
"BSON",
"::",
"ObjectId",
".",
"new",
"if",
"v",
".",
"nil?",
";",
"BSON",
"::",
"ObjectId",
".",
"from_string",
"(",
"v",
")",
"rescue",
"v",
"end"
] |
Convert to BSON ObjectId or make a new one
|
[
"Convert",
"to",
"BSON",
"ObjectId",
"or",
"make",
"a",
"new",
"one"
] |
a48675248eafcd4885278d3196600c8ebda46240
|
https://github.com/fugroup/easymongo/blob/a48675248eafcd4885278d3196600c8ebda46240/lib/easymongo/query.rb#L134-L136
|
8,272
|
pluginaweek/encrypted_attributes
|
lib/encrypted_attributes.rb
|
EncryptedAttributes.MacroMethods.encrypts
|
def encrypts(*attr_names, &config)
base_options = attr_names.last.is_a?(Hash) ? attr_names.pop : {}
attr_names.each do |attr_name|
options = base_options.dup
attr_name = attr_name.to_s
to_attr_name = (options.delete(:to) || attr_name).to_s
# Figure out what cipher is being configured for the attribute
mode = options.delete(:mode) || :sha
class_name = "#{mode.to_s.classify}Cipher"
if EncryptedAttributes.const_defined?(class_name)
cipher_class = EncryptedAttributes.const_get(class_name)
else
cipher_class = EncryptedStrings.const_get(class_name)
end
# Define encryption hooks
define_callbacks("before_encrypt_#{attr_name}", "after_encrypt_#{attr_name}")
send("before_encrypt_#{attr_name}", options.delete(:before)) if options.include?(:before)
send("after_encrypt_#{attr_name}", options.delete(:after)) if options.include?(:after)
# Set the encrypted value on the configured callback
callback = options.delete(:on) || :before_validation
# Create a callback method to execute on the callback event
send(callback, :if => options.delete(:if), :unless => options.delete(:unless)) do |record|
record.send(:write_encrypted_attribute, attr_name, to_attr_name, cipher_class, config || options)
true
end
# Define virtual source attribute
if attr_name != to_attr_name && !column_names.include?(attr_name)
attr_reader attr_name unless method_defined?(attr_name)
attr_writer attr_name unless method_defined?("#{attr_name}=")
end
# Define the reader when reading the encrypted attribute from the database
define_method(to_attr_name) do
read_encrypted_attribute(to_attr_name, cipher_class, config || options)
end
unless included_modules.include?(EncryptedAttributes::InstanceMethods)
include EncryptedAttributes::InstanceMethods
end
end
end
|
ruby
|
def encrypts(*attr_names, &config)
base_options = attr_names.last.is_a?(Hash) ? attr_names.pop : {}
attr_names.each do |attr_name|
options = base_options.dup
attr_name = attr_name.to_s
to_attr_name = (options.delete(:to) || attr_name).to_s
# Figure out what cipher is being configured for the attribute
mode = options.delete(:mode) || :sha
class_name = "#{mode.to_s.classify}Cipher"
if EncryptedAttributes.const_defined?(class_name)
cipher_class = EncryptedAttributes.const_get(class_name)
else
cipher_class = EncryptedStrings.const_get(class_name)
end
# Define encryption hooks
define_callbacks("before_encrypt_#{attr_name}", "after_encrypt_#{attr_name}")
send("before_encrypt_#{attr_name}", options.delete(:before)) if options.include?(:before)
send("after_encrypt_#{attr_name}", options.delete(:after)) if options.include?(:after)
# Set the encrypted value on the configured callback
callback = options.delete(:on) || :before_validation
# Create a callback method to execute on the callback event
send(callback, :if => options.delete(:if), :unless => options.delete(:unless)) do |record|
record.send(:write_encrypted_attribute, attr_name, to_attr_name, cipher_class, config || options)
true
end
# Define virtual source attribute
if attr_name != to_attr_name && !column_names.include?(attr_name)
attr_reader attr_name unless method_defined?(attr_name)
attr_writer attr_name unless method_defined?("#{attr_name}=")
end
# Define the reader when reading the encrypted attribute from the database
define_method(to_attr_name) do
read_encrypted_attribute(to_attr_name, cipher_class, config || options)
end
unless included_modules.include?(EncryptedAttributes::InstanceMethods)
include EncryptedAttributes::InstanceMethods
end
end
end
|
[
"def",
"encrypts",
"(",
"*",
"attr_names",
",",
"&",
"config",
")",
"base_options",
"=",
"attr_names",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"attr_names",
".",
"pop",
":",
"{",
"}",
"attr_names",
".",
"each",
"do",
"|",
"attr_name",
"|",
"options",
"=",
"base_options",
".",
"dup",
"attr_name",
"=",
"attr_name",
".",
"to_s",
"to_attr_name",
"=",
"(",
"options",
".",
"delete",
"(",
":to",
")",
"||",
"attr_name",
")",
".",
"to_s",
"# Figure out what cipher is being configured for the attribute",
"mode",
"=",
"options",
".",
"delete",
"(",
":mode",
")",
"||",
":sha",
"class_name",
"=",
"\"#{mode.to_s.classify}Cipher\"",
"if",
"EncryptedAttributes",
".",
"const_defined?",
"(",
"class_name",
")",
"cipher_class",
"=",
"EncryptedAttributes",
".",
"const_get",
"(",
"class_name",
")",
"else",
"cipher_class",
"=",
"EncryptedStrings",
".",
"const_get",
"(",
"class_name",
")",
"end",
"# Define encryption hooks",
"define_callbacks",
"(",
"\"before_encrypt_#{attr_name}\"",
",",
"\"after_encrypt_#{attr_name}\"",
")",
"send",
"(",
"\"before_encrypt_#{attr_name}\"",
",",
"options",
".",
"delete",
"(",
":before",
")",
")",
"if",
"options",
".",
"include?",
"(",
":before",
")",
"send",
"(",
"\"after_encrypt_#{attr_name}\"",
",",
"options",
".",
"delete",
"(",
":after",
")",
")",
"if",
"options",
".",
"include?",
"(",
":after",
")",
"# Set the encrypted value on the configured callback",
"callback",
"=",
"options",
".",
"delete",
"(",
":on",
")",
"||",
":before_validation",
"# Create a callback method to execute on the callback event",
"send",
"(",
"callback",
",",
":if",
"=>",
"options",
".",
"delete",
"(",
":if",
")",
",",
":unless",
"=>",
"options",
".",
"delete",
"(",
":unless",
")",
")",
"do",
"|",
"record",
"|",
"record",
".",
"send",
"(",
":write_encrypted_attribute",
",",
"attr_name",
",",
"to_attr_name",
",",
"cipher_class",
",",
"config",
"||",
"options",
")",
"true",
"end",
"# Define virtual source attribute",
"if",
"attr_name",
"!=",
"to_attr_name",
"&&",
"!",
"column_names",
".",
"include?",
"(",
"attr_name",
")",
"attr_reader",
"attr_name",
"unless",
"method_defined?",
"(",
"attr_name",
")",
"attr_writer",
"attr_name",
"unless",
"method_defined?",
"(",
"\"#{attr_name}=\"",
")",
"end",
"# Define the reader when reading the encrypted attribute from the database",
"define_method",
"(",
"to_attr_name",
")",
"do",
"read_encrypted_attribute",
"(",
"to_attr_name",
",",
"cipher_class",
",",
"config",
"||",
"options",
")",
"end",
"unless",
"included_modules",
".",
"include?",
"(",
"EncryptedAttributes",
"::",
"InstanceMethods",
")",
"include",
"EncryptedAttributes",
"::",
"InstanceMethods",
"end",
"end",
"end"
] |
Encrypts the given attribute.
Configuration options:
* <tt>:mode</tt> - The mode of encryption to use. Default is <tt>:sha</tt>.
See EncryptedStrings for other possible modes.
* <tt>:to</tt> - The attribute to write the encrypted value to. Default
is the same attribute being encrypted.
* <tt>:before</tt> - The callback to invoke every time *before* the
attribute is encrypted
* <tt>:after</tt> - The callback to invoke every time *after* the
attribute is encrypted
* <tt>:on</tt> - The ActiveRecord callback to use when triggering the
encryption. By default, this will encrypt on <tt>before_validation</tt>.
See ActiveRecord::Callbacks for a list of possible callbacks.
* <tt>:if</tt> - Specifies a method, proc or string to call to determine
if the encryption should occur. The method, proc or string should return
or evaluate to a true or false value.
* <tt>:unless</tt> - Specifies a method, proc or string to call to
determine if the encryption should not occur. The method, proc or string
should return or evaluate to a true or false value.
For additional configuration options used during the actual encryption,
see the individual cipher class for the specified mode.
== Encryption timeline
By default, attributes are encrypted immediately before a record is
validated. This means that you can still validate the presence of the
encrypted attribute, but other things like password length cannot be
validated without either (a) decrypting the value first or (b) using a
different encryption target. For example,
class User < ActiveRecord::Base
encrypts :password, :to => :crypted_password
validates_presence_of :password, :crypted_password
validates_length_of :password, :maximum => 16
end
In the above example, the actual encrypted password will be stored in
the +crypted_password+ attribute. This means that validations can
still run against the model for the original password value.
user = User.new(:password => 'secret')
user.password # => "secret"
user.crypted_password # => nil
user.valid? # => true
user.crypted_password # => "8152bc582f58c854f580cb101d3182813dec4afe"
user = User.new(:password => 'longer_than_the_maximum_allowed')
user.valid? # => false
user.crypted_password # => "e80a709f25798f87d9ca8005a7f64a645964d7c2"
user.errors[:password] # => "is too long (maximum is 16 characters)"
== Encryption mode examples
SHA encryption:
class User < ActiveRecord::Base
encrypts :password
# encrypts :password, :salt => 'secret'
end
Symmetric encryption:
class User < ActiveRecord::Base
encrypts :password, :mode => :symmetric
# encrypts :password, :mode => :symmetric, :key => 'custom'
end
Asymmetric encryption:
class User < ActiveRecord::Base
encrypts :password, :mode => :asymmetric
# encrypts :password, :mode => :asymmetric, :public_key_file => '/keys/public', :private_key_file => '/keys/private'
end
== Dynamic configuration
For better security, the encryption options (such as the salt value)
can be based on values in each individual record. In order to
dynamically configure the encryption options so that individual records
can be referenced, an optional block can be specified.
For example,
class User < ActiveRecord::Base
encrypts :password, :mode => :sha, :before => :create_salt do |user|
{:salt => user.salt}
end
private
def create_salt
self.salt = "#{login}-#{Time.now}"
end
end
In the above example, the SHA encryption's <tt>salt</tt> is configured
dynamically based on the user's login and the time at which it was
encrypted. This helps improve the security of the user's password.
|
[
"Encrypts",
"the",
"given",
"attribute",
"."
] |
2f5fba00800ab846b3b5a513d21ede19efcf681c
|
https://github.com/pluginaweek/encrypted_attributes/blob/2f5fba00800ab846b3b5a513d21ede19efcf681c/lib/encrypted_attributes.rb#L106-L152
|
8,273
|
pluginaweek/encrypted_attributes
|
lib/encrypted_attributes.rb
|
EncryptedAttributes.InstanceMethods.write_encrypted_attribute
|
def write_encrypted_attribute(attr_name, to_attr_name, cipher_class, options)
value = send(attr_name)
# Only encrypt values that actually have content and have not already
# been encrypted
unless value.blank? || value.encrypted?
callback("before_encrypt_#{attr_name}")
# Create the cipher configured for this attribute
cipher = create_cipher(cipher_class, options, value)
# Encrypt the value
value = cipher.encrypt(value)
value.cipher = cipher
# Update the value based on the target attribute
send("#{to_attr_name}=", value)
callback("after_encrypt_#{attr_name}")
end
end
|
ruby
|
def write_encrypted_attribute(attr_name, to_attr_name, cipher_class, options)
value = send(attr_name)
# Only encrypt values that actually have content and have not already
# been encrypted
unless value.blank? || value.encrypted?
callback("before_encrypt_#{attr_name}")
# Create the cipher configured for this attribute
cipher = create_cipher(cipher_class, options, value)
# Encrypt the value
value = cipher.encrypt(value)
value.cipher = cipher
# Update the value based on the target attribute
send("#{to_attr_name}=", value)
callback("after_encrypt_#{attr_name}")
end
end
|
[
"def",
"write_encrypted_attribute",
"(",
"attr_name",
",",
"to_attr_name",
",",
"cipher_class",
",",
"options",
")",
"value",
"=",
"send",
"(",
"attr_name",
")",
"# Only encrypt values that actually have content and have not already",
"# been encrypted",
"unless",
"value",
".",
"blank?",
"||",
"value",
".",
"encrypted?",
"callback",
"(",
"\"before_encrypt_#{attr_name}\"",
")",
"# Create the cipher configured for this attribute",
"cipher",
"=",
"create_cipher",
"(",
"cipher_class",
",",
"options",
",",
"value",
")",
"# Encrypt the value",
"value",
"=",
"cipher",
".",
"encrypt",
"(",
"value",
")",
"value",
".",
"cipher",
"=",
"cipher",
"# Update the value based on the target attribute",
"send",
"(",
"\"#{to_attr_name}=\"",
",",
"value",
")",
"callback",
"(",
"\"after_encrypt_#{attr_name}\"",
")",
"end",
"end"
] |
Encrypts the given attribute to a target location using the encryption
options configured for that attribute
|
[
"Encrypts",
"the",
"given",
"attribute",
"to",
"a",
"target",
"location",
"using",
"the",
"encryption",
"options",
"configured",
"for",
"that",
"attribute"
] |
2f5fba00800ab846b3b5a513d21ede19efcf681c
|
https://github.com/pluginaweek/encrypted_attributes/blob/2f5fba00800ab846b3b5a513d21ede19efcf681c/lib/encrypted_attributes.rb#L159-L179
|
8,274
|
pluginaweek/encrypted_attributes
|
lib/encrypted_attributes.rb
|
EncryptedAttributes.InstanceMethods.read_encrypted_attribute
|
def read_encrypted_attribute(to_attr_name, cipher_class, options)
value = read_attribute(to_attr_name)
# Make sure we set the cipher for equality comparison when reading
# from the database. This should only be done if the value is *not*
# blank, is *not* encrypted, and hasn't changed since it was read from
# the database. The dirty checking is important when the encypted value
# is written to the same attribute as the unencrypted value (i.e. you
# don't want to encrypt when a new value has been set)
unless value.blank? || value.encrypted? || attribute_changed?(to_attr_name)
# Create the cipher configured for this attribute
value.cipher = create_cipher(cipher_class, options, value)
end
value
end
|
ruby
|
def read_encrypted_attribute(to_attr_name, cipher_class, options)
value = read_attribute(to_attr_name)
# Make sure we set the cipher for equality comparison when reading
# from the database. This should only be done if the value is *not*
# blank, is *not* encrypted, and hasn't changed since it was read from
# the database. The dirty checking is important when the encypted value
# is written to the same attribute as the unencrypted value (i.e. you
# don't want to encrypt when a new value has been set)
unless value.blank? || value.encrypted? || attribute_changed?(to_attr_name)
# Create the cipher configured for this attribute
value.cipher = create_cipher(cipher_class, options, value)
end
value
end
|
[
"def",
"read_encrypted_attribute",
"(",
"to_attr_name",
",",
"cipher_class",
",",
"options",
")",
"value",
"=",
"read_attribute",
"(",
"to_attr_name",
")",
"# Make sure we set the cipher for equality comparison when reading",
"# from the database. This should only be done if the value is *not*",
"# blank, is *not* encrypted, and hasn't changed since it was read from",
"# the database. The dirty checking is important when the encypted value",
"# is written to the same attribute as the unencrypted value (i.e. you",
"# don't want to encrypt when a new value has been set)",
"unless",
"value",
".",
"blank?",
"||",
"value",
".",
"encrypted?",
"||",
"attribute_changed?",
"(",
"to_attr_name",
")",
"# Create the cipher configured for this attribute",
"value",
".",
"cipher",
"=",
"create_cipher",
"(",
"cipher_class",
",",
"options",
",",
"value",
")",
"end",
"value",
"end"
] |
Reads the given attribute from the database, adding contextual
information about how it was encrypted so that equality comparisons
can be used
|
[
"Reads",
"the",
"given",
"attribute",
"from",
"the",
"database",
"adding",
"contextual",
"information",
"about",
"how",
"it",
"was",
"encrypted",
"so",
"that",
"equality",
"comparisons",
"can",
"be",
"used"
] |
2f5fba00800ab846b3b5a513d21ede19efcf681c
|
https://github.com/pluginaweek/encrypted_attributes/blob/2f5fba00800ab846b3b5a513d21ede19efcf681c/lib/encrypted_attributes.rb#L184-L199
|
8,275
|
pluginaweek/encrypted_attributes
|
lib/encrypted_attributes.rb
|
EncryptedAttributes.InstanceMethods.create_cipher
|
def create_cipher(klass, options, value)
options = options.is_a?(Proc) ? options.call(self) : options.dup
# Only use the contextual information for this plugin's ciphers
klass.parent == EncryptedAttributes ? klass.new(value, options) : klass.new(options)
end
|
ruby
|
def create_cipher(klass, options, value)
options = options.is_a?(Proc) ? options.call(self) : options.dup
# Only use the contextual information for this plugin's ciphers
klass.parent == EncryptedAttributes ? klass.new(value, options) : klass.new(options)
end
|
[
"def",
"create_cipher",
"(",
"klass",
",",
"options",
",",
"value",
")",
"options",
"=",
"options",
".",
"is_a?",
"(",
"Proc",
")",
"?",
"options",
".",
"call",
"(",
"self",
")",
":",
"options",
".",
"dup",
"# Only use the contextual information for this plugin's ciphers",
"klass",
".",
"parent",
"==",
"EncryptedAttributes",
"?",
"klass",
".",
"new",
"(",
"value",
",",
"options",
")",
":",
"klass",
".",
"new",
"(",
"options",
")",
"end"
] |
Creates a new cipher with the given configuration options
|
[
"Creates",
"a",
"new",
"cipher",
"with",
"the",
"given",
"configuration",
"options"
] |
2f5fba00800ab846b3b5a513d21ede19efcf681c
|
https://github.com/pluginaweek/encrypted_attributes/blob/2f5fba00800ab846b3b5a513d21ede19efcf681c/lib/encrypted_attributes.rb#L202-L207
|
8,276
|
jeremyz/edoors-ruby
|
lib/edoors/room.rb
|
Edoors.Room.add_iota
|
def add_iota i
raise Edoors::Exception.new "Iota #{i.name} already has #{i.parent.name} as parent" if not i.parent.nil? and i.parent!=self
raise Edoors::Exception.new "Iota #{i.name} already exists in #{path}" if @iotas.has_key? i.name
i.parent = self if i.parent.nil?
@iotas[i.name]=i
end
|
ruby
|
def add_iota i
raise Edoors::Exception.new "Iota #{i.name} already has #{i.parent.name} as parent" if not i.parent.nil? and i.parent!=self
raise Edoors::Exception.new "Iota #{i.name} already exists in #{path}" if @iotas.has_key? i.name
i.parent = self if i.parent.nil?
@iotas[i.name]=i
end
|
[
"def",
"add_iota",
"i",
"raise",
"Edoors",
"::",
"Exception",
".",
"new",
"\"Iota #{i.name} already has #{i.parent.name} as parent\"",
"if",
"not",
"i",
".",
"parent",
".",
"nil?",
"and",
"i",
".",
"parent!",
"=",
"self",
"raise",
"Edoors",
"::",
"Exception",
".",
"new",
"\"Iota #{i.name} already exists in #{path}\"",
"if",
"@iotas",
".",
"has_key?",
"i",
".",
"name",
"i",
".",
"parent",
"=",
"self",
"if",
"i",
".",
"parent",
".",
"nil?",
"@iotas",
"[",
"i",
".",
"name",
"]",
"=",
"i",
"end"
] |
adds the given Iota to this Room
@param [Iota] i the Iota to add
@raise Edoors::Exception if i already has a parent or if a Iota with the same name already exists
|
[
"adds",
"the",
"given",
"Iota",
"to",
"this",
"Room"
] |
4f065f63125907b3a4f72fbab8722c58ccab41c1
|
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/room.rb#L90-L95
|
8,277
|
jeremyz/edoors-ruby
|
lib/edoors/room.rb
|
Edoors.Room.add_link
|
def add_link l
l.door = @iotas[l.src]
raise Edoors::Exception.new "Link source #{l.src} does not exist in #{path}" if l.door.nil?
(@links[l.src] ||= [])<< l
end
|
ruby
|
def add_link l
l.door = @iotas[l.src]
raise Edoors::Exception.new "Link source #{l.src} does not exist in #{path}" if l.door.nil?
(@links[l.src] ||= [])<< l
end
|
[
"def",
"add_link",
"l",
"l",
".",
"door",
"=",
"@iotas",
"[",
"l",
".",
"src",
"]",
"raise",
"Edoors",
"::",
"Exception",
".",
"new",
"\"Link source #{l.src} does not exist in #{path}\"",
"if",
"l",
".",
"door",
".",
"nil?",
"(",
"@links",
"[",
"l",
".",
"src",
"]",
"||=",
"[",
"]",
")",
"<<",
"l",
"end"
] |
adds the given Link to this Room
@param [Link] l the Link to add
@raise Edoors::Exception if the link source can't be found in this Room
|
[
"adds",
"the",
"given",
"Link",
"to",
"this",
"Room"
] |
4f065f63125907b3a4f72fbab8722c58ccab41c1
|
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/room.rb#L103-L107
|
8,278
|
jeremyz/edoors-ruby
|
lib/edoors/room.rb
|
Edoors.Room._try_links
|
def _try_links p
puts " -> try_links ..." if @spin.debug_routing
links = @links[p.src.name]
return false if links.nil?
pending_link = nil
links.each do |link|
if p.link_with? link
if pending_link
p2 = @spin.require_p p.class
p2.clone_data p
p2.apply_link! pending_link
send_p p2
end
pending_link = link
end
end
if pending_link
p.apply_link! pending_link
_send p
end
pending_link
end
|
ruby
|
def _try_links p
puts " -> try_links ..." if @spin.debug_routing
links = @links[p.src.name]
return false if links.nil?
pending_link = nil
links.each do |link|
if p.link_with? link
if pending_link
p2 = @spin.require_p p.class
p2.clone_data p
p2.apply_link! pending_link
send_p p2
end
pending_link = link
end
end
if pending_link
p.apply_link! pending_link
_send p
end
pending_link
end
|
[
"def",
"_try_links",
"p",
"puts",
"\" -> try_links ...\"",
"if",
"@spin",
".",
"debug_routing",
"links",
"=",
"@links",
"[",
"p",
".",
"src",
".",
"name",
"]",
"return",
"false",
"if",
"links",
".",
"nil?",
"pending_link",
"=",
"nil",
"links",
".",
"each",
"do",
"|",
"link",
"|",
"if",
"p",
".",
"link_with?",
"link",
"if",
"pending_link",
"p2",
"=",
"@spin",
".",
"require_p",
"p",
".",
"class",
"p2",
".",
"clone_data",
"p",
"p2",
".",
"apply_link!",
"pending_link",
"send_p",
"p2",
"end",
"pending_link",
"=",
"link",
"end",
"end",
"if",
"pending_link",
"p",
".",
"apply_link!",
"pending_link",
"_send",
"p",
"end",
"pending_link",
"end"
] |
search for a matching link
@param [Particle] p the Particle searching for a matching link
|
[
"search",
"for",
"a",
"matching",
"link"
] |
4f065f63125907b3a4f72fbab8722c58ccab41c1
|
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/room.rb#L149-L170
|
8,279
|
jeremyz/edoors-ruby
|
lib/edoors/room.rb
|
Edoors.Room._route
|
def _route p
if p.room.nil? or p.room==path
if door = @iotas[p.door]
p.dst_routed! door
else
p.error! Edoors::ERROR_ROUTE_RRWD
end
elsif door = @spin.search_world(p.room+Edoors::PATH_SEP+p.door)
p.dst_routed! door
else
p.error! Edoors::ERROR_ROUTE_DNE
end
end
|
ruby
|
def _route p
if p.room.nil? or p.room==path
if door = @iotas[p.door]
p.dst_routed! door
else
p.error! Edoors::ERROR_ROUTE_RRWD
end
elsif door = @spin.search_world(p.room+Edoors::PATH_SEP+p.door)
p.dst_routed! door
else
p.error! Edoors::ERROR_ROUTE_DNE
end
end
|
[
"def",
"_route",
"p",
"if",
"p",
".",
"room",
".",
"nil?",
"or",
"p",
".",
"room",
"==",
"path",
"if",
"door",
"=",
"@iotas",
"[",
"p",
".",
"door",
"]",
"p",
".",
"dst_routed!",
"door",
"else",
"p",
".",
"error!",
"Edoors",
"::",
"ERROR_ROUTE_RRWD",
"end",
"elsif",
"door",
"=",
"@spin",
".",
"search_world",
"(",
"p",
".",
"room",
"+",
"Edoors",
"::",
"PATH_SEP",
"+",
"p",
".",
"door",
")",
"p",
".",
"dst_routed!",
"door",
"else",
"p",
".",
"error!",
"Edoors",
"::",
"ERROR_ROUTE_DNE",
"end",
"end"
] |
route the given Particle
@param [Particle] p the Particle to be routed
|
[
"route",
"the",
"given",
"Particle"
] |
4f065f63125907b3a4f72fbab8722c58ccab41c1
|
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/room.rb#L177-L189
|
8,280
|
jeremyz/edoors-ruby
|
lib/edoors/room.rb
|
Edoors.Room._send
|
def _send p, sys=false
if not sys and p.src.nil?
# do not route non system orphan particles !!
p.error! Edoors::ERROR_ROUTE_NS, @spin
elsif p.dst
# direct routing through pointer
return
elsif p.door
# direct routing through path
_route p
elsif p.next_dst
p.split_dst!
if p.door
_route p
elsif not sys
# boomerang
p.dst_routed! p.src
elsif p.action
p.dst_routed! @spin
end
elsif not sys and _try_links p
return
else
p.error!( sys ? Edoors::ERROR_ROUTE_SND : Edoors::ERROR_ROUTE_NDNL)
end
end
|
ruby
|
def _send p, sys=false
if not sys and p.src.nil?
# do not route non system orphan particles !!
p.error! Edoors::ERROR_ROUTE_NS, @spin
elsif p.dst
# direct routing through pointer
return
elsif p.door
# direct routing through path
_route p
elsif p.next_dst
p.split_dst!
if p.door
_route p
elsif not sys
# boomerang
p.dst_routed! p.src
elsif p.action
p.dst_routed! @spin
end
elsif not sys and _try_links p
return
else
p.error!( sys ? Edoors::ERROR_ROUTE_SND : Edoors::ERROR_ROUTE_NDNL)
end
end
|
[
"def",
"_send",
"p",
",",
"sys",
"=",
"false",
"if",
"not",
"sys",
"and",
"p",
".",
"src",
".",
"nil?",
"# do not route non system orphan particles !!",
"p",
".",
"error!",
"Edoors",
"::",
"ERROR_ROUTE_NS",
",",
"@spin",
"elsif",
"p",
".",
"dst",
"# direct routing through pointer",
"return",
"elsif",
"p",
".",
"door",
"# direct routing through path",
"_route",
"p",
"elsif",
"p",
".",
"next_dst",
"p",
".",
"split_dst!",
"if",
"p",
".",
"door",
"_route",
"p",
"elsif",
"not",
"sys",
"# boomerang",
"p",
".",
"dst_routed!",
"p",
".",
"src",
"elsif",
"p",
".",
"action",
"p",
".",
"dst_routed!",
"@spin",
"end",
"elsif",
"not",
"sys",
"and",
"_try_links",
"p",
"return",
"else",
"p",
".",
"error!",
"(",
"sys",
"?",
"Edoors",
"::",
"ERROR_ROUTE_SND",
":",
"Edoors",
"::",
"ERROR_ROUTE_NDNL",
")",
"end",
"end"
] |
send the given Particle
@param [Particle] p the Particle to send
@param [Boolean] sys if true send to system Particle fifo
|
[
"send",
"the",
"given",
"Particle"
] |
4f065f63125907b3a4f72fbab8722c58ccab41c1
|
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/room.rb#L197-L222
|
8,281
|
jeremyz/edoors-ruby
|
lib/edoors/room.rb
|
Edoors.Room.send_p
|
def send_p p
puts " * send_p #{(p.next_dst.nil? ? 'no dst' : p.next_dst)} ..." if @spin.debug_routing
_send p
puts " -> #{p.dst.path}#{Edoors::ACT_SEP}#{p.action}" if @spin.debug_routing
@spin.post_p p
end
|
ruby
|
def send_p p
puts " * send_p #{(p.next_dst.nil? ? 'no dst' : p.next_dst)} ..." if @spin.debug_routing
_send p
puts " -> #{p.dst.path}#{Edoors::ACT_SEP}#{p.action}" if @spin.debug_routing
@spin.post_p p
end
|
[
"def",
"send_p",
"p",
"puts",
"\" * send_p #{(p.next_dst.nil? ? 'no dst' : p.next_dst)} ...\"",
"if",
"@spin",
".",
"debug_routing",
"_send",
"p",
"puts",
"\" -> #{p.dst.path}#{Edoors::ACT_SEP}#{p.action}\"",
"if",
"@spin",
".",
"debug_routing",
"@spin",
".",
"post_p",
"p",
"end"
] |
send the given Particle to application Particle fifo
@param [Particle] p the Particle to send
|
[
"send",
"the",
"given",
"Particle",
"to",
"application",
"Particle",
"fifo"
] |
4f065f63125907b3a4f72fbab8722c58ccab41c1
|
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/room.rb#L229-L234
|
8,282
|
jeremyz/edoors-ruby
|
lib/edoors/room.rb
|
Edoors.Room.send_sys_p
|
def send_sys_p p
puts " * send_sys_p #{(p.next_dst.nil? ? 'no dst' : p.next_dst)} ..." if @spin.debug_routing
_send p, true
puts " -> #{p.dst.path}#{Edoors::ACT_SEP}#{p.action}" if @spin.debug_routing
@spin.post_sys_p p
end
|
ruby
|
def send_sys_p p
puts " * send_sys_p #{(p.next_dst.nil? ? 'no dst' : p.next_dst)} ..." if @spin.debug_routing
_send p, true
puts " -> #{p.dst.path}#{Edoors::ACT_SEP}#{p.action}" if @spin.debug_routing
@spin.post_sys_p p
end
|
[
"def",
"send_sys_p",
"p",
"puts",
"\" * send_sys_p #{(p.next_dst.nil? ? 'no dst' : p.next_dst)} ...\"",
"if",
"@spin",
".",
"debug_routing",
"_send",
"p",
",",
"true",
"puts",
"\" -> #{p.dst.path}#{Edoors::ACT_SEP}#{p.action}\"",
"if",
"@spin",
".",
"debug_routing",
"@spin",
".",
"post_sys_p",
"p",
"end"
] |
send the given Particle to system Particle fifo
@param [Particle] p the Particle to send
|
[
"send",
"the",
"given",
"Particle",
"to",
"system",
"Particle",
"fifo"
] |
4f065f63125907b3a4f72fbab8722c58ccab41c1
|
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/room.rb#L240-L245
|
8,283
|
jeremyz/edoors-ruby
|
lib/edoors/room.rb
|
Edoors.Room.process_sys_p
|
def process_sys_p p
if p.action==Edoors::SYS_ACT_ADD_LINK
add_link Edoors::Link.from_particle p
elsif p.action==Edoors::SYS_ACT_ADD_ROOM
Edoors::Room.from_particle p, self
end
@spin.release_p p
end
|
ruby
|
def process_sys_p p
if p.action==Edoors::SYS_ACT_ADD_LINK
add_link Edoors::Link.from_particle p
elsif p.action==Edoors::SYS_ACT_ADD_ROOM
Edoors::Room.from_particle p, self
end
@spin.release_p p
end
|
[
"def",
"process_sys_p",
"p",
"if",
"p",
".",
"action",
"==",
"Edoors",
"::",
"SYS_ACT_ADD_LINK",
"add_link",
"Edoors",
"::",
"Link",
".",
"from_particle",
"p",
"elsif",
"p",
".",
"action",
"==",
"Edoors",
"::",
"SYS_ACT_ADD_ROOM",
"Edoors",
"::",
"Room",
".",
"from_particle",
"p",
",",
"self",
"end",
"@spin",
".",
"release_p",
"p",
"end"
] |
process the given system Particle
@param [Particle] p the Particle to be processed
@note the Particle is automatically released
|
[
"process",
"the",
"given",
"system",
"Particle"
] |
4f065f63125907b3a4f72fbab8722c58ccab41c1
|
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/room.rb#L253-L260
|
8,284
|
nobuhiko-ido/Ixyml
|
lib/ixyml/xyml.rb
|
Xyml.Document.out_XML
|
def out_XML io,indent=nil
if indent
Xyml.rawobj2domobj(@root).write(io,indent.to_i)
else
sio=StringIO.new
Xyml.rawobj2domobj(@root).write(sio)
sio.rewind
io.print sio.read,"\n"
end
io.close
end
|
ruby
|
def out_XML io,indent=nil
if indent
Xyml.rawobj2domobj(@root).write(io,indent.to_i)
else
sio=StringIO.new
Xyml.rawobj2domobj(@root).write(sio)
sio.rewind
io.print sio.read,"\n"
end
io.close
end
|
[
"def",
"out_XML",
"io",
",",
"indent",
"=",
"nil",
"if",
"indent",
"Xyml",
".",
"rawobj2domobj",
"(",
"@root",
")",
".",
"write",
"(",
"io",
",",
"indent",
".",
"to_i",
")",
"else",
"sio",
"=",
"StringIO",
".",
"new",
"Xyml",
".",
"rawobj2domobj",
"(",
"@root",
")",
".",
"write",
"(",
"sio",
")",
"sio",
".",
"rewind",
"io",
".",
"print",
"sio",
".",
"read",
",",
"\"\\n\"",
"end",
"io",
".",
"close",
"end"
] |
save an XML file corresponding to the tree data in the self through the designated IO.
自身のツリーデータを、指定されたIOを通して、XMLファイルに保存する。
==== Args
_indent_(if not nil) :: a saved XML file is formatted with the designaged indent.
xyml_tree=Xyml::Document.new({a: [{b: "ccc"},{d: ["eee"]}]})
#-> [{a: [{b: "ccc"},{d: ["eee"]}]}]
xyml_tree.out_XML(File.open("aaa.xml","w"))
#-> aaa.xml
# <a b="ccc">
# <d>eee</d>
# </a>
|
[
"save",
"an",
"XML",
"file",
"corresponding",
"to",
"the",
"tree",
"data",
"in",
"the",
"self",
"through",
"the",
"designated",
"IO",
"."
] |
6a540024cdf5f1fc92f7ec86c98badeeb18d5694
|
https://github.com/nobuhiko-ido/Ixyml/blob/6a540024cdf5f1fc92f7ec86c98badeeb18d5694/lib/ixyml/xyml.rb#L430-L441
|
8,285
|
nobuhiko-ido/Ixyml
|
lib/ixyml/xyml.rb
|
Xyml.Document.load_XYML
|
def load_XYML io
raw_yaml=YAML.load(io)
@root=Xyml.rawobj2element raw_yaml[0]
self.clear.push @root
io.close
end
|
ruby
|
def load_XYML io
raw_yaml=YAML.load(io)
@root=Xyml.rawobj2element raw_yaml[0]
self.clear.push @root
io.close
end
|
[
"def",
"load_XYML",
"io",
"raw_yaml",
"=",
"YAML",
".",
"load",
"(",
"io",
")",
"@root",
"=",
"Xyml",
".",
"rawobj2element",
"raw_yaml",
"[",
"0",
"]",
"self",
".",
"clear",
".",
"push",
"@root",
"io",
".",
"close",
"end"
] |
load an XYML file through the designated IO and set the tree data in the file to the self.
XYMLファイルをIOよりロードして、そのツリーデータを自身に設定する。
# aaa.xyml
# - a:
# -b: ccc
# -d:
# - eee
xyml_tree=Xyml::Document.new
xyml_tree.load_XYML(File.open("aaa.xyml"))
#-> [{a: [{b: "ccc"},{d: ["eee"]}]}]
|
[
"load",
"an",
"XYML",
"file",
"through",
"the",
"designated",
"IO",
"and",
"set",
"the",
"tree",
"data",
"in",
"the",
"file",
"to",
"the",
"self",
"."
] |
6a540024cdf5f1fc92f7ec86c98badeeb18d5694
|
https://github.com/nobuhiko-ido/Ixyml/blob/6a540024cdf5f1fc92f7ec86c98badeeb18d5694/lib/ixyml/xyml.rb#L495-L500
|
8,286
|
nobuhiko-ido/Ixyml
|
lib/ixyml/xyml.rb
|
Xyml.Document.out_JSON
|
def out_JSON io
serialized=JSON.generate(Xyml.remove_parent_rcsv(self))
io.print serialized
io.close
end
|
ruby
|
def out_JSON io
serialized=JSON.generate(Xyml.remove_parent_rcsv(self))
io.print serialized
io.close
end
|
[
"def",
"out_JSON",
"io",
"serialized",
"=",
"JSON",
".",
"generate",
"(",
"Xyml",
".",
"remove_parent_rcsv",
"(",
"self",
")",
")",
"io",
".",
"print",
"serialized",
"io",
".",
"close",
"end"
] |
save a JSON file corresponding to the tree data in the self through the designated IO.
Note that a JSON file can be loaded by load_XYML method because JSON is a part of YAML.
自身のツリーデータを、指定されたIOを通して、JSONファイルに保存する。JSONファイルのロードは、
_load_XYML_メソッドで実施できることに注意(JSONはYAML仕様の一部分となっているため)。
xyml_tree=Xyml::Document.new({a: [{b: "ccc"},{d: ["eee"]}]})
#-> [{a: [{b: "ccc"},{d: ["eee"]}]}]
xyml_tree.out_JSON(File.open("aaa.json","w"))
#-> aaa.jdon
# [{"a":[{"b":"ccc"},{"d":["eee"]}]}]
|
[
"save",
"a",
"JSON",
"file",
"corresponding",
"to",
"the",
"tree",
"data",
"in",
"the",
"self",
"through",
"the",
"designated",
"IO",
".",
"Note",
"that",
"a",
"JSON",
"file",
"can",
"be",
"loaded",
"by",
"load_XYML",
"method",
"because",
"JSON",
"is",
"a",
"part",
"of",
"YAML",
"."
] |
6a540024cdf5f1fc92f7ec86c98badeeb18d5694
|
https://github.com/nobuhiko-ido/Ixyml/blob/6a540024cdf5f1fc92f7ec86c98badeeb18d5694/lib/ixyml/xyml.rb#L512-L516
|
8,287
|
conversation/raca
|
lib/raca/account.rb
|
Raca.Account.public_endpoint
|
def public_endpoint(service_name, region = nil)
return IDENTITY_URL if service_name == "identity"
endpoints = service_endpoints(service_name)
if endpoints.size > 1 && region
region = region.to_s.upcase
endpoints = endpoints.select { |e| e["region"] == region } || {}
elsif endpoints.size > 1 && region.nil?
raise ArgumentError, "The requested service exists in multiple regions, please specify a region code"
end
if endpoints.size == 0
raise ArgumentError, "No matching services found"
else
endpoints.first["publicURL"]
end
end
|
ruby
|
def public_endpoint(service_name, region = nil)
return IDENTITY_URL if service_name == "identity"
endpoints = service_endpoints(service_name)
if endpoints.size > 1 && region
region = region.to_s.upcase
endpoints = endpoints.select { |e| e["region"] == region } || {}
elsif endpoints.size > 1 && region.nil?
raise ArgumentError, "The requested service exists in multiple regions, please specify a region code"
end
if endpoints.size == 0
raise ArgumentError, "No matching services found"
else
endpoints.first["publicURL"]
end
end
|
[
"def",
"public_endpoint",
"(",
"service_name",
",",
"region",
"=",
"nil",
")",
"return",
"IDENTITY_URL",
"if",
"service_name",
"==",
"\"identity\"",
"endpoints",
"=",
"service_endpoints",
"(",
"service_name",
")",
"if",
"endpoints",
".",
"size",
">",
"1",
"&&",
"region",
"region",
"=",
"region",
".",
"to_s",
".",
"upcase",
"endpoints",
"=",
"endpoints",
".",
"select",
"{",
"|",
"e",
"|",
"e",
"[",
"\"region\"",
"]",
"==",
"region",
"}",
"||",
"{",
"}",
"elsif",
"endpoints",
".",
"size",
">",
"1",
"&&",
"region",
".",
"nil?",
"raise",
"ArgumentError",
",",
"\"The requested service exists in multiple regions, please specify a region code\"",
"end",
"if",
"endpoints",
".",
"size",
"==",
"0",
"raise",
"ArgumentError",
",",
"\"No matching services found\"",
"else",
"endpoints",
".",
"first",
"[",
"\"publicURL\"",
"]",
"end",
"end"
] |
Return the public API URL for a particular rackspace service.
Use Account#service_names to see a list of valid service_name's for this.
Check the project README for an updated list of the available regions.
account = Raca::Account.new("username", "secret")
puts account.public_endpoint("cloudServers", :syd)
Some service APIs are not regioned. In those cases, the region code can be
left off:
account = Raca::Account.new("username", "secret")
puts account.public_endpoint("cloudDNS")
|
[
"Return",
"the",
"public",
"API",
"URL",
"for",
"a",
"particular",
"rackspace",
"service",
"."
] |
fa69dfde22359cc0e06f655055be4eadcc7019c0
|
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/account.rb#L47-L63
|
8,288
|
conversation/raca
|
lib/raca/account.rb
|
Raca.Account.refresh_cache
|
def refresh_cache
# Raca::HttpClient depends on Raca::Account, so we intentionally don't use it here
# to avoid a circular dependency
Net::HTTP.new(identity_host, 443).tap {|http|
http.use_ssl = true
}.start {|http|
payload = {
auth: {
'RAX-KSKEY:apiKeyCredentials' => {
username: @username,
apiKey: @key
}
}
}
response = http.post(
tokens_path,
JSON.dump(payload),
{'Content-Type' => 'application/json'},
)
if response.is_a?(Net::HTTPSuccess)
cache_write(cache_key, JSON.load(response.body))
else
raise_on_error(response)
end
}
end
|
ruby
|
def refresh_cache
# Raca::HttpClient depends on Raca::Account, so we intentionally don't use it here
# to avoid a circular dependency
Net::HTTP.new(identity_host, 443).tap {|http|
http.use_ssl = true
}.start {|http|
payload = {
auth: {
'RAX-KSKEY:apiKeyCredentials' => {
username: @username,
apiKey: @key
}
}
}
response = http.post(
tokens_path,
JSON.dump(payload),
{'Content-Type' => 'application/json'},
)
if response.is_a?(Net::HTTPSuccess)
cache_write(cache_key, JSON.load(response.body))
else
raise_on_error(response)
end
}
end
|
[
"def",
"refresh_cache",
"# Raca::HttpClient depends on Raca::Account, so we intentionally don't use it here",
"# to avoid a circular dependency",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"identity_host",
",",
"443",
")",
".",
"tap",
"{",
"|",
"http",
"|",
"http",
".",
"use_ssl",
"=",
"true",
"}",
".",
"start",
"{",
"|",
"http",
"|",
"payload",
"=",
"{",
"auth",
":",
"{",
"'RAX-KSKEY:apiKeyCredentials'",
"=>",
"{",
"username",
":",
"@username",
",",
"apiKey",
":",
"@key",
"}",
"}",
"}",
"response",
"=",
"http",
".",
"post",
"(",
"tokens_path",
",",
"JSON",
".",
"dump",
"(",
"payload",
")",
",",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
",",
")",
"if",
"response",
".",
"is_a?",
"(",
"Net",
"::",
"HTTPSuccess",
")",
"cache_write",
"(",
"cache_key",
",",
"JSON",
".",
"load",
"(",
"response",
".",
"body",
")",
")",
"else",
"raise_on_error",
"(",
"response",
")",
"end",
"}",
"end"
] |
Raca classes use this method to occasionally re-authenticate with the rackspace
servers. You can probably ignore it.
|
[
"Raca",
"classes",
"use",
"this",
"method",
"to",
"occasionally",
"re",
"-",
"authenticate",
"with",
"the",
"rackspace",
"servers",
".",
"You",
"can",
"probably",
"ignore",
"it",
"."
] |
fa69dfde22359cc0e06f655055be4eadcc7019c0
|
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/account.rb#L114-L139
|
8,289
|
conversation/raca
|
lib/raca/account.rb
|
Raca.Account.extract_value
|
def extract_value(data, *keys)
if keys.empty?
data
elsif data.respond_to?(:[]) && data[keys.first]
extract_value(data[keys.first], *keys.slice(1,100))
else
nil
end
end
|
ruby
|
def extract_value(data, *keys)
if keys.empty?
data
elsif data.respond_to?(:[]) && data[keys.first]
extract_value(data[keys.first], *keys.slice(1,100))
else
nil
end
end
|
[
"def",
"extract_value",
"(",
"data",
",",
"*",
"keys",
")",
"if",
"keys",
".",
"empty?",
"data",
"elsif",
"data",
".",
"respond_to?",
"(",
":[]",
")",
"&&",
"data",
"[",
"keys",
".",
"first",
"]",
"extract_value",
"(",
"data",
"[",
"keys",
".",
"first",
"]",
",",
"keys",
".",
"slice",
"(",
"1",
",",
"100",
")",
")",
"else",
"nil",
"end",
"end"
] |
This method is opaque, but it was the best I could come up with using just
the standard library. Sorry.
Use this to safely extract values from nested hashes:
data = {a: {b: {c: 1}}}
extract_value(data, :a, :b, :c)
=> 1
extract_value(data, :a, :b, :d)
=> nil
extract_value(data, :d)
=> nil
|
[
"This",
"method",
"is",
"opaque",
"but",
"it",
"was",
"the",
"best",
"I",
"could",
"come",
"up",
"with",
"using",
"just",
"the",
"standard",
"library",
".",
"Sorry",
"."
] |
fa69dfde22359cc0e06f655055be4eadcc7019c0
|
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/account.rb#L192-L200
|
8,290
|
mikemackintosh/slackdraft
|
lib/slackdraft/message.rb
|
Slackdraft.Message.generate_payload
|
def generate_payload
payload = {}
payload[:channel] = self.channel unless self.channel.nil?
payload[:username] = self.username unless self.username.nil?
payload[:icon_url] = self.icon_url unless self.icon_url.nil?
payload[:icon_emoji] = self.icon_emoji unless self.icon_emoji.nil?
payload[:text] = self.text unless self.text.nil?
payload[:attachments] = self.attachments unless self.attachments.empty?
payload
end
|
ruby
|
def generate_payload
payload = {}
payload[:channel] = self.channel unless self.channel.nil?
payload[:username] = self.username unless self.username.nil?
payload[:icon_url] = self.icon_url unless self.icon_url.nil?
payload[:icon_emoji] = self.icon_emoji unless self.icon_emoji.nil?
payload[:text] = self.text unless self.text.nil?
payload[:attachments] = self.attachments unless self.attachments.empty?
payload
end
|
[
"def",
"generate_payload",
"payload",
"=",
"{",
"}",
"payload",
"[",
":channel",
"]",
"=",
"self",
".",
"channel",
"unless",
"self",
".",
"channel",
".",
"nil?",
"payload",
"[",
":username",
"]",
"=",
"self",
".",
"username",
"unless",
"self",
".",
"username",
".",
"nil?",
"payload",
"[",
":icon_url",
"]",
"=",
"self",
".",
"icon_url",
"unless",
"self",
".",
"icon_url",
".",
"nil?",
"payload",
"[",
":icon_emoji",
"]",
"=",
"self",
".",
"icon_emoji",
"unless",
"self",
".",
"icon_emoji",
".",
"nil?",
"payload",
"[",
":text",
"]",
"=",
"self",
".",
"text",
"unless",
"self",
".",
"text",
".",
"nil?",
"payload",
"[",
":attachments",
"]",
"=",
"self",
".",
"attachments",
"unless",
"self",
".",
"attachments",
".",
"empty?",
"payload",
"end"
] |
Generate the payload if stuff was provided
|
[
"Generate",
"the",
"payload",
"if",
"stuff",
"was",
"provided"
] |
4025fe370f468750fdf5a0dc9741871bca897c0a
|
https://github.com/mikemackintosh/slackdraft/blob/4025fe370f468750fdf5a0dc9741871bca897c0a/lib/slackdraft/message.rb#L55-L65
|
8,291
|
zh/rss-client
|
lib/rss-client/http-access2.rb
|
HTTPAccess2.Client.set_basic_auth
|
def set_basic_auth(uri, user, passwd)
uri = urify(uri)
@www_auth.basic_auth.set(uri, user, passwd)
reset_all
end
|
ruby
|
def set_basic_auth(uri, user, passwd)
uri = urify(uri)
@www_auth.basic_auth.set(uri, user, passwd)
reset_all
end
|
[
"def",
"set_basic_auth",
"(",
"uri",
",",
"user",
",",
"passwd",
")",
"uri",
"=",
"urify",
"(",
"uri",
")",
"@www_auth",
".",
"basic_auth",
".",
"set",
"(",
"uri",
",",
"user",
",",
"passwd",
")",
"reset_all",
"end"
] |
for backward compatibility
|
[
"for",
"backward",
"compatibility"
] |
cbc4c5146e3b5d8188e221076f56d9471f752237
|
https://github.com/zh/rss-client/blob/cbc4c5146e3b5d8188e221076f56d9471f752237/lib/rss-client/http-access2.rb#L269-L273
|
8,292
|
zh/rss-client
|
lib/rss-client/http-access2.rb
|
HTTPAccess2.SSLConfig.set_client_cert_file
|
def set_client_cert_file(cert_file, key_file)
@client_cert = OpenSSL::X509::Certificate.new(File.open(cert_file).read)
@client_key = OpenSSL::PKey::RSA.new(File.open(key_file).read)
change_notify
end
|
ruby
|
def set_client_cert_file(cert_file, key_file)
@client_cert = OpenSSL::X509::Certificate.new(File.open(cert_file).read)
@client_key = OpenSSL::PKey::RSA.new(File.open(key_file).read)
change_notify
end
|
[
"def",
"set_client_cert_file",
"(",
"cert_file",
",",
"key_file",
")",
"@client_cert",
"=",
"OpenSSL",
"::",
"X509",
"::",
"Certificate",
".",
"new",
"(",
"File",
".",
"open",
"(",
"cert_file",
")",
".",
"read",
")",
"@client_key",
"=",
"OpenSSL",
"::",
"PKey",
"::",
"RSA",
".",
"new",
"(",
"File",
".",
"open",
"(",
"key_file",
")",
".",
"read",
")",
"change_notify",
"end"
] |
don't use if you don't know what it is.
|
[
"don",
"t",
"use",
"if",
"you",
"don",
"t",
"know",
"what",
"it",
"is",
"."
] |
cbc4c5146e3b5d8188e221076f56d9471f752237
|
https://github.com/zh/rss-client/blob/cbc4c5146e3b5d8188e221076f56d9471f752237/lib/rss-client/http-access2.rb#L641-L645
|
8,293
|
zh/rss-client
|
lib/rss-client/http-access2.rb
|
HTTPAccess2.SSLConfig.set_context
|
def set_context(ctx)
# Verification: Use Store#verify_callback instead of SSLContext#verify*?
ctx.cert_store = @cert_store
ctx.verify_mode = @verify_mode
ctx.verify_depth = @verify_depth if @verify_depth
ctx.verify_callback = @verify_callback || method(:default_verify_callback)
# SSL config
ctx.cert = @client_cert
ctx.key = @client_key
ctx.client_ca = @client_ca
ctx.timeout = @timeout
ctx.options = @options
ctx.ciphers = @ciphers
end
|
ruby
|
def set_context(ctx)
# Verification: Use Store#verify_callback instead of SSLContext#verify*?
ctx.cert_store = @cert_store
ctx.verify_mode = @verify_mode
ctx.verify_depth = @verify_depth if @verify_depth
ctx.verify_callback = @verify_callback || method(:default_verify_callback)
# SSL config
ctx.cert = @client_cert
ctx.key = @client_key
ctx.client_ca = @client_ca
ctx.timeout = @timeout
ctx.options = @options
ctx.ciphers = @ciphers
end
|
[
"def",
"set_context",
"(",
"ctx",
")",
"# Verification: Use Store#verify_callback instead of SSLContext#verify*?",
"ctx",
".",
"cert_store",
"=",
"@cert_store",
"ctx",
".",
"verify_mode",
"=",
"@verify_mode",
"ctx",
".",
"verify_depth",
"=",
"@verify_depth",
"if",
"@verify_depth",
"ctx",
".",
"verify_callback",
"=",
"@verify_callback",
"||",
"method",
"(",
":default_verify_callback",
")",
"# SSL config",
"ctx",
".",
"cert",
"=",
"@client_cert",
"ctx",
".",
"key",
"=",
"@client_key",
"ctx",
".",
"client_ca",
"=",
"@client_ca",
"ctx",
".",
"timeout",
"=",
"@timeout",
"ctx",
".",
"options",
"=",
"@options",
"ctx",
".",
"ciphers",
"=",
"@ciphers",
"end"
] |
interfaces for SSLSocketWrap.
|
[
"interfaces",
"for",
"SSLSocketWrap",
"."
] |
cbc4c5146e3b5d8188e221076f56d9471f752237
|
https://github.com/zh/rss-client/blob/cbc4c5146e3b5d8188e221076f56d9471f752237/lib/rss-client/http-access2.rb#L721-L734
|
8,294
|
zh/rss-client
|
lib/rss-client/http-access2.rb
|
HTTPAccess2.BasicAuth.set
|
def set(uri, user, passwd)
if uri.nil?
@cred = ["#{user}:#{passwd}"].pack('m').tr("\n", '')
else
uri = Util.uri_dirname(uri)
@auth[uri] = ["#{user}:#{passwd}"].pack('m').tr("\n", '')
end
end
|
ruby
|
def set(uri, user, passwd)
if uri.nil?
@cred = ["#{user}:#{passwd}"].pack('m').tr("\n", '')
else
uri = Util.uri_dirname(uri)
@auth[uri] = ["#{user}:#{passwd}"].pack('m').tr("\n", '')
end
end
|
[
"def",
"set",
"(",
"uri",
",",
"user",
",",
"passwd",
")",
"if",
"uri",
".",
"nil?",
"@cred",
"=",
"[",
"\"#{user}:#{passwd}\"",
"]",
".",
"pack",
"(",
"'m'",
")",
".",
"tr",
"(",
"\"\\n\"",
",",
"''",
")",
"else",
"uri",
"=",
"Util",
".",
"uri_dirname",
"(",
"uri",
")",
"@auth",
"[",
"uri",
"]",
"=",
"[",
"\"#{user}:#{passwd}\"",
"]",
".",
"pack",
"(",
"'m'",
")",
".",
"tr",
"(",
"\"\\n\"",
",",
"''",
")",
"end",
"end"
] |
uri == nil for generic purpose
|
[
"uri",
"==",
"nil",
"for",
"generic",
"purpose"
] |
cbc4c5146e3b5d8188e221076f56d9471f752237
|
https://github.com/zh/rss-client/blob/cbc4c5146e3b5d8188e221076f56d9471f752237/lib/rss-client/http-access2.rb#L892-L899
|
8,295
|
zh/rss-client
|
lib/rss-client/http-access2.rb
|
HTTPAccess2.Session.connect
|
def connect
site = @proxy || @dest
begin
retry_number = 0
timeout(@connect_timeout) do
@socket = create_socket(site)
begin
@src.host = @socket.addr[3]
@src.port = @socket.addr[1]
rescue SocketError
# to avoid IPSocket#addr problem on Mac OS X 10.3 + ruby-1.8.1.
# cf. [ruby-talk:84909], [ruby-talk:95827]
end
if @dest.scheme == 'https'
@socket = create_ssl_socket(@socket)
connect_ssl_proxy(@socket) if @proxy
@socket.ssl_connect
@socket.post_connection_check(@dest)
@ssl_peer_cert = @socket.peer_cert
end
# Use Ruby internal buffering instead of passing data immediatly
# to the underlying layer
# => we need to to call explicitely flush on the socket
@socket.sync = @socket_sync
end
rescue TimeoutError
if @connect_retry == 0
retry
else
retry_number += 1
retry if retry_number < @connect_retry
end
close
raise
end
@state = :WAIT
@readbuf = ''
end
|
ruby
|
def connect
site = @proxy || @dest
begin
retry_number = 0
timeout(@connect_timeout) do
@socket = create_socket(site)
begin
@src.host = @socket.addr[3]
@src.port = @socket.addr[1]
rescue SocketError
# to avoid IPSocket#addr problem on Mac OS X 10.3 + ruby-1.8.1.
# cf. [ruby-talk:84909], [ruby-talk:95827]
end
if @dest.scheme == 'https'
@socket = create_ssl_socket(@socket)
connect_ssl_proxy(@socket) if @proxy
@socket.ssl_connect
@socket.post_connection_check(@dest)
@ssl_peer_cert = @socket.peer_cert
end
# Use Ruby internal buffering instead of passing data immediatly
# to the underlying layer
# => we need to to call explicitely flush on the socket
@socket.sync = @socket_sync
end
rescue TimeoutError
if @connect_retry == 0
retry
else
retry_number += 1
retry if retry_number < @connect_retry
end
close
raise
end
@state = :WAIT
@readbuf = ''
end
|
[
"def",
"connect",
"site",
"=",
"@proxy",
"||",
"@dest",
"begin",
"retry_number",
"=",
"0",
"timeout",
"(",
"@connect_timeout",
")",
"do",
"@socket",
"=",
"create_socket",
"(",
"site",
")",
"begin",
"@src",
".",
"host",
"=",
"@socket",
".",
"addr",
"[",
"3",
"]",
"@src",
".",
"port",
"=",
"@socket",
".",
"addr",
"[",
"1",
"]",
"rescue",
"SocketError",
"# to avoid IPSocket#addr problem on Mac OS X 10.3 + ruby-1.8.1.",
"# cf. [ruby-talk:84909], [ruby-talk:95827]",
"end",
"if",
"@dest",
".",
"scheme",
"==",
"'https'",
"@socket",
"=",
"create_ssl_socket",
"(",
"@socket",
")",
"connect_ssl_proxy",
"(",
"@socket",
")",
"if",
"@proxy",
"@socket",
".",
"ssl_connect",
"@socket",
".",
"post_connection_check",
"(",
"@dest",
")",
"@ssl_peer_cert",
"=",
"@socket",
".",
"peer_cert",
"end",
"# Use Ruby internal buffering instead of passing data immediatly",
"# to the underlying layer",
"# => we need to to call explicitely flush on the socket",
"@socket",
".",
"sync",
"=",
"@socket_sync",
"end",
"rescue",
"TimeoutError",
"if",
"@connect_retry",
"==",
"0",
"retry",
"else",
"retry_number",
"+=",
"1",
"retry",
"if",
"retry_number",
"<",
"@connect_retry",
"end",
"close",
"raise",
"end",
"@state",
"=",
":WAIT",
"@readbuf",
"=",
"''",
"end"
] |
Connect to the server
|
[
"Connect",
"to",
"the",
"server"
] |
cbc4c5146e3b5d8188e221076f56d9471f752237
|
https://github.com/zh/rss-client/blob/cbc4c5146e3b5d8188e221076f56d9471f752237/lib/rss-client/http-access2.rb#L1783-L1821
|
8,296
|
zh/rss-client
|
lib/rss-client/http-access2.rb
|
HTTPAccess2.Session.read_header
|
def read_header
if @state == :DATA
get_data {}
check_state()
end
unless @state == :META
raise InvalidState, 'state != :META'
end
parse_header(@socket)
@content_length = nil
@chunked = false
@headers.each do |line|
case line
when /^Content-Length:\s+(\d+)/i
@content_length = $1.to_i
when /^Transfer-Encoding:\s+chunked/i
@chunked = true
@content_length = true # how?
@chunk_length = 0
when /^Connection:\s+([\-\w]+)/i, /^Proxy-Connection:\s+([\-\w]+)/i
case $1
when /^Keep-Alive$/i
@next_connection = true
when /^close$/i
@next_connection = false
end
else
# Nothing to parse.
end
end
# Head of the request has been parsed.
@state = :DATA
req = @requests.shift
if req.header.request_method == 'HEAD'
@content_length = 0
if @next_connection
@state = :WAIT
else
close
end
end
@next_connection = false unless @content_length
return [@version, @status, @reason]
end
|
ruby
|
def read_header
if @state == :DATA
get_data {}
check_state()
end
unless @state == :META
raise InvalidState, 'state != :META'
end
parse_header(@socket)
@content_length = nil
@chunked = false
@headers.each do |line|
case line
when /^Content-Length:\s+(\d+)/i
@content_length = $1.to_i
when /^Transfer-Encoding:\s+chunked/i
@chunked = true
@content_length = true # how?
@chunk_length = 0
when /^Connection:\s+([\-\w]+)/i, /^Proxy-Connection:\s+([\-\w]+)/i
case $1
when /^Keep-Alive$/i
@next_connection = true
when /^close$/i
@next_connection = false
end
else
# Nothing to parse.
end
end
# Head of the request has been parsed.
@state = :DATA
req = @requests.shift
if req.header.request_method == 'HEAD'
@content_length = 0
if @next_connection
@state = :WAIT
else
close
end
end
@next_connection = false unless @content_length
return [@version, @status, @reason]
end
|
[
"def",
"read_header",
"if",
"@state",
"==",
":DATA",
"get_data",
"{",
"}",
"check_state",
"(",
")",
"end",
"unless",
"@state",
"==",
":META",
"raise",
"InvalidState",
",",
"'state != :META'",
"end",
"parse_header",
"(",
"@socket",
")",
"@content_length",
"=",
"nil",
"@chunked",
"=",
"false",
"@headers",
".",
"each",
"do",
"|",
"line",
"|",
"case",
"line",
"when",
"/",
"\\s",
"\\d",
"/i",
"@content_length",
"=",
"$1",
".",
"to_i",
"when",
"/",
"\\s",
"/i",
"@chunked",
"=",
"true",
"@content_length",
"=",
"true",
"# how?",
"@chunk_length",
"=",
"0",
"when",
"/",
"\\s",
"\\-",
"\\w",
"/i",
",",
"/",
"\\s",
"\\-",
"\\w",
"/i",
"case",
"$1",
"when",
"/",
"/i",
"@next_connection",
"=",
"true",
"when",
"/",
"/i",
"@next_connection",
"=",
"false",
"end",
"else",
"# Nothing to parse.",
"end",
"end",
"# Head of the request has been parsed.",
"@state",
"=",
":DATA",
"req",
"=",
"@requests",
".",
"shift",
"if",
"req",
".",
"header",
".",
"request_method",
"==",
"'HEAD'",
"@content_length",
"=",
"0",
"if",
"@next_connection",
"@state",
"=",
":WAIT",
"else",
"close",
"end",
"end",
"@next_connection",
"=",
"false",
"unless",
"@content_length",
"return",
"[",
"@version",
",",
"@status",
",",
"@reason",
"]",
"end"
] |
Read status block.
|
[
"Read",
"status",
"block",
"."
] |
cbc4c5146e3b5d8188e221076f56d9471f752237
|
https://github.com/zh/rss-client/blob/cbc4c5146e3b5d8188e221076f56d9471f752237/lib/rss-client/http-access2.rb#L1854-L1899
|
8,297
|
marcboeker/mongolicious
|
lib/mongolicious/storage.rb
|
Mongolicious.Storage.upload
|
def upload(bucket, key, path)
Mongolicious.logger.info("Uploading archive to #{key}")
@con.put_object(
bucket, key, File.open(path, 'r'),
{'x-amz-acl' => 'private', 'Content-Type' => 'application/x-tar'}
)
end
|
ruby
|
def upload(bucket, key, path)
Mongolicious.logger.info("Uploading archive to #{key}")
@con.put_object(
bucket, key, File.open(path, 'r'),
{'x-amz-acl' => 'private', 'Content-Type' => 'application/x-tar'}
)
end
|
[
"def",
"upload",
"(",
"bucket",
",",
"key",
",",
"path",
")",
"Mongolicious",
".",
"logger",
".",
"info",
"(",
"\"Uploading archive to #{key}\"",
")",
"@con",
".",
"put_object",
"(",
"bucket",
",",
"key",
",",
"File",
".",
"open",
"(",
"path",
",",
"'r'",
")",
",",
"{",
"'x-amz-acl'",
"=>",
"'private'",
",",
"'Content-Type'",
"=>",
"'application/x-tar'",
"}",
")",
"end"
] |
Upload the given path to S3.
@param [String] bucket the bucket where to store the archive in.
@param [String] key the key where the archive is stored under.
@param [String] path the path, where the archive is located.
@return [Hash]
|
[
"Upload",
"the",
"given",
"path",
"to",
"S3",
"."
] |
bc1553188df97d3df825de6d826b34ab7185a431
|
https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/storage.rb#L36-L43
|
8,298
|
marcboeker/mongolicious
|
lib/mongolicious/storage.rb
|
Mongolicious.Storage.upload_part
|
def upload_part(bucket, key, upload_id, part_number, data)
response = @con.upload_part(bucket, key, upload_id, part_number, data)
return response.headers['ETag']
end
|
ruby
|
def upload_part(bucket, key, upload_id, part_number, data)
response = @con.upload_part(bucket, key, upload_id, part_number, data)
return response.headers['ETag']
end
|
[
"def",
"upload_part",
"(",
"bucket",
",",
"key",
",",
"upload_id",
",",
"part_number",
",",
"data",
")",
"response",
"=",
"@con",
".",
"upload_part",
"(",
"bucket",
",",
"key",
",",
"upload_id",
",",
"part_number",
",",
"data",
")",
"return",
"response",
".",
"headers",
"[",
"'ETag'",
"]",
"end"
] |
Upload a part for a multipart upload
@param [String] bucket Name of bucket to add part to
@param [String] key Name of object to add part to
@param [String] upload_id Id of upload to add part to
@param [String] part_number Index of part in upload
@param [String] data Contect of part
@return [String] ETag etag of new object. Will be needed to complete upload
|
[
"Upload",
"a",
"part",
"for",
"a",
"multipart",
"upload"
] |
bc1553188df97d3df825de6d826b34ab7185a431
|
https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/storage.rb#L69-L73
|
8,299
|
marcboeker/mongolicious
|
lib/mongolicious/storage.rb
|
Mongolicious.Storage.complete_multipart_upload
|
def complete_multipart_upload(bucket, key, upload_id, parts)
response = @con.complete_multipart_upload(bucket, key, upload_id, parts)
return response
end
|
ruby
|
def complete_multipart_upload(bucket, key, upload_id, parts)
response = @con.complete_multipart_upload(bucket, key, upload_id, parts)
return response
end
|
[
"def",
"complete_multipart_upload",
"(",
"bucket",
",",
"key",
",",
"upload_id",
",",
"parts",
")",
"response",
"=",
"@con",
".",
"complete_multipart_upload",
"(",
"bucket",
",",
"key",
",",
"upload_id",
",",
"parts",
")",
"return",
"response",
"end"
] |
Complete a multipart upload
@param [String] bucket Name of bucket to complete multipart upload for
@param [String] key Name of object to complete multipart upload for
@param [String] upload_id Id of upload to add part to
@param [String] parts Array of etags for parts
@return [Excon::Response]
|
[
"Complete",
"a",
"multipart",
"upload"
] |
bc1553188df97d3df825de6d826b34ab7185a431
|
https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/storage.rb#L83-L87
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.