id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
200
feduxorg/filegen
lib/filegen/erb_generator.rb
Filegen.ErbGenerator.compile
def compile(source, destination) erb = ERB.new(source.read, nil, '-') begin destination.puts erb.result(data.instance_binding) rescue SyntaxError => e raise Exceptions::ErbTemplateHasSyntaxErrors, e.message end end
ruby
def compile(source, destination) erb = ERB.new(source.read, nil, '-') begin destination.puts erb.result(data.instance_binding) rescue SyntaxError => e raise Exceptions::ErbTemplateHasSyntaxErrors, e.message end end
[ "def", "compile", "(", "source", ",", "destination", ")", "erb", "=", "ERB", ".", "new", "(", "source", ".", "read", ",", "nil", ",", "'-'", ")", "begin", "destination", ".", "puts", "erb", ".", "result", "(", "data", ".", "instance_binding", ")", "rescue", "SyntaxError", "=>", "e", "raise", "Exceptions", "::", "ErbTemplateHasSyntaxErrors", ",", "e", ".", "message", "end", "end" ]
Create erb generator @param [Data] data The data class to be used within the template Compile the template @param [IO] source The source template to be used @param [IO] destination The output io handle
[ "Create", "erb", "generator" ]
08c31d3caa7fb7ac61a6544154714b9d79b88985
https://github.com/feduxorg/filegen/blob/08c31d3caa7fb7ac61a6544154714b9d79b88985/lib/filegen/erb_generator.rb#L25-L32
201
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/instance_methods.rb
ActsAsSolr.InstanceMethods.solr_save
def solr_save return true if indexing_disabled? if evaluate_condition(:if, self) debug "solr_save: #{self.class.name} : #{record_id(self)}" solr_add to_solr_doc solr_commit if configuration[:auto_commit] true else solr_destroy end end
ruby
def solr_save return true if indexing_disabled? if evaluate_condition(:if, self) debug "solr_save: #{self.class.name} : #{record_id(self)}" solr_add to_solr_doc solr_commit if configuration[:auto_commit] true else solr_destroy end end
[ "def", "solr_save", "return", "true", "if", "indexing_disabled?", "if", "evaluate_condition", "(", ":if", ",", "self", ")", "debug", "\"solr_save: #{self.class.name} : #{record_id(self)}\"", "solr_add", "to_solr_doc", "solr_commit", "if", "configuration", "[", ":auto_commit", "]", "true", "else", "solr_destroy", "end", "end" ]
saves to the Solr index
[ "saves", "to", "the", "Solr", "index" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/instance_methods.rb#L11-L21
202
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/instance_methods.rb
ActsAsSolr.InstanceMethods.to_solr_doc
def to_solr_doc debug "to_solr_doc: creating doc for class: #{self.class.name}, id: #{record_id(self)}" doc = Solr::Document.new doc.boost = validate_boost(configuration[:boost]) if configuration[:boost] doc << {:id => solr_id, solr_configuration[:type_field] => self.class.name, solr_configuration[:primary_key_field] => record_id(self).to_s} # iterate through the fields and add them to the document, configuration[:solr_fields].each do |field_name, options| next if [self.class.primary_key, "type"].include?(field_name.to_s) field_boost = options[:boost] || solr_configuration[:default_boost] field_type = get_solr_field_type(options[:type]) solr_name = options[:as] || field_name value = self.send("#{field_name}_for_solr") rescue nil next if value.nil? suffix = get_solr_field_type(field_type) value = Array(value).map{ |v| ERB::Util.html_escape(v) } # escape each value value = value.first if value.size == 1 field = Solr::Field.new(:name => "#{solr_name}_#{suffix}", :value => value) processed_boost = validate_boost(field_boost) field.boost = processed_boost doc << field end add_dynamic_attributes(doc) add_includes(doc) add_tags(doc) add_space(doc) debug doc.to_json doc end
ruby
def to_solr_doc debug "to_solr_doc: creating doc for class: #{self.class.name}, id: #{record_id(self)}" doc = Solr::Document.new doc.boost = validate_boost(configuration[:boost]) if configuration[:boost] doc << {:id => solr_id, solr_configuration[:type_field] => self.class.name, solr_configuration[:primary_key_field] => record_id(self).to_s} # iterate through the fields and add them to the document, configuration[:solr_fields].each do |field_name, options| next if [self.class.primary_key, "type"].include?(field_name.to_s) field_boost = options[:boost] || solr_configuration[:default_boost] field_type = get_solr_field_type(options[:type]) solr_name = options[:as] || field_name value = self.send("#{field_name}_for_solr") rescue nil next if value.nil? suffix = get_solr_field_type(field_type) value = Array(value).map{ |v| ERB::Util.html_escape(v) } # escape each value value = value.first if value.size == 1 field = Solr::Field.new(:name => "#{solr_name}_#{suffix}", :value => value) processed_boost = validate_boost(field_boost) field.boost = processed_boost doc << field end add_dynamic_attributes(doc) add_includes(doc) add_tags(doc) add_space(doc) debug doc.to_json doc end
[ "def", "to_solr_doc", "debug", "\"to_solr_doc: creating doc for class: #{self.class.name}, id: #{record_id(self)}\"", "doc", "=", "Solr", "::", "Document", ".", "new", "doc", ".", "boost", "=", "validate_boost", "(", "configuration", "[", ":boost", "]", ")", "if", "configuration", "[", ":boost", "]", "doc", "<<", "{", ":id", "=>", "solr_id", ",", "solr_configuration", "[", ":type_field", "]", "=>", "self", ".", "class", ".", "name", ",", "solr_configuration", "[", ":primary_key_field", "]", "=>", "record_id", "(", "self", ")", ".", "to_s", "}", "# iterate through the fields and add them to the document,", "configuration", "[", ":solr_fields", "]", ".", "each", "do", "|", "field_name", ",", "options", "|", "next", "if", "[", "self", ".", "class", ".", "primary_key", ",", "\"type\"", "]", ".", "include?", "(", "field_name", ".", "to_s", ")", "field_boost", "=", "options", "[", ":boost", "]", "||", "solr_configuration", "[", ":default_boost", "]", "field_type", "=", "get_solr_field_type", "(", "options", "[", ":type", "]", ")", "solr_name", "=", "options", "[", ":as", "]", "||", "field_name", "value", "=", "self", ".", "send", "(", "\"#{field_name}_for_solr\"", ")", "rescue", "nil", "next", "if", "value", ".", "nil?", "suffix", "=", "get_solr_field_type", "(", "field_type", ")", "value", "=", "Array", "(", "value", ")", ".", "map", "{", "|", "v", "|", "ERB", "::", "Util", ".", "html_escape", "(", "v", ")", "}", "# escape each value", "value", "=", "value", ".", "first", "if", "value", ".", "size", "==", "1", "field", "=", "Solr", "::", "Field", ".", "new", "(", ":name", "=>", "\"#{solr_name}_#{suffix}\"", ",", ":value", "=>", "value", ")", "processed_boost", "=", "validate_boost", "(", "field_boost", ")", "field", ".", "boost", "=", "processed_boost", "doc", "<<", "field", "end", "add_dynamic_attributes", "(", "doc", ")", "add_includes", "(", "doc", ")", "add_tags", "(", "doc", ")", "add_space", "(", "doc", ")", "debug", "doc", ".", "to_json", "doc", "end" ]
convert instance to Solr document
[ "convert", "instance", "to", "Solr", "document" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/instance_methods.rb#L37-L74
203
stereobooster/typograf
lib/typograf/client.rb
Typograf.Client.send_request
def send_request(text) params = { 'text' => text.encode("cp1251"), } params['xml'] = @xml if @xml request = Net::HTTP::Post.new(@url.path) request.set_form_data(params) begin response = Net::HTTP.new(@url.host, @url.port).start do |http| http.request(request) end rescue StandardError => exception raise NetworkError.new(exception.message, exception.backtrace) end if !response.is_a?(Net::HTTPOK) raise NetworkError, "#{response.code}: #{response.message}" end body = response.body.force_encoding("cp1251").encode("utf-8") # error = "\xCE\xF8\xE8\xE1\xEA\xE0: \xE2\xFB \xE7\xE0\xE1\xFB\xEB\xE8 \xEF\xE5\xF0\xE5\xE4\xE0\xF2\xFC \xF2\xE5\xEA\xF1\xF2" # error.force_encoding("ASCII-8BIT") if error.respond_to?(:force_encoding) if body == "Ошибка: вы забыли передать текст" raise NetworkError, "Ошибка: вы забыли передать текст" end if @options[:symbols] == 2 HTMLEntities.new.decode(body.chomp) else body.chomp end end
ruby
def send_request(text) params = { 'text' => text.encode("cp1251"), } params['xml'] = @xml if @xml request = Net::HTTP::Post.new(@url.path) request.set_form_data(params) begin response = Net::HTTP.new(@url.host, @url.port).start do |http| http.request(request) end rescue StandardError => exception raise NetworkError.new(exception.message, exception.backtrace) end if !response.is_a?(Net::HTTPOK) raise NetworkError, "#{response.code}: #{response.message}" end body = response.body.force_encoding("cp1251").encode("utf-8") # error = "\xCE\xF8\xE8\xE1\xEA\xE0: \xE2\xFB \xE7\xE0\xE1\xFB\xEB\xE8 \xEF\xE5\xF0\xE5\xE4\xE0\xF2\xFC \xF2\xE5\xEA\xF1\xF2" # error.force_encoding("ASCII-8BIT") if error.respond_to?(:force_encoding) if body == "Ошибка: вы забыли передать текст" raise NetworkError, "Ошибка: вы забыли передать текст" end if @options[:symbols] == 2 HTMLEntities.new.decode(body.chomp) else body.chomp end end
[ "def", "send_request", "(", "text", ")", "params", "=", "{", "'text'", "=>", "text", ".", "encode", "(", "\"cp1251\"", ")", ",", "}", "params", "[", "'xml'", "]", "=", "@xml", "if", "@xml", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "@url", ".", "path", ")", "request", ".", "set_form_data", "(", "params", ")", "begin", "response", "=", "Net", "::", "HTTP", ".", "new", "(", "@url", ".", "host", ",", "@url", ".", "port", ")", ".", "start", "do", "|", "http", "|", "http", ".", "request", "(", "request", ")", "end", "rescue", "StandardError", "=>", "exception", "raise", "NetworkError", ".", "new", "(", "exception", ".", "message", ",", "exception", ".", "backtrace", ")", "end", "if", "!", "response", ".", "is_a?", "(", "Net", "::", "HTTPOK", ")", "raise", "NetworkError", ",", "\"#{response.code}: #{response.message}\"", "end", "body", "=", "response", ".", "body", ".", "force_encoding", "(", "\"cp1251\"", ")", ".", "encode", "(", "\"utf-8\"", ")", "# error = \"\\xCE\\xF8\\xE8\\xE1\\xEA\\xE0: \\xE2\\xFB \\xE7\\xE0\\xE1\\xFB\\xEB\\xE8 \\xEF\\xE5\\xF0\\xE5\\xE4\\xE0\\xF2\\xFC \\xF2\\xE5\\xEA\\xF1\\xF2\"", "# error.force_encoding(\"ASCII-8BIT\") if error.respond_to?(:force_encoding)", "if", "body", "==", "\"Ошибка: вы забыли передать текст\"", "raise", "NetworkError", ",", "\"Ошибка: вы забыли передать текст\"", "end", "if", "@options", "[", ":symbols", "]", "==", "2", "HTMLEntities", ".", "new", ".", "decode", "(", "body", ".", "chomp", ")", "else", "body", ".", "chomp", "end", "end" ]
Process text with remote web-service
[ "Process", "text", "with", "remote", "web", "-", "service" ]
c2f89dac63361e58a856801e474db55f2fb8a472
https://github.com/stereobooster/typograf/blob/c2f89dac63361e58a856801e474db55f2fb8a472/lib/typograf/client.rb#L118-L151
204
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/acts_methods.rb
ActsAsSolr.ActsMethods.acts_as_solr
def acts_as_solr(options={}, solr_options={}, &deferred_solr_configuration) $solr_indexed_models << self extend ClassMethods include InstanceMethods include CommonMethods include ParserMethods define_solr_configuration_methods acts_as_taggable_on :tags if options[:taggable] has_many :dynamic_attributes, :as => "dynamicable" if options[:dynamic_attributes] has_one :local, :as => "localizable" if options[:spatial] after_save :solr_save after_destroy :solr_destroy if deferred_solr_configuration self.deferred_solr_configuration = deferred_solr_configuration else process_acts_as_solr(options, solr_options) end end
ruby
def acts_as_solr(options={}, solr_options={}, &deferred_solr_configuration) $solr_indexed_models << self extend ClassMethods include InstanceMethods include CommonMethods include ParserMethods define_solr_configuration_methods acts_as_taggable_on :tags if options[:taggable] has_many :dynamic_attributes, :as => "dynamicable" if options[:dynamic_attributes] has_one :local, :as => "localizable" if options[:spatial] after_save :solr_save after_destroy :solr_destroy if deferred_solr_configuration self.deferred_solr_configuration = deferred_solr_configuration else process_acts_as_solr(options, solr_options) end end
[ "def", "acts_as_solr", "(", "options", "=", "{", "}", ",", "solr_options", "=", "{", "}", ",", "&", "deferred_solr_configuration", ")", "$solr_indexed_models", "<<", "self", "extend", "ClassMethods", "include", "InstanceMethods", "include", "CommonMethods", "include", "ParserMethods", "define_solr_configuration_methods", "acts_as_taggable_on", ":tags", "if", "options", "[", ":taggable", "]", "has_many", ":dynamic_attributes", ",", ":as", "=>", "\"dynamicable\"", "if", "options", "[", ":dynamic_attributes", "]", "has_one", ":local", ",", ":as", "=>", "\"localizable\"", "if", "options", "[", ":spatial", "]", "after_save", ":solr_save", "after_destroy", ":solr_destroy", "if", "deferred_solr_configuration", "self", ".", "deferred_solr_configuration", "=", "deferred_solr_configuration", "else", "process_acts_as_solr", "(", "options", ",", "solr_options", ")", "end", "end" ]
declares a class as solr-searchable ==== options: fields:: This option can be used to specify only the fields you'd like to index. If not given, all the attributes from the class will be indexed. You can also use this option to include methods that should be indexed as fields class Movie < ActiveRecord::Base acts_as_solr :fields => [:name, :description, :current_time] def current_time Time.now.to_s end end Each field passed can also be a hash with the value being a field type class Electronic < ActiveRecord::Base acts_as_solr :fields => [{:price => :range_float}] def current_time Time.now end end The field types accepted are: :float:: Index the field value as a float (ie.: 12.87) :integer:: Index the field value as an integer (ie.: 31) :boolean:: Index the field value as a boolean (ie.: true/false) :date:: Index the field value as a date (ie.: Wed Nov 15 23:13:03 PST 2006) :string:: Index the field value as a text string, not applying the same indexing filters as a regular text field :range_integer:: Index the field value for integer range queries (ie.:[5 TO 20]) :range_float:: Index the field value for float range queries (ie.:[14.56 TO 19.99]) Setting the field type preserves its original type when indexed The field may also be passed with a hash value containing options class Author < ActiveRecord::Base acts_as_solr :fields => [{:full_name => {:type => :text, :as => :name}}] def full_name self.first_name + ' ' + self.last_name end end The options accepted are: :type:: Index the field using the specified type :as:: Index the field using the specified field name additional_fields:: This option takes fields to be include in the index in addition to those derived from the database. You can also use this option to include custom fields derived from methods you define. This option will be ignored if the :fields option is given. It also accepts the same field types as the option above class Movie < ActiveRecord::Base acts_as_solr :additional_fields => [:current_time] def current_time Time.now.to_s end end exclude_fields:: This option taks an array of fields that should be ignored from indexing: class User < ActiveRecord::Base acts_as_solr :exclude_fields => [:password, :login, :credit_card_number] end include:: This option can be used for association indexing, which means you can include any :has_one, :has_many, :belongs_to and :has_and_belongs_to_many association to be indexed: class Category < ActiveRecord::Base has_many :books acts_as_solr :include => [:books] end Each association may also be specified as a hash with an option hash as a value class Book < ActiveRecord::Base belongs_to :author has_many :distribution_companies has_many :copyright_dates has_many :media_types acts_as_solr( :fields => [:name, :description], :include => [ {:author => {:using => :fullname, :as => :name}}, {:media_types => {:using => lambda{|media| type_lookup(media.id)}}} {:distribution_companies => {:as => :distributor, :multivalued => true}}, {:copyright_dates => {:as => :copyright, :type => :date}} ] ] The options accepted are: :type:: Index the associated objects using the specified type :as:: Index the associated objects using the specified field name :using:: Index the associated objects using the value returned by the specified method or proc. If a method symbol is supplied, it will be sent to each object to look up the value to index; if a proc is supplied, it will be called once for each object with the object as the only argument :multivalued:: Index the associated objects using one field for each object rather than joining them all into a single field facets:: This option can be used to specify the fields you'd like to index as facet fields class Electronic < ActiveRecord::Base acts_as_solr :facets => [:category, :manufacturer] end boost:: You can pass a boost (float) value that will be used to boost the document and/or a field. To specify a more boost for the document, you can either pass a block or a symbol. The block will be called with the record as an argument, a symbol will result in the according method being called: class Electronic < ActiveRecord::Base acts_as_solr :fields => [{:price => {:boost => 5.0}}], :boost => 10.0 end class Electronic < ActiveRecord::Base acts_as_solr :fields => [{:price => {:boost => 5.0}}], :boost => proc {|record| record.id + 120*37} end class Electronic < ActiveRecord::Base acts_as_solr :fields => [{:price => {:boost => :price_rating}}], :boost => 10.0 end if:: Only indexes the record if the condition evaluated is true. The argument has to be either a symbol, string (to be eval'ed), proc/method, or class implementing a static validation method. It behaves the same way as ActiveRecord's :if option. class Electronic < ActiveRecord::Base acts_as_solr :if => proc{|record| record.is_active?} end offline:: Assumes that your using an outside mechanism to explicitly trigger indexing records, e.g. you only want to update your index through some asynchronous mechanism. Will accept either a boolean or a block that will be evaluated before actually contacting the index for saving or destroying a document. Defaults to false. It doesn't refer to the mechanism of an offline index in general, but just to get a centralized point where you can control indexing. Note: This is only enabled for saving records. acts_as_solr doesn't always like it, if you have a different number of results coming from the database and the index. This might be rectified in another patch to support lazy loading. class Electronic < ActiveRecord::Base acts_as_solr :offline => proc {|record| record.automatic_indexing_disabled?} end auto_commit:: The commit command will be sent to Solr only if its value is set to true: class Author < ActiveRecord::Base acts_as_solr :auto_commit => false end dynamic_attributes: Default false. When true, requires a has_many relationship to a DynamicAttribute (:name, :value) model. Then, all dynamic attributes will be mapped as normal attributes in Solr, so you can filter like this: Model.find_by_solr "#{dynamic_attribute.name}:Lorem" taggable: Default false. When true, indexes tags with field name tag. Tags are taken from taggings.tag spatial: Default false. When true, indexes model.local.latitude and model.local.longitude as coordinates.
[ "declares", "a", "class", "as", "solr", "-", "searchable" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/acts_methods.rb#L172-L195
205
alphasights/json-api-client
lib/json_api_client/mapper.rb
JsonApiClient.Mapper.build_linked_resources_map
def build_linked_resources_map(data) data["linked"].each_with_object({}) do |(type, resources), obj| obj[type] ||= {} resources.each do |linked_resource| obj[type][linked_resource["id"]] = linked_resource end end end
ruby
def build_linked_resources_map(data) data["linked"].each_with_object({}) do |(type, resources), obj| obj[type] ||= {} resources.each do |linked_resource| obj[type][linked_resource["id"]] = linked_resource end end end
[ "def", "build_linked_resources_map", "(", "data", ")", "data", "[", "\"linked\"", "]", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "type", ",", "resources", ")", ",", "obj", "|", "obj", "[", "type", "]", "||=", "{", "}", "resources", ".", "each", "do", "|", "linked_resource", "|", "obj", "[", "type", "]", "[", "linked_resource", "[", "\"id\"", "]", "]", "=", "linked_resource", "end", "end", "end" ]
Builds a map to enable getting references by type and id eg. { "users" => { "1" => { "id" => "1", "name" => "John" }, "5" => { "id" => "5", "name" => "Walter" }, } }
[ "Builds", "a", "map", "to", "enable", "getting", "references", "by", "type", "and", "id" ]
00598445ea200f5db352fd50ce3a7e5ae3a37b9e
https://github.com/alphasights/json-api-client/blob/00598445ea200f5db352fd50ce3a7e5ae3a37b9e/lib/json_api_client/mapper.rb#L72-L79
206
alphasights/json-api-client
lib/json_api_client/mapper.rb
JsonApiClient.Mapper.build_link_type_map
def build_link_type_map(data) data["links"].each_with_object({}) do |(key, value), obj| association = key.split(".").last obj[association] = value["type"].pluralize end end
ruby
def build_link_type_map(data) data["links"].each_with_object({}) do |(key, value), obj| association = key.split(".").last obj[association] = value["type"].pluralize end end
[ "def", "build_link_type_map", "(", "data", ")", "data", "[", "\"links\"", "]", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "key", ",", "value", ")", ",", "obj", "|", "association", "=", "key", ".", "split", "(", "\".\"", ")", ".", "last", "obj", "[", "association", "]", "=", "value", "[", "\"type\"", "]", ".", "pluralize", "end", "end" ]
Builds a map to translate references to types eg. { "author" => "users", "comments" => "comments" }
[ "Builds", "a", "map", "to", "translate", "references", "to", "types" ]
00598445ea200f5db352fd50ce3a7e5ae3a37b9e
https://github.com/alphasights/json-api-client/blob/00598445ea200f5db352fd50ce3a7e5ae3a37b9e/lib/json_api_client/mapper.rb#L85-L90
207
redding/dk
lib/dk/tree_runner.rb
Dk.TreeRunner.build_and_run_task
def build_and_run_task(task_class, params = nil) task_run = TaskRun.new(task_class, params) @task_run_stack.last.runs << task_run @task_run_stack.push(task_run) task = super(task_class, params) @task_run_stack.pop task end
ruby
def build_and_run_task(task_class, params = nil) task_run = TaskRun.new(task_class, params) @task_run_stack.last.runs << task_run @task_run_stack.push(task_run) task = super(task_class, params) @task_run_stack.pop task end
[ "def", "build_and_run_task", "(", "task_class", ",", "params", "=", "nil", ")", "task_run", "=", "TaskRun", ".", "new", "(", "task_class", ",", "params", ")", "@task_run_stack", ".", "last", ".", "runs", "<<", "task_run", "@task_run_stack", ".", "push", "(", "task_run", ")", "task", "=", "super", "(", "task_class", ",", "params", ")", "@task_run_stack", ".", "pop", "task", "end" ]
track all task runs
[ "track", "all", "task", "runs" ]
9b6122ce815467c698811014c01518cca539946e
https://github.com/redding/dk/blob/9b6122ce815467c698811014c01518cca539946e/lib/dk/tree_runner.rb#L41-L49
208
JonnieCache/tinyci
lib/tinyci/runner.rb
TinyCI.Runner.run!
def run! begin ensure_path target_path setup_log log_info "Commit: #{@commit}" log_info "Cleaning..." clean log_info "Exporting..." ensure_path export_path export begin load_config rescue ConfigMissingError => e log_error e.message log_error 'Removing export...' clean return false end @builder ||= instantiate_builder @tester ||= instantiate_tester @hooker ||= instantiate_hooker log_info "Building..." run_hook! :before_build begin @builder.build rescue => e run_hook! :after_build_failure raise e if ENV['TINYCI_ENV'] == 'test' log_error e log_debug e.backtrace return false else run_hook! :after_build_success ensure run_hook! :after_build end log_info "Testing..." run_hook! :before_test begin @tester.test rescue => e run_hook! :after_test_failure raise e if ENV['TINYCI_ENV'] == 'test' log_error e log_debug e.backtrace return false else run_hook! :after_test_success ensure run_hook! :after_test end log_info "Finished #{@commit}" rescue => e raise e if ENV['TINYCI_ENV'] == 'test' log_error e log_debug e.backtrace return false end true end
ruby
def run! begin ensure_path target_path setup_log log_info "Commit: #{@commit}" log_info "Cleaning..." clean log_info "Exporting..." ensure_path export_path export begin load_config rescue ConfigMissingError => e log_error e.message log_error 'Removing export...' clean return false end @builder ||= instantiate_builder @tester ||= instantiate_tester @hooker ||= instantiate_hooker log_info "Building..." run_hook! :before_build begin @builder.build rescue => e run_hook! :after_build_failure raise e if ENV['TINYCI_ENV'] == 'test' log_error e log_debug e.backtrace return false else run_hook! :after_build_success ensure run_hook! :after_build end log_info "Testing..." run_hook! :before_test begin @tester.test rescue => e run_hook! :after_test_failure raise e if ENV['TINYCI_ENV'] == 'test' log_error e log_debug e.backtrace return false else run_hook! :after_test_success ensure run_hook! :after_test end log_info "Finished #{@commit}" rescue => e raise e if ENV['TINYCI_ENV'] == 'test' log_error e log_debug e.backtrace return false end true end
[ "def", "run!", "begin", "ensure_path", "target_path", "setup_log", "log_info", "\"Commit: #{@commit}\"", "log_info", "\"Cleaning...\"", "clean", "log_info", "\"Exporting...\"", "ensure_path", "export_path", "export", "begin", "load_config", "rescue", "ConfigMissingError", "=>", "e", "log_error", "e", ".", "message", "log_error", "'Removing export...'", "clean", "return", "false", "end", "@builder", "||=", "instantiate_builder", "@tester", "||=", "instantiate_tester", "@hooker", "||=", "instantiate_hooker", "log_info", "\"Building...\"", "run_hook!", ":before_build", "begin", "@builder", ".", "build", "rescue", "=>", "e", "run_hook!", ":after_build_failure", "raise", "e", "if", "ENV", "[", "'TINYCI_ENV'", "]", "==", "'test'", "log_error", "e", "log_debug", "e", ".", "backtrace", "return", "false", "else", "run_hook!", ":after_build_success", "ensure", "run_hook!", ":after_build", "end", "log_info", "\"Testing...\"", "run_hook!", ":before_test", "begin", "@tester", ".", "test", "rescue", "=>", "e", "run_hook!", ":after_test_failure", "raise", "e", "if", "ENV", "[", "'TINYCI_ENV'", "]", "==", "'test'", "log_error", "e", "log_debug", "e", ".", "backtrace", "return", "false", "else", "run_hook!", ":after_test_success", "ensure", "run_hook!", ":after_test", "end", "log_info", "\"Finished #{@commit}\"", "rescue", "=>", "e", "raise", "e", "if", "ENV", "[", "'TINYCI_ENV'", "]", "==", "'test'", "log_error", "e", "log_debug", "e", ".", "backtrace", "return", "false", "end", "true", "end" ]
Constructor, allows injection of generic configuration params. @param working_dir [String] The working directory to execute against. @param commit [String] SHA1 of git object to run against @param logger [Logger] Logger object @param time [Time] Override time of object creation. Used solely for testing at this time. @param config [Hash] Override TinyCI config object, normally loaded from `.tinyci` file. Used solely for testing at this time. Runs the TinyCI system against the single git object referenced in `@commit`. @return [Boolean] `true` if the commit was built and tested successfully, `false` otherwise
[ "Constructor", "allows", "injection", "of", "generic", "configuration", "params", "." ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/runner.rb#L48-L126
209
JonnieCache/tinyci
lib/tinyci/runner.rb
TinyCI.Runner.instantiate_builder
def instantiate_builder klass = TinyCI::Builders.const_get(@config[:builder][:class]) klass.new(@config[:builder][:config].merge(target: export_path), logger: @logger) end
ruby
def instantiate_builder klass = TinyCI::Builders.const_get(@config[:builder][:class]) klass.new(@config[:builder][:config].merge(target: export_path), logger: @logger) end
[ "def", "instantiate_builder", "klass", "=", "TinyCI", "::", "Builders", ".", "const_get", "(", "@config", "[", ":builder", "]", "[", ":class", "]", ")", "klass", ".", "new", "(", "@config", "[", ":builder", "]", "[", ":config", "]", ".", "merge", "(", "target", ":", "export_path", ")", ",", "logger", ":", "@logger", ")", "end" ]
Instantiate the Builder object according to the class named in the config
[ "Instantiate", "the", "Builder", "object", "according", "to", "the", "class", "named", "in", "the", "config" ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/runner.rb#L158-L161
210
JonnieCache/tinyci
lib/tinyci/runner.rb
TinyCI.Runner.instantiate_hooker
def instantiate_hooker return nil unless @config[:hooker].is_a? Hash klass = TinyCI::Hookers.const_get(@config[:hooker][:class]) klass.new(@config[:hooker][:config].merge(target: export_path), logger: @logger) end
ruby
def instantiate_hooker return nil unless @config[:hooker].is_a? Hash klass = TinyCI::Hookers.const_get(@config[:hooker][:class]) klass.new(@config[:hooker][:config].merge(target: export_path), logger: @logger) end
[ "def", "instantiate_hooker", "return", "nil", "unless", "@config", "[", ":hooker", "]", ".", "is_a?", "Hash", "klass", "=", "TinyCI", "::", "Hookers", ".", "const_get", "(", "@config", "[", ":hooker", "]", "[", ":class", "]", ")", "klass", ".", "new", "(", "@config", "[", ":hooker", "]", "[", ":config", "]", ".", "merge", "(", "target", ":", "export_path", ")", ",", "logger", ":", "@logger", ")", "end" ]
Instantiate the Hooker object according to the class named in the config
[ "Instantiate", "the", "Hooker", "object", "according", "to", "the", "class", "named", "in", "the", "config" ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/runner.rb#L170-L175
211
sosedoff/grooveshark
lib/grooveshark/playlist.rb
Grooveshark.Playlist.load_songs
def load_songs @songs = [] playlist = @client.request('getPlaylistByID', playlistID: @id) @songs = playlist['songs'].map! do |s| Song.new(s) end if playlist.key?('songs') @songs end
ruby
def load_songs @songs = [] playlist = @client.request('getPlaylistByID', playlistID: @id) @songs = playlist['songs'].map! do |s| Song.new(s) end if playlist.key?('songs') @songs end
[ "def", "load_songs", "@songs", "=", "[", "]", "playlist", "=", "@client", ".", "request", "(", "'getPlaylistByID'", ",", "playlistID", ":", "@id", ")", "@songs", "=", "playlist", "[", "'songs'", "]", ".", "map!", "do", "|", "s", "|", "Song", ".", "new", "(", "s", ")", "end", "if", "playlist", ".", "key?", "(", "'songs'", ")", "@songs", "end" ]
Fetch playlist songs
[ "Fetch", "playlist", "songs" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/playlist.rb#L24-L31
212
PRX/audio_monster
lib/audio_monster/monster.rb
AudioMonster.Monster.create_wav_wrapped_mpeg
def create_wav_wrapped_mpeg(mpeg_path, result_path, options={}) options.to_options! start_at = get_datetime_for_option(options[:start_at]) end_at = get_datetime_for_option(options[:end_at]) wav_wrapped_mpeg = NuWav::WaveFile.from_mpeg(mpeg_path) cart = wav_wrapped_mpeg.chunks[:cart] cart.title = options[:title] || File.basename(mpeg_path) cart.artist = options[:artist] cart.cut_id = options[:cut_id] cart.producer_app_id = options[:producer_app_id] if options[:producer_app_id] cart.start_date = start_at.strftime(PRSS_DATE_FORMAT) cart.start_time = start_at.strftime(AES46_2002_TIME_FORMAT) cart.end_date = end_at.strftime(PRSS_DATE_FORMAT) cart.end_time = end_at.strftime(AES46_2002_TIME_FORMAT) # pass in the options used by NuWav - # :no_pad_byte - when true, will not add the pad byte to the data chunk nu_wav_options = options.slice(:no_pad_byte) wav_wrapped_mpeg.to_file(result_path, nu_wav_options) check_local_file(result_path) return true end
ruby
def create_wav_wrapped_mpeg(mpeg_path, result_path, options={}) options.to_options! start_at = get_datetime_for_option(options[:start_at]) end_at = get_datetime_for_option(options[:end_at]) wav_wrapped_mpeg = NuWav::WaveFile.from_mpeg(mpeg_path) cart = wav_wrapped_mpeg.chunks[:cart] cart.title = options[:title] || File.basename(mpeg_path) cart.artist = options[:artist] cart.cut_id = options[:cut_id] cart.producer_app_id = options[:producer_app_id] if options[:producer_app_id] cart.start_date = start_at.strftime(PRSS_DATE_FORMAT) cart.start_time = start_at.strftime(AES46_2002_TIME_FORMAT) cart.end_date = end_at.strftime(PRSS_DATE_FORMAT) cart.end_time = end_at.strftime(AES46_2002_TIME_FORMAT) # pass in the options used by NuWav - # :no_pad_byte - when true, will not add the pad byte to the data chunk nu_wav_options = options.slice(:no_pad_byte) wav_wrapped_mpeg.to_file(result_path, nu_wav_options) check_local_file(result_path) return true end
[ "def", "create_wav_wrapped_mpeg", "(", "mpeg_path", ",", "result_path", ",", "options", "=", "{", "}", ")", "options", ".", "to_options!", "start_at", "=", "get_datetime_for_option", "(", "options", "[", ":start_at", "]", ")", "end_at", "=", "get_datetime_for_option", "(", "options", "[", ":end_at", "]", ")", "wav_wrapped_mpeg", "=", "NuWav", "::", "WaveFile", ".", "from_mpeg", "(", "mpeg_path", ")", "cart", "=", "wav_wrapped_mpeg", ".", "chunks", "[", ":cart", "]", "cart", ".", "title", "=", "options", "[", ":title", "]", "||", "File", ".", "basename", "(", "mpeg_path", ")", "cart", ".", "artist", "=", "options", "[", ":artist", "]", "cart", ".", "cut_id", "=", "options", "[", ":cut_id", "]", "cart", ".", "producer_app_id", "=", "options", "[", ":producer_app_id", "]", "if", "options", "[", ":producer_app_id", "]", "cart", ".", "start_date", "=", "start_at", ".", "strftime", "(", "PRSS_DATE_FORMAT", ")", "cart", ".", "start_time", "=", "start_at", ".", "strftime", "(", "AES46_2002_TIME_FORMAT", ")", "cart", ".", "end_date", "=", "end_at", ".", "strftime", "(", "PRSS_DATE_FORMAT", ")", "cart", ".", "end_time", "=", "end_at", ".", "strftime", "(", "AES46_2002_TIME_FORMAT", ")", "# pass in the options used by NuWav -", "# :no_pad_byte - when true, will not add the pad byte to the data chunk", "nu_wav_options", "=", "options", ".", "slice", "(", ":no_pad_byte", ")", "wav_wrapped_mpeg", ".", "to_file", "(", "result_path", ",", "nu_wav_options", ")", "check_local_file", "(", "result_path", ")", "return", "true", "end" ]
need start_at, ends_on
[ "need", "start_at", "ends_on" ]
51654ec0937258902c0c7af1f7d230c5cd2c932b
https://github.com/PRX/audio_monster/blob/51654ec0937258902c0c7af1f7d230c5cd2c932b/lib/audio_monster/monster.rb#L566-L591
213
PRX/audio_monster
lib/audio_monster/monster.rb
AudioMonster.Monster.run_command
def run_command(command, options={}) timeout = options[:timeout] || 7200 # default to adding a nice 13 if nothing specified nice = if options.key?(:nice) (options[:nice] == 'n') ? '' : "nice -n #{options[:nice]} " else 'nice -n 19 ' end echo_return = (options.key?(:echo_return) && !options[:echo_return]) ? '' : '; echo $?' cmd = "#{nice}#{command}#{echo_return}" logger.info "run_command: #{cmd}" begin result = Timeout::timeout(timeout) { Open3::popen3(cmd) do |i,o,e| out_str = "" err_str = "" i.close # important! o.sync = true e.sync = true o.each{|line| out_str << line line.chomp! logger.debug "stdout: #{line}" } e.each { |line| err_str << line line.chomp! logger.debug "stderr: #{line}" } return out_str, err_str end } rescue Timeout::Error => toe logger.error "run_command:Timeout Error - running command, took longer than #{timeout} seconds to execute: '#{cmd}'" raise toe end end
ruby
def run_command(command, options={}) timeout = options[:timeout] || 7200 # default to adding a nice 13 if nothing specified nice = if options.key?(:nice) (options[:nice] == 'n') ? '' : "nice -n #{options[:nice]} " else 'nice -n 19 ' end echo_return = (options.key?(:echo_return) && !options[:echo_return]) ? '' : '; echo $?' cmd = "#{nice}#{command}#{echo_return}" logger.info "run_command: #{cmd}" begin result = Timeout::timeout(timeout) { Open3::popen3(cmd) do |i,o,e| out_str = "" err_str = "" i.close # important! o.sync = true e.sync = true o.each{|line| out_str << line line.chomp! logger.debug "stdout: #{line}" } e.each { |line| err_str << line line.chomp! logger.debug "stderr: #{line}" } return out_str, err_str end } rescue Timeout::Error => toe logger.error "run_command:Timeout Error - running command, took longer than #{timeout} seconds to execute: '#{cmd}'" raise toe end end
[ "def", "run_command", "(", "command", ",", "options", "=", "{", "}", ")", "timeout", "=", "options", "[", ":timeout", "]", "||", "7200", "# default to adding a nice 13 if nothing specified", "nice", "=", "if", "options", ".", "key?", "(", ":nice", ")", "(", "options", "[", ":nice", "]", "==", "'n'", ")", "?", "''", ":", "\"nice -n #{options[:nice]} \"", "else", "'nice -n 19 '", "end", "echo_return", "=", "(", "options", ".", "key?", "(", ":echo_return", ")", "&&", "!", "options", "[", ":echo_return", "]", ")", "?", "''", ":", "'; echo $?'", "cmd", "=", "\"#{nice}#{command}#{echo_return}\"", "logger", ".", "info", "\"run_command: #{cmd}\"", "begin", "result", "=", "Timeout", "::", "timeout", "(", "timeout", ")", "{", "Open3", "::", "popen3", "(", "cmd", ")", "do", "|", "i", ",", "o", ",", "e", "|", "out_str", "=", "\"\"", "err_str", "=", "\"\"", "i", ".", "close", "# important!", "o", ".", "sync", "=", "true", "e", ".", "sync", "=", "true", "o", ".", "each", "{", "|", "line", "|", "out_str", "<<", "line", "line", ".", "chomp!", "logger", ".", "debug", "\"stdout: #{line}\"", "}", "e", ".", "each", "{", "|", "line", "|", "err_str", "<<", "line", "line", ".", "chomp!", "logger", ".", "debug", "\"stderr: #{line}\"", "}", "return", "out_str", ",", "err_str", "end", "}", "rescue", "Timeout", "::", "Error", "=>", "toe", "logger", ".", "error", "\"run_command:Timeout Error - running command, took longer than #{timeout} seconds to execute: '#{cmd}'\"", "raise", "toe", "end", "end" ]
Pass the command to run, and a timeout
[ "Pass", "the", "command", "to", "run", "and", "a", "timeout" ]
51654ec0937258902c0c7af1f7d230c5cd2c932b
https://github.com/PRX/audio_monster/blob/51654ec0937258902c0c7af1f7d230c5cd2c932b/lib/audio_monster/monster.rb#L903-L943
214
GetEmerson/emerson-rb
lib/emerson/responder.rb
Emerson.Responder.key_for_primary
def key_for_primary @_key_for_primary ||= if options[:as] options[:as] else controller_name = controller.controller_name (resource.respond_to?(:each) ? controller_name : controller_name.singularize).intern end end
ruby
def key_for_primary @_key_for_primary ||= if options[:as] options[:as] else controller_name = controller.controller_name (resource.respond_to?(:each) ? controller_name : controller_name.singularize).intern end end
[ "def", "key_for_primary", "@_key_for_primary", "||=", "if", "options", "[", ":as", "]", "options", "[", ":as", "]", "else", "controller_name", "=", "controller", ".", "controller_name", "(", "resource", ".", "respond_to?", "(", ":each", ")", "?", "controller_name", ":", "controller_name", ".", "singularize", ")", ".", "intern", "end", "end" ]
The primary resource is keyed per the request.
[ "The", "primary", "resource", "is", "keyed", "per", "the", "request", "." ]
184facb853e69fdf79c977fb7573f350844603b5
https://github.com/GetEmerson/emerson-rb/blob/184facb853e69fdf79c977fb7573f350844603b5/lib/emerson/responder.rb#L150-L157
215
juandebravo/quora-client
lib/quora/client.rb
Quora.Client.get
def get(field, filter = true) if field.nil? or !field.instance_of?(String) raise ArgumentError, "Field value must be a string" end resp = http.get("#{BASEPATH}?fields=#{field}", headers) data = resp.body[RESP_PREFIX.length..-1] data = JSON.parse(data) if filter && data.has_key?(field) data[field] else data end end
ruby
def get(field, filter = true) if field.nil? or !field.instance_of?(String) raise ArgumentError, "Field value must be a string" end resp = http.get("#{BASEPATH}?fields=#{field}", headers) data = resp.body[RESP_PREFIX.length..-1] data = JSON.parse(data) if filter && data.has_key?(field) data[field] else data end end
[ "def", "get", "(", "field", ",", "filter", "=", "true", ")", "if", "field", ".", "nil?", "or", "!", "field", ".", "instance_of?", "(", "String", ")", "raise", "ArgumentError", ",", "\"Field value must be a string\"", "end", "resp", "=", "http", ".", "get", "(", "\"#{BASEPATH}?fields=#{field}\"", ",", "headers", ")", "data", "=", "resp", ".", "body", "[", "RESP_PREFIX", ".", "length", "..", "-", "1", "]", "data", "=", "JSON", ".", "parse", "(", "data", ")", "if", "filter", "&&", "data", ".", "has_key?", "(", "field", ")", "data", "[", "field", "]", "else", "data", "end", "end" ]
Base method to send a request to Quora API. @param [required, string] supported field (or multiple fields CSV) to retrieve @param [optional, bool] filter if field is a key in result hash, only this value is returned
[ "Base", "method", "to", "send", "a", "request", "to", "Quora", "API", "." ]
eb09bbb70aef5c5c77887dc0b689ccb422fba49f
https://github.com/juandebravo/quora-client/blob/eb09bbb70aef5c5c77887dc0b689ccb422fba49f/lib/quora/client.rb#L83-L95
216
juandebravo/quora-client
lib/quora/client.rb
Quora.Client.method_missing
def method_missing(method_id, *arguments, &block) if method_id.to_s =~ /^get_[\w]+/ self.class.send :define_method, method_id do field = method_id.to_s[4..-1] get(field) end self.send(method_id) else super end end
ruby
def method_missing(method_id, *arguments, &block) if method_id.to_s =~ /^get_[\w]+/ self.class.send :define_method, method_id do field = method_id.to_s[4..-1] get(field) end self.send(method_id) else super end end
[ "def", "method_missing", "(", "method_id", ",", "*", "arguments", ",", "&", "block", ")", "if", "method_id", ".", "to_s", "=~", "/", "\\w", "/", "self", ".", "class", ".", "send", ":define_method", ",", "method_id", "do", "field", "=", "method_id", ".", "to_s", "[", "4", "..", "-", "1", "]", "get", "(", "field", ")", "end", "self", ".", "send", "(", "method_id", ")", "else", "super", "end", "end" ]
Override method_missing so any method that starts with "get_" will be defined. i.e. client.get_profile will generate => def get_profile get("profile") end
[ "Override", "method_missing", "so", "any", "method", "that", "starts", "with", "get_", "will", "be", "defined", "." ]
eb09bbb70aef5c5c77887dc0b689ccb422fba49f
https://github.com/juandebravo/quora-client/blob/eb09bbb70aef5c5c77887dc0b689ccb422fba49f/lib/quora/client.rb#L131-L141
217
phusion/union_station_hooks_core
lib/union_station_hooks_core/request_reporter/controllers.rb
UnionStationHooks.RequestReporter.log_controller_action_block
def log_controller_action_block(options = {}) if null? do_nothing_on_null(:log_controller_action_block) yield else build_full_controller_action_string(options) has_error = true begin_time = UnionStationHooks.now begin result = yield has_error = false result ensure log_controller_action( options.merge( :begin_time => begin_time, :end_time => UnionStationHooks.now, :has_error => has_error ) ) end end end
ruby
def log_controller_action_block(options = {}) if null? do_nothing_on_null(:log_controller_action_block) yield else build_full_controller_action_string(options) has_error = true begin_time = UnionStationHooks.now begin result = yield has_error = false result ensure log_controller_action( options.merge( :begin_time => begin_time, :end_time => UnionStationHooks.now, :has_error => has_error ) ) end end end
[ "def", "log_controller_action_block", "(", "options", "=", "{", "}", ")", "if", "null?", "do_nothing_on_null", "(", ":log_controller_action_block", ")", "yield", "else", "build_full_controller_action_string", "(", "options", ")", "has_error", "=", "true", "begin_time", "=", "UnionStationHooks", ".", "now", "begin", "result", "=", "yield", "has_error", "=", "false", "result", "ensure", "log_controller_action", "(", "options", ".", "merge", "(", ":begin_time", "=>", "begin_time", ",", ":end_time", "=>", "UnionStationHooks", ".", "now", ",", ":has_error", "=>", "has_error", ")", ")", "end", "end", "end" ]
Logging controller-related information Logs that you are calling a web framework controller action. Of course, you should only call this if your web framework has the concept of controller actions. For example Rails does, but Sinatra and Grape don't. This form takes an options hash as well as a block. You can pass additional information about the web framework controller action, which will be logged. The block is expected to perform the actual request handling. When the block returns, timing information about the block is automatically logged. See also {#log_controller_action} for a form that doesn't expect a block. The `union_station_hooks_rails` gem automatically calls this for you if your application is a Rails app. @yield The given block is expected to perform request handling. @param [Hash] options Information about the controller action. All options are optional. @option options [String] :controller_name The controller's name, e.g. `PostsController`. @option options [String] :action_name The controller action's name, e.g. `create`. @option options [String] :method The HTTP method that the web framework thinks this request should have, e.g. `GET` and `PUT`. The main use case for this option is to support Rails's HTTP verb emulation. Rails uses a parameter named [`_method`](http://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-patch-put-or-delete-methods-work-questionmark) to emulate HTTP verbs besides GET and POST. Other web frameworks may have a similar mechanism. @return The return value of the block. @example Rails example # This example shows what to put inside a Rails controller action # method. Note that all of this is automatically done for you if you # use the union_station_hooks_rails gem. options = { :controller_name => self.class.name, :action_name => action_name, :method => request.request_method } reporter.log_controller_action_block(options) do do_some_request_processing_here end
[ "Logging", "controller", "-", "related", "information", "Logs", "that", "you", "are", "calling", "a", "web", "framework", "controller", "action", ".", "Of", "course", "you", "should", "only", "call", "this", "if", "your", "web", "framework", "has", "the", "concept", "of", "controller", "actions", ".", "For", "example", "Rails", "does", "but", "Sinatra", "and", "Grape", "don", "t", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/request_reporter/controllers.rb#L75-L97
218
phusion/union_station_hooks_core
lib/union_station_hooks_core/request_reporter/controllers.rb
UnionStationHooks.RequestReporter.log_controller_action
def log_controller_action(options) return do_nothing_on_null(:log_controller_action) if null? Utils.require_key(options, :begin_time) Utils.require_key(options, :end_time) if options[:controller_name] build_full_controller_action_string(options) @transaction.message("Controller action: #{@controller_action}") end if options[:method] @transaction.message("Application request method: #{options[:method]}") end @transaction.log_activity('framework request processing', options[:begin_time], options[:end_time], nil, options[:has_error]) end
ruby
def log_controller_action(options) return do_nothing_on_null(:log_controller_action) if null? Utils.require_key(options, :begin_time) Utils.require_key(options, :end_time) if options[:controller_name] build_full_controller_action_string(options) @transaction.message("Controller action: #{@controller_action}") end if options[:method] @transaction.message("Application request method: #{options[:method]}") end @transaction.log_activity('framework request processing', options[:begin_time], options[:end_time], nil, options[:has_error]) end
[ "def", "log_controller_action", "(", "options", ")", "return", "do_nothing_on_null", "(", ":log_controller_action", ")", "if", "null?", "Utils", ".", "require_key", "(", "options", ",", ":begin_time", ")", "Utils", ".", "require_key", "(", "options", ",", ":end_time", ")", "if", "options", "[", ":controller_name", "]", "build_full_controller_action_string", "(", "options", ")", "@transaction", ".", "message", "(", "\"Controller action: #{@controller_action}\"", ")", "end", "if", "options", "[", ":method", "]", "@transaction", ".", "message", "(", "\"Application request method: #{options[:method]}\"", ")", "end", "@transaction", ".", "log_activity", "(", "'framework request processing'", ",", "options", "[", ":begin_time", "]", ",", "options", "[", ":end_time", "]", ",", "nil", ",", "options", "[", ":has_error", "]", ")", "end" ]
Logs that you are calling a web framework controller action. Of course, you should only call this if your web framework has the concept of controller actions. For example Rails does, but Sinatra and Grape don't. You can pass additional information about the web framework controller action, which will be logged. Unlike {#log_controller_action_block}, this form does not expect a block. However, you are expected to pass timing information to the options hash. The `union_station_hooks_rails` gem automatically calls {#log_controller_action_block} for you if your application is a Rails app. @param [Hash] options Information about the controller action. @option options [String] :controller_name (optional) The controller's name, e.g. `PostsController`. @option options [String] :action_name (optional if :controller_name isn't set) The controller action's name, e.g. `create`. @option options [String] :method (optional) The HTTP method that the web framework thinks this request should have, e.g. `GET` and `PUT`. The main use case for this option is to support Rails's HTTP verb emulation. Rails uses a parameter named [`_method`](http://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-patch-put-or-delete-methods-work-questionmark) to emulate HTTP verbs besides GET and POST. Other web frameworks may have a similar mechanism. @option options [TimePoint or Time] :begin_time The time at which the controller action begun. See {UnionStationHooks.now} to learn more. @option options [TimePoint or Time] :end_time The time at which the controller action ended. See {UnionStationHooks.now} to learn more. @option options [Boolean] :has_error (optional) Whether an uncaught exception occurred during the request. Default: false. @example # This example shows what to put inside a Rails controller action # method. Note that all of this is automatically done for you if you # use the union_station_hooks_rails gem. options = { :controller_name => self.class.name, :action_name => action_name, :method => request.request_method, :begin_time => UnionStationHooks.now } begin do_some_request_processing_here rescue Exception options[:has_error] = true raise ensure options[:end_time] = UnionStationHooks.now reporter.log_controller_action(options) end
[ "Logs", "that", "you", "are", "calling", "a", "web", "framework", "controller", "action", ".", "Of", "course", "you", "should", "only", "call", "this", "if", "your", "web", "framework", "has", "the", "concept", "of", "controller", "actions", ".", "For", "example", "Rails", "does", "but", "Sinatra", "and", "Grape", "don", "t", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/request_reporter/controllers.rb#L153-L167
219
MrMicrowaveOven/zadt
lib/zadt/AbstractDataTypes/Graph/graph.rb
Zadt.Graph.remove_vertex
def remove_vertex(vertex) # The vertex must exist raise "not a vertex" unless vertex.is_a?(Vertex) if !vertex raise "Vertex does not exist" # The vertex must not be connected to anything elsif !vertex.connections.empty? raise "Vertex has edges. Break them first." # If it exists and isn't connected, delete it else @vertices.delete(vertex) end end
ruby
def remove_vertex(vertex) # The vertex must exist raise "not a vertex" unless vertex.is_a?(Vertex) if !vertex raise "Vertex does not exist" # The vertex must not be connected to anything elsif !vertex.connections.empty? raise "Vertex has edges. Break them first." # If it exists and isn't connected, delete it else @vertices.delete(vertex) end end
[ "def", "remove_vertex", "(", "vertex", ")", "# The vertex must exist", "raise", "\"not a vertex\"", "unless", "vertex", ".", "is_a?", "(", "Vertex", ")", "if", "!", "vertex", "raise", "\"Vertex does not exist\"", "# The vertex must not be connected to anything", "elsif", "!", "vertex", ".", "connections", ".", "empty?", "raise", "\"Vertex has edges. Break them first.\"", "# If it exists and isn't connected, delete it", "else", "@vertices", ".", "delete", "(", "vertex", ")", "end", "end" ]
Remove a vertex
[ "Remove", "a", "vertex" ]
789420b1e05f7545f886309c07b235dd560f6696
https://github.com/MrMicrowaveOven/zadt/blob/789420b1e05f7545f886309c07b235dd560f6696/lib/zadt/AbstractDataTypes/Graph/graph.rb#L31-L43
220
MrMicrowaveOven/zadt
lib/zadt/AbstractDataTypes/Graph/graph.rb
Zadt.Graph.make_connection
def make_connection(v1, v2) raise "not a vertex" unless v1.is_a?(Vertex) && v2.is_a?(Vertex) raise "already connected" if is_connected?(v1, v2) # Make new edge edge = Edge.new(v1, v2) # Connect the two using the vertex method "connect" v1.connect(v2, edge) v2.connect(v1, edge) # Add to edge catalog @edges << edge edge end
ruby
def make_connection(v1, v2) raise "not a vertex" unless v1.is_a?(Vertex) && v2.is_a?(Vertex) raise "already connected" if is_connected?(v1, v2) # Make new edge edge = Edge.new(v1, v2) # Connect the two using the vertex method "connect" v1.connect(v2, edge) v2.connect(v1, edge) # Add to edge catalog @edges << edge edge end
[ "def", "make_connection", "(", "v1", ",", "v2", ")", "raise", "\"not a vertex\"", "unless", "v1", ".", "is_a?", "(", "Vertex", ")", "&&", "v2", ".", "is_a?", "(", "Vertex", ")", "raise", "\"already connected\"", "if", "is_connected?", "(", "v1", ",", "v2", ")", "# Make new edge", "edge", "=", "Edge", ".", "new", "(", "v1", ",", "v2", ")", "# Connect the two using the vertex method \"connect\"", "v1", ".", "connect", "(", "v2", ",", "edge", ")", "v2", ".", "connect", "(", "v1", ",", "edge", ")", "# Add to edge catalog", "@edges", "<<", "edge", "edge", "end" ]
Make an edge between two vertices
[ "Make", "an", "edge", "between", "two", "vertices" ]
789420b1e05f7545f886309c07b235dd560f6696
https://github.com/MrMicrowaveOven/zadt/blob/789420b1e05f7545f886309c07b235dd560f6696/lib/zadt/AbstractDataTypes/Graph/graph.rb#L46-L58
221
MrMicrowaveOven/zadt
lib/zadt/AbstractDataTypes/Graph/graph.rb
Zadt.Graph.find_connection
def find_connection(v1, v2) raise "not a vertex" unless v1.is_a?(Vertex) && v2.is_a?(Vertex) raise "Vertices not connected" if !is_connected?(v1, v2) connection = v1.edges.select {|edge| edge.connection.include?(v2)} raise "Error finding connection" if connection.length > 1 connection.first end
ruby
def find_connection(v1, v2) raise "not a vertex" unless v1.is_a?(Vertex) && v2.is_a?(Vertex) raise "Vertices not connected" if !is_connected?(v1, v2) connection = v1.edges.select {|edge| edge.connection.include?(v2)} raise "Error finding connection" if connection.length > 1 connection.first end
[ "def", "find_connection", "(", "v1", ",", "v2", ")", "raise", "\"not a vertex\"", "unless", "v1", ".", "is_a?", "(", "Vertex", ")", "&&", "v2", ".", "is_a?", "(", "Vertex", ")", "raise", "\"Vertices not connected\"", "if", "!", "is_connected?", "(", "v1", ",", "v2", ")", "connection", "=", "v1", ".", "edges", ".", "select", "{", "|", "edge", "|", "edge", ".", "connection", ".", "include?", "(", "v2", ")", "}", "raise", "\"Error finding connection\"", "if", "connection", ".", "length", ">", "1", "connection", ".", "first", "end" ]
Find the edge connecting two vertices
[ "Find", "the", "edge", "connecting", "two", "vertices" ]
789420b1e05f7545f886309c07b235dd560f6696
https://github.com/MrMicrowaveOven/zadt/blob/789420b1e05f7545f886309c07b235dd560f6696/lib/zadt/AbstractDataTypes/Graph/graph.rb#L61-L67
222
MrMicrowaveOven/zadt
lib/zadt/AbstractDataTypes/Graph/graph.rb
Zadt.Graph.is_connected?
def is_connected?(v1, v2) raise "not a vertex" unless v1.is_a?(Vertex) && v2.is_a?(Vertex) v1.connections.include?(v2) end
ruby
def is_connected?(v1, v2) raise "not a vertex" unless v1.is_a?(Vertex) && v2.is_a?(Vertex) v1.connections.include?(v2) end
[ "def", "is_connected?", "(", "v1", ",", "v2", ")", "raise", "\"not a vertex\"", "unless", "v1", ".", "is_a?", "(", "Vertex", ")", "&&", "v2", ".", "is_a?", "(", "Vertex", ")", "v1", ".", "connections", ".", "include?", "(", "v2", ")", "end" ]
Returns whether two vertices are connected
[ "Returns", "whether", "two", "vertices", "are", "connected" ]
789420b1e05f7545f886309c07b235dd560f6696
https://github.com/MrMicrowaveOven/zadt/blob/789420b1e05f7545f886309c07b235dd560f6696/lib/zadt/AbstractDataTypes/Graph/graph.rb#L70-L73
223
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/class_methods.rb
ActsAsSolr.ClassMethods.find_by_solr
def find_by_solr(query, options={}) data = parse_query(query, options) return parse_results(data, options) end
ruby
def find_by_solr(query, options={}) data = parse_query(query, options) return parse_results(data, options) end
[ "def", "find_by_solr", "(", "query", ",", "options", "=", "{", "}", ")", "data", "=", "parse_query", "(", "query", ",", "options", ")", "return", "parse_results", "(", "data", ",", "options", ")", "end" ]
Finds instances of a model. Terms are ANDed by default, can be overwritten by using OR between terms Here's a sample (untested) code for your controller: def search results = Book.find_by_solr params[:query] end For specific fields searching use :filter_queries options ====options: offset:: - The first document to be retrieved (offset) page:: - The page to be retrieved limit:: - The number of rows per page per_page:: - Alias for limit filter_queries:: - Use solr filter queries to sort by fields Book.find_by_solr 'ruby', :filter_queries => ['price:5'] sort:: - Orders (sort by) the result set using a given criteria: Book.find_by_solr 'ruby', :sort => 'description asc' field_types:: This option is deprecated and will be obsolete by version 1.0. There's no need to specify the :field_types anymore when doing a search in a model that specifies a field type for a field. The field types are automatically traced back when they're included. class Electronic < ActiveRecord::Base acts_as_solr :fields => [{:price => :range_float}] end facets:: This option argument accepts the following arguments: fields:: The fields to be included in the faceted search (Solr's facet.field) query:: The queries to be included in the faceted search (Solr's facet.query) zeros:: Display facets with count of zero. (true|false) sort:: Sorts the faceted resuls by highest to lowest count. (true|false) browse:: This is where the 'drill-down' of the facets work. Accepts an array of fields in the format "facet_field:term" mincount:: Replacement for zeros (it has been deprecated in Solr). Specifies the minimum count necessary for a facet field to be returned. (Solr's facet.mincount) Overrides :zeros if it is specified. Default is 0. dates:: Run date faceted queries using the following arguments: fields:: The fields to be included in the faceted date search (Solr's facet.date). It may be either a String/Symbol or Hash. If it's a hash the options are the same as date_facets minus the fields option (i.e., :start:, :end, :gap, :other, :between). These options if provided will override the base options. (Solr's f.<field_name>.date.<key>=<value>). start:: The lower bound for the first date range for all Date Faceting. Required if :fields is present end:: The upper bound for the last date range for all Date Faceting. Required if :fields is prsent gap:: The size of each date range expressed as an interval to be added to the lower bound using the DateMathParser syntax. Required if :fields is prsent hardend:: A Boolean parameter instructing Solr what do do in the event that facet.date.gap does not divide evenly between facet.date.start and facet.date.end. other:: This param indicates that in addition to the counts for each date range constraint between facet.date.start and facet.date.end, other counds should be calculated. May specify more then one in an Array. The possible options are: before:: - all records with lower bound less than start after:: - all records with upper bound greater than end between:: - all records with field values between start and end none:: - compute no other bounds (useful in per field assignment) all:: - shortcut for before, after, and between filter:: Similar to :query option provided by :facets, in that accepts an array of of date queries to limit results. Can not be used as a part of a :field hash. This is the only option that can be used if :fields is not present. Example: Electronic.find_by_solr "memory", :facets => {:zeros => false, :sort => true, :query => ["price:[* TO 200]", "price:[200 TO 500]", "price:[500 TO *]"], :fields => [:category, :manufacturer], :browse => ["category:Memory","manufacturer:Someone"]} Examples of date faceting: basic: Electronic.find_by_solr "memory", :facets => {:dates => {:fields => [:updated_at, :created_at], :start => 'NOW-10YEARS/DAY', :end => 'NOW/DAY', :gap => '+2YEARS', :other => :before}} advanced: Electronic.find_by_solr "memory", :facets => {:dates => {:fields => [:updated_at, {:created_at => {:start => 'NOW-20YEARS/DAY', :end => 'NOW-10YEARS/DAY', :other => [:before, :after]} }], :start => 'NOW-10YEARS/DAY', :end => 'NOW/DAY', :other => :before, :filter => ["created_at:[NOW-10YEARS/DAY TO NOW/DAY]", "updated_at:[NOW-1YEAR/DAY TO NOW/DAY]"]}} filter only: Electronic.find_by_solr "memory", :facets => {:dates => {:filter => "updated_at:[NOW-1YEAR/DAY TO NOW/DAY]"}} scores:: If set to true this will return the score as a 'solr_score' attribute for each one of the instances found. Does not currently work with find_id_by_solr books = Book.find_by_solr 'ruby OR splinter', :scores => true books.records.first.solr_score => 1.21321397 books.records.last.solr_score => 0.12321548 lazy:: If set to true the search will return objects that will touch the database when you ask for one of their attributes for the first time. Useful when you're using fragment caching based solely on types and ids. relevance:: Sets fields relevance Book.find_by_solr "zidane", :relevance => {:title => 5, :author => 2}
[ "Finds", "instances", "of", "a", "model", ".", "Terms", "are", "ANDed", "by", "default", "can", "be", "overwritten", "by", "using", "OR", "between", "terms" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/class_methods.rb#L121-L124
224
dcrec1/acts_as_solr_reloaded
lib/acts_as_solr/class_methods.rb
ActsAsSolr.ClassMethods.rebuild_solr_index
def rebuild_solr_index(batch_size=300, options = {}, &finder) finder ||= lambda do |ar, sql_options| ar.all sql_options.merge!({:order => self.primary_key, :include => configuration[:solr_includes].keys}) end start_time = Time.now options[:offset] ||= 0 options[:threads] ||= 2 options[:delayed_job] &= defined?(Delayed::Job) if batch_size > 0 items_processed = 0 offset = options[:offset] end_reached = false threads = [] mutex = Mutex.new queue = Queue.new loop do items = finder.call(self, {:limit => batch_size, :offset => offset}) add_batch = items.collect { |content| content.to_solr_doc } offset += items.size end_reached = items.size == 0 break if end_reached if options[:threads] == threads.size threads.first.join threads.shift end queue << [items, add_batch] threads << Thread.new do iteration_start = Time.now iteration_items, iteration_add_batch = queue.pop(true) if options[:delayed_job] delay.solr_add iteration_add_batch else solr_add iteration_add_batch solr_commit end last_id = iteration_items.last.id time_so_far = Time.now - start_time iteration_time = Time.now - iteration_start mutex.synchronize do items_processed += iteration_items.size if options[:delayed_job] logger.info "#{Process.pid}: #{items_processed} items for #{self.name} have been sent to Delayed::Job in #{'%.3f' % time_so_far}s at #{'%.3f' % (items_processed / time_so_far)} items/sec. Last id: #{last_id}" else logger.info "#{Process.pid}: #{items_processed} items for #{self.name} have been batch added to index in #{'%.3f' % time_so_far}s at #{'%.3f' % (items_processed / time_so_far)} items/sec. Last id: #{last_id}" end end end end solr_commit if options[:delayed_job] threads.each{ |t| t.join } else items = finder.call(self, {}) items.each { |content| content.solr_save } items_processed = items.size end if items_processed > 0 solr_optimize time_elapsed = Time.now - start_time logger.info "Index for #{self.name} has been rebuilt (took #{'%.3f' % time_elapsed}s)" else "Nothing to index for #{self.name}" end end
ruby
def rebuild_solr_index(batch_size=300, options = {}, &finder) finder ||= lambda do |ar, sql_options| ar.all sql_options.merge!({:order => self.primary_key, :include => configuration[:solr_includes].keys}) end start_time = Time.now options[:offset] ||= 0 options[:threads] ||= 2 options[:delayed_job] &= defined?(Delayed::Job) if batch_size > 0 items_processed = 0 offset = options[:offset] end_reached = false threads = [] mutex = Mutex.new queue = Queue.new loop do items = finder.call(self, {:limit => batch_size, :offset => offset}) add_batch = items.collect { |content| content.to_solr_doc } offset += items.size end_reached = items.size == 0 break if end_reached if options[:threads] == threads.size threads.first.join threads.shift end queue << [items, add_batch] threads << Thread.new do iteration_start = Time.now iteration_items, iteration_add_batch = queue.pop(true) if options[:delayed_job] delay.solr_add iteration_add_batch else solr_add iteration_add_batch solr_commit end last_id = iteration_items.last.id time_so_far = Time.now - start_time iteration_time = Time.now - iteration_start mutex.synchronize do items_processed += iteration_items.size if options[:delayed_job] logger.info "#{Process.pid}: #{items_processed} items for #{self.name} have been sent to Delayed::Job in #{'%.3f' % time_so_far}s at #{'%.3f' % (items_processed / time_so_far)} items/sec. Last id: #{last_id}" else logger.info "#{Process.pid}: #{items_processed} items for #{self.name} have been batch added to index in #{'%.3f' % time_so_far}s at #{'%.3f' % (items_processed / time_so_far)} items/sec. Last id: #{last_id}" end end end end solr_commit if options[:delayed_job] threads.each{ |t| t.join } else items = finder.call(self, {}) items.each { |content| content.solr_save } items_processed = items.size end if items_processed > 0 solr_optimize time_elapsed = Time.now - start_time logger.info "Index for #{self.name} has been rebuilt (took #{'%.3f' % time_elapsed}s)" else "Nothing to index for #{self.name}" end end
[ "def", "rebuild_solr_index", "(", "batch_size", "=", "300", ",", "options", "=", "{", "}", ",", "&", "finder", ")", "finder", "||=", "lambda", "do", "|", "ar", ",", "sql_options", "|", "ar", ".", "all", "sql_options", ".", "merge!", "(", "{", ":order", "=>", "self", ".", "primary_key", ",", ":include", "=>", "configuration", "[", ":solr_includes", "]", ".", "keys", "}", ")", "end", "start_time", "=", "Time", ".", "now", "options", "[", ":offset", "]", "||=", "0", "options", "[", ":threads", "]", "||=", "2", "options", "[", ":delayed_job", "]", "&=", "defined?", "(", "Delayed", "::", "Job", ")", "if", "batch_size", ">", "0", "items_processed", "=", "0", "offset", "=", "options", "[", ":offset", "]", "end_reached", "=", "false", "threads", "=", "[", "]", "mutex", "=", "Mutex", ".", "new", "queue", "=", "Queue", ".", "new", "loop", "do", "items", "=", "finder", ".", "call", "(", "self", ",", "{", ":limit", "=>", "batch_size", ",", ":offset", "=>", "offset", "}", ")", "add_batch", "=", "items", ".", "collect", "{", "|", "content", "|", "content", ".", "to_solr_doc", "}", "offset", "+=", "items", ".", "size", "end_reached", "=", "items", ".", "size", "==", "0", "break", "if", "end_reached", "if", "options", "[", ":threads", "]", "==", "threads", ".", "size", "threads", ".", "first", ".", "join", "threads", ".", "shift", "end", "queue", "<<", "[", "items", ",", "add_batch", "]", "threads", "<<", "Thread", ".", "new", "do", "iteration_start", "=", "Time", ".", "now", "iteration_items", ",", "iteration_add_batch", "=", "queue", ".", "pop", "(", "true", ")", "if", "options", "[", ":delayed_job", "]", "delay", ".", "solr_add", "iteration_add_batch", "else", "solr_add", "iteration_add_batch", "solr_commit", "end", "last_id", "=", "iteration_items", ".", "last", ".", "id", "time_so_far", "=", "Time", ".", "now", "-", "start_time", "iteration_time", "=", "Time", ".", "now", "-", "iteration_start", "mutex", ".", "synchronize", "do", "items_processed", "+=", "iteration_items", ".", "size", "if", "options", "[", ":delayed_job", "]", "logger", ".", "info", "\"#{Process.pid}: #{items_processed} items for #{self.name} have been sent to Delayed::Job in #{'%.3f' % time_so_far}s at #{'%.3f' % (items_processed / time_so_far)} items/sec. Last id: #{last_id}\"", "else", "logger", ".", "info", "\"#{Process.pid}: #{items_processed} items for #{self.name} have been batch added to index in #{'%.3f' % time_so_far}s at #{'%.3f' % (items_processed / time_so_far)} items/sec. Last id: #{last_id}\"", "end", "end", "end", "end", "solr_commit", "if", "options", "[", ":delayed_job", "]", "threads", ".", "each", "{", "|", "t", "|", "t", ".", "join", "}", "else", "items", "=", "finder", ".", "call", "(", "self", ",", "{", "}", ")", "items", ".", "each", "{", "|", "content", "|", "content", ".", "solr_save", "}", "items_processed", "=", "items", ".", "size", "end", "if", "items_processed", ">", "0", "solr_optimize", "time_elapsed", "=", "Time", ".", "now", "-", "start_time", "logger", ".", "info", "\"Index for #{self.name} has been rebuilt (took #{'%.3f' % time_elapsed}s)\"", "else", "\"Nothing to index for #{self.name}\"", "end", "end" ]
It's used to rebuild the Solr index for a specific model. Book.rebuild_solr_index If batch_size is greater than 0, adds will be done in batches. NOTE: If using sqlserver, be sure to use a finder with an explicit order. Non-edge versions of rails do not handle pagination correctly for sqlserver without an order clause. If a finder block is given, it will be called to retrieve the items to index. This can be very useful for things such as updating based on conditions or using eager loading for indexed associations.
[ "It", "s", "used", "to", "rebuild", "the", "Solr", "index", "for", "a", "specific", "model", ".", "Book", ".", "rebuild_solr_index" ]
20900d1339daa1f805c74c0d2203afb37edde3db
https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/class_methods.rb#L205-L274
225
grosser/s3_meta_sync
lib/s3_meta_sync/syncer.rb
S3MetaSync.Syncer.delete_old_temp_folders
def delete_old_temp_folders path = File.join(Dir.tmpdir, STAGING_AREA_PREFIX + '*') day = 24 * 60 * 60 dirs = Dir.glob(path) dirs.select! { |dir| Time.now.utc - File.ctime(dir).utc > day } # only stale ones removed = dirs.each { |dir| FileUtils.rm_rf(dir) } log "Removed #{removed} old temp folder(s)" if removed.count > 0 end
ruby
def delete_old_temp_folders path = File.join(Dir.tmpdir, STAGING_AREA_PREFIX + '*') day = 24 * 60 * 60 dirs = Dir.glob(path) dirs.select! { |dir| Time.now.utc - File.ctime(dir).utc > day } # only stale ones removed = dirs.each { |dir| FileUtils.rm_rf(dir) } log "Removed #{removed} old temp folder(s)" if removed.count > 0 end
[ "def", "delete_old_temp_folders", "path", "=", "File", ".", "join", "(", "Dir", ".", "tmpdir", ",", "STAGING_AREA_PREFIX", "+", "'*'", ")", "day", "=", "24", "*", "60", "*", "60", "dirs", "=", "Dir", ".", "glob", "(", "path", ")", "dirs", ".", "select!", "{", "|", "dir", "|", "Time", ".", "now", ".", "utc", "-", "File", ".", "ctime", "(", "dir", ")", ".", "utc", ">", "day", "}", "# only stale ones", "removed", "=", "dirs", ".", "each", "{", "|", "dir", "|", "FileUtils", ".", "rm_rf", "(", "dir", ")", "}", "log", "\"Removed #{removed} old temp folder(s)\"", "if", "removed", ".", "count", ">", "0", "end" ]
Sometimes SIGTERM causes Dir.mktmpdir to not properly delete the temp folder Remove 1 day old folders
[ "Sometimes", "SIGTERM", "causes", "Dir", ".", "mktmpdir", "to", "not", "properly", "delete", "the", "temp", "folder", "Remove", "1", "day", "old", "folders" ]
52178496c15aa9b1d868064cbf72e452193d757e
https://github.com/grosser/s3_meta_sync/blob/52178496c15aa9b1d868064cbf72e452193d757e/lib/s3_meta_sync/syncer.rb#L97-L106
226
coupler/linkage
lib/linkage/field_set.rb
Linkage.FieldSet.fetch_key
def fetch_key(key) string_key = key.to_s keys.detect { |k| k.to_s.casecmp(string_key) == 0 } end
ruby
def fetch_key(key) string_key = key.to_s keys.detect { |k| k.to_s.casecmp(string_key) == 0 } end
[ "def", "fetch_key", "(", "key", ")", "string_key", "=", "key", ".", "to_s", "keys", ".", "detect", "{", "|", "k", "|", "k", ".", "to_s", ".", "casecmp", "(", "string_key", ")", "==", "0", "}", "end" ]
Returns a key that matches the parameter in a case-insensitive manner. @param key [String, Symbol] @return [Symbol]
[ "Returns", "a", "key", "that", "matches", "the", "parameter", "in", "a", "case", "-", "insensitive", "manner", "." ]
2f208ae0709a141a6a8e5ba3bc6914677e986cb0
https://github.com/coupler/linkage/blob/2f208ae0709a141a6a8e5ba3bc6914677e986cb0/lib/linkage/field_set.rb#L38-L41
227
appoxy/simple_record
lib/simple_record/translations.rb
SimpleRecord.Translations.ruby_to_sdb
def ruby_to_sdb(name, value) return nil if value.nil? name = name.to_s # puts "Converting #{name} to sdb value=#{value}" # puts "atts_local=" + defined_attributes_local.inspect att_meta = get_att_meta(name) if value.is_a? Array ret = value.collect { |x| ruby_to_string_val(att_meta, x) } else ret = ruby_to_string_val(att_meta, value) end unless value.blank? if att_meta.options if att_meta.options[:encrypted] # puts "ENCRYPTING #{name} value #{value}" ret = Translations.encrypt(ret, att_meta.options[:encrypted]) # puts 'encrypted value=' + ret.to_s end if att_meta.options[:hashed] # puts "hashing #{name}" ret = Translations.pass_hash(ret) # puts "hashed value=" + ret.inspect end end end return ret end
ruby
def ruby_to_sdb(name, value) return nil if value.nil? name = name.to_s # puts "Converting #{name} to sdb value=#{value}" # puts "atts_local=" + defined_attributes_local.inspect att_meta = get_att_meta(name) if value.is_a? Array ret = value.collect { |x| ruby_to_string_val(att_meta, x) } else ret = ruby_to_string_val(att_meta, value) end unless value.blank? if att_meta.options if att_meta.options[:encrypted] # puts "ENCRYPTING #{name} value #{value}" ret = Translations.encrypt(ret, att_meta.options[:encrypted]) # puts 'encrypted value=' + ret.to_s end if att_meta.options[:hashed] # puts "hashing #{name}" ret = Translations.pass_hash(ret) # puts "hashed value=" + ret.inspect end end end return ret end
[ "def", "ruby_to_sdb", "(", "name", ",", "value", ")", "return", "nil", "if", "value", ".", "nil?", "name", "=", "name", ".", "to_s", "# puts \"Converting #{name} to sdb value=#{value}\"", "# puts \"atts_local=\" + defined_attributes_local.inspect", "att_meta", "=", "get_att_meta", "(", "name", ")", "if", "value", ".", "is_a?", "Array", "ret", "=", "value", ".", "collect", "{", "|", "x", "|", "ruby_to_string_val", "(", "att_meta", ",", "x", ")", "}", "else", "ret", "=", "ruby_to_string_val", "(", "att_meta", ",", "value", ")", "end", "unless", "value", ".", "blank?", "if", "att_meta", ".", "options", "if", "att_meta", ".", "options", "[", ":encrypted", "]", "# puts \"ENCRYPTING #{name} value #{value}\"", "ret", "=", "Translations", ".", "encrypt", "(", "ret", ",", "att_meta", ".", "options", "[", ":encrypted", "]", ")", "# puts 'encrypted value=' + ret.to_s", "end", "if", "att_meta", ".", "options", "[", ":hashed", "]", "# puts \"hashing #{name}\"", "ret", "=", "Translations", ".", "pass_hash", "(", "ret", ")", "# puts \"hashed value=\" + ret.inspect", "end", "end", "end", "return", "ret", "end" ]
Time to second precision
[ "Time", "to", "second", "precision" ]
0252a022a938f368d6853ab1ae31f77f80b9f044
https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/translations.rb#L22-L53
228
appoxy/simple_record
lib/simple_record/translations.rb
SimpleRecord.Translations.sdb_to_ruby
def sdb_to_ruby(name, value) # puts 'sdb_to_ruby arg=' + name.inspect + ' - ' + name.class.name + ' - value=' + value.to_s return nil if value.nil? att_meta = get_att_meta(name) if att_meta.options if att_meta.options[:encrypted] value = Translations.decrypt(value, att_meta.options[:encrypted]) end if att_meta.options[:hashed] return PasswordHashed.new(value) end end if !has_id_on_end(name) && att_meta.type == :belongs_to class_name = att_meta.options[:class_name] || name.to_s[0...1].capitalize + name.to_s[1...name.to_s.length] # Camelize classnames with underscores (ie my_model.rb --> MyModel) class_name = class_name.camelize # puts "attr=" + @attributes[arg_id].inspect # puts 'val=' + @attributes[arg_id][0].inspect unless @attributes[arg_id].nil? ret = nil arg_id = name.to_s + '_id' arg_id_val = send("#{arg_id}") if arg_id_val if !cache_store.nil? # arg_id_val = @attributes[arg_id][0] cache_key = self.class.cache_key(class_name, arg_id_val) # puts 'cache_key=' + cache_key ret = cache_store.read(cache_key) # puts 'belongs_to incache=' + ret.inspect end if ret.nil? to_eval = "#{class_name}.find('#{arg_id_val}')" # puts 'to eval=' + to_eval begin ret = eval(to_eval) # (defined? #{arg}_id) rescue SimpleRecord::ActiveSdb::ActiveSdbError => ex if ex.message.include? "Couldn't find" ret = RemoteNil.new else raise ex end end end end value = ret else if value.is_a? Array value = value.collect { |x| string_val_to_ruby(att_meta, x) } else value = string_val_to_ruby(att_meta, value) end end value end
ruby
def sdb_to_ruby(name, value) # puts 'sdb_to_ruby arg=' + name.inspect + ' - ' + name.class.name + ' - value=' + value.to_s return nil if value.nil? att_meta = get_att_meta(name) if att_meta.options if att_meta.options[:encrypted] value = Translations.decrypt(value, att_meta.options[:encrypted]) end if att_meta.options[:hashed] return PasswordHashed.new(value) end end if !has_id_on_end(name) && att_meta.type == :belongs_to class_name = att_meta.options[:class_name] || name.to_s[0...1].capitalize + name.to_s[1...name.to_s.length] # Camelize classnames with underscores (ie my_model.rb --> MyModel) class_name = class_name.camelize # puts "attr=" + @attributes[arg_id].inspect # puts 'val=' + @attributes[arg_id][0].inspect unless @attributes[arg_id].nil? ret = nil arg_id = name.to_s + '_id' arg_id_val = send("#{arg_id}") if arg_id_val if !cache_store.nil? # arg_id_val = @attributes[arg_id][0] cache_key = self.class.cache_key(class_name, arg_id_val) # puts 'cache_key=' + cache_key ret = cache_store.read(cache_key) # puts 'belongs_to incache=' + ret.inspect end if ret.nil? to_eval = "#{class_name}.find('#{arg_id_val}')" # puts 'to eval=' + to_eval begin ret = eval(to_eval) # (defined? #{arg}_id) rescue SimpleRecord::ActiveSdb::ActiveSdbError => ex if ex.message.include? "Couldn't find" ret = RemoteNil.new else raise ex end end end end value = ret else if value.is_a? Array value = value.collect { |x| string_val_to_ruby(att_meta, x) } else value = string_val_to_ruby(att_meta, value) end end value end
[ "def", "sdb_to_ruby", "(", "name", ",", "value", ")", "# puts 'sdb_to_ruby arg=' + name.inspect + ' - ' + name.class.name + ' - value=' + value.to_s", "return", "nil", "if", "value", ".", "nil?", "att_meta", "=", "get_att_meta", "(", "name", ")", "if", "att_meta", ".", "options", "if", "att_meta", ".", "options", "[", ":encrypted", "]", "value", "=", "Translations", ".", "decrypt", "(", "value", ",", "att_meta", ".", "options", "[", ":encrypted", "]", ")", "end", "if", "att_meta", ".", "options", "[", ":hashed", "]", "return", "PasswordHashed", ".", "new", "(", "value", ")", "end", "end", "if", "!", "has_id_on_end", "(", "name", ")", "&&", "att_meta", ".", "type", "==", ":belongs_to", "class_name", "=", "att_meta", ".", "options", "[", ":class_name", "]", "||", "name", ".", "to_s", "[", "0", "...", "1", "]", ".", "capitalize", "+", "name", ".", "to_s", "[", "1", "...", "name", ".", "to_s", ".", "length", "]", "# Camelize classnames with underscores (ie my_model.rb --> MyModel)", "class_name", "=", "class_name", ".", "camelize", "# puts \"attr=\" + @attributes[arg_id].inspect", "# puts 'val=' + @attributes[arg_id][0].inspect unless @attributes[arg_id].nil?", "ret", "=", "nil", "arg_id", "=", "name", ".", "to_s", "+", "'_id'", "arg_id_val", "=", "send", "(", "\"#{arg_id}\"", ")", "if", "arg_id_val", "if", "!", "cache_store", ".", "nil?", "# arg_id_val = @attributes[arg_id][0]", "cache_key", "=", "self", ".", "class", ".", "cache_key", "(", "class_name", ",", "arg_id_val", ")", "# puts 'cache_key=' + cache_key", "ret", "=", "cache_store", ".", "read", "(", "cache_key", ")", "# puts 'belongs_to incache=' + ret.inspect", "end", "if", "ret", ".", "nil?", "to_eval", "=", "\"#{class_name}.find('#{arg_id_val}')\"", "# puts 'to eval=' + to_eval", "begin", "ret", "=", "eval", "(", "to_eval", ")", "# (defined? #{arg}_id)", "rescue", "SimpleRecord", "::", "ActiveSdb", "::", "ActiveSdbError", "=>", "ex", "if", "ex", ".", "message", ".", "include?", "\"Couldn't find\"", "ret", "=", "RemoteNil", ".", "new", "else", "raise", "ex", "end", "end", "end", "end", "value", "=", "ret", "else", "if", "value", ".", "is_a?", "Array", "value", "=", "value", ".", "collect", "{", "|", "x", "|", "string_val_to_ruby", "(", "att_meta", ",", "x", ")", "}", "else", "value", "=", "string_val_to_ruby", "(", "att_meta", ",", "value", ")", "end", "end", "value", "end" ]
Convert value from SimpleDB String version to real ruby value.
[ "Convert", "value", "from", "SimpleDB", "String", "version", "to", "real", "ruby", "value", "." ]
0252a022a938f368d6853ab1ae31f77f80b9f044
https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/translations.rb#L57-L113
229
jimmyz/familysearch-rb
lib/familysearch/url_template.rb
FamilySearch.URLTemplate.head
def head(template_values) raise FamilySearch::Error::MethodNotAllowed unless allow.include?('head') template_values = validate_values(template_values) t = Addressable::Template.new(@template) url = t.expand(template_values).to_s @client.head url end
ruby
def head(template_values) raise FamilySearch::Error::MethodNotAllowed unless allow.include?('head') template_values = validate_values(template_values) t = Addressable::Template.new(@template) url = t.expand(template_values).to_s @client.head url end
[ "def", "head", "(", "template_values", ")", "raise", "FamilySearch", "::", "Error", "::", "MethodNotAllowed", "unless", "allow", ".", "include?", "(", "'head'", ")", "template_values", "=", "validate_values", "(", "template_values", ")", "t", "=", "Addressable", "::", "Template", ".", "new", "(", "@template", ")", "url", "=", "t", ".", "expand", "(", "template_values", ")", ".", "to_s", "@client", ".", "head", "url", "end" ]
Calls HTTP HEAD on the URL template. It takes the +template_values+ hash and merges the values into the template. A template will contain a URL like this: https://sandbox.familysearch.org/platform/tree/persons-with-relationships{?access_token,person} or https://sandbox.familysearch.org/platform/tree/persons/{pid}/matches{?access_token} The {?person} type attributes in the first example will be passed as querystring parameters. These will automatically be URL Encoded by the underlying Faraday library that handles the HTTP request. The {pid} type attibutes will simply be substituted into the URL. *Note*: The +access_token+ parameter doesn't need to be passed here. This should be handled by the FamilySearch::Client's Authorization header. *Args* : - +template_values+: A Hash object containing the values for the items in the URL template. For example, if the URL is: https://sandbox.familysearch.org/platform/tree/persons-with-relationships{?access_token,person} then you would pass a hash like this: :person => 'KWQS-BBQ' or 'person' => 'KWQS-BBQ' *Returns* : - +Faraday::Response+ object. This object contains methods +body+, +headers+, and +status+. +body+ should contain a Hash of the parsed result of the request. *Raises* : - +FamilySearch::Error::MethodNotAllowed+: if you call +head+ for a template that doesn't allow HEAD method.
[ "Calls", "HTTP", "HEAD", "on", "the", "URL", "template", ".", "It", "takes", "the", "+", "template_values", "+", "hash", "and", "merges", "the", "values", "into", "the", "template", "." ]
be6ae2ea6f4ad4734a3355fa5f8fdf8d33f0c7a1
https://github.com/jimmyz/familysearch-rb/blob/be6ae2ea6f4ad4734a3355fa5f8fdf8d33f0c7a1/lib/familysearch/url_template.rb#L122-L128
230
LAS-IT/ps_utilities
lib/ps_utilities/pre_built_get.rb
PsUtilities.PreBuiltGet.get_one_student
def get_one_student(params) # api_path = "/ws/v1/district/student/{dcid}?expansions=school_enrollment,contact&q=student_username==xxxxxx237" ps_dcid = params[:dcid] || params[:dc_id] || params[:id] api_path = "/ws/v1/student/#{ps_dcid.to_i}" options = { query: { "extensions" => "s_stu_crdc_x,activities,c_studentlocator,u_students_extension,u_studentsuserfields,s_stu_ncea_x,s_stu_edfi_x,studentcorefields", "expansions" => "demographics,addresses,alerts,phones,school_enrollment,ethnicity_race,contact,contact_info,initial_enrollment,schedule_setup,fees,lunch" } } return {"errorMessage"=>{"message"=>"A valid dcid must be entered."}} if "#{ps_dcid.to_i}".eql? "0" answer = api(:get, api_path, options) return { student: (answer["student"] || []) } if answer.code.to_s.eql? "200" # return { student: (answer.parsed_response["student"] || []) } if answer.code.to_s.eql? "200" return {"errorMessage"=>"#{answer.response}"} end
ruby
def get_one_student(params) # api_path = "/ws/v1/district/student/{dcid}?expansions=school_enrollment,contact&q=student_username==xxxxxx237" ps_dcid = params[:dcid] || params[:dc_id] || params[:id] api_path = "/ws/v1/student/#{ps_dcid.to_i}" options = { query: { "extensions" => "s_stu_crdc_x,activities,c_studentlocator,u_students_extension,u_studentsuserfields,s_stu_ncea_x,s_stu_edfi_x,studentcorefields", "expansions" => "demographics,addresses,alerts,phones,school_enrollment,ethnicity_race,contact,contact_info,initial_enrollment,schedule_setup,fees,lunch" } } return {"errorMessage"=>{"message"=>"A valid dcid must be entered."}} if "#{ps_dcid.to_i}".eql? "0" answer = api(:get, api_path, options) return { student: (answer["student"] || []) } if answer.code.to_s.eql? "200" # return { student: (answer.parsed_response["student"] || []) } if answer.code.to_s.eql? "200" return {"errorMessage"=>"#{answer.response}"} end
[ "def", "get_one_student", "(", "params", ")", "# api_path = \"/ws/v1/district/student/{dcid}?expansions=school_enrollment,contact&q=student_username==xxxxxx237\"", "ps_dcid", "=", "params", "[", ":dcid", "]", "||", "params", "[", ":dc_id", "]", "||", "params", "[", ":id", "]", "api_path", "=", "\"/ws/v1/student/#{ps_dcid.to_i}\"", "options", "=", "{", "query", ":", "{", "\"extensions\"", "=>", "\"s_stu_crdc_x,activities,c_studentlocator,u_students_extension,u_studentsuserfields,s_stu_ncea_x,s_stu_edfi_x,studentcorefields\"", ",", "\"expansions\"", "=>", "\"demographics,addresses,alerts,phones,school_enrollment,ethnicity_race,contact,contact_info,initial_enrollment,schedule_setup,fees,lunch\"", "}", "}", "return", "{", "\"errorMessage\"", "=>", "{", "\"message\"", "=>", "\"A valid dcid must be entered.\"", "}", "}", "if", "\"#{ps_dcid.to_i}\"", ".", "eql?", "\"0\"", "answer", "=", "api", "(", ":get", ",", "api_path", ",", "options", ")", "return", "{", "student", ":", "(", "answer", "[", "\"student\"", "]", "||", "[", "]", ")", "}", "if", "answer", ".", "code", ".", "to_s", ".", "eql?", "\"200\"", "# return { student: (answer.parsed_response[\"student\"] || []) } if answer.code.to_s.eql? \"200\"", "return", "{", "\"errorMessage\"", "=>", "\"#{answer.response}\"", "}", "end" ]
retrieves all individual student's details - you must use the DCID !!! @param params [Hash] - use either: {dcid: "12345"} or {id: "12345"} @return [Hash] - in the format of: { :student=> { "@expansions"=> "demographics, addresses, alerts, phones, school_enrollment, ethnicity_race, contact, contact_info, initial_enrollment, schedule_setup, fees, lunch", "@extensions"=> "s_stu_crdc_x,activities,c_studentlocator,u_students_extension,u_studentsuserfields,s_stu_ncea_x,s_stu_edfi_x,studentcorefields", "_extension_data"=> { "_table_extension"=> [ { "recordFound"=>false, "_field"=> [ {"name"=>"preferredname", "type"=>"String", "value"=>"Guy"}, {"name"=>"student_email", "type"=>"String", "value"=>"guy@las.ch"} ], "name"=>"u_students_extension" }, { "recordFound"=>false, "_field"=> [ {"name"=>"transcriptaddrzip", "type"=>"String", "value"=>1858}, {"name"=>"transcriptaddrcountry", "type"=>"String", "value"=>"CH"}, {"name"=>"transcriptaddrcity", "type"=>"String", "value"=>"Bex"}, {"name"=>"transcriptaddrstate", "type"=>"String", "value"=>"VD"}, {"name"=>"transcriptaddrline1", "type"=>"String", "value"=>"LAS"}, {"name"=>"transcriptaddrline2", "type"=>"String", "value"=>"CP 108"} ], "name"=>"u_studentsuserfields" } ] }, "id"=>7337, "local_id"=>555807, "student_username"=>"guy807", "name"=>{"first_name"=>"Mountain", "last_name"=>"BIV"}, "demographics"=>{"gender"=>"M", "birth_date"=>"2002-08-26", "projected_graduation_year"=>2021}, "addresses"=>"", "alerts"=>"", "phones"=>"", "school_enrollment"=> { "enroll_status"=>"A", "enroll_status_description"=>"Active", "enroll_status_code"=>0, "grade_level"=>9, "entry_date"=>"2018-06-22", "exit_date"=>"2019-08-06", "school_number"=>2, "school_id"=>2, "full_time_equivalency"=>{"fteid"=>970, "name"=>"FTE Admissions"} }, "ethnicity_race"=>{"federal_ethnicity"=>"NO"}, "contact"=>{"guardian_email"=>"guydad@orchid.ch"}, "contact_info"=>{"email"=>"guy@las.ch"}, "initial_enrollment"=>{"district_entry_grade_level"=>0, "school_entry_grade_level"=>0}, "schedule_setup"=>{"next_school"=>33, "sched_next_year_grade"=>10}, "fees"=>"", "lunch"=>{"balance_1"=>"0.00", "balance_2"=>"0.00", "balance_3"=>"0.00", "balance_4"=>"0.00", "lunch_id"=>0} } } @note the data within "u_students_extension" - is unique for each school
[ "retrieves", "all", "individual", "student", "s", "details", "-", "you", "must", "use", "the", "DCID", "!!!" ]
85fbb528d982b66ca706de5fdb70b4410f21e637
https://github.com/LAS-IT/ps_utilities/blob/85fbb528d982b66ca706de5fdb70b4410f21e637/lib/ps_utilities/pre_built_get.rb#L108-L123
231
LAS-IT/ps_utilities
lib/ps_utilities/pre_built_get.rb
PsUtilities.PreBuiltGet.build_query
def build_query(params) query = [] query << "school_enrollment.enroll_status_code==#{params[:status_code]}" if params.has_key?(:status_code) query << "school_enrollment.enroll_status==#{params[:enroll_status]}" if params.has_key?(:enroll_status) query << "student_username==#{params[:username]}" if params.has_key?(:username) query << "name.last_name==#{params[:last_name]}" if params.has_key?(:last_name) query << "name.first_name==#{params[:first_name]}" if params.has_key?(:first_name) query << "local_id==#{params[:local_id]}" if params.has_key?(:local_id) query << "local_id==#{params[:student_id]}" if params.has_key?(:student_id) query << "id==#{params[:dcid]}" if params.has_key?(:dcid) query << "id==#{params[:id]}" if params.has_key?(:id) answer = query.join(";") answer end
ruby
def build_query(params) query = [] query << "school_enrollment.enroll_status_code==#{params[:status_code]}" if params.has_key?(:status_code) query << "school_enrollment.enroll_status==#{params[:enroll_status]}" if params.has_key?(:enroll_status) query << "student_username==#{params[:username]}" if params.has_key?(:username) query << "name.last_name==#{params[:last_name]}" if params.has_key?(:last_name) query << "name.first_name==#{params[:first_name]}" if params.has_key?(:first_name) query << "local_id==#{params[:local_id]}" if params.has_key?(:local_id) query << "local_id==#{params[:student_id]}" if params.has_key?(:student_id) query << "id==#{params[:dcid]}" if params.has_key?(:dcid) query << "id==#{params[:id]}" if params.has_key?(:id) answer = query.join(";") answer end
[ "def", "build_query", "(", "params", ")", "query", "=", "[", "]", "query", "<<", "\"school_enrollment.enroll_status_code==#{params[:status_code]}\"", "if", "params", ".", "has_key?", "(", ":status_code", ")", "query", "<<", "\"school_enrollment.enroll_status==#{params[:enroll_status]}\"", "if", "params", ".", "has_key?", "(", ":enroll_status", ")", "query", "<<", "\"student_username==#{params[:username]}\"", "if", "params", ".", "has_key?", "(", ":username", ")", "query", "<<", "\"name.last_name==#{params[:last_name]}\"", "if", "params", ".", "has_key?", "(", ":last_name", ")", "query", "<<", "\"name.first_name==#{params[:first_name]}\"", "if", "params", ".", "has_key?", "(", ":first_name", ")", "query", "<<", "\"local_id==#{params[:local_id]}\"", "if", "params", ".", "has_key?", "(", ":local_id", ")", "query", "<<", "\"local_id==#{params[:student_id]}\"", "if", "params", ".", "has_key?", "(", ":student_id", ")", "query", "<<", "\"id==#{params[:dcid]}\"", "if", "params", ".", "has_key?", "(", ":dcid", ")", "query", "<<", "\"id==#{params[:id]}\"", "if", "params", ".", "has_key?", "(", ":id", ")", "answer", "=", "query", ".", "join", "(", "\";\"", ")", "answer", "end" ]
build the api query - you can use splats to match any character @param params [Hash] - valid keys include: :status_code (or :enroll_status), :username, :last_name, :first_name, :student_id (or :local_id), :id (or :dcid) @return [String] - "id==345;name.last_name==BA*"
[ "build", "the", "api", "query", "-", "you", "can", "use", "splats", "to", "match", "any", "character" ]
85fbb528d982b66ca706de5fdb70b4410f21e637
https://github.com/LAS-IT/ps_utilities/blob/85fbb528d982b66ca706de5fdb70b4410f21e637/lib/ps_utilities/pre_built_get.rb#L131-L144
232
JonnieCache/tinyci
lib/tinyci/compactor.rb
TinyCI.Compactor.directories_to_compact
def directories_to_compact builds = Dir.entries builds_dir builds.select! {|e| File.directory? builds_dir(e) } builds.reject! {|e| %w{. ..}.include? e } builds.sort! builds = builds[0..-(@num_builds_to_leave+1)] builds.reject! {|e| @builds_to_leave.include?(e) || @builds_to_leave.include?(builds_dir(e, 'export'))} builds end
ruby
def directories_to_compact builds = Dir.entries builds_dir builds.select! {|e| File.directory? builds_dir(e) } builds.reject! {|e| %w{. ..}.include? e } builds.sort! builds = builds[0..-(@num_builds_to_leave+1)] builds.reject! {|e| @builds_to_leave.include?(e) || @builds_to_leave.include?(builds_dir(e, 'export'))} builds end
[ "def", "directories_to_compact", "builds", "=", "Dir", ".", "entries", "builds_dir", "builds", ".", "select!", "{", "|", "e", "|", "File", ".", "directory?", "builds_dir", "(", "e", ")", "}", "builds", ".", "reject!", "{", "|", "e", "|", "%w{", ".", "..", "}", ".", "include?", "e", "}", "builds", ".", "sort!", "builds", "=", "builds", "[", "0", "..", "-", "(", "@num_builds_to_leave", "+", "1", ")", "]", "builds", ".", "reject!", "{", "|", "e", "|", "@builds_to_leave", ".", "include?", "(", "e", ")", "||", "@builds_to_leave", ".", "include?", "(", "builds_dir", "(", "e", ",", "'export'", ")", ")", "}", "builds", "end" ]
Build the list of directories to compact according to the options
[ "Build", "the", "list", "of", "directories", "to", "compact", "according", "to", "the", "options" ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/compactor.rb#L47-L57
233
JonnieCache/tinyci
lib/tinyci/compactor.rb
TinyCI.Compactor.compress_directory
def compress_directory(dir) File.open archive_path(dir), 'wb' do |oarchive_path| Zlib::GzipWriter.wrap oarchive_path do |gz| Gem::Package::TarWriter.new gz do |tar| Find.find "#{builds_dir}/"+dir do |f| relative_path = f.sub "#{builds_dir}/", "" mode = File.stat(f).mode size = File.stat(f).size if File.directory? f tar.mkdir relative_path, mode else tar.add_file_simple relative_path, mode, size do |tio| File.open f, 'rb' do |rio| while buffer = rio.read(BLOCKSIZE_TO_READ) tio.write buffer end end end end end end end end end
ruby
def compress_directory(dir) File.open archive_path(dir), 'wb' do |oarchive_path| Zlib::GzipWriter.wrap oarchive_path do |gz| Gem::Package::TarWriter.new gz do |tar| Find.find "#{builds_dir}/"+dir do |f| relative_path = f.sub "#{builds_dir}/", "" mode = File.stat(f).mode size = File.stat(f).size if File.directory? f tar.mkdir relative_path, mode else tar.add_file_simple relative_path, mode, size do |tio| File.open f, 'rb' do |rio| while buffer = rio.read(BLOCKSIZE_TO_READ) tio.write buffer end end end end end end end end end
[ "def", "compress_directory", "(", "dir", ")", "File", ".", "open", "archive_path", "(", "dir", ")", ",", "'wb'", "do", "|", "oarchive_path", "|", "Zlib", "::", "GzipWriter", ".", "wrap", "oarchive_path", "do", "|", "gz", "|", "Gem", "::", "Package", "::", "TarWriter", ".", "new", "gz", "do", "|", "tar", "|", "Find", ".", "find", "\"#{builds_dir}/\"", "+", "dir", "do", "|", "f", "|", "relative_path", "=", "f", ".", "sub", "\"#{builds_dir}/\"", ",", "\"\"", "mode", "=", "File", ".", "stat", "(", "f", ")", ".", "mode", "size", "=", "File", ".", "stat", "(", "f", ")", ".", "size", "if", "File", ".", "directory?", "f", "tar", ".", "mkdir", "relative_path", ",", "mode", "else", "tar", ".", "add_file_simple", "relative_path", ",", "mode", ",", "size", "do", "|", "tio", "|", "File", ".", "open", "f", ",", "'rb'", "do", "|", "rio", "|", "while", "buffer", "=", "rio", ".", "read", "(", "BLOCKSIZE_TO_READ", ")", "tio", ".", "write", "buffer", "end", "end", "end", "end", "end", "end", "end", "end", "end" ]
Create a .tar.gz file from a directory Done in pure ruby to ensure portability
[ "Create", "a", ".", "tar", ".", "gz", "file", "from", "a", "directory", "Done", "in", "pure", "ruby", "to", "ensure", "portability" ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/compactor.rb#L71-L97
234
JonnieCache/tinyci
lib/tinyci/subprocesses.rb
TinyCI.Subprocesses.execute
def execute(*command, label: nil) output, status = Open3.capture2(*command.flatten) log_debug caller[0] log_debug "CMD: #{command.join(' ')}" log_debug "OUT: #{output}" unless status.success? log_error output raise SubprocessError.new(label, command.join(' '), status) end output.chomp end
ruby
def execute(*command, label: nil) output, status = Open3.capture2(*command.flatten) log_debug caller[0] log_debug "CMD: #{command.join(' ')}" log_debug "OUT: #{output}" unless status.success? log_error output raise SubprocessError.new(label, command.join(' '), status) end output.chomp end
[ "def", "execute", "(", "*", "command", ",", "label", ":", "nil", ")", "output", ",", "status", "=", "Open3", ".", "capture2", "(", "command", ".", "flatten", ")", "log_debug", "caller", "[", "0", "]", "log_debug", "\"CMD: #{command.join(' ')}\"", "log_debug", "\"OUT: #{output}\"", "unless", "status", ".", "success?", "log_error", "output", "raise", "SubprocessError", ".", "new", "(", "label", ",", "command", ".", "join", "(", "' '", ")", ",", "status", ")", "end", "output", ".", "chomp", "end" ]
Synchronously execute a command as a subprocess and return the output. @param [Array<String>] command The command line @param [String] label A label for debug and logging purposes @return [String] The output of the command @raise [SubprocessError] if the subprocess returns status > 0
[ "Synchronously", "execute", "a", "command", "as", "a", "subprocess", "and", "return", "the", "output", "." ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/subprocesses.rb#L15-L28
235
JonnieCache/tinyci
lib/tinyci/subprocesses.rb
TinyCI.Subprocesses.execute_pipe
def execute_pipe(*commands, label: nil) stdout, waiters = Open3.pipeline_r(*commands) output = stdout.read waiters.each_with_index do |waiter, i| status = waiter.value unless status.success? log_error output raise SubprocessError.new(label, commands[i].join(' '), status) end end output.chomp end
ruby
def execute_pipe(*commands, label: nil) stdout, waiters = Open3.pipeline_r(*commands) output = stdout.read waiters.each_with_index do |waiter, i| status = waiter.value unless status.success? log_error output raise SubprocessError.new(label, commands[i].join(' '), status) end end output.chomp end
[ "def", "execute_pipe", "(", "*", "commands", ",", "label", ":", "nil", ")", "stdout", ",", "waiters", "=", "Open3", ".", "pipeline_r", "(", "commands", ")", "output", "=", "stdout", ".", "read", "waiters", ".", "each_with_index", "do", "|", "waiter", ",", "i", "|", "status", "=", "waiter", ".", "value", "unless", "status", ".", "success?", "log_error", "output", "raise", "SubprocessError", ".", "new", "(", "label", ",", "commands", "[", "i", "]", ".", "join", "(", "' '", ")", ",", "status", ")", "end", "end", "output", ".", "chomp", "end" ]
Synchronously execute a chain multiple commands piped into each other as a subprocess and return the output. @param [Array<Array<String>>] commands The command lines @param [String] label A label for debug and logging purposes @return [String] The output of the command @raise [SubprocessError] if the subprocess returns status > 0
[ "Synchronously", "execute", "a", "chain", "multiple", "commands", "piped", "into", "each", "other", "as", "a", "subprocess", "and", "return", "the", "output", "." ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/subprocesses.rb#L38-L51
236
JonnieCache/tinyci
lib/tinyci/subprocesses.rb
TinyCI.Subprocesses.execute_stream
def execute_stream(*command, label: nil, pwd: nil) opts = {} opts[:chdir] = pwd unless pwd.nil? Open3.popen2e(command.join(' '), opts) do |stdin, stdout_and_stderr, wait_thr| stdin.close until stdout_and_stderr.closed? || stdout_and_stderr.eof? line = stdout_and_stderr.gets log_info line.chomp $stdout.flush end unless wait_thr.value.success? raise SubprocessError.new(label, command.join(' '), wait_thr.value) end stdout_and_stderr.close end true end
ruby
def execute_stream(*command, label: nil, pwd: nil) opts = {} opts[:chdir] = pwd unless pwd.nil? Open3.popen2e(command.join(' '), opts) do |stdin, stdout_and_stderr, wait_thr| stdin.close until stdout_and_stderr.closed? || stdout_and_stderr.eof? line = stdout_and_stderr.gets log_info line.chomp $stdout.flush end unless wait_thr.value.success? raise SubprocessError.new(label, command.join(' '), wait_thr.value) end stdout_and_stderr.close end true end
[ "def", "execute_stream", "(", "*", "command", ",", "label", ":", "nil", ",", "pwd", ":", "nil", ")", "opts", "=", "{", "}", "opts", "[", ":chdir", "]", "=", "pwd", "unless", "pwd", ".", "nil?", "Open3", ".", "popen2e", "(", "command", ".", "join", "(", "' '", ")", ",", "opts", ")", "do", "|", "stdin", ",", "stdout_and_stderr", ",", "wait_thr", "|", "stdin", ".", "close", "until", "stdout_and_stderr", ".", "closed?", "||", "stdout_and_stderr", ".", "eof?", "line", "=", "stdout_and_stderr", ".", "gets", "log_info", "line", ".", "chomp", "$stdout", ".", "flush", "end", "unless", "wait_thr", ".", "value", ".", "success?", "raise", "SubprocessError", ".", "new", "(", "label", ",", "command", ".", "join", "(", "' '", ")", ",", "wait_thr", ".", "value", ")", "end", "stdout_and_stderr", ".", "close", "end", "true", "end" ]
Synchronously execute a command as a subprocess and and stream the output to `STDOUT` @param [Array<String>] command The command line @param [String] label A label for debug and logging purposes @param [String] pwd Optionally specify a different working directory in which to execute the command @return [TrueClass] `true` if the command executed successfully @raise [SubprocessError] if the subprocess returns status > 0
[ "Synchronously", "execute", "a", "command", "as", "a", "subprocess", "and", "and", "stream", "the", "output", "to", "STDOUT" ]
6dc23fc201f3527718afd814223eee0238ef8b06
https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/subprocesses.rb#L62-L82
237
fairfaxmedia/borderlands
lib/borderlands/propertymanager.rb
Borderlands.PropertyManager.property
def property(contractid, groupid, propertyid) begin property_hash = @client.get_json_body( "/papi/v0/properties/#{propertyid}", { 'contractId' => contractid, 'groupId' => groupid, }, ) rescue puts "# unable to retrieve property for (group=#{groupid},contract=#{contractid},property=#{propertyid}): #{e.message}" end Property.new property_hash['properties']['items'].first end
ruby
def property(contractid, groupid, propertyid) begin property_hash = @client.get_json_body( "/papi/v0/properties/#{propertyid}", { 'contractId' => contractid, 'groupId' => groupid, }, ) rescue puts "# unable to retrieve property for (group=#{groupid},contract=#{contractid},property=#{propertyid}): #{e.message}" end Property.new property_hash['properties']['items'].first end
[ "def", "property", "(", "contractid", ",", "groupid", ",", "propertyid", ")", "begin", "property_hash", "=", "@client", ".", "get_json_body", "(", "\"/papi/v0/properties/#{propertyid}\"", ",", "{", "'contractId'", "=>", "contractid", ",", "'groupId'", "=>", "groupid", ",", "}", ",", ")", "rescue", "puts", "\"# unable to retrieve property for (group=#{groupid},contract=#{contractid},property=#{propertyid}): #{e.message}\"", "end", "Property", ".", "new", "property_hash", "[", "'properties'", "]", "[", "'items'", "]", ".", "first", "end" ]
fetch a single property
[ "fetch", "a", "single", "property" ]
7285467ef0dca520a692ebfeae3b1fc53295b7d5
https://github.com/fairfaxmedia/borderlands/blob/7285467ef0dca520a692ebfeae3b1fc53295b7d5/lib/borderlands/propertymanager.rb#L40-L50
238
fairfaxmedia/borderlands
lib/borderlands/propertymanager.rb
Borderlands.PropertyManager.properties
def properties properties = [] contract_group_pairs.each do |cg| begin properties_hash = @client.get_json_body( "/papi/v0/properties/", { 'contractId' => cg[:contract], 'groupId' => cg[:group], } ) if properties_hash && properties_hash['properties']['items'] properties_hash['properties']['items'].each do |prp| properties << Property.new(prp) end end rescue Exception => e # probably due to Akamai PM permissions, don't raise for caller to handle puts "# unable to retrieve properties for (group=#{cg[:group]},contract=#{cg[:contract]}): #{e.message}" end end properties end
ruby
def properties properties = [] contract_group_pairs.each do |cg| begin properties_hash = @client.get_json_body( "/papi/v0/properties/", { 'contractId' => cg[:contract], 'groupId' => cg[:group], } ) if properties_hash && properties_hash['properties']['items'] properties_hash['properties']['items'].each do |prp| properties << Property.new(prp) end end rescue Exception => e # probably due to Akamai PM permissions, don't raise for caller to handle puts "# unable to retrieve properties for (group=#{cg[:group]},contract=#{cg[:contract]}): #{e.message}" end end properties end
[ "def", "properties", "properties", "=", "[", "]", "contract_group_pairs", ".", "each", "do", "|", "cg", "|", "begin", "properties_hash", "=", "@client", ".", "get_json_body", "(", "\"/papi/v0/properties/\"", ",", "{", "'contractId'", "=>", "cg", "[", ":contract", "]", ",", "'groupId'", "=>", "cg", "[", ":group", "]", ",", "}", ")", "if", "properties_hash", "&&", "properties_hash", "[", "'properties'", "]", "[", "'items'", "]", "properties_hash", "[", "'properties'", "]", "[", "'items'", "]", ".", "each", "do", "|", "prp", "|", "properties", "<<", "Property", ".", "new", "(", "prp", ")", "end", "end", "rescue", "Exception", "=>", "e", "# probably due to Akamai PM permissions, don't raise for caller to handle", "puts", "\"# unable to retrieve properties for (group=#{cg[:group]},contract=#{cg[:contract]}): #{e.message}\"", "end", "end", "properties", "end" ]
takes a long time to complete!
[ "takes", "a", "long", "time", "to", "complete!" ]
7285467ef0dca520a692ebfeae3b1fc53295b7d5
https://github.com/fairfaxmedia/borderlands/blob/7285467ef0dca520a692ebfeae3b1fc53295b7d5/lib/borderlands/propertymanager.rb#L53-L72
239
fairfaxmedia/borderlands
lib/borderlands/propertymanager.rb
Borderlands.PropertyManager.hostnames
def hostnames(property, skip_update_dns_status = false, version = nil) raise 'property must be a Borderlands::Property object' unless property.is_a? Property version ||= property.productionversion begin hostnames_hash = @client.get_json_body( "/papi/v0/properties/#{property.id}/versions/#{version}/hostnames/", { 'contractId' => property.contractid, 'groupId' => property.groupid }, ) rescue Exception => e raise "unable to retrieve hostnames for #{property.name}: #{e.message}" end if hostnames_hash && hostnames_hash['hostnames'] && hostnames_hash['hostnames']['items'] hostnames = hostnames_hash['hostnames']['items'].map do |ehn| h = Hostname.new ehn h.update_status unless skip_update_dns_status h end else # no hostnames returned hostnames = nil end hostnames end
ruby
def hostnames(property, skip_update_dns_status = false, version = nil) raise 'property must be a Borderlands::Property object' unless property.is_a? Property version ||= property.productionversion begin hostnames_hash = @client.get_json_body( "/papi/v0/properties/#{property.id}/versions/#{version}/hostnames/", { 'contractId' => property.contractid, 'groupId' => property.groupid }, ) rescue Exception => e raise "unable to retrieve hostnames for #{property.name}: #{e.message}" end if hostnames_hash && hostnames_hash['hostnames'] && hostnames_hash['hostnames']['items'] hostnames = hostnames_hash['hostnames']['items'].map do |ehn| h = Hostname.new ehn h.update_status unless skip_update_dns_status h end else # no hostnames returned hostnames = nil end hostnames end
[ "def", "hostnames", "(", "property", ",", "skip_update_dns_status", "=", "false", ",", "version", "=", "nil", ")", "raise", "'property must be a Borderlands::Property object'", "unless", "property", ".", "is_a?", "Property", "version", "||=", "property", ".", "productionversion", "begin", "hostnames_hash", "=", "@client", ".", "get_json_body", "(", "\"/papi/v0/properties/#{property.id}/versions/#{version}/hostnames/\"", ",", "{", "'contractId'", "=>", "property", ".", "contractid", ",", "'groupId'", "=>", "property", ".", "groupid", "}", ",", ")", "rescue", "Exception", "=>", "e", "raise", "\"unable to retrieve hostnames for #{property.name}: #{e.message}\"", "end", "if", "hostnames_hash", "&&", "hostnames_hash", "[", "'hostnames'", "]", "&&", "hostnames_hash", "[", "'hostnames'", "]", "[", "'items'", "]", "hostnames", "=", "hostnames_hash", "[", "'hostnames'", "]", "[", "'items'", "]", ".", "map", "do", "|", "ehn", "|", "h", "=", "Hostname", ".", "new", "ehn", "h", ".", "update_status", "unless", "skip_update_dns_status", "h", "end", "else", "# no hostnames returned", "hostnames", "=", "nil", "end", "hostnames", "end" ]
version defaults to the current production version, which is pretty much always going to be the most meaningful thing to look at
[ "version", "defaults", "to", "the", "current", "production", "version", "which", "is", "pretty", "much", "always", "going", "to", "be", "the", "most", "meaningful", "thing", "to", "look", "at" ]
7285467ef0dca520a692ebfeae3b1fc53295b7d5
https://github.com/fairfaxmedia/borderlands/blob/7285467ef0dca520a692ebfeae3b1fc53295b7d5/lib/borderlands/propertymanager.rb#L76-L98
240
fairfaxmedia/borderlands
lib/borderlands/propertymanager.rb
Borderlands.PropertyManager.ruletree
def ruletree(property,version = nil) raise 'property must be a Borderlands::Property object' unless property.is_a? Property version ||= property.productionversion tree = nil begin rt = @client.get_json_body( "/papi/v0/properties/#{property.id}/versions/#{version}/rules/", { 'contractId' => property.contractid, 'groupId' => property.groupid }, ) tree = Rule.new rt['rules'] rescue Exception => e raise "unable to retrieve rule tree for #{property.name}: #{e.message}" end tree end
ruby
def ruletree(property,version = nil) raise 'property must be a Borderlands::Property object' unless property.is_a? Property version ||= property.productionversion tree = nil begin rt = @client.get_json_body( "/papi/v0/properties/#{property.id}/versions/#{version}/rules/", { 'contractId' => property.contractid, 'groupId' => property.groupid }, ) tree = Rule.new rt['rules'] rescue Exception => e raise "unable to retrieve rule tree for #{property.name}: #{e.message}" end tree end
[ "def", "ruletree", "(", "property", ",", "version", "=", "nil", ")", "raise", "'property must be a Borderlands::Property object'", "unless", "property", ".", "is_a?", "Property", "version", "||=", "property", ".", "productionversion", "tree", "=", "nil", "begin", "rt", "=", "@client", ".", "get_json_body", "(", "\"/papi/v0/properties/#{property.id}/versions/#{version}/rules/\"", ",", "{", "'contractId'", "=>", "property", ".", "contractid", ",", "'groupId'", "=>", "property", ".", "groupid", "}", ",", ")", "tree", "=", "Rule", ".", "new", "rt", "[", "'rules'", "]", "rescue", "Exception", "=>", "e", "raise", "\"unable to retrieve rule tree for #{property.name}: #{e.message}\"", "end", "tree", "end" ]
version defaults to current production version here too
[ "version", "defaults", "to", "current", "production", "version", "here", "too" ]
7285467ef0dca520a692ebfeae3b1fc53295b7d5
https://github.com/fairfaxmedia/borderlands/blob/7285467ef0dca520a692ebfeae3b1fc53295b7d5/lib/borderlands/propertymanager.rb#L101-L115
241
phusion/union_station_hooks_core
lib/union_station_hooks_core/spec_helper.rb
UnionStationHooks.SpecHelper.find_passenger_config
def find_passenger_config passenger_config = ENV['PASSENGER_CONFIG'] if passenger_config.nil? || passenger_config.empty? passenger_config = find_passenger_config_vendor || find_passenger_config_in_path end if passenger_config.nil? || passenger_config.empty? abort 'ERROR: The unit tests are to be run against a specific ' \ 'Passenger version. However, the \'passenger-config\' command is ' \ 'not found. Please install Passenger, or (if you are sure ' \ 'Passenger is installed) set the PASSENGER_CONFIG environment ' \ 'variable to the \'passenger-config\' command.' end passenger_config end
ruby
def find_passenger_config passenger_config = ENV['PASSENGER_CONFIG'] if passenger_config.nil? || passenger_config.empty? passenger_config = find_passenger_config_vendor || find_passenger_config_in_path end if passenger_config.nil? || passenger_config.empty? abort 'ERROR: The unit tests are to be run against a specific ' \ 'Passenger version. However, the \'passenger-config\' command is ' \ 'not found. Please install Passenger, or (if you are sure ' \ 'Passenger is installed) set the PASSENGER_CONFIG environment ' \ 'variable to the \'passenger-config\' command.' end passenger_config end
[ "def", "find_passenger_config", "passenger_config", "=", "ENV", "[", "'PASSENGER_CONFIG'", "]", "if", "passenger_config", ".", "nil?", "||", "passenger_config", ".", "empty?", "passenger_config", "=", "find_passenger_config_vendor", "||", "find_passenger_config_in_path", "end", "if", "passenger_config", ".", "nil?", "||", "passenger_config", ".", "empty?", "abort", "'ERROR: The unit tests are to be run against a specific '", "'Passenger version. However, the \\'passenger-config\\' command is '", "'not found. Please install Passenger, or (if you are sure '", "'Passenger is installed) set the PASSENGER_CONFIG environment '", "'variable to the \\'passenger-config\\' command.'", "end", "passenger_config", "end" ]
Lookup the `passenger-config` command, either by respecting the `PASSENGER_CONFIG` environment variable, or by looking it up in `PATH`. If the command cannot be found, the current process aborts with an error message.
[ "Lookup", "the", "passenger", "-", "config", "command", "either", "by", "respecting", "the", "PASSENGER_CONFIG", "environment", "variable", "or", "by", "looking", "it", "up", "in", "PATH", ".", "If", "the", "command", "cannot", "be", "found", "the", "current", "process", "aborts", "with", "an", "error", "message", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/spec_helper.rb#L56-L70
242
phusion/union_station_hooks_core
lib/union_station_hooks_core/spec_helper.rb
UnionStationHooks.SpecHelper.undo_bundler
def undo_bundler clean_env = nil Bundler.with_clean_env do clean_env = ENV.to_hash end ENV.replace(clean_env) end
ruby
def undo_bundler clean_env = nil Bundler.with_clean_env do clean_env = ENV.to_hash end ENV.replace(clean_env) end
[ "def", "undo_bundler", "clean_env", "=", "nil", "Bundler", ".", "with_clean_env", "do", "clean_env", "=", "ENV", ".", "to_hash", "end", "ENV", ".", "replace", "(", "clean_env", ")", "end" ]
Unit tests must undo the Bundler environment so that the gem's own Gemfile doesn't affect subprocesses that may have their own Gemfile.
[ "Unit", "tests", "must", "undo", "the", "Bundler", "environment", "so", "that", "the", "gem", "s", "own", "Gemfile", "doesn", "t", "affect", "subprocesses", "that", "may", "have", "their", "own", "Gemfile", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/spec_helper.rb#L134-L140
243
phusion/union_station_hooks_core
lib/union_station_hooks_core/spec_helper.rb
UnionStationHooks.SpecHelper.write_file
def write_file(path, content) dir = File.dirname(path) if !File.exist?(dir) FileUtils.mkdir_p(dir) end File.open(path, 'wb') do |f| f.write(content) end end
ruby
def write_file(path, content) dir = File.dirname(path) if !File.exist?(dir) FileUtils.mkdir_p(dir) end File.open(path, 'wb') do |f| f.write(content) end end
[ "def", "write_file", "(", "path", ",", "content", ")", "dir", "=", "File", ".", "dirname", "(", "path", ")", "if", "!", "File", ".", "exist?", "(", "dir", ")", "FileUtils", ".", "mkdir_p", "(", "dir", ")", "end", "File", ".", "open", "(", "path", ",", "'wb'", ")", "do", "|", "f", "|", "f", ".", "write", "(", "content", ")", "end", "end" ]
Writes the given content to the file at the given path. If or or more parent directories don't exist, then they are created.
[ "Writes", "the", "given", "content", "to", "the", "file", "at", "the", "given", "path", ".", "If", "or", "or", "more", "parent", "directories", "don", "t", "exist", "then", "they", "are", "created", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/spec_helper.rb#L149-L157
244
phusion/union_station_hooks_core
lib/union_station_hooks_core/spec_helper.rb
UnionStationHooks.SpecHelper.debug_shell
def debug_shell puts '------ Opening debug shell -----' @orig_dir = Dir.pwd begin if respond_to?(:prepare_debug_shell) prepare_debug_shell end system('bash') ensure Dir.chdir(@orig_dir) end puts '------ Exiting debug shell -----' end
ruby
def debug_shell puts '------ Opening debug shell -----' @orig_dir = Dir.pwd begin if respond_to?(:prepare_debug_shell) prepare_debug_shell end system('bash') ensure Dir.chdir(@orig_dir) end puts '------ Exiting debug shell -----' end
[ "def", "debug_shell", "puts", "'------ Opening debug shell -----'", "@orig_dir", "=", "Dir", ".", "pwd", "begin", "if", "respond_to?", "(", ":prepare_debug_shell", ")", "prepare_debug_shell", "end", "system", "(", "'bash'", ")", "ensure", "Dir", ".", "chdir", "(", "@orig_dir", ")", "end", "puts", "'------ Exiting debug shell -----'", "end" ]
Opens a debug shell. By default, the debug shell is opened in the current working directory. If the current module has the `prepare_debug_shell` method, that method is called before opening the debug shell. The method could, for example, change the working directory. This method does *not* raise an exception if the debug shell exits with an error.
[ "Opens", "a", "debug", "shell", ".", "By", "default", "the", "debug", "shell", "is", "opened", "in", "the", "current", "working", "directory", ".", "If", "the", "current", "module", "has", "the", "prepare_debug_shell", "method", "that", "method", "is", "called", "before", "opening", "the", "debug", "shell", ".", "The", "method", "could", "for", "example", "change", "the", "working", "directory", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/spec_helper.rb#L187-L199
245
phusion/union_station_hooks_core
lib/union_station_hooks_core/spec_helper.rb
UnionStationHooks.SpecHelper.eventually
def eventually(deadline_duration = 3, check_interval = 0.05) deadline = Time.now + deadline_duration while Time.now < deadline if yield return else sleep(check_interval) end end raise 'Time limit exceeded' end
ruby
def eventually(deadline_duration = 3, check_interval = 0.05) deadline = Time.now + deadline_duration while Time.now < deadline if yield return else sleep(check_interval) end end raise 'Time limit exceeded' end
[ "def", "eventually", "(", "deadline_duration", "=", "3", ",", "check_interval", "=", "0.05", ")", "deadline", "=", "Time", ".", "now", "+", "deadline_duration", "while", "Time", ".", "now", "<", "deadline", "if", "yield", "return", "else", "sleep", "(", "check_interval", ")", "end", "end", "raise", "'Time limit exceeded'", "end" ]
Asserts that something should eventually happen. This is done by checking that the given block eventually returns true. The block is called once every `check_interval` msec. If the block does not return true within `deadline_duration` secs, then an exception is raised.
[ "Asserts", "that", "something", "should", "eventually", "happen", ".", "This", "is", "done", "by", "checking", "that", "the", "given", "block", "eventually", "returns", "true", ".", "The", "block", "is", "called", "once", "every", "check_interval", "msec", ".", "If", "the", "block", "does", "not", "return", "true", "within", "deadline_duration", "secs", "then", "an", "exception", "is", "raised", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/spec_helper.rb#L252-L262
246
phusion/union_station_hooks_core
lib/union_station_hooks_core/spec_helper.rb
UnionStationHooks.SpecHelper.should_never_happen
def should_never_happen(deadline_duration = 0.5, check_interval = 0.05) deadline = Time.now + deadline_duration while Time.now < deadline if yield raise "That which shouldn't happen happened anyway" else sleep(check_interval) end end end
ruby
def should_never_happen(deadline_duration = 0.5, check_interval = 0.05) deadline = Time.now + deadline_duration while Time.now < deadline if yield raise "That which shouldn't happen happened anyway" else sleep(check_interval) end end end
[ "def", "should_never_happen", "(", "deadline_duration", "=", "0.5", ",", "check_interval", "=", "0.05", ")", "deadline", "=", "Time", ".", "now", "+", "deadline_duration", "while", "Time", ".", "now", "<", "deadline", "if", "yield", "raise", "\"That which shouldn't happen happened anyway\"", "else", "sleep", "(", "check_interval", ")", "end", "end", "end" ]
Asserts that something should never happen. This is done by checking that the given block never returns true. The block is called once every `check_interval` msec, until `deadline_duration` seconds have passed. If the block ever returns true, then an exception is raised.
[ "Asserts", "that", "something", "should", "never", "happen", ".", "This", "is", "done", "by", "checking", "that", "the", "given", "block", "never", "returns", "true", ".", "The", "block", "is", "called", "once", "every", "check_interval", "msec", "until", "deadline_duration", "seconds", "have", "passed", ".", "If", "the", "block", "ever", "returns", "true", "then", "an", "exception", "is", "raised", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/spec_helper.rb#L268-L277
247
nosolosoftware/runnable
lib/runnable.rb
Runnable.ClassMethods.define_command
def define_command( name, opts = {}, &block ) blocking = opts[:blocking] || false log_path = opts[:log_path] || false commands[name] = { :blocking => blocking } define_method( name ) do |*args| if block run name, block.call(*args), log_path else run name, nil, log_path end join if blocking end end
ruby
def define_command( name, opts = {}, &block ) blocking = opts[:blocking] || false log_path = opts[:log_path] || false commands[name] = { :blocking => blocking } define_method( name ) do |*args| if block run name, block.call(*args), log_path else run name, nil, log_path end join if blocking end end
[ "def", "define_command", "(", "name", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "blocking", "=", "opts", "[", ":blocking", "]", "||", "false", "log_path", "=", "opts", "[", ":log_path", "]", "||", "false", "commands", "[", "name", "]", "=", "{", ":blocking", "=>", "blocking", "}", "define_method", "(", "name", ")", "do", "|", "*", "args", "|", "if", "block", "run", "name", ",", "block", ".", "call", "(", "args", ")", ",", "log_path", "else", "run", "name", ",", "nil", ",", "log_path", "end", "join", "if", "blocking", "end", "end" ]
Create a user definde command @return [nil] @param [Symbol] name The user defined command name @param [Hash] options Options. @option options :blocking (false) Describe if the execution is blocking or non-blocking @option options :log_path (false) Path used to store logs # (dont store logs if no path specified)
[ "Create", "a", "user", "definde", "command" ]
32a03690c24d18122f698519a052f8176ad7044c
https://github.com/nosolosoftware/runnable/blob/32a03690c24d18122f698519a052f8176ad7044c/lib/runnable.rb#L62-L76
248
nosolosoftware/runnable
lib/runnable.rb
Runnable.ClassMethods.method_missing
def method_missing( name, *opts ) raise NoMethodError.new( name.to_s ) unless name.to_s =~ /([a-z]*)_([a-z]*)/ # command_processors if $2 == "processors" commands[$1.to_sym][:outputs] = opts.first[:outputs] commands[$1.to_sym][:exceptions] = opts.first[:exceptions] end end
ruby
def method_missing( name, *opts ) raise NoMethodError.new( name.to_s ) unless name.to_s =~ /([a-z]*)_([a-z]*)/ # command_processors if $2 == "processors" commands[$1.to_sym][:outputs] = opts.first[:outputs] commands[$1.to_sym][:exceptions] = opts.first[:exceptions] end end
[ "def", "method_missing", "(", "name", ",", "*", "opts", ")", "raise", "NoMethodError", ".", "new", "(", "name", ".", "to_s", ")", "unless", "name", ".", "to_s", "=~", "/", "/", "# command_processors", "if", "$2", "==", "\"processors\"", "commands", "[", "$1", ".", "to_sym", "]", "[", ":outputs", "]", "=", "opts", ".", "first", "[", ":outputs", "]", "commands", "[", "$1", ".", "to_sym", "]", "[", ":exceptions", "]", "=", "opts", ".", "first", "[", ":exceptions", "]", "end", "end" ]
Method missing processing for the command processors
[ "Method", "missing", "processing", "for", "the", "command", "processors" ]
32a03690c24d18122f698519a052f8176ad7044c
https://github.com/nosolosoftware/runnable/blob/32a03690c24d18122f698519a052f8176ad7044c/lib/runnable.rb#L92-L100
249
sosedoff/grooveshark
lib/grooveshark/user.rb
Grooveshark.User.library_remove
def library_remove(song) fail ArgumentError, 'Song object required' unless song.is_a?(Song) req = { userID: @id, songID: song.id, albumID: song.album_id, artistID: song.artist_id } @client.request('userRemoveSongFromLibrary', req) end
ruby
def library_remove(song) fail ArgumentError, 'Song object required' unless song.is_a?(Song) req = { userID: @id, songID: song.id, albumID: song.album_id, artistID: song.artist_id } @client.request('userRemoveSongFromLibrary', req) end
[ "def", "library_remove", "(", "song", ")", "fail", "ArgumentError", ",", "'Song object required'", "unless", "song", ".", "is_a?", "(", "Song", ")", "req", "=", "{", "userID", ":", "@id", ",", "songID", ":", "song", ".", "id", ",", "albumID", ":", "song", ".", "album_id", ",", "artistID", ":", "song", ".", "artist_id", "}", "@client", ".", "request", "(", "'userRemoveSongFromLibrary'", ",", "req", ")", "end" ]
Remove song from user library
[ "Remove", "song", "from", "user", "library" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/user.rb#L59-L66
250
sosedoff/grooveshark
lib/grooveshark/user.rb
Grooveshark.User.get_playlist
def get_playlist(id) result = playlists.select { |p| p.id == id } result.nil? ? nil : result.first end
ruby
def get_playlist(id) result = playlists.select { |p| p.id == id } result.nil? ? nil : result.first end
[ "def", "get_playlist", "(", "id", ")", "result", "=", "playlists", ".", "select", "{", "|", "p", "|", "p", ".", "id", "==", "id", "}", "result", ".", "nil?", "?", "nil", ":", "result", ".", "first", "end" ]
Get playlist by ID
[ "Get", "playlist", "by", "ID" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/user.rb#L87-L90
251
sosedoff/grooveshark
lib/grooveshark/user.rb
Grooveshark.User.create_playlist
def create_playlist(name, description = '', songs = []) @client.request('createPlaylist', 'playlistName' => name, 'playlistAbout' => description, 'songIDs' => songs.map do |s| s.is_a?(Song) ? s.id : s.to_s end) end
ruby
def create_playlist(name, description = '', songs = []) @client.request('createPlaylist', 'playlistName' => name, 'playlistAbout' => description, 'songIDs' => songs.map do |s| s.is_a?(Song) ? s.id : s.to_s end) end
[ "def", "create_playlist", "(", "name", ",", "description", "=", "''", ",", "songs", "=", "[", "]", ")", "@client", ".", "request", "(", "'createPlaylist'", ",", "'playlistName'", "=>", "name", ",", "'playlistAbout'", "=>", "description", ",", "'songIDs'", "=>", "songs", ".", "map", "do", "|", "s", "|", "s", ".", "is_a?", "(", "Song", ")", "?", "s", ".", "id", ":", "s", ".", "to_s", "end", ")", "end" ]
Create new user playlist
[ "Create", "new", "user", "playlist" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/user.rb#L95-L102
252
sosedoff/grooveshark
lib/grooveshark/user.rb
Grooveshark.User.add_favorite
def add_favorite(song) song_id = song.is_a?(Song) ? song.id : song @client.request('favorite', what: 'Song', ID: song_id) end
ruby
def add_favorite(song) song_id = song.is_a?(Song) ? song.id : song @client.request('favorite', what: 'Song', ID: song_id) end
[ "def", "add_favorite", "(", "song", ")", "song_id", "=", "song", ".", "is_a?", "(", "Song", ")", "?", "song", ".", "id", ":", "song", "@client", ".", "request", "(", "'favorite'", ",", "what", ":", "'Song'", ",", "ID", ":", "song_id", ")", "end" ]
Add song to favorites
[ "Add", "song", "to", "favorites" ]
e55686c620c13848fa6d918cc2980fd44cf40e35
https://github.com/sosedoff/grooveshark/blob/e55686c620c13848fa6d918cc2980fd44cf40e35/lib/grooveshark/user.rb#L116-L119
253
4rlm/crm_formatter
lib/crm_formatter/phone.rb
CrmFormatter.Phone.check_phone_status
def check_phone_status(hsh) phone = hsh[:phone] phone_f = hsh[:phone_f] status = 'invalid' status = phone != phone_f ? 'formatted' : 'unchanged' if phone && phone_f hsh[:phone_status] = status if status.present? hsh end
ruby
def check_phone_status(hsh) phone = hsh[:phone] phone_f = hsh[:phone_f] status = 'invalid' status = phone != phone_f ? 'formatted' : 'unchanged' if phone && phone_f hsh[:phone_status] = status if status.present? hsh end
[ "def", "check_phone_status", "(", "hsh", ")", "phone", "=", "hsh", "[", ":phone", "]", "phone_f", "=", "hsh", "[", ":phone_f", "]", "status", "=", "'invalid'", "status", "=", "phone", "!=", "phone_f", "?", "'formatted'", ":", "'unchanged'", "if", "phone", "&&", "phone_f", "hsh", "[", ":phone_status", "]", "=", "status", "if", "status", ".", "present?", "hsh", "end" ]
COMPARE ORIGINAL AND FORMATTED PHONE
[ "COMPARE", "ORIGINAL", "AND", "FORMATTED", "PHONE" ]
5060d27552a3871257cd08612c8e93b7b2b6a350
https://github.com/4rlm/crm_formatter/blob/5060d27552a3871257cd08612c8e93b7b2b6a350/lib/crm_formatter/phone.rb#L20-L27
254
arrac/eluka
lib/eluka/model.rb
Eluka.Model.add
def add (data, label) raise "No meaningful label associated with data" unless ([:positive, :negative].include? label) #Create a data point in the vector space from the datum given data_point = Eluka::DataPoint.new(data, @analyzer) #Add the data point to the feature space #Expand the training feature space to include the data point @fv_train.add(data_point.vector, @labels[label]) end
ruby
def add (data, label) raise "No meaningful label associated with data" unless ([:positive, :negative].include? label) #Create a data point in the vector space from the datum given data_point = Eluka::DataPoint.new(data, @analyzer) #Add the data point to the feature space #Expand the training feature space to include the data point @fv_train.add(data_point.vector, @labels[label]) end
[ "def", "add", "(", "data", ",", "label", ")", "raise", "\"No meaningful label associated with data\"", "unless", "(", "[", ":positive", ",", ":negative", "]", ".", "include?", "label", ")", "#Create a data point in the vector space from the datum given", "data_point", "=", "Eluka", "::", "DataPoint", ".", "new", "(", "data", ",", "@analyzer", ")", "#Add the data point to the feature space", "#Expand the training feature space to include the data point", "@fv_train", ".", "add", "(", "data_point", ".", "vector", ",", "@labels", "[", "label", "]", ")", "end" ]
Initialize the classifier with sane defaults if customised data is not provided Adds a data point to the training data
[ "Initialize", "the", "classifier", "with", "sane", "defaults", "if", "customised", "data", "is", "not", "provided", "Adds", "a", "data", "point", "to", "the", "training", "data" ]
1293f0cc6f9810a1a289ad74c8fab234db786212
https://github.com/arrac/eluka/blob/1293f0cc6f9810a1a289ad74c8fab234db786212/lib/eluka/model.rb#L61-L70
255
rapid7/rex-sslscan
lib/rex/sslscan/result.rb
Rex::SSLScan.Result.add_cipher
def add_cipher(version, cipher, key_length, status) unless @supported_versions.include? version raise ArgumentError, "Must be a supported SSL Version" end unless OpenSSL::SSL::SSLContext.new(version).ciphers.flatten.include?(cipher) || @deprecated_weak_ciphers.include?(cipher) raise ArgumentError, "Must be a valid SSL Cipher for #{version}!" end unless key_length.kind_of? Integer raise ArgumentError, "Must supply a valid key length" end unless [:accepted, :rejected].include? status raise ArgumentError, "Status must be either :accepted or :rejected" end strong_cipher_ctx = OpenSSL::SSL::SSLContext.new(version) # OpenSSL Directive For Strong Ciphers # See: http://www.rapid7.com/vulndb/lookup/ssl-weak-ciphers strong_cipher_ctx.ciphers = "ALL:!aNULL:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM" if strong_cipher_ctx.ciphers.flatten.include? cipher weak = false else weak = true end cipher_details = {:version => version, :cipher => cipher, :key_length => key_length, :weak => weak, :status => status} @ciphers << cipher_details end
ruby
def add_cipher(version, cipher, key_length, status) unless @supported_versions.include? version raise ArgumentError, "Must be a supported SSL Version" end unless OpenSSL::SSL::SSLContext.new(version).ciphers.flatten.include?(cipher) || @deprecated_weak_ciphers.include?(cipher) raise ArgumentError, "Must be a valid SSL Cipher for #{version}!" end unless key_length.kind_of? Integer raise ArgumentError, "Must supply a valid key length" end unless [:accepted, :rejected].include? status raise ArgumentError, "Status must be either :accepted or :rejected" end strong_cipher_ctx = OpenSSL::SSL::SSLContext.new(version) # OpenSSL Directive For Strong Ciphers # See: http://www.rapid7.com/vulndb/lookup/ssl-weak-ciphers strong_cipher_ctx.ciphers = "ALL:!aNULL:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM" if strong_cipher_ctx.ciphers.flatten.include? cipher weak = false else weak = true end cipher_details = {:version => version, :cipher => cipher, :key_length => key_length, :weak => weak, :status => status} @ciphers << cipher_details end
[ "def", "add_cipher", "(", "version", ",", "cipher", ",", "key_length", ",", "status", ")", "unless", "@supported_versions", ".", "include?", "version", "raise", "ArgumentError", ",", "\"Must be a supported SSL Version\"", "end", "unless", "OpenSSL", "::", "SSL", "::", "SSLContext", ".", "new", "(", "version", ")", ".", "ciphers", ".", "flatten", ".", "include?", "(", "cipher", ")", "||", "@deprecated_weak_ciphers", ".", "include?", "(", "cipher", ")", "raise", "ArgumentError", ",", "\"Must be a valid SSL Cipher for #{version}!\"", "end", "unless", "key_length", ".", "kind_of?", "Integer", "raise", "ArgumentError", ",", "\"Must supply a valid key length\"", "end", "unless", "[", ":accepted", ",", ":rejected", "]", ".", "include?", "status", "raise", "ArgumentError", ",", "\"Status must be either :accepted or :rejected\"", "end", "strong_cipher_ctx", "=", "OpenSSL", "::", "SSL", "::", "SSLContext", ".", "new", "(", "version", ")", "# OpenSSL Directive For Strong Ciphers", "# See: http://www.rapid7.com/vulndb/lookup/ssl-weak-ciphers", "strong_cipher_ctx", ".", "ciphers", "=", "\"ALL:!aNULL:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM\"", "if", "strong_cipher_ctx", ".", "ciphers", ".", "flatten", ".", "include?", "cipher", "weak", "=", "false", "else", "weak", "=", "true", "end", "cipher_details", "=", "{", ":version", "=>", "version", ",", ":cipher", "=>", "cipher", ",", ":key_length", "=>", "key_length", ",", ":weak", "=>", "weak", ",", ":status", "=>", "status", "}", "@ciphers", "<<", "cipher_details", "end" ]
Adds the details of a cipher test to the Result object. @param version [Symbol] the SSL Version @param cipher [String] the SSL cipher @param key_length [Integer] the length of encryption key @param status [Symbol] :accepted or :rejected
[ "Adds", "the", "details", "of", "a", "cipher", "test", "to", "the", "Result", "object", "." ]
a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a
https://github.com/rapid7/rex-sslscan/blob/a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a/lib/rex/sslscan/result.rb#L143-L170
256
talis/blueprint_rb
lib/blueprint_ruby_client/api/asset_type_templates_api.rb
BlueprintClient.AssetTypeTemplatesApi.add
def add(namespace, asset_type, template_body, opts = {}) data, _status_code, _headers = add_with_http_info(namespace, asset_type, template_body, opts) return data end
ruby
def add(namespace, asset_type, template_body, opts = {}) data, _status_code, _headers = add_with_http_info(namespace, asset_type, template_body, opts) return data end
[ "def", "add", "(", "namespace", ",", "asset_type", ",", "template_body", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "add_with_http_info", "(", "namespace", ",", "asset_type", ",", "template_body", ",", "opts", ")", "return", "data", "end" ]
Configure a template for a given asset type @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param asset_type subtype of Asset, e.g. &#39;textbooks&#39;, &#39;digitisations&#39;, etc. @param template_body template body @param [Hash] opts the optional parameters @return [TemplateBody]
[ "Configure", "a", "template", "for", "a", "given", "asset", "type" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/asset_type_templates_api.rb#L30-L33
257
talis/blueprint_rb
lib/blueprint_ruby_client/api/asset_type_templates_api.rb
BlueprintClient.AssetTypeTemplatesApi.delete
def delete(namespace, asset_type, opts = {}) data, _status_code, _headers = delete_with_http_info(namespace, asset_type, opts) return data end
ruby
def delete(namespace, asset_type, opts = {}) data, _status_code, _headers = delete_with_http_info(namespace, asset_type, opts) return data end
[ "def", "delete", "(", "namespace", ",", "asset_type", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "delete_with_http_info", "(", "namespace", ",", "asset_type", ",", "opts", ")", "return", "data", "end" ]
Delete a template for a given asset type @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param asset_type subtype of Asset, e.g. &#39;textbooks&#39;, &#39;digitisations&#39;, etc. @param [Hash] opts the optional parameters @return [TemplateBody]
[ "Delete", "a", "template", "for", "a", "given", "asset", "type" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/asset_type_templates_api.rb#L114-L117
258
talis/blueprint_rb
lib/blueprint_ruby_client/api/asset_type_templates_api.rb
BlueprintClient.AssetTypeTemplatesApi.put
def put(namespace, asset_type, template_body, opts = {}) data, _status_code, _headers = put_with_http_info(namespace, asset_type, template_body, opts) return data end
ruby
def put(namespace, asset_type, template_body, opts = {}) data, _status_code, _headers = put_with_http_info(namespace, asset_type, template_body, opts) return data end
[ "def", "put", "(", "namespace", ",", "asset_type", ",", "template_body", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "put_with_http_info", "(", "namespace", ",", "asset_type", ",", "template_body", ",", "opts", ")", "return", "data", "end" ]
update a template for a given asset type @param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores. @param asset_type subtype of Asset, e.g. &#39;textbooks&#39;, &#39;digitisations&#39;, etc. @param template_body template body @param [Hash] opts the optional parameters @return [TemplateBody]
[ "update", "a", "template", "for", "a", "given", "asset", "type" ]
0ded0734161d288ba2d81485b3d3ec82a4063e1e
https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/asset_type_templates_api.rb#L190-L193
259
mikisvaz/rbbt-util
lib/rbbt/util/log/progress/report.rb
Log.ProgressBar.thr_msg
def thr_msg if @history.nil? @history ||= [[@ticks, Time.now] ] else @history << [@ticks, Time.now] max_history ||= case when @ticks > 20 count = @ticks - @last_count count = 1 if count == 0 if @max times = @max / count num = times / 20 num = 2 if num < 2 else num = 10 end count * num else 20 end max_history = 30 if max_history > 30 @history.shift if @history.length > max_history end @mean_max ||= 0 if @history.length > 3 sticks, stime = @history.first ssticks, sstime = @history[-3] lticks, ltime = @history.last mean = @mean = (lticks - sticks).to_f / (ltime - stime) short_mean = (lticks - ssticks).to_f / (ltime - sstime) @mean_max = mean if mean > @mean_max end if short_mean thr = short_mean else thr = begin (@ticks || 1) / (Time.now - @start) rescue 1 end end thr = 0.0000001 if thr == 0 if mean.nil? or mean.to_i > 1 str = "#{ Log.color :blue, thr.to_i.to_s } per sec." #str << " #{ Log.color :yellow, mean.to_i.to_s } avg. #{Log.color :yellow, @mean_max.to_i.to_s} max." if @mean_max > 0 else str = "#{ Log.color :blue, (1/thr).ceil.to_s } secs each" #str << " #{ Log.color :yellow, (1/mean).ceil.to_s } avg. #{Log.color :yellow, (1/@mean_max).ceil.to_s} min." if @mean_max > 0 end str end
ruby
def thr_msg if @history.nil? @history ||= [[@ticks, Time.now] ] else @history << [@ticks, Time.now] max_history ||= case when @ticks > 20 count = @ticks - @last_count count = 1 if count == 0 if @max times = @max / count num = times / 20 num = 2 if num < 2 else num = 10 end count * num else 20 end max_history = 30 if max_history > 30 @history.shift if @history.length > max_history end @mean_max ||= 0 if @history.length > 3 sticks, stime = @history.first ssticks, sstime = @history[-3] lticks, ltime = @history.last mean = @mean = (lticks - sticks).to_f / (ltime - stime) short_mean = (lticks - ssticks).to_f / (ltime - sstime) @mean_max = mean if mean > @mean_max end if short_mean thr = short_mean else thr = begin (@ticks || 1) / (Time.now - @start) rescue 1 end end thr = 0.0000001 if thr == 0 if mean.nil? or mean.to_i > 1 str = "#{ Log.color :blue, thr.to_i.to_s } per sec." #str << " #{ Log.color :yellow, mean.to_i.to_s } avg. #{Log.color :yellow, @mean_max.to_i.to_s} max." if @mean_max > 0 else str = "#{ Log.color :blue, (1/thr).ceil.to_s } secs each" #str << " #{ Log.color :yellow, (1/mean).ceil.to_s } avg. #{Log.color :yellow, (1/@mean_max).ceil.to_s} min." if @mean_max > 0 end str end
[ "def", "thr_msg", "if", "@history", ".", "nil?", "@history", "||=", "[", "[", "@ticks", ",", "Time", ".", "now", "]", "]", "else", "@history", "<<", "[", "@ticks", ",", "Time", ".", "now", "]", "max_history", "||=", "case", "when", "@ticks", ">", "20", "count", "=", "@ticks", "-", "@last_count", "count", "=", "1", "if", "count", "==", "0", "if", "@max", "times", "=", "@max", "/", "count", "num", "=", "times", "/", "20", "num", "=", "2", "if", "num", "<", "2", "else", "num", "=", "10", "end", "count", "*", "num", "else", "20", "end", "max_history", "=", "30", "if", "max_history", ">", "30", "@history", ".", "shift", "if", "@history", ".", "length", ">", "max_history", "end", "@mean_max", "||=", "0", "if", "@history", ".", "length", ">", "3", "sticks", ",", "stime", "=", "@history", ".", "first", "ssticks", ",", "sstime", "=", "@history", "[", "-", "3", "]", "lticks", ",", "ltime", "=", "@history", ".", "last", "mean", "=", "@mean", "=", "(", "lticks", "-", "sticks", ")", ".", "to_f", "/", "(", "ltime", "-", "stime", ")", "short_mean", "=", "(", "lticks", "-", "ssticks", ")", ".", "to_f", "/", "(", "ltime", "-", "sstime", ")", "@mean_max", "=", "mean", "if", "mean", ">", "@mean_max", "end", "if", "short_mean", "thr", "=", "short_mean", "else", "thr", "=", "begin", "(", "@ticks", "||", "1", ")", "/", "(", "Time", ".", "now", "-", "@start", ")", "rescue", "1", "end", "end", "thr", "=", "0.0000001", "if", "thr", "==", "0", "if", "mean", ".", "nil?", "or", "mean", ".", "to_i", ">", "1", "str", "=", "\"#{ Log.color :blue, thr.to_i.to_s } per sec.\"", "#str << \" #{ Log.color :yellow, mean.to_i.to_s } avg. #{Log.color :yellow, @mean_max.to_i.to_s} max.\" if @mean_max > 0", "else", "str", "=", "\"#{ Log.color :blue, (1/thr).ceil.to_s } secs each\"", "#str << \" #{ Log.color :yellow, (1/mean).ceil.to_s } avg. #{Log.color :yellow, (1/@mean_max).ceil.to_s} min.\" if @mean_max > 0", "end", "str", "end" ]
def thr count = (@ticks - @last_count).to_f if @last_time.nil? seconds = 0.001 else seconds = Time.now - @last_time end thr = count / seconds end def thr_msg thr = self.thr if @history.nil? @history ||= [thr] else @history << thr max_history ||= case when @ticks > 20 count = @ticks - @last_count if @max times = @max / count num = times / 20 num = 2 if num < 2 else num = 10 end count * num else 20 end max_history = 30 if max_history > 30 max_history = 100 @history.shift if @history.length > max_history end @mean_max ||= 0 if @history.length > 3 w_mean = 0 total_w = 0 @history.each_with_index do |v,i| c = i ** 10 w_mean += v * c total_w += c end mean = @mean = w_mean.to_f / total_w @mean_max = mean if mean > @mean_max end if mean.nil? or mean.to_i > 1 str = "#{ Log.color :blue, thr.to_i.to_s } per sec." str << " #{ Log.color :yellow, mean.to_i.to_s } avg. #{Log.color :yellow, @mean_max.to_i.to_s} max." if @mean_max > 0 else str = "#{ Log.color :blue, (1/thr).ceil.to_s } secs each" str << " #{ Log.color :yellow, (1/mean).ceil.to_s } avg. #{Log.color :yellow, (1/@mean_max).ceil.to_s} min." if @mean_max > 0 end str end
[ "def", "thr", "count", "=", "(" ]
dfa78eea3dfcf4bb40972e8a2a85963d21ce1688
https://github.com/mikisvaz/rbbt-util/blob/dfa78eea3dfcf4bb40972e8a2a85963d21ce1688/lib/rbbt/util/log/progress/report.rb#L75-L133
260
rapid7/rex-sslscan
lib/rex/sslscan/scanner.rb
Rex::SSLScan.Scanner.valid?
def valid? begin @host = Rex::Socket.getaddress(@host, true) rescue return false end @port.kind_of?(Integer) && @port >= 0 && @port <= 65535 && @timeout.kind_of?(Integer) end
ruby
def valid? begin @host = Rex::Socket.getaddress(@host, true) rescue return false end @port.kind_of?(Integer) && @port >= 0 && @port <= 65535 && @timeout.kind_of?(Integer) end
[ "def", "valid?", "begin", "@host", "=", "Rex", "::", "Socket", ".", "getaddress", "(", "@host", ",", "true", ")", "rescue", "return", "false", "end", "@port", ".", "kind_of?", "(", "Integer", ")", "&&", "@port", ">=", "0", "&&", "@port", "<=", "65535", "&&", "@timeout", ".", "kind_of?", "(", "Integer", ")", "end" ]
Initializes the scanner object @param host [String] IP address or hostname to scan @param port [Integer] Port number to scan, default: 443 @param timeout [Integer] Timeout for connections, in seconds. default: 5 @raise [StandardError] Raised when the configuration is invalid Checks whether the scanner option has a valid configuration @return [Boolean] True or False, the configuration is valid.
[ "Initializes", "the", "scanner", "object" ]
a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a
https://github.com/rapid7/rex-sslscan/blob/a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a/lib/rex/sslscan/scanner.rb#L42-L49
261
rapid7/rex-sslscan
lib/rex/sslscan/scanner.rb
Rex::SSLScan.Scanner.scan
def scan scan_result = Rex::SSLScan::Result.new scan_result.openssl_sslv2 = sslv2 # If we can't get any SSL connection, then don't bother testing # individual ciphers. if test_ssl == :rejected and test_tls == :rejected return scan_result end threads = [] ciphers = Queue.new @supported_versions.each do |ssl_version| sslctx = OpenSSL::SSL::SSLContext.new(ssl_version) sslctx.ciphers.each do |cipher_name, ssl_ver, key_length, alg_length| threads << Thread.new do begin status = test_cipher(ssl_version, cipher_name) ciphers << [ssl_version, cipher_name, key_length, status] if status == :accepted and scan_result.cert.nil? scan_result.cert = get_cert(ssl_version, cipher_name) end rescue Rex::SSLScan::Scanner::InvalidCipher next end end end end threads.each { |thr| thr.join } until ciphers.empty? do cipher = ciphers.pop scan_result.add_cipher(*cipher) end scan_result end
ruby
def scan scan_result = Rex::SSLScan::Result.new scan_result.openssl_sslv2 = sslv2 # If we can't get any SSL connection, then don't bother testing # individual ciphers. if test_ssl == :rejected and test_tls == :rejected return scan_result end threads = [] ciphers = Queue.new @supported_versions.each do |ssl_version| sslctx = OpenSSL::SSL::SSLContext.new(ssl_version) sslctx.ciphers.each do |cipher_name, ssl_ver, key_length, alg_length| threads << Thread.new do begin status = test_cipher(ssl_version, cipher_name) ciphers << [ssl_version, cipher_name, key_length, status] if status == :accepted and scan_result.cert.nil? scan_result.cert = get_cert(ssl_version, cipher_name) end rescue Rex::SSLScan::Scanner::InvalidCipher next end end end end threads.each { |thr| thr.join } until ciphers.empty? do cipher = ciphers.pop scan_result.add_cipher(*cipher) end scan_result end
[ "def", "scan", "scan_result", "=", "Rex", "::", "SSLScan", "::", "Result", ".", "new", "scan_result", ".", "openssl_sslv2", "=", "sslv2", "# If we can't get any SSL connection, then don't bother testing", "# individual ciphers.", "if", "test_ssl", "==", ":rejected", "and", "test_tls", "==", ":rejected", "return", "scan_result", "end", "threads", "=", "[", "]", "ciphers", "=", "Queue", ".", "new", "@supported_versions", ".", "each", "do", "|", "ssl_version", "|", "sslctx", "=", "OpenSSL", "::", "SSL", "::", "SSLContext", ".", "new", "(", "ssl_version", ")", "sslctx", ".", "ciphers", ".", "each", "do", "|", "cipher_name", ",", "ssl_ver", ",", "key_length", ",", "alg_length", "|", "threads", "<<", "Thread", ".", "new", "do", "begin", "status", "=", "test_cipher", "(", "ssl_version", ",", "cipher_name", ")", "ciphers", "<<", "[", "ssl_version", ",", "cipher_name", ",", "key_length", ",", "status", "]", "if", "status", "==", ":accepted", "and", "scan_result", ".", "cert", ".", "nil?", "scan_result", ".", "cert", "=", "get_cert", "(", "ssl_version", ",", "cipher_name", ")", "end", "rescue", "Rex", "::", "SSLScan", "::", "Scanner", "::", "InvalidCipher", "next", "end", "end", "end", "end", "threads", ".", "each", "{", "|", "thr", "|", "thr", ".", "join", "}", "until", "ciphers", ".", "empty?", "do", "cipher", "=", "ciphers", ".", "pop", "scan_result", ".", "add_cipher", "(", "cipher", ")", "end", "scan_result", "end" ]
Initiate the Scan against the target. Will test each cipher one at a time. @return [Result] object containing the details of the scan
[ "Initiate", "the", "Scan", "against", "the", "target", ".", "Will", "test", "each", "cipher", "one", "at", "a", "time", "." ]
a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a
https://github.com/rapid7/rex-sslscan/blob/a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a/lib/rex/sslscan/scanner.rb#L53-L87
262
rapid7/rex-sslscan
lib/rex/sslscan/scanner.rb
Rex::SSLScan.Scanner.get_cert
def get_cert(ssl_version, cipher) validate_params(ssl_version,cipher) begin scan_client = Rex::Socket::Tcp.create( 'PeerHost' => @host, 'PeerPort' => @port, 'SSL' => true, 'SSLVersion' => ssl_version, 'SSLCipher' => cipher, 'Timeout' => @timeout ) cert = scan_client.peer_cert if cert.kind_of? OpenSSL::X509::Certificate return cert else return nil end rescue ::Exception => e return nil ensure if scan_client scan_client.close end end end
ruby
def get_cert(ssl_version, cipher) validate_params(ssl_version,cipher) begin scan_client = Rex::Socket::Tcp.create( 'PeerHost' => @host, 'PeerPort' => @port, 'SSL' => true, 'SSLVersion' => ssl_version, 'SSLCipher' => cipher, 'Timeout' => @timeout ) cert = scan_client.peer_cert if cert.kind_of? OpenSSL::X509::Certificate return cert else return nil end rescue ::Exception => e return nil ensure if scan_client scan_client.close end end end
[ "def", "get_cert", "(", "ssl_version", ",", "cipher", ")", "validate_params", "(", "ssl_version", ",", "cipher", ")", "begin", "scan_client", "=", "Rex", "::", "Socket", "::", "Tcp", ".", "create", "(", "'PeerHost'", "=>", "@host", ",", "'PeerPort'", "=>", "@port", ",", "'SSL'", "=>", "true", ",", "'SSLVersion'", "=>", "ssl_version", ",", "'SSLCipher'", "=>", "cipher", ",", "'Timeout'", "=>", "@timeout", ")", "cert", "=", "scan_client", ".", "peer_cert", "if", "cert", ".", "kind_of?", "OpenSSL", "::", "X509", "::", "Certificate", "return", "cert", "else", "return", "nil", "end", "rescue", "::", "Exception", "=>", "e", "return", "nil", "ensure", "if", "scan_client", "scan_client", ".", "close", "end", "end", "end" ]
Retrieve the X509 Cert from the target service, @param ssl_version [Symbol] The SSL version to use (:SSLv2, :SSLv3, :TLSv1) @param cipher [String] The SSL Cipher to use @return [OpenSSL::X509::Certificate] if the certificate was retrieved @return [Nil] if the cert couldn't be retrieved
[ "Retrieve", "the", "X509", "Cert", "from", "the", "target", "service" ]
a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a
https://github.com/rapid7/rex-sslscan/blob/a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a/lib/rex/sslscan/scanner.rb#L161-L185
263
rapid7/rex-sslscan
lib/rex/sslscan/scanner.rb
Rex::SSLScan.Scanner.validate_params
def validate_params(ssl_version, cipher) raise StandardError, "The scanner configuration is invalid" unless valid? unless @supported_versions.include? ssl_version raise StandardError, "SSL Version must be one of: #{@supported_versions.to_s}" end if ssl_version == :SSLv2 and sslv2 == false raise StandardError, "Your OS hates freedom! Your OpenSSL libs are compiled without SSLv2 support!" else unless OpenSSL::SSL::SSLContext.new(ssl_version).ciphers.flatten.include? cipher raise InvalidCipher, "Must be a valid SSL Cipher for #{ssl_version}!" end end end
ruby
def validate_params(ssl_version, cipher) raise StandardError, "The scanner configuration is invalid" unless valid? unless @supported_versions.include? ssl_version raise StandardError, "SSL Version must be one of: #{@supported_versions.to_s}" end if ssl_version == :SSLv2 and sslv2 == false raise StandardError, "Your OS hates freedom! Your OpenSSL libs are compiled without SSLv2 support!" else unless OpenSSL::SSL::SSLContext.new(ssl_version).ciphers.flatten.include? cipher raise InvalidCipher, "Must be a valid SSL Cipher for #{ssl_version}!" end end end
[ "def", "validate_params", "(", "ssl_version", ",", "cipher", ")", "raise", "StandardError", ",", "\"The scanner configuration is invalid\"", "unless", "valid?", "unless", "@supported_versions", ".", "include?", "ssl_version", "raise", "StandardError", ",", "\"SSL Version must be one of: #{@supported_versions.to_s}\"", "end", "if", "ssl_version", "==", ":SSLv2", "and", "sslv2", "==", "false", "raise", "StandardError", ",", "\"Your OS hates freedom! Your OpenSSL libs are compiled without SSLv2 support!\"", "else", "unless", "OpenSSL", "::", "SSL", "::", "SSLContext", ".", "new", "(", "ssl_version", ")", ".", "ciphers", ".", "flatten", ".", "include?", "cipher", "raise", "InvalidCipher", ",", "\"Must be a valid SSL Cipher for #{ssl_version}!\"", "end", "end", "end" ]
Validates that the SSL Version and Cipher are valid both seperately and together as part of an SSL Context. @param ssl_version [Symbol] The SSL version to use (:SSLv2, :SSLv3, :TLSv1) @param cipher [String] The SSL Cipher to use @raise [StandardError] If an invalid or unsupported SSL Version was supplied @raise [StandardError] If the cipher is not valid for that version of SSL
[ "Validates", "that", "the", "SSL", "Version", "and", "Cipher", "are", "valid", "both", "seperately", "and", "together", "as", "part", "of", "an", "SSL", "Context", "." ]
a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a
https://github.com/rapid7/rex-sslscan/blob/a52c53ec09bd70cdd025b49c16dfeafe9fd3be5a/lib/rex/sslscan/scanner.rb#L196-L208
264
phusion/union_station_hooks_core
lib/union_station_hooks_core/request_reporter/misc.rb
UnionStationHooks.RequestReporter.log_user_activity_begin
def log_user_activity_begin(name) return do_nothing_on_null(:log_user_activity_begin) if null? id = next_user_activity_name @transaction.log_activity_begin(id, UnionStationHooks.now, name) id end
ruby
def log_user_activity_begin(name) return do_nothing_on_null(:log_user_activity_begin) if null? id = next_user_activity_name @transaction.log_activity_begin(id, UnionStationHooks.now, name) id end
[ "def", "log_user_activity_begin", "(", "name", ")", "return", "do_nothing_on_null", "(", ":log_user_activity_begin", ")", "if", "null?", "id", "=", "next_user_activity_name", "@transaction", ".", "log_activity_begin", "(", "id", ",", "UnionStationHooks", ".", "now", ",", "name", ")", "id", "end" ]
Logs the begin of a user-defined activity, for display in the activity timeline. An activity is a block in the activity timeline in the Union Station user interace. It has a name, a begin time and an end time. This form logs only the name and the begin time. You *must* also call {#log_user_activity_end} later with the same name to log the end time. @param name The name that should show up in the activity timeline. It can be any arbitrary name but may not contain newlines. @return id An ID which you must pass to {#log_user_activity_end} later.
[ "Logs", "the", "begin", "of", "a", "user", "-", "defined", "activity", "for", "display", "in", "the", "activity", "timeline", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/request_reporter/misc.rb#L71-L76
265
phusion/union_station_hooks_core
lib/union_station_hooks_core/request_reporter/misc.rb
UnionStationHooks.RequestReporter.log_user_activity_end
def log_user_activity_end(id, has_error = false) return do_nothing_on_null(:log_user_activity_end) if null? @transaction.log_activity_end(id, UnionStationHooks.now, has_error) end
ruby
def log_user_activity_end(id, has_error = false) return do_nothing_on_null(:log_user_activity_end) if null? @transaction.log_activity_end(id, UnionStationHooks.now, has_error) end
[ "def", "log_user_activity_end", "(", "id", ",", "has_error", "=", "false", ")", "return", "do_nothing_on_null", "(", ":log_user_activity_end", ")", "if", "null?", "@transaction", ".", "log_activity_end", "(", "id", ",", "UnionStationHooks", ".", "now", ",", "has_error", ")", "end" ]
Logs the end of a user-defined activity, for display in the activity timeline. An activity is a block in the activity timeline in the Union Station user interace. It has a name, a begin time and an end time. This form logs only the name and the end time. You *must* also have called {#log_user_activity_begin} earlier with the same name to log the begin time. @param id The ID which you obtained from {#log_user_activity_begin} earlier. @param [Boolean] has_error Whether an uncaught exception occurred during the activity.
[ "Logs", "the", "end", "of", "a", "user", "-", "defined", "activity", "for", "display", "in", "the", "activity", "timeline", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/request_reporter/misc.rb#L92-L95
266
phusion/union_station_hooks_core
lib/union_station_hooks_core/request_reporter/misc.rb
UnionStationHooks.RequestReporter.log_user_activity
def log_user_activity(name, begin_time, end_time, has_error = false) return do_nothing_on_null(:log_user_activity) if null? @transaction.log_activity(next_user_activity_name, begin_time, end_time, name, has_error) end
ruby
def log_user_activity(name, begin_time, end_time, has_error = false) return do_nothing_on_null(:log_user_activity) if null? @transaction.log_activity(next_user_activity_name, begin_time, end_time, name, has_error) end
[ "def", "log_user_activity", "(", "name", ",", "begin_time", ",", "end_time", ",", "has_error", "=", "false", ")", "return", "do_nothing_on_null", "(", ":log_user_activity", ")", "if", "null?", "@transaction", ".", "log_activity", "(", "next_user_activity_name", ",", "begin_time", ",", "end_time", ",", "name", ",", "has_error", ")", "end" ]
Logs a user-defined activity, for display in the activity timeline. An activity is a block in the activity timeline in the Union Station user interace. It has a name, a begin time and an end time. Unlike {#log_user_activity_block}, this form does not expect a block. However, you are expected to pass timing information. @param name The name that should show up in the activity timeline. It can be any arbitrary name but may not contain newlines. @param [TimePoint or Time] begin_time The time at which this activity begun. See {UnionStationHooks.now} to learn more. @param [TimePoint or Time] end_time The time at which this activity ended. See {UnionStationHooks.now} to learn more. @param [Boolean] has_error Whether an uncaught exception occurred during the activity.
[ "Logs", "a", "user", "-", "defined", "activity", "for", "display", "in", "the", "activity", "timeline", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/request_reporter/misc.rb#L113-L117
267
phusion/union_station_hooks_core
lib/union_station_hooks_core/request_reporter/misc.rb
UnionStationHooks.RequestReporter.log_exception
def log_exception(exception) transaction = @context.new_transaction( @app_group_name, :exceptions, @key) begin return do_nothing_on_null(:log_exception) if transaction.null? base64_message = exception.message base64_message = exception.to_s if base64_message.empty? base64_message = Utils.base64(base64_message) base64_backtrace = Utils.base64(exception.backtrace.join("\n")) if controller_action_logged? transaction.message("Controller action: #{@controller_action}") end transaction.message("Request transaction ID: #{@txn_id}") transaction.message("Message: #{base64_message}") transaction.message("Class: #{exception.class.name}") transaction.message("Backtrace: #{base64_backtrace}") ensure transaction.close end end
ruby
def log_exception(exception) transaction = @context.new_transaction( @app_group_name, :exceptions, @key) begin return do_nothing_on_null(:log_exception) if transaction.null? base64_message = exception.message base64_message = exception.to_s if base64_message.empty? base64_message = Utils.base64(base64_message) base64_backtrace = Utils.base64(exception.backtrace.join("\n")) if controller_action_logged? transaction.message("Controller action: #{@controller_action}") end transaction.message("Request transaction ID: #{@txn_id}") transaction.message("Message: #{base64_message}") transaction.message("Class: #{exception.class.name}") transaction.message("Backtrace: #{base64_backtrace}") ensure transaction.close end end
[ "def", "log_exception", "(", "exception", ")", "transaction", "=", "@context", ".", "new_transaction", "(", "@app_group_name", ",", ":exceptions", ",", "@key", ")", "begin", "return", "do_nothing_on_null", "(", ":log_exception", ")", "if", "transaction", ".", "null?", "base64_message", "=", "exception", ".", "message", "base64_message", "=", "exception", ".", "to_s", "if", "base64_message", ".", "empty?", "base64_message", "=", "Utils", ".", "base64", "(", "base64_message", ")", "base64_backtrace", "=", "Utils", ".", "base64", "(", "exception", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", ")", "if", "controller_action_logged?", "transaction", ".", "message", "(", "\"Controller action: #{@controller_action}\"", ")", "end", "transaction", ".", "message", "(", "\"Request transaction ID: #{@txn_id}\"", ")", "transaction", ".", "message", "(", "\"Message: #{base64_message}\"", ")", "transaction", ".", "message", "(", "\"Class: #{exception.class.name}\"", ")", "transaction", ".", "message", "(", "\"Backtrace: #{base64_backtrace}\"", ")", "ensure", "transaction", ".", "close", "end", "end" ]
Logs an exception that occurred during a request. If you want to use an exception that occurred outside the request/response cycle, e.g. an exception that occurred in a thread, use {UnionStationHooks.log_exception} instead. If {#log_controller_action_block} or {#log_controller_action} was called during the same request, then the information passed to those methods will be included in the exception report. @param [Exception] exception
[ "Logs", "an", "exception", "that", "occurred", "during", "a", "request", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/request_reporter/misc.rb#L178-L201
268
phusion/union_station_hooks_core
lib/union_station_hooks_core/request_reporter/misc.rb
UnionStationHooks.RequestReporter.log_database_query
def log_database_query(options) return do_nothing_on_null(:log_database_query) if null? Utils.require_key(options, :begin_time) Utils.require_key(options, :end_time) Utils.require_non_empty_key(options, :query) name = options[:name] || 'SQL' begin_time = options[:begin_time] end_time = options[:end_time] query = options[:query] @transaction.log_activity(next_database_query_name, begin_time, end_time, "#{name}\n#{query}") end
ruby
def log_database_query(options) return do_nothing_on_null(:log_database_query) if null? Utils.require_key(options, :begin_time) Utils.require_key(options, :end_time) Utils.require_non_empty_key(options, :query) name = options[:name] || 'SQL' begin_time = options[:begin_time] end_time = options[:end_time] query = options[:query] @transaction.log_activity(next_database_query_name, begin_time, end_time, "#{name}\n#{query}") end
[ "def", "log_database_query", "(", "options", ")", "return", "do_nothing_on_null", "(", ":log_database_query", ")", "if", "null?", "Utils", ".", "require_key", "(", "options", ",", ":begin_time", ")", "Utils", ".", "require_key", "(", "options", ",", ":end_time", ")", "Utils", ".", "require_non_empty_key", "(", "options", ",", ":query", ")", "name", "=", "options", "[", ":name", "]", "||", "'SQL'", "begin_time", "=", "options", "[", ":begin_time", "]", "end_time", "=", "options", "[", ":end_time", "]", "query", "=", "options", "[", ":query", "]", "@transaction", ".", "log_activity", "(", "next_database_query_name", ",", "begin_time", ",", "end_time", ",", "\"#{name}\\n#{query}\"", ")", "end" ]
Logs a database query that was performed during the request. @option options [String] :name (optional) A name for this database query activity. Default: "SQL" @option options [TimePoint or Time] :begin_time The time at which this database query begun. See {UnionStationHooks.now} to learn more. @option options [TimePoint or Time] :end_time The time at which this database query ended. See {UnionStationHooks.now} to learn more. @option options [String] :query The database query string.
[ "Logs", "a", "database", "query", "that", "was", "performed", "during", "the", "request", "." ]
e4b1797736a9b72a348db8e6d4ceebb62b30d478
https://github.com/phusion/union_station_hooks_core/blob/e4b1797736a9b72a348db8e6d4ceebb62b30d478/lib/union_station_hooks_core/request_reporter/misc.rb#L212-L225
269
coupler/linkage
lib/linkage/matcher.rb
Linkage.Matcher.mean
def mean w = @comparators.collect { |comparator| comparator.weight || 1 } @score_set.open_for_reading @score_set.each_pair do |id_1, id_2, scores| sum = 0 scores.each do |key, value| sum += value * w[key-1] end mean = sum / @comparators.length.to_f if mean >= @threshold changed notify_observers(id_1, id_2, mean) end end @score_set.close end
ruby
def mean w = @comparators.collect { |comparator| comparator.weight || 1 } @score_set.open_for_reading @score_set.each_pair do |id_1, id_2, scores| sum = 0 scores.each do |key, value| sum += value * w[key-1] end mean = sum / @comparators.length.to_f if mean >= @threshold changed notify_observers(id_1, id_2, mean) end end @score_set.close end
[ "def", "mean", "w", "=", "@comparators", ".", "collect", "{", "|", "comparator", "|", "comparator", ".", "weight", "||", "1", "}", "@score_set", ".", "open_for_reading", "@score_set", ".", "each_pair", "do", "|", "id_1", ",", "id_2", ",", "scores", "|", "sum", "=", "0", "scores", ".", "each", "do", "|", "key", ",", "value", "|", "sum", "+=", "value", "*", "w", "[", "key", "-", "1", "]", "end", "mean", "=", "sum", "/", "@comparators", ".", "length", ".", "to_f", "if", "mean", ">=", "@threshold", "changed", "notify_observers", "(", "id_1", ",", "id_2", ",", "mean", ")", "end", "end", "@score_set", ".", "close", "end" ]
Combine scores for each pair of records via mean, then compare the combined score to the threshold. Notify observers if there's a match.
[ "Combine", "scores", "for", "each", "pair", "of", "records", "via", "mean", "then", "compare", "the", "combined", "score", "to", "the", "threshold", ".", "Notify", "observers", "if", "there", "s", "a", "match", "." ]
2f208ae0709a141a6a8e5ba3bc6914677e986cb0
https://github.com/coupler/linkage/blob/2f208ae0709a141a6a8e5ba3bc6914677e986cb0/lib/linkage/matcher.rb#L41-L56
270
blambeau/finitio-rb
lib/finitio/type/sub_type.rb
Finitio.SubType.dress
def dress(value, handler = DressHelper.new) # Check that the supertype is able to dress the value. # Rewrite and set cause to any encountered TypeError. uped = handler.try(self, value) do super_type.dress(value, handler) end # Check each constraint in turn constraints.each do |constraint| next if constraint===uped msg = handler.default_error_message(self, value) if constraint.named? && constraints.size>1 msg << " (not #{constraint.name})" end handler.fail!(msg) end # seems good, return the uped value uped end
ruby
def dress(value, handler = DressHelper.new) # Check that the supertype is able to dress the value. # Rewrite and set cause to any encountered TypeError. uped = handler.try(self, value) do super_type.dress(value, handler) end # Check each constraint in turn constraints.each do |constraint| next if constraint===uped msg = handler.default_error_message(self, value) if constraint.named? && constraints.size>1 msg << " (not #{constraint.name})" end handler.fail!(msg) end # seems good, return the uped value uped end
[ "def", "dress", "(", "value", ",", "handler", "=", "DressHelper", ".", "new", ")", "# Check that the supertype is able to dress the value.", "# Rewrite and set cause to any encountered TypeError.", "uped", "=", "handler", ".", "try", "(", "self", ",", "value", ")", "do", "super_type", ".", "dress", "(", "value", ",", "handler", ")", "end", "# Check each constraint in turn", "constraints", ".", "each", "do", "|", "constraint", "|", "next", "if", "constraint", "===", "uped", "msg", "=", "handler", ".", "default_error_message", "(", "self", ",", "value", ")", "if", "constraint", ".", "named?", "&&", "constraints", ".", "size", ">", "1", "msg", "<<", "\" (not #{constraint.name})\"", "end", "handler", ".", "fail!", "(", "msg", ")", "end", "# seems good, return the uped value", "uped", "end" ]
Check that `value` can be uped through the supertype, then verify all constraints. Raise an error if anything goes wrong.
[ "Check", "that", "value", "can", "be", "uped", "through", "the", "supertype", "then", "verify", "all", "constraints", ".", "Raise", "an", "error", "if", "anything", "goes", "wrong", "." ]
c07a3887a6af26b2ed1eb3c50b101e210d3d8b40
https://github.com/blambeau/finitio-rb/blob/c07a3887a6af26b2ed1eb3c50b101e210d3d8b40/lib/finitio/type/sub_type.rb#L63-L82
271
juandebravo/quora-client
lib/quora/auth.rb
Quora.Auth.login
def login(user, password) endpoint = URI.parse(QUORA_URI) http = Net::HTTP.new(endpoint.host, endpoint.port) resp = http.get('/login/') cookie = resp["set-cookie"] # TODO: improve this rubbish # get formkey value start = resp.body.index("Q.formkey") formkey = resp.body[start..start+200].split("\"")[1] # get window value start = resp.body.index("webnode2.windowId") window = resp.body[start..start+200].split("\"")[1] # get __vcon_json value start = resp.body.index("InlineLogin") vcon_json = resp.body[start..start+200] start = vcon_json.index("live") vcon_json = vcon_json[start..-1] vcon_json = vcon_json.split("\"")[0] vcon_json = vcon_json.split(":") vcon_json.map! { |value| "\"#{value}\"" } vcon_json = "[#{vcon_json.join(",")}]" vcon_json = CGI::escape(vcon_json) user = CGI::escape(user) password = CGI::escape(password) body = "json=%7B%22args%22%3A%5B%22#{user}%22%2C%22#{password}%22%2Ctrue%5D%2C%22kwargs%22%3A%7B%7D%7D&formkey=#{formkey}&window_id=#{window}&__vcon_json=#{vcon_json}&__vcon_method=do_login" headers = { "Content-Type" => "application/x-www-form-urlencoded", "X-Requested-With" => "XMLHttpRequest", "Accept" => "application/json, text/javascript, */*", "Cookie" => cookie, "User-Agent" => "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.237 Safari/534.10", "Content-Length" => body.length.to_s, "Accept-Charset" => "ISO-8859-1,utf-8;q=0.7,*;q=0.3", "Accept-Language" => "es-ES,es;q=0.8", "Accept-Encoding" => "gzip,deflate,sdch", "Origin" => "http://www.quora.com", "Host" => "www.quora.com", "Referer" => "http://www.quora.com/login/" } resp = http.post("/webnode2/server_call_POST", body, headers) if resp.code == "200" cookie else "" end end
ruby
def login(user, password) endpoint = URI.parse(QUORA_URI) http = Net::HTTP.new(endpoint.host, endpoint.port) resp = http.get('/login/') cookie = resp["set-cookie"] # TODO: improve this rubbish # get formkey value start = resp.body.index("Q.formkey") formkey = resp.body[start..start+200].split("\"")[1] # get window value start = resp.body.index("webnode2.windowId") window = resp.body[start..start+200].split("\"")[1] # get __vcon_json value start = resp.body.index("InlineLogin") vcon_json = resp.body[start..start+200] start = vcon_json.index("live") vcon_json = vcon_json[start..-1] vcon_json = vcon_json.split("\"")[0] vcon_json = vcon_json.split(":") vcon_json.map! { |value| "\"#{value}\"" } vcon_json = "[#{vcon_json.join(",")}]" vcon_json = CGI::escape(vcon_json) user = CGI::escape(user) password = CGI::escape(password) body = "json=%7B%22args%22%3A%5B%22#{user}%22%2C%22#{password}%22%2Ctrue%5D%2C%22kwargs%22%3A%7B%7D%7D&formkey=#{formkey}&window_id=#{window}&__vcon_json=#{vcon_json}&__vcon_method=do_login" headers = { "Content-Type" => "application/x-www-form-urlencoded", "X-Requested-With" => "XMLHttpRequest", "Accept" => "application/json, text/javascript, */*", "Cookie" => cookie, "User-Agent" => "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.237 Safari/534.10", "Content-Length" => body.length.to_s, "Accept-Charset" => "ISO-8859-1,utf-8;q=0.7,*;q=0.3", "Accept-Language" => "es-ES,es;q=0.8", "Accept-Encoding" => "gzip,deflate,sdch", "Origin" => "http://www.quora.com", "Host" => "www.quora.com", "Referer" => "http://www.quora.com/login/" } resp = http.post("/webnode2/server_call_POST", body, headers) if resp.code == "200" cookie else "" end end
[ "def", "login", "(", "user", ",", "password", ")", "endpoint", "=", "URI", ".", "parse", "(", "QUORA_URI", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "endpoint", ".", "host", ",", "endpoint", ".", "port", ")", "resp", "=", "http", ".", "get", "(", "'/login/'", ")", "cookie", "=", "resp", "[", "\"set-cookie\"", "]", "# TODO: improve this rubbish", "# get formkey value", "start", "=", "resp", ".", "body", ".", "index", "(", "\"Q.formkey\"", ")", "formkey", "=", "resp", ".", "body", "[", "start", "..", "start", "+", "200", "]", ".", "split", "(", "\"\\\"\"", ")", "[", "1", "]", "# get window value", "start", "=", "resp", ".", "body", ".", "index", "(", "\"webnode2.windowId\"", ")", "window", "=", "resp", ".", "body", "[", "start", "..", "start", "+", "200", "]", ".", "split", "(", "\"\\\"\"", ")", "[", "1", "]", "# get __vcon_json value", "start", "=", "resp", ".", "body", ".", "index", "(", "\"InlineLogin\"", ")", "vcon_json", "=", "resp", ".", "body", "[", "start", "..", "start", "+", "200", "]", "start", "=", "vcon_json", ".", "index", "(", "\"live\"", ")", "vcon_json", "=", "vcon_json", "[", "start", "..", "-", "1", "]", "vcon_json", "=", "vcon_json", ".", "split", "(", "\"\\\"\"", ")", "[", "0", "]", "vcon_json", "=", "vcon_json", ".", "split", "(", "\":\"", ")", "vcon_json", ".", "map!", "{", "|", "value", "|", "\"\\\"#{value}\\\"\"", "}", "vcon_json", "=", "\"[#{vcon_json.join(\",\")}]\"", "vcon_json", "=", "CGI", "::", "escape", "(", "vcon_json", ")", "user", "=", "CGI", "::", "escape", "(", "user", ")", "password", "=", "CGI", "::", "escape", "(", "password", ")", "body", "=", "\"json=%7B%22args%22%3A%5B%22#{user}%22%2C%22#{password}%22%2Ctrue%5D%2C%22kwargs%22%3A%7B%7D%7D&formkey=#{formkey}&window_id=#{window}&__vcon_json=#{vcon_json}&__vcon_method=do_login\"", "headers", "=", "{", "\"Content-Type\"", "=>", "\"application/x-www-form-urlencoded\"", ",", "\"X-Requested-With\"", "=>", "\"XMLHttpRequest\"", ",", "\"Accept\"", "=>", "\"application/json, text/javascript, */*\"", ",", "\"Cookie\"", "=>", "cookie", ",", "\"User-Agent\"", "=>", "\"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.237 Safari/534.10\"", ",", "\"Content-Length\"", "=>", "body", ".", "length", ".", "to_s", ",", "\"Accept-Charset\"", "=>", "\"ISO-8859-1,utf-8;q=0.7,*;q=0.3\"", ",", "\"Accept-Language\"", "=>", "\"es-ES,es;q=0.8\"", ",", "\"Accept-Encoding\"", "=>", "\"gzip,deflate,sdch\"", ",", "\"Origin\"", "=>", "\"http://www.quora.com\"", ",", "\"Host\"", "=>", "\"www.quora.com\"", ",", "\"Referer\"", "=>", "\"http://www.quora.com/login/\"", "}", "resp", "=", "http", ".", "post", "(", "\"/webnode2/server_call_POST\"", ",", "body", ",", "headers", ")", "if", "resp", ".", "code", "==", "\"200\"", "cookie", "else", "\"\"", "end", "end" ]
login with Quora user and password
[ "login", "with", "Quora", "user", "and", "password" ]
eb09bbb70aef5c5c77887dc0b689ccb422fba49f
https://github.com/juandebravo/quora-client/blob/eb09bbb70aef5c5c77887dc0b689ccb422fba49f/lib/quora/auth.rb#L24-L79
272
justintanner/column_pack
lib/column_pack/bin_packer.rb
ColumnPack.BinPacker.empty_space
def empty_space pack_all if @needs_packing max = @sizes.each.max space = 0 @sizes.each { |size| space += max - size } space end
ruby
def empty_space pack_all if @needs_packing max = @sizes.each.max space = 0 @sizes.each { |size| space += max - size } space end
[ "def", "empty_space", "pack_all", "if", "@needs_packing", "max", "=", "@sizes", ".", "each", ".", "max", "space", "=", "0", "@sizes", ".", "each", "{", "|", "size", "|", "space", "+=", "max", "-", "size", "}", "space", "end" ]
Total empty space left over by uneven packing.
[ "Total", "empty", "space", "left", "over", "by", "uneven", "packing", "." ]
bffe22f74063718fdcf7b9c5dce1001ceabe8046
https://github.com/justintanner/column_pack/blob/bffe22f74063718fdcf7b9c5dce1001ceabe8046/lib/column_pack/bin_packer.rb#L45-L53
273
justintanner/column_pack
lib/column_pack/bin_packer.rb
ColumnPack.BinPacker.tall_to_middle
def tall_to_middle if (@total_bins > 1) && ((@total_bins % 2) != 0) _, max_col = @sizes.each_with_index.max mid_col = @total_bins / 2 temp = @bins[mid_col].clone @bins[mid_col] = @bins[max_col] @bins[max_col] = temp end end
ruby
def tall_to_middle if (@total_bins > 1) && ((@total_bins % 2) != 0) _, max_col = @sizes.each_with_index.max mid_col = @total_bins / 2 temp = @bins[mid_col].clone @bins[mid_col] = @bins[max_col] @bins[max_col] = temp end end
[ "def", "tall_to_middle", "if", "(", "@total_bins", ">", "1", ")", "&&", "(", "(", "@total_bins", "%", "2", ")", "!=", "0", ")", "_", ",", "max_col", "=", "@sizes", ".", "each_with_index", ".", "max", "mid_col", "=", "@total_bins", "/", "2", "temp", "=", "@bins", "[", "mid_col", "]", ".", "clone", "@bins", "[", "mid_col", "]", "=", "@bins", "[", "max_col", "]", "@bins", "[", "max_col", "]", "=", "temp", "end", "end" ]
moves the tallest bin to the middle
[ "moves", "the", "tallest", "bin", "to", "the", "middle" ]
bffe22f74063718fdcf7b9c5dce1001ceabe8046
https://github.com/justintanner/column_pack/blob/bffe22f74063718fdcf7b9c5dce1001ceabe8046/lib/column_pack/bin_packer.rb#L90-L99
274
LAS-IT/ps_utilities
lib/ps_utilities/connection.rb
PsUtilities.Connection.api
def api(verb, api_path, options={}) count = 0 retries = 3 ps_url = base_uri + api_path options = options.merge(headers) begin HTTParty.send(verb, ps_url, options) rescue Net::ReadTimeout, Net::OpenTimeout if count < retries count += 1 retry else { error: "no response (timeout) from URL: #{url}" } end end end
ruby
def api(verb, api_path, options={}) count = 0 retries = 3 ps_url = base_uri + api_path options = options.merge(headers) begin HTTParty.send(verb, ps_url, options) rescue Net::ReadTimeout, Net::OpenTimeout if count < retries count += 1 retry else { error: "no response (timeout) from URL: #{url}" } end end end
[ "def", "api", "(", "verb", ",", "api_path", ",", "options", "=", "{", "}", ")", "count", "=", "0", "retries", "=", "3", "ps_url", "=", "base_uri", "+", "api_path", "options", "=", "options", ".", "merge", "(", "headers", ")", "begin", "HTTParty", ".", "send", "(", "verb", ",", "ps_url", ",", "options", ")", "rescue", "Net", "::", "ReadTimeout", ",", "Net", "::", "OpenTimeout", "if", "count", "<", "retries", "count", "+=", "1", "retry", "else", "{", "error", ":", "\"no response (timeout) from URL: #{url}\"", "}", "end", "end", "end" ]
Direct API access @param verb [Symbol] hmtl verbs (:delete, :get, :patch, :post, :put) @param options [Hash] allowed keys are {query: {}, body: {}} - uses :query for gets, and use :body for put and post @return [HTTParty] - useful things to access include: obj.parsed_response (to access returned data) & obj.code to be sure the response was successful "200"
[ "Direct", "API", "access" ]
85fbb528d982b66ca706de5fdb70b4410f21e637
https://github.com/LAS-IT/ps_utilities/blob/85fbb528d982b66ca706de5fdb70b4410f21e637/lib/ps_utilities/connection.rb#L89-L104
275
LAS-IT/ps_utilities
lib/ps_utilities/connection.rb
PsUtilities.Connection.authenticate
def authenticate ps_url = base_uri + auth_path response = HTTParty.post( ps_url, { headers: auth_headers, body: 'grant_type=client_credentials'} ) if response.code.to_s.eql? "200" @auth_info = response.parsed_response @auth_info['token_expires'] = Time.now + response.parsed_response['expires_in'].to_i @headers[:headers].merge!('Authorization' => 'Bearer ' + auth_info['access_token']) return auth_info else # throw error if - error returned -- nothing else will work raise AuthError.new("No Auth Token Returned", ps_url, client ) end end
ruby
def authenticate ps_url = base_uri + auth_path response = HTTParty.post( ps_url, { headers: auth_headers, body: 'grant_type=client_credentials'} ) if response.code.to_s.eql? "200" @auth_info = response.parsed_response @auth_info['token_expires'] = Time.now + response.parsed_response['expires_in'].to_i @headers[:headers].merge!('Authorization' => 'Bearer ' + auth_info['access_token']) return auth_info else # throw error if - error returned -- nothing else will work raise AuthError.new("No Auth Token Returned", ps_url, client ) end end
[ "def", "authenticate", "ps_url", "=", "base_uri", "+", "auth_path", "response", "=", "HTTParty", ".", "post", "(", "ps_url", ",", "{", "headers", ":", "auth_headers", ",", "body", ":", "'grant_type=client_credentials'", "}", ")", "if", "response", ".", "code", ".", "to_s", ".", "eql?", "\"200\"", "@auth_info", "=", "response", ".", "parsed_response", "@auth_info", "[", "'token_expires'", "]", "=", "Time", ".", "now", "+", "response", ".", "parsed_response", "[", "'expires_in'", "]", ".", "to_i", "@headers", "[", ":headers", "]", ".", "merge!", "(", "'Authorization'", "=>", "'Bearer '", "+", "auth_info", "[", "'access_token'", "]", ")", "return", "auth_info", "else", "# throw error if - error returned -- nothing else will work", "raise", "AuthError", ".", "new", "(", "\"No Auth Token Returned\"", ",", "ps_url", ",", "client", ")", "end", "end" ]
gets API auth token and puts in header HASH for future requests with PS server @return [Hash] - of auth token and time to live from powerschol server {'access_token' => "addsfabe-aads-4444-bbbb-444411ffffbb", 'token_type' => "Bearer", 'expires_in' => "2504956" 'token_expires' => (Time.now + 3600)} @note - to enable PS API - In PowerSchool go to System>System Settings>Plugin Management Configuration>your plugin>Data Provider Configuration to manually check plugin expiration date
[ "gets", "API", "auth", "token", "and", "puts", "in", "header", "HASH", "for", "future", "requests", "with", "PS", "server" ]
85fbb528d982b66ca706de5fdb70b4410f21e637
https://github.com/LAS-IT/ps_utilities/blob/85fbb528d982b66ca706de5fdb70b4410f21e637/lib/ps_utilities/connection.rb#L124-L138
276
TheLevelUp/levelup-sdk-ruby
lib/levelup/api.rb
Levelup.Api.apps
def apps(app_id = nil) if app_id Endpoints::SpecificApp.new(app_id) else Endpoints::Apps.new(app_access_token) end end
ruby
def apps(app_id = nil) if app_id Endpoints::SpecificApp.new(app_id) else Endpoints::Apps.new(app_access_token) end end
[ "def", "apps", "(", "app_id", "=", "nil", ")", "if", "app_id", "Endpoints", "::", "SpecificApp", ".", "new", "(", "app_id", ")", "else", "Endpoints", "::", "Apps", ".", "new", "(", "app_access_token", ")", "end", "end" ]
Generates an interface for the +apps+ endpoint.
[ "Generates", "an", "interface", "for", "the", "+", "apps", "+", "endpoint", "." ]
efe23ddeeec363354c868d0c22d9cfad7a4190af
https://github.com/TheLevelUp/levelup-sdk-ruby/blob/efe23ddeeec363354c868d0c22d9cfad7a4190af/lib/levelup/api.rb#L32-L38
277
TheLevelUp/levelup-sdk-ruby
lib/levelup/api.rb
Levelup.Api.orders
def orders(order_uuid = nil) if order_uuid Endpoints::SpecificOrder.new(order_uuid) else Endpoints::Orders.new end end
ruby
def orders(order_uuid = nil) if order_uuid Endpoints::SpecificOrder.new(order_uuid) else Endpoints::Orders.new end end
[ "def", "orders", "(", "order_uuid", "=", "nil", ")", "if", "order_uuid", "Endpoints", "::", "SpecificOrder", ".", "new", "(", "order_uuid", ")", "else", "Endpoints", "::", "Orders", ".", "new", "end", "end" ]
Generates the interface for the +orders+ endpoint. Supply an order UUID if you would like to access endpoints for a specific order, otherwise, supply no parameters.
[ "Generates", "the", "interface", "for", "the", "+", "orders", "+", "endpoint", ".", "Supply", "an", "order", "UUID", "if", "you", "would", "like", "to", "access", "endpoints", "for", "a", "specific", "order", "otherwise", "supply", "no", "parameters", "." ]
efe23ddeeec363354c868d0c22d9cfad7a4190af
https://github.com/TheLevelUp/levelup-sdk-ruby/blob/efe23ddeeec363354c868d0c22d9cfad7a4190af/lib/levelup/api.rb#L68-L74
278
ChadBowman/kril
lib/kril/consumer.rb
Kril.Consumer.consume_all
def consume_all(topic) config = @config.clone config[:group_id] = SecureRandom.uuid consumer = build_consumer(topic, true, config) consumer.each_message do |message| yield decode(message), consumer end ensure consumer.stop end
ruby
def consume_all(topic) config = @config.clone config[:group_id] = SecureRandom.uuid consumer = build_consumer(topic, true, config) consumer.each_message do |message| yield decode(message), consumer end ensure consumer.stop end
[ "def", "consume_all", "(", "topic", ")", "config", "=", "@config", ".", "clone", "config", "[", ":group_id", "]", "=", "SecureRandom", ".", "uuid", "consumer", "=", "build_consumer", "(", "topic", ",", "true", ",", "config", ")", "consumer", ".", "each_message", "do", "|", "message", "|", "yield", "decode", "(", "message", ")", ",", "consumer", "end", "ensure", "consumer", ".", "stop", "end" ]
Consume all records from a topic. Each record will be yielded to block along with consumer instance. Will listen to topic after all records have been consumed. topic - topic to consume from [String] yields - record, consumer [String, Kafka::Consumer] return - [nil]
[ "Consume", "all", "records", "from", "a", "topic", ".", "Each", "record", "will", "be", "yielded", "to", "block", "along", "with", "consumer", "instance", ".", "Will", "listen", "to", "topic", "after", "all", "records", "have", "been", "consumed", "." ]
3581b77387b0f6d0c0c3a45248ad7d027cd89816
https://github.com/ChadBowman/kril/blob/3581b77387b0f6d0c0c3a45248ad7d027cd89816/lib/kril/consumer.rb#L42-L51
279
beerlington/sudo_attributes
lib/sudo_attributes.rb
SudoAttributes.ClassMethods.sudo_create!
def sudo_create!(attributes = nil, &block) if attributes.is_a?(Array) attributes.collect { |attr| sudo_create!(attr, &block) } else object = sudo_new(attributes) yield(object) if block_given? object.save! object end end
ruby
def sudo_create!(attributes = nil, &block) if attributes.is_a?(Array) attributes.collect { |attr| sudo_create!(attr, &block) } else object = sudo_new(attributes) yield(object) if block_given? object.save! object end end
[ "def", "sudo_create!", "(", "attributes", "=", "nil", ",", "&", "block", ")", "if", "attributes", ".", "is_a?", "(", "Array", ")", "attributes", ".", "collect", "{", "|", "attr", "|", "sudo_create!", "(", "attr", ",", "block", ")", "}", "else", "object", "=", "sudo_new", "(", "attributes", ")", "yield", "(", "object", ")", "if", "block_given?", "object", ".", "save!", "object", "end", "end" ]
Creates an object just like sudo_create but calls save! instead of save so an exception is raised if the record is invalid ==== Example # Create a single new object where admin is a protected attribute User.sudo_create!(:first_name => 'Pete', :admin => true)
[ "Creates", "an", "object", "just", "like", "sudo_create", "but", "calls", "save!", "instead", "of", "save", "so", "an", "exception", "is", "raised", "if", "the", "record", "is", "invalid" ]
3bf0814153c9e8faa9b57c2e6c69fac4ca39e3c8
https://github.com/beerlington/sudo_attributes/blob/3bf0814153c9e8faa9b57c2e6c69fac4ca39e3c8/lib/sudo_attributes.rb#L41-L50
280
coupler/linkage
lib/linkage/field.rb
Linkage.Field.ruby_type
def ruby_type unless @ruby_type hsh = case @schema[:db_type].downcase when /\A(medium|small)?int(?:eger)?(?:\((\d+)\))?( unsigned)?\z/o if !$1 && $2 && $2.to_i >= 10 && $3 # Unsigned integer type with 10 digits can potentially contain values which # don't fit signed integer type, so use bigint type in target database. {:type=>Bignum} else {:type=>Integer} end when /\Atinyint(?:\((\d+)\))?(?: unsigned)?\z/o {:type =>schema[:type] == :boolean ? TrueClass : Integer} when /\Abigint(?:\((?:\d+)\))?(?: unsigned)?\z/o {:type=>Bignum} when /\A(?:real|float|double(?: precision)?|double\(\d+,\d+\)(?: unsigned)?)\z/o {:type=>Float} when 'boolean' {:type=>TrueClass} when /\A(?:(?:tiny|medium|long|n)?text|clob)\z/o {:type=>String, :text=>true} when 'date' {:type=>Date} when /\A(?:small)?datetime\z/o {:type=>DateTime} when /\Atimestamp(?:\((\d+)\))?(?: with(?:out)? time zone)?\z/o {:type=>DateTime, :size=>($1.to_i if $1)} when /\Atime(?: with(?:out)? time zone)?\z/o {:type=>Time, :only_time=>true} when /\An?char(?:acter)?(?:\((\d+)\))?\z/o {:type=>String, :size=>($1.to_i if $1), :fixed=>true} when /\A(?:n?varchar|character varying|bpchar|string)(?:\((\d+)\))?\z/o {:type=>String, :size=>($1.to_i if $1)} when /\A(?:small)?money\z/o {:type=>BigDecimal, :size=>[19,2]} when /\A(?:decimal|numeric|number)(?:\((\d+)(?:,\s*(\d+))?\))?\z/o s = [($1.to_i if $1), ($2.to_i if $2)].compact {:type=>BigDecimal, :size=>(s.empty? ? nil : s)} when /\A(?:bytea|(?:tiny|medium|long)?blob|(?:var)?binary)(?:\((\d+)\))?\z/o {:type=>File, :size=>($1.to_i if $1)} when /\A(?:year|(?:int )?identity)\z/o {:type=>Integer} else {:type=>String} end hsh.delete_if { |k, v| v.nil? } @ruby_type = {:type => hsh.delete(:type)} @ruby_type[:opts] = hsh if !hsh.empty? end @ruby_type end
ruby
def ruby_type unless @ruby_type hsh = case @schema[:db_type].downcase when /\A(medium|small)?int(?:eger)?(?:\((\d+)\))?( unsigned)?\z/o if !$1 && $2 && $2.to_i >= 10 && $3 # Unsigned integer type with 10 digits can potentially contain values which # don't fit signed integer type, so use bigint type in target database. {:type=>Bignum} else {:type=>Integer} end when /\Atinyint(?:\((\d+)\))?(?: unsigned)?\z/o {:type =>schema[:type] == :boolean ? TrueClass : Integer} when /\Abigint(?:\((?:\d+)\))?(?: unsigned)?\z/o {:type=>Bignum} when /\A(?:real|float|double(?: precision)?|double\(\d+,\d+\)(?: unsigned)?)\z/o {:type=>Float} when 'boolean' {:type=>TrueClass} when /\A(?:(?:tiny|medium|long|n)?text|clob)\z/o {:type=>String, :text=>true} when 'date' {:type=>Date} when /\A(?:small)?datetime\z/o {:type=>DateTime} when /\Atimestamp(?:\((\d+)\))?(?: with(?:out)? time zone)?\z/o {:type=>DateTime, :size=>($1.to_i if $1)} when /\Atime(?: with(?:out)? time zone)?\z/o {:type=>Time, :only_time=>true} when /\An?char(?:acter)?(?:\((\d+)\))?\z/o {:type=>String, :size=>($1.to_i if $1), :fixed=>true} when /\A(?:n?varchar|character varying|bpchar|string)(?:\((\d+)\))?\z/o {:type=>String, :size=>($1.to_i if $1)} when /\A(?:small)?money\z/o {:type=>BigDecimal, :size=>[19,2]} when /\A(?:decimal|numeric|number)(?:\((\d+)(?:,\s*(\d+))?\))?\z/o s = [($1.to_i if $1), ($2.to_i if $2)].compact {:type=>BigDecimal, :size=>(s.empty? ? nil : s)} when /\A(?:bytea|(?:tiny|medium|long)?blob|(?:var)?binary)(?:\((\d+)\))?\z/o {:type=>File, :size=>($1.to_i if $1)} when /\A(?:year|(?:int )?identity)\z/o {:type=>Integer} else {:type=>String} end hsh.delete_if { |k, v| v.nil? } @ruby_type = {:type => hsh.delete(:type)} @ruby_type[:opts] = hsh if !hsh.empty? end @ruby_type end
[ "def", "ruby_type", "unless", "@ruby_type", "hsh", "=", "case", "@schema", "[", ":db_type", "]", ".", "downcase", "when", "/", "\\A", "\\(", "\\d", "\\)", "\\z", "/o", "if", "!", "$1", "&&", "$2", "&&", "$2", ".", "to_i", ">=", "10", "&&", "$3", "# Unsigned integer type with 10 digits can potentially contain values which", "# don't fit signed integer type, so use bigint type in target database.", "{", ":type", "=>", "Bignum", "}", "else", "{", ":type", "=>", "Integer", "}", "end", "when", "/", "\\A", "\\(", "\\d", "\\)", "\\z", "/o", "{", ":type", "=>", "schema", "[", ":type", "]", "==", ":boolean", "?", "TrueClass", ":", "Integer", "}", "when", "/", "\\A", "\\(", "\\d", "\\)", "\\z", "/o", "{", ":type", "=>", "Bignum", "}", "when", "/", "\\A", "\\(", "\\d", "\\d", "\\)", "\\z", "/o", "{", ":type", "=>", "Float", "}", "when", "'boolean'", "{", ":type", "=>", "TrueClass", "}", "when", "/", "\\A", "\\z", "/o", "{", ":type", "=>", "String", ",", ":text", "=>", "true", "}", "when", "'date'", "{", ":type", "=>", "Date", "}", "when", "/", "\\A", "\\z", "/o", "{", ":type", "=>", "DateTime", "}", "when", "/", "\\A", "\\(", "\\d", "\\)", "\\z", "/o", "{", ":type", "=>", "DateTime", ",", ":size", "=>", "(", "$1", ".", "to_i", "if", "$1", ")", "}", "when", "/", "\\A", "\\z", "/o", "{", ":type", "=>", "Time", ",", ":only_time", "=>", "true", "}", "when", "/", "\\A", "\\(", "\\d", "\\)", "\\z", "/o", "{", ":type", "=>", "String", ",", ":size", "=>", "(", "$1", ".", "to_i", "if", "$1", ")", ",", ":fixed", "=>", "true", "}", "when", "/", "\\A", "\\(", "\\d", "\\)", "\\z", "/o", "{", ":type", "=>", "String", ",", ":size", "=>", "(", "$1", ".", "to_i", "if", "$1", ")", "}", "when", "/", "\\A", "\\z", "/o", "{", ":type", "=>", "BigDecimal", ",", ":size", "=>", "[", "19", ",", "2", "]", "}", "when", "/", "\\A", "\\(", "\\d", "\\s", "\\d", "\\)", "\\z", "/o", "s", "=", "[", "(", "$1", ".", "to_i", "if", "$1", ")", ",", "(", "$2", ".", "to_i", "if", "$2", ")", "]", ".", "compact", "{", ":type", "=>", "BigDecimal", ",", ":size", "=>", "(", "s", ".", "empty?", "?", "nil", ":", "s", ")", "}", "when", "/", "\\A", "\\(", "\\d", "\\)", "\\z", "/o", "{", ":type", "=>", "File", ",", ":size", "=>", "(", "$1", ".", "to_i", "if", "$1", ")", "}", "when", "/", "\\A", "\\z", "/o", "{", ":type", "=>", "Integer", "}", "else", "{", ":type", "=>", "String", "}", "end", "hsh", ".", "delete_if", "{", "|", "k", ",", "v", "|", "v", ".", "nil?", "}", "@ruby_type", "=", "{", ":type", "=>", "hsh", ".", "delete", "(", ":type", ")", "}", "@ruby_type", "[", ":opts", "]", "=", "hsh", "if", "!", "hsh", ".", "empty?", "end", "@ruby_type", "end" ]
Returns a new instance of Field. @param [Symbol] name The field's name @param [Hash] schema The field's schema information Convert the column schema information to a hash of column options, one of which is `:type`. The other options modify that type (e.g. `:size`). Here are some examples: | Database type | Ruby type | Other modifiers | |------------------|--------------------|-----------------------| | mediumint | Fixnum | | | smallint | Fixnum | | | int | Fixnum | | | int(10) unsigned | Bignum | | | tinyint | TrueClass, Integer | | | bigint | Bignum | | | real | Float | | | float | Float | | | double | Float | | | boolean | TrueClass | | | text | String | text: true | | date | Date | | | datetime | DateTime | | | timestamp | DateTime | | | time | Time | only_time: true | | varchar(255) | String | size: 255 | | char(10) | String | size: 10, fixed: true | | money | BigDecimal | size: [19, 2] | | decimal | BigDecimal | | | numeric | BigDecimal | | | number | BigDecimal | | | blob | File | | | year | Integer | | | identity | Integer | | | **other types** | String | | @note This method is copied from {http://sequel.jeremyevans.net/rdoc-plugins/classes/Sequel/SchemaDumper.html `Sequel::SchemaDumper`}. @return [Hash]
[ "Returns", "a", "new", "instance", "of", "Field", "." ]
2f208ae0709a141a6a8e5ba3bc6914677e986cb0
https://github.com/coupler/linkage/blob/2f208ae0709a141a6a8e5ba3bc6914677e986cb0/lib/linkage/field.rb#L56-L108
281
tylercunnion/crawler
lib/crawler/observer.rb
Crawler.Observer.update
def update(response, url) @log.puts "Scanning: #{url}" if response.kind_of?(Net::HTTPClientError) or response.kind_of?(Net::HTTPServerError) @log.puts "#{response.code} encountered for #{url}" end end
ruby
def update(response, url) @log.puts "Scanning: #{url}" if response.kind_of?(Net::HTTPClientError) or response.kind_of?(Net::HTTPServerError) @log.puts "#{response.code} encountered for #{url}" end end
[ "def", "update", "(", "response", ",", "url", ")", "@log", ".", "puts", "\"Scanning: #{url}\"", "if", "response", ".", "kind_of?", "(", "Net", "::", "HTTPClientError", ")", "or", "response", ".", "kind_of?", "(", "Net", "::", "HTTPServerError", ")", "@log", ".", "puts", "\"#{response.code} encountered for #{url}\"", "end", "end" ]
Creates a new Observer object Called by the Observable module through Webcrawler.
[ "Creates", "a", "new", "Observer", "object", "Called", "by", "the", "Observable", "module", "through", "Webcrawler", "." ]
5ee0358a6c9c6961b88b0366d6f0442c48f5e3c2
https://github.com/tylercunnion/crawler/blob/5ee0358a6c9c6961b88b0366d6f0442c48f5e3c2/lib/crawler/observer.rb#L15-L20
282
Antti/skyper
lib/skyper/skype.rb
Skyper.Skype.answer
def answer(call) cmd = "ALTER CALL #{call.call_id} ANSWER" r = Skype.send_command cmd raise RuntimeError("Failed to answer call. Skype returned '#{r}'") unless r == cmd end
ruby
def answer(call) cmd = "ALTER CALL #{call.call_id} ANSWER" r = Skype.send_command cmd raise RuntimeError("Failed to answer call. Skype returned '#{r}'") unless r == cmd end
[ "def", "answer", "(", "call", ")", "cmd", "=", "\"ALTER CALL #{call.call_id} ANSWER\"", "r", "=", "Skype", ".", "send_command", "cmd", "raise", "RuntimeError", "(", "\"Failed to answer call. Skype returned '#{r}'\"", ")", "unless", "r", "==", "cmd", "end" ]
Answers a call given a skype Call ID. Returns an Array of Call objects.
[ "Answers", "a", "call", "given", "a", "skype", "Call", "ID", ".", "Returns", "an", "Array", "of", "Call", "objects", "." ]
16c1c19a485be24376acfa0b7e0a7775ec16b30c
https://github.com/Antti/skyper/blob/16c1c19a485be24376acfa0b7e0a7775ec16b30c/lib/skyper/skype.rb#L41-L45
283
appoxy/simple_record
lib/simple_record/attributes.rb
SimpleRecord.Attributes.get_attribute
def get_attribute(name) # puts "get_attribute #{name}" # Check if this arg is already converted name_s = name.to_s name = name.to_sym att_meta = get_att_meta(name) # puts "att_meta for #{name}: " + att_meta.inspect if att_meta && att_meta.type == :clob ret = @lobs[name] # puts 'get_attribute clob ' + ret.inspect if ret if ret.is_a? RemoteNil return nil else return ret end end # get it from s3 unless new_record? if self.class.get_sr_config[:single_clob] begin single_clob = s3_bucket(false, :s3_bucket=>:new).get(single_clob_id) single_clob = JSON.parse(single_clob) # puts "single_clob=" + single_clob.inspect single_clob.each_pair do |name2, val| @lobs[name2.to_sym] = val end ret = @lobs[name] SimpleRecord.stats.s3_gets += 1 rescue Aws::AwsError => ex if ex.include?(/NoSuchKey/) || ex.include?(/NoSuchBucket/) ret = nil else raise ex end end else begin ret = s3_bucket.get(s3_lob_id(name)) # puts 'got from s3 ' + ret.inspect SimpleRecord.stats.s3_gets += 1 rescue Aws::AwsError => ex if ex.include?(/NoSuchKey/) || ex.include?(/NoSuchBucket/) ret = nil else raise ex end end end if ret.nil? ret = RemoteNil.new end end @lobs[name] = ret return nil if ret.is_a? RemoteNil return ret else @attributes_rb = {} unless @attributes_rb # was getting errors after upgrade. ret = @attributes_rb[name_s] # instance_variable_get(instance_var) return ret unless ret.nil? return nil if ret.is_a? RemoteNil ret = get_attribute_sdb(name) # p ret ret = sdb_to_ruby(name, ret) # p ret @attributes_rb[name_s] = ret return ret end end
ruby
def get_attribute(name) # puts "get_attribute #{name}" # Check if this arg is already converted name_s = name.to_s name = name.to_sym att_meta = get_att_meta(name) # puts "att_meta for #{name}: " + att_meta.inspect if att_meta && att_meta.type == :clob ret = @lobs[name] # puts 'get_attribute clob ' + ret.inspect if ret if ret.is_a? RemoteNil return nil else return ret end end # get it from s3 unless new_record? if self.class.get_sr_config[:single_clob] begin single_clob = s3_bucket(false, :s3_bucket=>:new).get(single_clob_id) single_clob = JSON.parse(single_clob) # puts "single_clob=" + single_clob.inspect single_clob.each_pair do |name2, val| @lobs[name2.to_sym] = val end ret = @lobs[name] SimpleRecord.stats.s3_gets += 1 rescue Aws::AwsError => ex if ex.include?(/NoSuchKey/) || ex.include?(/NoSuchBucket/) ret = nil else raise ex end end else begin ret = s3_bucket.get(s3_lob_id(name)) # puts 'got from s3 ' + ret.inspect SimpleRecord.stats.s3_gets += 1 rescue Aws::AwsError => ex if ex.include?(/NoSuchKey/) || ex.include?(/NoSuchBucket/) ret = nil else raise ex end end end if ret.nil? ret = RemoteNil.new end end @lobs[name] = ret return nil if ret.is_a? RemoteNil return ret else @attributes_rb = {} unless @attributes_rb # was getting errors after upgrade. ret = @attributes_rb[name_s] # instance_variable_get(instance_var) return ret unless ret.nil? return nil if ret.is_a? RemoteNil ret = get_attribute_sdb(name) # p ret ret = sdb_to_ruby(name, ret) # p ret @attributes_rb[name_s] = ret return ret end end
[ "def", "get_attribute", "(", "name", ")", "# puts \"get_attribute #{name}\"", "# Check if this arg is already converted", "name_s", "=", "name", ".", "to_s", "name", "=", "name", ".", "to_sym", "att_meta", "=", "get_att_meta", "(", "name", ")", "# puts \"att_meta for #{name}: \" + att_meta.inspect", "if", "att_meta", "&&", "att_meta", ".", "type", "==", ":clob", "ret", "=", "@lobs", "[", "name", "]", "# puts 'get_attribute clob ' + ret.inspect", "if", "ret", "if", "ret", ".", "is_a?", "RemoteNil", "return", "nil", "else", "return", "ret", "end", "end", "# get it from s3", "unless", "new_record?", "if", "self", ".", "class", ".", "get_sr_config", "[", ":single_clob", "]", "begin", "single_clob", "=", "s3_bucket", "(", "false", ",", ":s3_bucket", "=>", ":new", ")", ".", "get", "(", "single_clob_id", ")", "single_clob", "=", "JSON", ".", "parse", "(", "single_clob", ")", "# puts \"single_clob=\" + single_clob.inspect", "single_clob", ".", "each_pair", "do", "|", "name2", ",", "val", "|", "@lobs", "[", "name2", ".", "to_sym", "]", "=", "val", "end", "ret", "=", "@lobs", "[", "name", "]", "SimpleRecord", ".", "stats", ".", "s3_gets", "+=", "1", "rescue", "Aws", "::", "AwsError", "=>", "ex", "if", "ex", ".", "include?", "(", "/", "/", ")", "||", "ex", ".", "include?", "(", "/", "/", ")", "ret", "=", "nil", "else", "raise", "ex", "end", "end", "else", "begin", "ret", "=", "s3_bucket", ".", "get", "(", "s3_lob_id", "(", "name", ")", ")", "# puts 'got from s3 ' + ret.inspect", "SimpleRecord", ".", "stats", ".", "s3_gets", "+=", "1", "rescue", "Aws", "::", "AwsError", "=>", "ex", "if", "ex", ".", "include?", "(", "/", "/", ")", "||", "ex", ".", "include?", "(", "/", "/", ")", "ret", "=", "nil", "else", "raise", "ex", "end", "end", "end", "if", "ret", ".", "nil?", "ret", "=", "RemoteNil", ".", "new", "end", "end", "@lobs", "[", "name", "]", "=", "ret", "return", "nil", "if", "ret", ".", "is_a?", "RemoteNil", "return", "ret", "else", "@attributes_rb", "=", "{", "}", "unless", "@attributes_rb", "# was getting errors after upgrade.", "ret", "=", "@attributes_rb", "[", "name_s", "]", "# instance_variable_get(instance_var)", "return", "ret", "unless", "ret", ".", "nil?", "return", "nil", "if", "ret", ".", "is_a?", "RemoteNil", "ret", "=", "get_attribute_sdb", "(", "name", ")", "# p ret", "ret", "=", "sdb_to_ruby", "(", "name", ",", "ret", ")", "# p ret", "@attributes_rb", "[", "name_s", "]", "=", "ret", "return", "ret", "end", "end" ]
Since SimpleDB supports multiple attributes per value, the values are an array. This method will return the value unwrapped if it's the only, otherwise it will return the array.
[ "Since", "SimpleDB", "supports", "multiple", "attributes", "per", "value", "the", "values", "are", "an", "array", ".", "This", "method", "will", "return", "the", "value", "unwrapped", "if", "it", "s", "the", "only", "otherwise", "it", "will", "return", "the", "array", "." ]
0252a022a938f368d6853ab1ae31f77f80b9f044
https://github.com/appoxy/simple_record/blob/0252a022a938f368d6853ab1ae31f77f80b9f044/lib/simple_record/attributes.rb#L328-L398
284
OSC/ood_support
lib/ood_support/acl.rb
OodSupport.ACL.ordered_check
def ordered_check(**kwargs) entries.each do |entry| if entry.match(**kwargs) # Check if its an allow or deny acl entry (may not be both) return true if entry.is_allow? return false if entry.is_deny? end end return default # default allow or default deny end
ruby
def ordered_check(**kwargs) entries.each do |entry| if entry.match(**kwargs) # Check if its an allow or deny acl entry (may not be both) return true if entry.is_allow? return false if entry.is_deny? end end return default # default allow or default deny end
[ "def", "ordered_check", "(", "**", "kwargs", ")", "entries", ".", "each", "do", "|", "entry", "|", "if", "entry", ".", "match", "(", "**", "kwargs", ")", "# Check if its an allow or deny acl entry (may not be both)", "return", "true", "if", "entry", ".", "is_allow?", "return", "false", "if", "entry", ".", "is_deny?", "end", "end", "return", "default", "# default allow or default deny", "end" ]
Check each entry in order from array
[ "Check", "each", "entry", "in", "order", "from", "array" ]
a5e42a1b31d90763964f39ebe241e69c15d0f404
https://github.com/OSC/ood_support/blob/a5e42a1b31d90763964f39ebe241e69c15d0f404/lib/ood_support/acl.rb#L78-L87
285
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.ScheduledEvent.inspect
def inspect insp = String.new("#<#{self.class}:#{"0x00%x" % (self.__id__ << 1)} ") insp << "trigger_count=#{@trigger_count} " insp << "config=#{info} " if self.respond_to?(:info, true) insp << "next_scheduled=#{to_time(@next_scheduled)} " insp << "last_scheduled=#{to_time(@last_scheduled)} created=#{to_time(@created)}>" insp end
ruby
def inspect insp = String.new("#<#{self.class}:#{"0x00%x" % (self.__id__ << 1)} ") insp << "trigger_count=#{@trigger_count} " insp << "config=#{info} " if self.respond_to?(:info, true) insp << "next_scheduled=#{to_time(@next_scheduled)} " insp << "last_scheduled=#{to_time(@last_scheduled)} created=#{to_time(@created)}>" insp end
[ "def", "inspect", "insp", "=", "String", ".", "new", "(", "\"#<#{self.class}:#{\"0x00%x\" % (self.__id__ << 1)} \"", ")", "insp", "<<", "\"trigger_count=#{@trigger_count} \"", "insp", "<<", "\"config=#{info} \"", "if", "self", ".", "respond_to?", "(", ":info", ",", "true", ")", "insp", "<<", "\"next_scheduled=#{to_time(@next_scheduled)} \"", "insp", "<<", "\"last_scheduled=#{to_time(@last_scheduled)} created=#{to_time(@created)}>\"", "insp", "end" ]
Provide relevant inspect information
[ "Provide", "relevant", "inspect", "information" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L39-L46
286
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.OneShot.update
def update(time) @last_scheduled = @reactor.now parsed_time = Scheduler.parse_in(time, :quiet) if parsed_time.nil? # Parse at will throw an error if time is invalid parsed_time = Scheduler.parse_at(time) - @scheduler.time_diff else parsed_time += @last_scheduled end @next_scheduled = parsed_time @scheduler.reschedule(self) end
ruby
def update(time) @last_scheduled = @reactor.now parsed_time = Scheduler.parse_in(time, :quiet) if parsed_time.nil? # Parse at will throw an error if time is invalid parsed_time = Scheduler.parse_at(time) - @scheduler.time_diff else parsed_time += @last_scheduled end @next_scheduled = parsed_time @scheduler.reschedule(self) end
[ "def", "update", "(", "time", ")", "@last_scheduled", "=", "@reactor", ".", "now", "parsed_time", "=", "Scheduler", ".", "parse_in", "(", "time", ",", ":quiet", ")", "if", "parsed_time", ".", "nil?", "# Parse at will throw an error if time is invalid", "parsed_time", "=", "Scheduler", ".", "parse_at", "(", "time", ")", "-", "@scheduler", ".", "time_diff", "else", "parsed_time", "+=", "@last_scheduled", "end", "@next_scheduled", "=", "parsed_time", "@scheduler", ".", "reschedule", "(", "self", ")", "end" ]
Updates the scheduled time
[ "Updates", "the", "scheduled", "time" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L81-L94
287
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Repeat.update
def update(every, timezone: nil) time = Scheduler.parse_in(every, :quiet) || Scheduler.parse_cron(every, :quiet, timezone: timezone) raise ArgumentError.new("couldn't parse \"#{o}\"") if time.nil? @every = time reschedule end
ruby
def update(every, timezone: nil) time = Scheduler.parse_in(every, :quiet) || Scheduler.parse_cron(every, :quiet, timezone: timezone) raise ArgumentError.new("couldn't parse \"#{o}\"") if time.nil? @every = time reschedule end
[ "def", "update", "(", "every", ",", "timezone", ":", "nil", ")", "time", "=", "Scheduler", ".", "parse_in", "(", "every", ",", ":quiet", ")", "||", "Scheduler", ".", "parse_cron", "(", "every", ",", ":quiet", ",", "timezone", ":", "timezone", ")", "raise", "ArgumentError", ".", "new", "(", "\"couldn't parse \\\"#{o}\\\"\"", ")", "if", "time", ".", "nil?", "@every", "=", "time", "reschedule", "end" ]
Update the time period of the repeating event @param schedule [String] a standard CRON job line or a human readable string representing a time period.
[ "Update", "the", "time", "period", "of", "the", "repeating", "event" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L114-L120
288
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.every
def every(time) ms = Scheduler.parse_in(time) event = Repeat.new(self, ms) event.progress &Proc.new if block_given? schedule(event) event end
ruby
def every(time) ms = Scheduler.parse_in(time) event = Repeat.new(self, ms) event.progress &Proc.new if block_given? schedule(event) event end
[ "def", "every", "(", "time", ")", "ms", "=", "Scheduler", ".", "parse_in", "(", "time", ")", "event", "=", "Repeat", ".", "new", "(", "self", ",", "ms", ")", "event", ".", "progress", "Proc", ".", "new", "if", "block_given?", "schedule", "(", "event", ")", "event", "end" ]
Create a repeating event that occurs each time period @param time [String] a human readable string representing the time period. 3w2d4h1m2s for example. @param callback [Proc] a block or method to execute when the event triggers @return [::UV::Repeat]
[ "Create", "a", "repeating", "event", "that", "occurs", "each", "time", "period" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L213-L219
289
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.in
def in(time) ms = @reactor.now + Scheduler.parse_in(time) event = OneShot.new(self, ms) event.progress &Proc.new if block_given? schedule(event) event end
ruby
def in(time) ms = @reactor.now + Scheduler.parse_in(time) event = OneShot.new(self, ms) event.progress &Proc.new if block_given? schedule(event) event end
[ "def", "in", "(", "time", ")", "ms", "=", "@reactor", ".", "now", "+", "Scheduler", ".", "parse_in", "(", "time", ")", "event", "=", "OneShot", ".", "new", "(", "self", ",", "ms", ")", "event", ".", "progress", "Proc", ".", "new", "if", "block_given?", "schedule", "(", "event", ")", "event", "end" ]
Create a one off event that occurs after the time period @param time [String] a human readable string representing the time period. 3w2d4h1m2s for example. @param callback [Proc] a block or method to execute when the event triggers @return [::UV::OneShot]
[ "Create", "a", "one", "off", "event", "that", "occurs", "after", "the", "time", "period" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L226-L232
290
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.at
def at(time) ms = Scheduler.parse_at(time) - @time_diff event = OneShot.new(self, ms) event.progress &Proc.new if block_given? schedule(event) event end
ruby
def at(time) ms = Scheduler.parse_at(time) - @time_diff event = OneShot.new(self, ms) event.progress &Proc.new if block_given? schedule(event) event end
[ "def", "at", "(", "time", ")", "ms", "=", "Scheduler", ".", "parse_at", "(", "time", ")", "-", "@time_diff", "event", "=", "OneShot", ".", "new", "(", "self", ",", "ms", ")", "event", ".", "progress", "Proc", ".", "new", "if", "block_given?", "schedule", "(", "event", ")", "event", "end" ]
Create a one off event that occurs at a particular date and time @param time [String, Time] a representation of a date and time that can be parsed @param callback [Proc] a block or method to execute when the event triggers @return [::UV::OneShot]
[ "Create", "a", "one", "off", "event", "that", "occurs", "at", "a", "particular", "date", "and", "time" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L239-L245
291
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.cron
def cron(schedule, timezone: nil) ms = Scheduler.parse_cron(schedule, timezone: timezone) event = Repeat.new(self, ms) event.progress &Proc.new if block_given? schedule(event) event end
ruby
def cron(schedule, timezone: nil) ms = Scheduler.parse_cron(schedule, timezone: timezone) event = Repeat.new(self, ms) event.progress &Proc.new if block_given? schedule(event) event end
[ "def", "cron", "(", "schedule", ",", "timezone", ":", "nil", ")", "ms", "=", "Scheduler", ".", "parse_cron", "(", "schedule", ",", "timezone", ":", "timezone", ")", "event", "=", "Repeat", ".", "new", "(", "self", ",", "ms", ")", "event", ".", "progress", "Proc", ".", "new", "if", "block_given?", "schedule", "(", "event", ")", "event", "end" ]
Create a repeating event that uses a CRON line to determine the trigger time @param schedule [String] a standard CRON job line. @param callback [Proc] a block or method to execute when the event triggers @return [::UV::Repeat]
[ "Create", "a", "repeating", "event", "that", "uses", "a", "CRON", "line", "to", "determine", "the", "trigger", "time" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L252-L258
292
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.reschedule
def reschedule(event) # Check promise is not resolved return if event.resolved? @critical.synchronize { # Remove the event from the scheduled list and ensure it is in the schedules set if @schedules.include?(event) remove(event) else @schedules << event end # optimal algorithm for inserting into an already sorted list Bisect.insort(@scheduled, event) # Update the timer check_timer } end
ruby
def reschedule(event) # Check promise is not resolved return if event.resolved? @critical.synchronize { # Remove the event from the scheduled list and ensure it is in the schedules set if @schedules.include?(event) remove(event) else @schedules << event end # optimal algorithm for inserting into an already sorted list Bisect.insort(@scheduled, event) # Update the timer check_timer } end
[ "def", "reschedule", "(", "event", ")", "# Check promise is not resolved", "return", "if", "event", ".", "resolved?", "@critical", ".", "synchronize", "{", "# Remove the event from the scheduled list and ensure it is in the schedules set", "if", "@schedules", ".", "include?", "(", "event", ")", "remove", "(", "event", ")", "else", "@schedules", "<<", "event", "end", "# optimal algorithm for inserting into an already sorted list", "Bisect", ".", "insort", "(", "@scheduled", ",", "event", ")", "# Update the timer", "check_timer", "}", "end" ]
Schedules an event for execution @param event [ScheduledEvent]
[ "Schedules", "an", "event", "for", "execution" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L263-L281
293
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.unschedule
def unschedule(event) @critical.synchronize { # Only call delete and update the timer when required if @schedules.include?(event) @schedules.delete(event) remove(event) check_timer end } end
ruby
def unschedule(event) @critical.synchronize { # Only call delete and update the timer when required if @schedules.include?(event) @schedules.delete(event) remove(event) check_timer end } end
[ "def", "unschedule", "(", "event", ")", "@critical", ".", "synchronize", "{", "# Only call delete and update the timer when required", "if", "@schedules", ".", "include?", "(", "event", ")", "@schedules", ".", "delete", "(", "event", ")", "remove", "(", "event", ")", "check_timer", "end", "}", "end" ]
Removes an event from the schedule @param event [ScheduledEvent]
[ "Removes", "an", "event", "from", "the", "schedule" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L286-L295
294
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.remove
def remove(obj) position = nil @scheduled.each_index do |i| # object level comparison if obj.equal? @scheduled[i] position = i break end end @scheduled.slice!(position) unless position.nil? end
ruby
def remove(obj) position = nil @scheduled.each_index do |i| # object level comparison if obj.equal? @scheduled[i] position = i break end end @scheduled.slice!(position) unless position.nil? end
[ "def", "remove", "(", "obj", ")", "position", "=", "nil", "@scheduled", ".", "each_index", "do", "|", "i", "|", "# object level comparison", "if", "obj", ".", "equal?", "@scheduled", "[", "i", "]", "position", "=", "i", "break", "end", "end", "@scheduled", ".", "slice!", "(", "position", ")", "unless", "position", ".", "nil?", "end" ]
Remove an element from the array
[ "Remove", "an", "element", "from", "the", "array" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L302-L314
295
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.check_timer
def check_timer @reactor.update_time existing = @next schedule = @scheduled.first @next = schedule.nil? ? nil : schedule.next_scheduled if existing != @next # lazy load the timer if @timer.nil? new_timer else @timer.stop end if not @next.nil? in_time = @next - @reactor.now # Ensure there are never negative start times if in_time > 3 @timer.start(in_time) else # Effectively next tick @timer.start(0) end end end end
ruby
def check_timer @reactor.update_time existing = @next schedule = @scheduled.first @next = schedule.nil? ? nil : schedule.next_scheduled if existing != @next # lazy load the timer if @timer.nil? new_timer else @timer.stop end if not @next.nil? in_time = @next - @reactor.now # Ensure there are never negative start times if in_time > 3 @timer.start(in_time) else # Effectively next tick @timer.start(0) end end end end
[ "def", "check_timer", "@reactor", ".", "update_time", "existing", "=", "@next", "schedule", "=", "@scheduled", ".", "first", "@next", "=", "schedule", ".", "nil?", "?", "nil", ":", "schedule", ".", "next_scheduled", "if", "existing", "!=", "@next", "# lazy load the timer", "if", "@timer", ".", "nil?", "new_timer", "else", "@timer", ".", "stop", "end", "if", "not", "@next", ".", "nil?", "in_time", "=", "@next", "-", "@reactor", ".", "now", "# Ensure there are never negative start times", "if", "in_time", ">", "3", "@timer", ".", "start", "(", "in_time", ")", "else", "# Effectively next tick", "@timer", ".", "start", "(", "0", ")", "end", "end", "end", "end" ]
Ensures the current timer, if any, is still accurate by checking the head of the schedule
[ "Ensures", "the", "current", "timer", "if", "any", "is", "still", "accurate", "by", "checking", "the", "head", "of", "the", "schedule" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L327-L354
296
cotag/uv-rays
lib/uv-rays/scheduler.rb
UV.Scheduler.on_timer
def on_timer @critical.synchronize { schedule = @scheduled.shift @schedules.delete(schedule) schedule.trigger # execute schedules that are within 3ms of this event # Basic timer coalescing.. now = @reactor.now + 3 while @scheduled.first && @scheduled.first.next_scheduled <= now schedule = @scheduled.shift @schedules.delete(schedule) schedule.trigger end check_timer } end
ruby
def on_timer @critical.synchronize { schedule = @scheduled.shift @schedules.delete(schedule) schedule.trigger # execute schedules that are within 3ms of this event # Basic timer coalescing.. now = @reactor.now + 3 while @scheduled.first && @scheduled.first.next_scheduled <= now schedule = @scheduled.shift @schedules.delete(schedule) schedule.trigger end check_timer } end
[ "def", "on_timer", "@critical", ".", "synchronize", "{", "schedule", "=", "@scheduled", ".", "shift", "@schedules", ".", "delete", "(", "schedule", ")", "schedule", ".", "trigger", "# execute schedules that are within 3ms of this event", "# Basic timer coalescing..", "now", "=", "@reactor", ".", "now", "+", "3", "while", "@scheduled", ".", "first", "&&", "@scheduled", ".", "first", ".", "next_scheduled", "<=", "now", "schedule", "=", "@scheduled", ".", "shift", "@schedules", ".", "delete", "(", "schedule", ")", "schedule", ".", "trigger", "end", "check_timer", "}", "end" ]
Is called when the libuv timer fires
[ "Is", "called", "when", "the", "libuv", "timer", "fires" ]
cf98e7ee7169d203d68bc527e84db86ca47afbca
https://github.com/cotag/uv-rays/blob/cf98e7ee7169d203d68bc527e84db86ca47afbca/lib/uv-rays/scheduler.rb#L357-L373
297
rtwomey/stately
lib/stately.rb
Stately.Core.stately
def stately(*opts, &block) options = opts.last.is_a?(Hash) ? opts.last : {} options[:attr] ||= :state @stately_machine = Stately::Machine.new(options[:attr], options[:start]) @stately_machine.instance_eval(&block) if block_given? include Stately::InstanceMethods end
ruby
def stately(*opts, &block) options = opts.last.is_a?(Hash) ? opts.last : {} options[:attr] ||= :state @stately_machine = Stately::Machine.new(options[:attr], options[:start]) @stately_machine.instance_eval(&block) if block_given? include Stately::InstanceMethods end
[ "def", "stately", "(", "*", "opts", ",", "&", "block", ")", "options", "=", "opts", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "opts", ".", "last", ":", "{", "}", "options", "[", ":attr", "]", "||=", ":state", "@stately_machine", "=", "Stately", "::", "Machine", ".", "new", "(", "options", "[", ":attr", "]", ",", "options", "[", ":start", "]", ")", "@stately_machine", ".", "instance_eval", "(", "block", ")", "if", "block_given?", "include", "Stately", "::", "InstanceMethods", "end" ]
Define a new Stately state machine. As an example, let's say you have an Order object and you'd like an elegant state machine for it. Here's one way you might set it up: Class Order do stately start: :processing do state :completed do prevent_from :refunded before_transition from: :processing, do: :calculate_total after_transition do: :email_receipt validate :validates_credit_card end state :invalid do prevent_from :completed, :refunded end state :refunded do allow_from :completed after_transition do: :email_receipt end end end This example is doing quite a few things, paraphrased as: * It sets up a new state machine using the default state attribute on Order to store the current state. It also indicates the initial state should be :processing. * It defines three states: :completed, :refunded, and :invalid * Order can transition to the completed state from all but the refunded state. Similar definitions are setup for the other two states. * Callbacks are setup using before_transition and after_transition * Validations are added. If a validation fails, it prevents the transition. Stately tries hard not to surprise you. In a typical Stately implementation, you'll always have an after_transition, primarily to call save (or whatever the equivalent is to store the instance's current state).
[ "Define", "a", "new", "Stately", "state", "machine", "." ]
03c01e21e024e14c5bb93202eea1c85a08e42821
https://github.com/rtwomey/stately/blob/03c01e21e024e14c5bb93202eea1c85a08e42821/lib/stately.rb#L52-L60
298
redding/dk
lib/dk/runner.rb
Dk.Runner.build_local_cmd
def build_local_cmd(task, cmd_str, input, given_opts) Local::Cmd.new(cmd_str, given_opts) end
ruby
def build_local_cmd(task, cmd_str, input, given_opts) Local::Cmd.new(cmd_str, given_opts) end
[ "def", "build_local_cmd", "(", "task", ",", "cmd_str", ",", "input", ",", "given_opts", ")", "Local", "::", "Cmd", ".", "new", "(", "cmd_str", ",", "given_opts", ")", "end" ]
input is needed for the `TestRunner` so it can use it with stubbing otherwise it is ignored when building a local cmd
[ "input", "is", "needed", "for", "the", "TestRunner", "so", "it", "can", "use", "it", "with", "stubbing", "otherwise", "it", "is", "ignored", "when", "building", "a", "local", "cmd" ]
9b6122ce815467c698811014c01518cca539946e
https://github.com/redding/dk/blob/9b6122ce815467c698811014c01518cca539946e/lib/dk/runner.rb#L172-L174
299
redding/dk
lib/dk/runner.rb
Dk.Runner.build_remote_cmd
def build_remote_cmd(task, cmd_str, input, given_opts, ssh_opts) Remote::Cmd.new(cmd_str, ssh_opts) end
ruby
def build_remote_cmd(task, cmd_str, input, given_opts, ssh_opts) Remote::Cmd.new(cmd_str, ssh_opts) end
[ "def", "build_remote_cmd", "(", "task", ",", "cmd_str", ",", "input", ",", "given_opts", ",", "ssh_opts", ")", "Remote", "::", "Cmd", ".", "new", "(", "cmd_str", ",", "ssh_opts", ")", "end" ]
input and given opts are needed for the `TestRunner` so it can use it with stubbing otherwise they are ignored when building a remote cmd
[ "input", "and", "given", "opts", "are", "needed", "for", "the", "TestRunner", "so", "it", "can", "use", "it", "with", "stubbing", "otherwise", "they", "are", "ignored", "when", "building", "a", "remote", "cmd" ]
9b6122ce815467c698811014c01518cca539946e
https://github.com/redding/dk/blob/9b6122ce815467c698811014c01518cca539946e/lib/dk/runner.rb#L193-L195