id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
8,300
marcboeker/mongolicious
lib/mongolicious/storage.rb
Mongolicious.Storage.cleanup
def cleanup(bucket, prefix, versions) objects = @con.get_bucket(bucket, :prefix => prefix).body['Contents'] return if objects.size <= versions objects[0...(objects.size - versions)].each do |o| Mongolicious.logger.info("Removing outdated version #{o['Key']}") @con.delete_object(bucket, o['Key']) end end
ruby
def cleanup(bucket, prefix, versions) objects = @con.get_bucket(bucket, :prefix => prefix).body['Contents'] return if objects.size <= versions objects[0...(objects.size - versions)].each do |o| Mongolicious.logger.info("Removing outdated version #{o['Key']}") @con.delete_object(bucket, o['Key']) end end
[ "def", "cleanup", "(", "bucket", ",", "prefix", ",", "versions", ")", "objects", "=", "@con", ".", "get_bucket", "(", "bucket", ",", ":prefix", "=>", "prefix", ")", ".", "body", "[", "'Contents'", "]", "return", "if", "objects", ".", "size", "<=", "versions", "objects", "[", "0", "...", "(", "objects", ".", "size", "-", "versions", ")", "]", ".", "each", "do", "|", "o", "|", "Mongolicious", ".", "logger", ".", "info", "(", "\"Removing outdated version #{o['Key']}\"", ")", "@con", ".", "delete_object", "(", "bucket", ",", "o", "[", "'Key'", "]", ")", "end", "end" ]
Remove old versions of a backup. @param [String] bucket the bucket where the archive is stored in. @param [String] prefix the prefix where to look for outdated versions. @param [Integer] versions number of versions to keep. @return [nil]
[ "Remove", "old", "versions", "of", "a", "backup", "." ]
bc1553188df97d3df825de6d826b34ab7185a431
https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/storage.rb#L107-L116
8,301
richo/twat
lib/twat/subcommands/base.rb
Twat::Subcommands.Base.format
def format(twt, idx = nil) idx = pad(idx) if idx text = deentitize(twt.text) if config.colors? buf = idx ? "#{idx.cyan}:" : "" if twt.as_user == config.account_name.to_s buf += "#{twt.as_user.bold.blue}: #{text}" elsif text.mentions?(config.account_name) buf += "#{twt.as_user.bold.red}: #{text}" else buf += "#{twt.as_user.bold.cyan}: #{text}" end buf.colorise! else buf = idx ? "#{idx}: " : "" buf += "#{twt.as_user}: #{text}" end end
ruby
def format(twt, idx = nil) idx = pad(idx) if idx text = deentitize(twt.text) if config.colors? buf = idx ? "#{idx.cyan}:" : "" if twt.as_user == config.account_name.to_s buf += "#{twt.as_user.bold.blue}: #{text}" elsif text.mentions?(config.account_name) buf += "#{twt.as_user.bold.red}: #{text}" else buf += "#{twt.as_user.bold.cyan}: #{text}" end buf.colorise! else buf = idx ? "#{idx}: " : "" buf += "#{twt.as_user}: #{text}" end end
[ "def", "format", "(", "twt", ",", "idx", "=", "nil", ")", "idx", "=", "pad", "(", "idx", ")", "if", "idx", "text", "=", "deentitize", "(", "twt", ".", "text", ")", "if", "config", ".", "colors?", "buf", "=", "idx", "?", "\"#{idx.cyan}:\"", ":", "\"\"", "if", "twt", ".", "as_user", "==", "config", ".", "account_name", ".", "to_s", "buf", "+=", "\"#{twt.as_user.bold.blue}: #{text}\"", "elsif", "text", ".", "mentions?", "(", "config", ".", "account_name", ")", "buf", "+=", "\"#{twt.as_user.bold.red}: #{text}\"", "else", "buf", "+=", "\"#{twt.as_user.bold.cyan}: #{text}\"", "end", "buf", ".", "colorise!", "else", "buf", "=", "idx", "?", "\"#{idx}: \"", ":", "\"\"", "buf", "+=", "\"#{twt.as_user}: #{text}\"", "end", "end" ]
Format a tweet all pretty like
[ "Format", "a", "tweet", "all", "pretty", "like" ]
0354059c2d9643a8c3b855dbb18105fa80bf651e
https://github.com/richo/twat/blob/0354059c2d9643a8c3b855dbb18105fa80bf651e/lib/twat/subcommands/base.rb#L66-L83
8,302
teodor-pripoae/scalaroid
lib/scalaroid/transaction.rb
Scalaroid.Transaction.write
def write(key, value, binary = false) result = req_list(new_req_list().add_write(key, value, binary))[0] _process_result_commit(result) end
ruby
def write(key, value, binary = false) result = req_list(new_req_list().add_write(key, value, binary))[0] _process_result_commit(result) end
[ "def", "write", "(", "key", ",", "value", ",", "binary", "=", "false", ")", "result", "=", "req_list", "(", "new_req_list", "(", ")", ".", "add_write", "(", "key", ",", "value", ",", "binary", ")", ")", "[", "0", "]", "_process_result_commit", "(", "result", ")", "end" ]
Issues a write operation to Scalaris and adds it to the current transaction.
[ "Issues", "a", "write", "operation", "to", "Scalaris", "and", "adds", "it", "to", "the", "current", "transaction", "." ]
4e9e90e71ce3008da79a72eae40fe2f187580be2
https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/transaction.rb#L117-L120
8,303
teodor-pripoae/scalaroid
lib/scalaroid/transaction.rb
Scalaroid.Transaction.add_del_on_list
def add_del_on_list(key, to_add, to_remove) result = req_list(new_req_list().add_add_del_on_list(key, to_add, to_remove))[0] process_result_add_del_on_list(result) end
ruby
def add_del_on_list(key, to_add, to_remove) result = req_list(new_req_list().add_add_del_on_list(key, to_add, to_remove))[0] process_result_add_del_on_list(result) end
[ "def", "add_del_on_list", "(", "key", ",", "to_add", ",", "to_remove", ")", "result", "=", "req_list", "(", "new_req_list", "(", ")", ".", "add_add_del_on_list", "(", "key", ",", "to_add", ",", "to_remove", ")", ")", "[", "0", "]", "process_result_add_del_on_list", "(", "result", ")", "end" ]
Issues a add_del_on_list operation to scalaris and adds it to the current transaction. Changes the list stored at the given key, i.e. first adds all items in to_add then removes all items in to_remove. Both, to_add and to_remove, must be lists. Assumes en empty list if no value exists at key.
[ "Issues", "a", "add_del_on_list", "operation", "to", "scalaris", "and", "adds", "it", "to", "the", "current", "transaction", ".", "Changes", "the", "list", "stored", "at", "the", "given", "key", "i", ".", "e", ".", "first", "adds", "all", "items", "in", "to_add", "then", "removes", "all", "items", "in", "to_remove", ".", "Both", "to_add", "and", "to_remove", "must", "be", "lists", ".", "Assumes", "en", "empty", "list", "if", "no", "value", "exists", "at", "key", "." ]
4e9e90e71ce3008da79a72eae40fe2f187580be2
https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/transaction.rb#L128-L131
8,304
teodor-pripoae/scalaroid
lib/scalaroid/transaction.rb
Scalaroid.Transaction.add_on_nr
def add_on_nr(key, to_add) result = req_list(new_req_list().add_add_on_nr(key, to_add))[0] process_result_add_on_nr(result) end
ruby
def add_on_nr(key, to_add) result = req_list(new_req_list().add_add_on_nr(key, to_add))[0] process_result_add_on_nr(result) end
[ "def", "add_on_nr", "(", "key", ",", "to_add", ")", "result", "=", "req_list", "(", "new_req_list", "(", ")", ".", "add_add_on_nr", "(", "key", ",", "to_add", ")", ")", "[", "0", "]", "process_result_add_on_nr", "(", "result", ")", "end" ]
Issues a add_on_nr operation to scalaris and adds it to the current transaction. Changes the number stored at the given key, i.e. adds some value. Assumes 0 if no value exists at key.
[ "Issues", "a", "add_on_nr", "operation", "to", "scalaris", "and", "adds", "it", "to", "the", "current", "transaction", ".", "Changes", "the", "number", "stored", "at", "the", "given", "key", "i", ".", "e", ".", "adds", "some", "value", ".", "Assumes", "0", "if", "no", "value", "exists", "at", "key", "." ]
4e9e90e71ce3008da79a72eae40fe2f187580be2
https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/transaction.rb#L137-L140
8,305
nigel-lowry/random_outcome
lib/random_outcome/simulator.rb
RandomOutcome.Simulator.outcome
def outcome num = random_float_including_zero_and_excluding_one # don't inline @probability_range_to_outcome.detect { |probability_range, _| num.in? probability_range }.last end
ruby
def outcome num = random_float_including_zero_and_excluding_one # don't inline @probability_range_to_outcome.detect { |probability_range, _| num.in? probability_range }.last end
[ "def", "outcome", "num", "=", "random_float_including_zero_and_excluding_one", "# don't inline", "@probability_range_to_outcome", ".", "detect", "{", "|", "probability_range", ",", "_", "|", "num", ".", "in?", "probability_range", "}", ".", "last", "end" ]
creates a new Simulator which will return the desired outcomes with the given probability @param outcome_to_probability [Hash<Symbol, Number>] hash of outcomes to their probability (represented as numbers between zero and one) @note raises errors if there is only one possible outcome (why bother using this if there's only one outcome?), if the probabilities don't total one (use Rationals if this proves problematic with rounding) or if any of the outcomes are impossible (why include them if they can never happen?) generate an outcome with the initialised probabilities @return [Symbol] symbol for outcome
[ "creates", "a", "new", "Simulator", "which", "will", "return", "the", "desired", "outcomes", "with", "the", "given", "probability" ]
f124cfcfd9077ee4b05bdfc2110fd1d2edf40985
https://github.com/nigel-lowry/random_outcome/blob/f124cfcfd9077ee4b05bdfc2110fd1d2edf40985/lib/random_outcome/simulator.rb#L23-L26
8,306
device-independent/restless_router
lib/restless_router/routes.rb
RestlessRouter.Routes.add_route
def add_route(route) raise InvalidRouteError.new('Route must respond to #url_for') unless valid_route?(route) @routes << route unless route_exists?(route) end
ruby
def add_route(route) raise InvalidRouteError.new('Route must respond to #url_for') unless valid_route?(route) @routes << route unless route_exists?(route) end
[ "def", "add_route", "(", "route", ")", "raise", "InvalidRouteError", ".", "new", "(", "'Route must respond to #url_for'", ")", "unless", "valid_route?", "(", "route", ")", "@routes", "<<", "route", "unless", "route_exists?", "(", "route", ")", "end" ]
Add a new route to the Routes collection @return [Array] Routes collection
[ "Add", "a", "new", "route", "to", "the", "Routes", "collection" ]
c20ea03ec53b889d192393c7ab18bcacb0b5e46f
https://github.com/device-independent/restless_router/blob/c20ea03ec53b889d192393c7ab18bcacb0b5e46f/lib/restless_router/routes.rb#L38-L41
8,307
device-independent/restless_router
lib/restless_router/routes.rb
RestlessRouter.Routes.add_route!
def add_route!(route) # Raise exception if the route is existing, too raise InvalidRouteError.new('Route must respond to #url_for') unless valid_route?(route) raise ExistingRouteError.new(("Route already exists for %s" % [route.name])) if route_exists?(route) @routes << route end
ruby
def add_route!(route) # Raise exception if the route is existing, too raise InvalidRouteError.new('Route must respond to #url_for') unless valid_route?(route) raise ExistingRouteError.new(("Route already exists for %s" % [route.name])) if route_exists?(route) @routes << route end
[ "def", "add_route!", "(", "route", ")", "# Raise exception if the route is existing, too", "raise", "InvalidRouteError", ".", "new", "(", "'Route must respond to #url_for'", ")", "unless", "valid_route?", "(", "route", ")", "raise", "ExistingRouteError", ".", "new", "(", "(", "\"Route already exists for %s\"", "%", "[", "route", ".", "name", "]", ")", ")", "if", "route_exists?", "(", "route", ")", "@routes", "<<", "route", "end" ]
Raise an exception if the route is invalid or already exists
[ "Raise", "an", "exception", "if", "the", "route", "is", "invalid", "or", "already", "exists" ]
c20ea03ec53b889d192393c7ab18bcacb0b5e46f
https://github.com/device-independent/restless_router/blob/c20ea03ec53b889d192393c7ab18bcacb0b5e46f/lib/restless_router/routes.rb#L46-L52
8,308
device-independent/restless_router
lib/restless_router/routes.rb
RestlessRouter.Routes.route_for
def route_for(name) name = name.to_s @routes.select { |entry| entry.name == name }.first end
ruby
def route_for(name) name = name.to_s @routes.select { |entry| entry.name == name }.first end
[ "def", "route_for", "(", "name", ")", "name", "=", "name", ".", "to_s", "@routes", ".", "select", "{", "|", "entry", "|", "entry", ".", "name", "==", "name", "}", ".", "first", "end" ]
Retrieve a route by it's link relationship name @return [Route, nil] Instance of the route by name or nil
[ "Retrieve", "a", "route", "by", "it", "s", "link", "relationship", "name" ]
c20ea03ec53b889d192393c7ab18bcacb0b5e46f
https://github.com/device-independent/restless_router/blob/c20ea03ec53b889d192393c7ab18bcacb0b5e46f/lib/restless_router/routes.rb#L57-L60
8,309
device-independent/restless_router
lib/restless_router/routes.rb
RestlessRouter.Routes.route_for!
def route_for!(name) route = route_for(name) raise RouteNotFoundError.new(("Route not found for %s" % [name])) if route.nil? route end
ruby
def route_for!(name) route = route_for(name) raise RouteNotFoundError.new(("Route not found for %s" % [name])) if route.nil? route end
[ "def", "route_for!", "(", "name", ")", "route", "=", "route_for", "(", "name", ")", "raise", "RouteNotFoundError", ".", "new", "(", "(", "\"Route not found for %s\"", "%", "[", "name", "]", ")", ")", "if", "route", ".", "nil?", "route", "end" ]
Raise an exception of the route's not found
[ "Raise", "an", "exception", "of", "the", "route", "s", "not", "found" ]
c20ea03ec53b889d192393c7ab18bcacb0b5e46f
https://github.com/device-independent/restless_router/blob/c20ea03ec53b889d192393c7ab18bcacb0b5e46f/lib/restless_router/routes.rb#L65-L69
8,310
bcantin/auditing
lib/auditing/base.rb
Auditing.Base.audit_enabled
def audit_enabled(opts={}) include InstanceMethods class_attribute :auditing_fields has_many :audits, :as => :auditable, :order => 'created_at DESC, id DESC' self.auditing_fields = gather_fields_for_auditing(opts[:fields]) after_create :log_creation after_update :log_update end
ruby
def audit_enabled(opts={}) include InstanceMethods class_attribute :auditing_fields has_many :audits, :as => :auditable, :order => 'created_at DESC, id DESC' self.auditing_fields = gather_fields_for_auditing(opts[:fields]) after_create :log_creation after_update :log_update end
[ "def", "audit_enabled", "(", "opts", "=", "{", "}", ")", "include", "InstanceMethods", "class_attribute", ":auditing_fields", "has_many", ":audits", ",", ":as", "=>", ":auditable", ",", ":order", "=>", "'created_at DESC, id DESC'", "self", ".", "auditing_fields", "=", "gather_fields_for_auditing", "(", "opts", "[", ":fields", "]", ")", "after_create", ":log_creation", "after_update", ":log_update", "end" ]
Auditing creates audit objects for a record. @examples class School < ActiveRecord::Base audit_enabled end class School < ActiveRecord::Base audit_enabled :fields => [:name, :established_on] end
[ "Auditing", "creates", "audit", "objects", "for", "a", "record", "." ]
495b9e2d465c8263e7709623a003bb933ff540b7
https://github.com/bcantin/auditing/blob/495b9e2d465c8263e7709623a003bb933ff540b7/lib/auditing/base.rb#L13-L24
8,311
scotdalton/institutions
lib/institutions/institution/util.rb
Institutions.Util.method_missing
def method_missing(method, *args, &block) instance_variable = instance_variablize(method) if respond_to_missing?(method) and instance_variable_defined?(instance_variable) self.class.send :attr_reader, method.to_sym instance_variable_get instance_variable else super end end
ruby
def method_missing(method, *args, &block) instance_variable = instance_variablize(method) if respond_to_missing?(method) and instance_variable_defined?(instance_variable) self.class.send :attr_reader, method.to_sym instance_variable_get instance_variable else super end end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "instance_variable", "=", "instance_variablize", "(", "method", ")", "if", "respond_to_missing?", "(", "method", ")", "and", "instance_variable_defined?", "(", "instance_variable", ")", "self", ".", "class", ".", "send", ":attr_reader", ",", "method", ".", "to_sym", "instance_variable_get", "instance_variable", "else", "super", "end", "end" ]
Dynamically sets attr_readers for elements
[ "Dynamically", "sets", "attr_readers", "for", "elements" ]
e979f42d54abca3cc629b70eb3dd82aa84f19982
https://github.com/scotdalton/institutions/blob/e979f42d54abca3cc629b70eb3dd82aa84f19982/lib/institutions/institution/util.rb#L23-L31
8,312
scotdalton/institutions
lib/institutions/institution/util.rb
Institutions.Util.respond_to_missing?
def respond_to_missing?(method, include_private = false) # Short circuit if we have invalid instance variable name, # otherwise we get an exception that we don't need. return super unless valid_instance_variable? method if instance_variable_defined? instance_variablize(method) true else super end end
ruby
def respond_to_missing?(method, include_private = false) # Short circuit if we have invalid instance variable name, # otherwise we get an exception that we don't need. return super unless valid_instance_variable? method if instance_variable_defined? instance_variablize(method) true else super end end
[ "def", "respond_to_missing?", "(", "method", ",", "include_private", "=", "false", ")", "# Short circuit if we have invalid instance variable name,", "# otherwise we get an exception that we don't need.", "return", "super", "unless", "valid_instance_variable?", "method", "if", "instance_variable_defined?", "instance_variablize", "(", "method", ")", "true", "else", "super", "end", "end" ]
Tells users that we respond to missing methods if they are instance variables.
[ "Tells", "users", "that", "we", "respond", "to", "missing", "methods", "if", "they", "are", "instance", "variables", "." ]
e979f42d54abca3cc629b70eb3dd82aa84f19982
https://github.com/scotdalton/institutions/blob/e979f42d54abca3cc629b70eb3dd82aa84f19982/lib/institutions/institution/util.rb#L37-L46
8,313
threez/mapkit
lib/mapkit.rb
MapKit.Point.in?
def in?(bounding_box) top, left, bottom, right = bounding_box.coords (left..right) === @lng && (top..bottom) === @lat end
ruby
def in?(bounding_box) top, left, bottom, right = bounding_box.coords (left..right) === @lng && (top..bottom) === @lat end
[ "def", "in?", "(", "bounding_box", ")", "top", ",", "left", ",", "bottom", ",", "right", "=", "bounding_box", ".", "coords", "(", "left", "..", "right", ")", "===", "@lng", "&&", "(", "top", "..", "bottom", ")", "===", "@lat", "end" ]
initializes a point object using latitude and longitude returns true if point is in bounding_box, false otherwise
[ "initializes", "a", "point", "object", "using", "latitude", "and", "longitude", "returns", "true", "if", "point", "is", "in", "bounding_box", "false", "otherwise" ]
ffd212e6748b457c946f82cf4556a61d68e0939a
https://github.com/threez/mapkit/blob/ffd212e6748b457c946f82cf4556a61d68e0939a/lib/mapkit.rb#L40-L43
8,314
threez/mapkit
lib/mapkit.rb
MapKit.Point.pixel
def pixel(bounding_box) x, y = MapKit.latlng2pixel(@lat, @lng, bounding_box.zoom) tile_x, tile_y = MapKit.latlng2pixel(bounding_box.top, bounding_box.left, bounding_box.zoom) [x-tile_x, y-tile_y] end
ruby
def pixel(bounding_box) x, y = MapKit.latlng2pixel(@lat, @lng, bounding_box.zoom) tile_x, tile_y = MapKit.latlng2pixel(bounding_box.top, bounding_box.left, bounding_box.zoom) [x-tile_x, y-tile_y] end
[ "def", "pixel", "(", "bounding_box", ")", "x", ",", "y", "=", "MapKit", ".", "latlng2pixel", "(", "@lat", ",", "@lng", ",", "bounding_box", ".", "zoom", ")", "tile_x", ",", "tile_y", "=", "MapKit", ".", "latlng2pixel", "(", "bounding_box", ".", "top", ",", "bounding_box", ".", "left", ",", "bounding_box", ".", "zoom", ")", "[", "x", "-", "tile_x", ",", "y", "-", "tile_y", "]", "end" ]
returns relative x and y for point in bounding_box
[ "returns", "relative", "x", "and", "y", "for", "point", "in", "bounding_box" ]
ffd212e6748b457c946f82cf4556a61d68e0939a
https://github.com/threez/mapkit/blob/ffd212e6748b457c946f82cf4556a61d68e0939a/lib/mapkit.rb#L46-L50
8,315
threez/mapkit
lib/mapkit.rb
MapKit.BoundingBox.grow!
def grow!(percent) lng = ((100.0 + percent) * (width / 2.0 / 100.0)) / 2.0 lat = ((100.0 + percent) * (height / 2.0 / 100.0)) / 2.0 @top += lat @left -= lng @bottom -= lat @right += lng end
ruby
def grow!(percent) lng = ((100.0 + percent) * (width / 2.0 / 100.0)) / 2.0 lat = ((100.0 + percent) * (height / 2.0 / 100.0)) / 2.0 @top += lat @left -= lng @bottom -= lat @right += lng end
[ "def", "grow!", "(", "percent", ")", "lng", "=", "(", "(", "100.0", "+", "percent", ")", "*", "(", "width", "/", "2.0", "/", "100.0", ")", ")", "/", "2.0", "lat", "=", "(", "(", "100.0", "+", "percent", ")", "*", "(", "height", "/", "2.0", "/", "100.0", ")", ")", "/", "2.0", "@top", "+=", "lat", "@left", "-=", "lng", "@bottom", "-=", "lat", "@right", "+=", "lng", "end" ]
grow bounding box by percentage
[ "grow", "bounding", "box", "by", "percentage" ]
ffd212e6748b457c946f82cf4556a61d68e0939a
https://github.com/threez/mapkit/blob/ffd212e6748b457c946f82cf4556a61d68e0939a/lib/mapkit.rb#L98-L105
8,316
ideonetwork/lato-blog
lib/lato_blog/interfaces/fields.rb
LatoBlog.Interface::Fields.blog__sync_config_post_fields_with_db_post_fields
def blog__sync_config_post_fields_with_db_post_fields posts = LatoBlog::Post.all # create / update fields on database posts.map { |p| blog__sync_config_post_fields_with_db_post_fields_for_post(p) } end
ruby
def blog__sync_config_post_fields_with_db_post_fields posts = LatoBlog::Post.all # create / update fields on database posts.map { |p| blog__sync_config_post_fields_with_db_post_fields_for_post(p) } end
[ "def", "blog__sync_config_post_fields_with_db_post_fields", "posts", "=", "LatoBlog", "::", "Post", ".", "all", "# create / update fields on database", "posts", ".", "map", "{", "|", "p", "|", "blog__sync_config_post_fields_with_db_post_fields_for_post", "(", "p", ")", "}", "end" ]
This function syncronizes the config post fields with the post fields on database.
[ "This", "function", "syncronizes", "the", "config", "post", "fields", "with", "the", "post", "fields", "on", "database", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/fields.rb#L7-L11
8,317
ideonetwork/lato-blog
lib/lato_blog/interfaces/fields.rb
LatoBlog.Interface::Fields.blog__sync_config_post_fields_with_db_post_fields_for_post
def blog__sync_config_post_fields_with_db_post_fields_for_post(post) # save or update post fields from config post_fields = CONFIGS[:lato_blog][:post_fields] post_fields.map { |key, content| blog__sync_config_post_field(post, key, content) } # remove old post fields db_post_fields = post.post_fields.visibles.roots db_post_fields.map { |dbpf| blog__sync_db_post_field(post, dbpf) } end
ruby
def blog__sync_config_post_fields_with_db_post_fields_for_post(post) # save or update post fields from config post_fields = CONFIGS[:lato_blog][:post_fields] post_fields.map { |key, content| blog__sync_config_post_field(post, key, content) } # remove old post fields db_post_fields = post.post_fields.visibles.roots db_post_fields.map { |dbpf| blog__sync_db_post_field(post, dbpf) } end
[ "def", "blog__sync_config_post_fields_with_db_post_fields_for_post", "(", "post", ")", "# save or update post fields from config", "post_fields", "=", "CONFIGS", "[", ":lato_blog", "]", "[", ":post_fields", "]", "post_fields", ".", "map", "{", "|", "key", ",", "content", "|", "blog__sync_config_post_field", "(", "post", ",", "key", ",", "content", ")", "}", "# remove old post fields", "db_post_fields", "=", "post", ".", "post_fields", ".", "visibles", ".", "roots", "db_post_fields", ".", "map", "{", "|", "dbpf", "|", "blog__sync_db_post_field", "(", "post", ",", "dbpf", ")", "}", "end" ]
This function syncronizes the config post fields with the post fields on database for a single post object.
[ "This", "function", "syncronizes", "the", "config", "post", "fields", "with", "the", "post", "fields", "on", "database", "for", "a", "single", "post", "object", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/fields.rb#L15-L22
8,318
ideonetwork/lato-blog
lib/lato_blog/interfaces/fields.rb
LatoBlog.Interface::Fields.blog__sync_config_post_field
def blog__sync_config_post_field(post, key, content) db_post_field = LatoBlog::PostField.find_by( key: key, lato_blog_post_id: post.id, lato_blog_post_field_id: nil ) # check if post field can be created for the post if content[:categories] && !content[:categories].empty? db_categories = LatoBlog::Category.where(meta_permalink: content[:categories]) return if (post.categories.pluck(:id) & db_categories.pluck(:id)).empty? end # run correct action for field if db_post_field blog__update_db_post_field(db_post_field, content) else blog__create_db_post_field(post, key, content) end end
ruby
def blog__sync_config_post_field(post, key, content) db_post_field = LatoBlog::PostField.find_by( key: key, lato_blog_post_id: post.id, lato_blog_post_field_id: nil ) # check if post field can be created for the post if content[:categories] && !content[:categories].empty? db_categories = LatoBlog::Category.where(meta_permalink: content[:categories]) return if (post.categories.pluck(:id) & db_categories.pluck(:id)).empty? end # run correct action for field if db_post_field blog__update_db_post_field(db_post_field, content) else blog__create_db_post_field(post, key, content) end end
[ "def", "blog__sync_config_post_field", "(", "post", ",", "key", ",", "content", ")", "db_post_field", "=", "LatoBlog", "::", "PostField", ".", "find_by", "(", "key", ":", "key", ",", "lato_blog_post_id", ":", "post", ".", "id", ",", "lato_blog_post_field_id", ":", "nil", ")", "# check if post field can be created for the post", "if", "content", "[", ":categories", "]", "&&", "!", "content", "[", ":categories", "]", ".", "empty?", "db_categories", "=", "LatoBlog", "::", "Category", ".", "where", "(", "meta_permalink", ":", "content", "[", ":categories", "]", ")", "return", "if", "(", "post", ".", "categories", ".", "pluck", "(", ":id", ")", "&", "db_categories", ".", "pluck", "(", ":id", ")", ")", ".", "empty?", "end", "# run correct action for field", "if", "db_post_field", "blog__update_db_post_field", "(", "db_post_field", ",", "content", ")", "else", "blog__create_db_post_field", "(", "post", ",", "key", ",", "content", ")", "end", "end" ]
This function syncronizes a single post field of a specific post with database.
[ "This", "function", "syncronizes", "a", "single", "post", "field", "of", "a", "specific", "post", "with", "database", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/fields.rb#L25-L42
8,319
ideonetwork/lato-blog
lib/lato_blog/interfaces/fields.rb
LatoBlog.Interface::Fields.blog__sync_db_post_field
def blog__sync_db_post_field(post, db_post_field) post_fields = CONFIGS[:lato_blog][:post_fields] # search db post field on config file content = post_fields[db_post_field.key] db_post_field.update(meta_visible: false) && return unless content # check category of post field is accepted if content[:categories] && !content[:categories].empty? db_categories = LatoBlog::Category.where(meta_permalink: content[:categories]) db_post_field.update(meta_visible: false) && return if (post.categories.pluck(:id) & db_categories.pluck(:id)).empty? end end
ruby
def blog__sync_db_post_field(post, db_post_field) post_fields = CONFIGS[:lato_blog][:post_fields] # search db post field on config file content = post_fields[db_post_field.key] db_post_field.update(meta_visible: false) && return unless content # check category of post field is accepted if content[:categories] && !content[:categories].empty? db_categories = LatoBlog::Category.where(meta_permalink: content[:categories]) db_post_field.update(meta_visible: false) && return if (post.categories.pluck(:id) & db_categories.pluck(:id)).empty? end end
[ "def", "blog__sync_db_post_field", "(", "post", ",", "db_post_field", ")", "post_fields", "=", "CONFIGS", "[", ":lato_blog", "]", "[", ":post_fields", "]", "# search db post field on config file", "content", "=", "post_fields", "[", "db_post_field", ".", "key", "]", "db_post_field", ".", "update", "(", "meta_visible", ":", "false", ")", "&&", "return", "unless", "content", "# check category of post field is accepted", "if", "content", "[", ":categories", "]", "&&", "!", "content", "[", ":categories", "]", ".", "empty?", "db_categories", "=", "LatoBlog", "::", "Category", ".", "where", "(", "meta_permalink", ":", "content", "[", ":categories", "]", ")", "db_post_field", ".", "update", "(", "meta_visible", ":", "false", ")", "&&", "return", "if", "(", "post", ".", "categories", ".", "pluck", "(", ":id", ")", "&", "db_categories", ".", "pluck", "(", ":id", ")", ")", ".", "empty?", "end", "end" ]
This function syncronizes a single post field of a specific post with config file.
[ "This", "function", "syncronizes", "a", "single", "post", "field", "of", "a", "specific", "post", "with", "config", "file", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/fields.rb#L45-L55
8,320
ideonetwork/lato-blog
lib/lato_blog/interfaces/fields.rb
LatoBlog.Interface::Fields.blog__update_db_post_field
def blog__update_db_post_field(db_post_field, content, post_field_parent = nil) # run minimum updates db_post_field.update( position: content[:position], meta_visible: true ) # run custom update for type case db_post_field.typology when 'text' update_db_post_field_text(db_post_field, content, post_field_parent) when 'textarea' update_db_post_field_textarea(db_post_field, content, post_field_parent) when 'datetime' update_db_post_field_datetime(db_post_field, content, post_field_parent) when 'editor' update_db_post_field_editor(db_post_field, content, post_field_parent) when 'geolocalization' update_db_post_field_geolocalization(db_post_field, content, post_field_parent) when 'image' update_db_post_field_image(db_post_field, content, post_field_parent) when 'gallery' update_db_post_field_gallery(db_post_field, content, post_field_parent) when 'youtube' update_db_post_field_youtube(db_post_field, content, post_field_parent) when 'composed' update_db_post_field_composed(db_post_field, content, post_field_parent) when 'relay' update_db_post_field_relay(db_post_field, content, post_field_parent) end end
ruby
def blog__update_db_post_field(db_post_field, content, post_field_parent = nil) # run minimum updates db_post_field.update( position: content[:position], meta_visible: true ) # run custom update for type case db_post_field.typology when 'text' update_db_post_field_text(db_post_field, content, post_field_parent) when 'textarea' update_db_post_field_textarea(db_post_field, content, post_field_parent) when 'datetime' update_db_post_field_datetime(db_post_field, content, post_field_parent) when 'editor' update_db_post_field_editor(db_post_field, content, post_field_parent) when 'geolocalization' update_db_post_field_geolocalization(db_post_field, content, post_field_parent) when 'image' update_db_post_field_image(db_post_field, content, post_field_parent) when 'gallery' update_db_post_field_gallery(db_post_field, content, post_field_parent) when 'youtube' update_db_post_field_youtube(db_post_field, content, post_field_parent) when 'composed' update_db_post_field_composed(db_post_field, content, post_field_parent) when 'relay' update_db_post_field_relay(db_post_field, content, post_field_parent) end end
[ "def", "blog__update_db_post_field", "(", "db_post_field", ",", "content", ",", "post_field_parent", "=", "nil", ")", "# run minimum updates", "db_post_field", ".", "update", "(", "position", ":", "content", "[", ":position", "]", ",", "meta_visible", ":", "true", ")", "# run custom update for type", "case", "db_post_field", ".", "typology", "when", "'text'", "update_db_post_field_text", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'textarea'", "update_db_post_field_textarea", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'datetime'", "update_db_post_field_datetime", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'editor'", "update_db_post_field_editor", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'geolocalization'", "update_db_post_field_geolocalization", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'image'", "update_db_post_field_image", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'gallery'", "update_db_post_field_gallery", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'youtube'", "update_db_post_field_youtube", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'composed'", "update_db_post_field_composed", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'relay'", "update_db_post_field_relay", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "end", "end" ]
This function update an existing post field on database with new content.
[ "This", "function", "update", "an", "existing", "post", "field", "on", "database", "with", "new", "content", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/fields.rb#L75-L104
8,321
westlakedesign/auth_net_receiver
app/models/auth_net_receiver/raw_transaction.rb
AuthNetReceiver.RawTransaction.json_data
def json_data begin return JSON.parse(self.data) rescue JSON::ParserError, TypeError => e logger.warn "Error while parsing raw transaction data: #{e.message}" return {} end end
ruby
def json_data begin return JSON.parse(self.data) rescue JSON::ParserError, TypeError => e logger.warn "Error while parsing raw transaction data: #{e.message}" return {} end end
[ "def", "json_data", "begin", "return", "JSON", ".", "parse", "(", "self", ".", "data", ")", "rescue", "JSON", "::", "ParserError", ",", "TypeError", "=>", "e", "logger", ".", "warn", "\"Error while parsing raw transaction data: #{e.message}\"", "return", "{", "}", "end", "end" ]
Return the JSON data on this record as a hash
[ "Return", "the", "JSON", "data", "on", "this", "record", "as", "a", "hash" ]
723887c2ce39d08431c676a72bf7dc3041b7f27e
https://github.com/westlakedesign/auth_net_receiver/blob/723887c2ce39d08431c676a72bf7dc3041b7f27e/app/models/auth_net_receiver/raw_transaction.rb#L29-L36
8,322
westlakedesign/auth_net_receiver
app/models/auth_net_receiver/raw_transaction.rb
AuthNetReceiver.RawTransaction.md5_hash_is_valid?
def md5_hash_is_valid?(json) if AuthNetReceiver.config.hash_value.nil? || AuthNetReceiver.config.gateway_login.nil? raise StandardError, 'AuthNetReceiver hash_value and gateway_login cannot be nil!' end parts = [] parts << AuthNetReceiver.config.hash_value parts << AuthNetReceiver.config.gateway_login if json['x_subscription_id'].blank? parts << json['x_trans_id'] parts << json['x_amount'] hash = Digest::MD5.hexdigest(parts.join()).upcase return hash == json['x_MD5_Hash'] end
ruby
def md5_hash_is_valid?(json) if AuthNetReceiver.config.hash_value.nil? || AuthNetReceiver.config.gateway_login.nil? raise StandardError, 'AuthNetReceiver hash_value and gateway_login cannot be nil!' end parts = [] parts << AuthNetReceiver.config.hash_value parts << AuthNetReceiver.config.gateway_login if json['x_subscription_id'].blank? parts << json['x_trans_id'] parts << json['x_amount'] hash = Digest::MD5.hexdigest(parts.join()).upcase return hash == json['x_MD5_Hash'] end
[ "def", "md5_hash_is_valid?", "(", "json", ")", "if", "AuthNetReceiver", ".", "config", ".", "hash_value", ".", "nil?", "||", "AuthNetReceiver", ".", "config", ".", "gateway_login", ".", "nil?", "raise", "StandardError", ",", "'AuthNetReceiver hash_value and gateway_login cannot be nil!'", "end", "parts", "=", "[", "]", "parts", "<<", "AuthNetReceiver", ".", "config", ".", "hash_value", "parts", "<<", "AuthNetReceiver", ".", "config", ".", "gateway_login", "if", "json", "[", "'x_subscription_id'", "]", ".", "blank?", "parts", "<<", "json", "[", "'x_trans_id'", "]", "parts", "<<", "json", "[", "'x_amount'", "]", "hash", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "parts", ".", "join", "(", ")", ")", ".", "upcase", "return", "hash", "==", "json", "[", "'x_MD5_Hash'", "]", "end" ]
Check that the x_MD5_Hash value matches our expectations The formula for the hash differs for subscription vs regular transactions. Regular transactions will be associated with the gateway ID that was used in the originating API call. Subscriptions however are ran on the server at later date, and therefore will not be associated to a gateway ID. * Subscriptions: MD5 Digest(AUTH_NET_HASH_VAL + TRANSACTION_ID + TRANSACTION_AMOUNT) * Other Transactions: MD5 Digest(AUTH_NET_HASH_VAL + GATEWAY_LOGIN + TRANSACTION_ID + TRANSACTION_AMOUNT)
[ "Check", "that", "the", "x_MD5_Hash", "value", "matches", "our", "expectations" ]
723887c2ce39d08431c676a72bf7dc3041b7f27e
https://github.com/westlakedesign/auth_net_receiver/blob/723887c2ce39d08431c676a72bf7dc3041b7f27e/app/models/auth_net_receiver/raw_transaction.rb#L78-L89
8,323
agios/simple_form-dojo
lib/simple_form-dojo/form_builder.rb
SimpleFormDojo.FormBuilder.button
def button(type, *args, &block) # set options to value if first arg is a Hash options = args.extract_options! button_type = 'dijit/form/Button' button_type = 'dojox/form/BusyButton' if options[:busy] options.reverse_merge!(:'data-dojo-type' => button_type) content = '' if value = options.delete(:value) content = value.html_safe else content = button_default_value end options.reverse_merge!({ :type => type, :value => content }) dojo_props = {} dojo_props.merge!(options[:dojo_html]) if options.include?(:dojo_html) options[:'data-dojo-props'] = SimpleFormDojo::FormBuilder.encode_as_dojo_props(dojo_props) options[:class] = "button #{options[:class]}".strip template.content_tag(:button, content, *(args << options), &block) end
ruby
def button(type, *args, &block) # set options to value if first arg is a Hash options = args.extract_options! button_type = 'dijit/form/Button' button_type = 'dojox/form/BusyButton' if options[:busy] options.reverse_merge!(:'data-dojo-type' => button_type) content = '' if value = options.delete(:value) content = value.html_safe else content = button_default_value end options.reverse_merge!({ :type => type, :value => content }) dojo_props = {} dojo_props.merge!(options[:dojo_html]) if options.include?(:dojo_html) options[:'data-dojo-props'] = SimpleFormDojo::FormBuilder.encode_as_dojo_props(dojo_props) options[:class] = "button #{options[:class]}".strip template.content_tag(:button, content, *(args << options), &block) end
[ "def", "button", "(", "type", ",", "*", "args", ",", "&", "block", ")", "# set options to value if first arg is a Hash", "options", "=", "args", ".", "extract_options!", "button_type", "=", "'dijit/form/Button'", "button_type", "=", "'dojox/form/BusyButton'", "if", "options", "[", ":busy", "]", "options", ".", "reverse_merge!", "(", ":'", "'", "=>", "button_type", ")", "content", "=", "''", "if", "value", "=", "options", ".", "delete", "(", ":value", ")", "content", "=", "value", ".", "html_safe", "else", "content", "=", "button_default_value", "end", "options", ".", "reverse_merge!", "(", "{", ":type", "=>", "type", ",", ":value", "=>", "content", "}", ")", "dojo_props", "=", "{", "}", "dojo_props", ".", "merge!", "(", "options", "[", ":dojo_html", "]", ")", "if", "options", ".", "include?", "(", ":dojo_html", ")", "options", "[", ":'", "'", "]", "=", "SimpleFormDojo", "::", "FormBuilder", ".", "encode_as_dojo_props", "(", "dojo_props", ")", "options", "[", ":class", "]", "=", "\"button #{options[:class]}\"", ".", "strip", "template", ".", "content_tag", "(", ":button", ",", "content", ",", "(", "args", "<<", "options", ")", ",", "block", ")", "end" ]
Simple override of initializer in order to add in the dojo_props attribute Creates a button overrides simple_form's button method dojo_form_for @user do |f| f.button :submit, :value => 'Save Me' end To use dojox/form/BusyButton, pass :busy => true dojo_form_for @uswer do |f| f.button :submit, :busy => true, :value => 'Save Me' end If :value doesn't exist, tries to determine the the value based on the current object
[ "Simple", "override", "of", "initializer", "in", "order", "to", "add", "in", "the", "dojo_props", "attribute", "Creates", "a", "button" ]
c4b134f56f4cb68cba81d583038965360c70fba4
https://github.com/agios/simple_form-dojo/blob/c4b134f56f4cb68cba81d583038965360c70fba4/lib/simple_form-dojo/form_builder.rb#L41-L59
8,324
agios/simple_form-dojo
lib/simple_form-dojo/form_builder.rb
SimpleFormDojo.FormBuilder.button_default_value
def button_default_value obj = object.respond_to?(:to_model) ? object.to_model : object key = obj ? (obj.persisted? ? :edit : :new) : :submit model = if obj.class.respond_to?(:model_name) obj.class.model_name.human else object_name.to_s.humanize end defaults = [] defaults << "helpers.submit.#{object_name}.#{key}" defaults << "#{key.to_s.humanize} #{model}" I18n.t(defaults.shift, :default => defaults) end
ruby
def button_default_value obj = object.respond_to?(:to_model) ? object.to_model : object key = obj ? (obj.persisted? ? :edit : :new) : :submit model = if obj.class.respond_to?(:model_name) obj.class.model_name.human else object_name.to_s.humanize end defaults = [] defaults << "helpers.submit.#{object_name}.#{key}" defaults << "#{key.to_s.humanize} #{model}" I18n.t(defaults.shift, :default => defaults) end
[ "def", "button_default_value", "obj", "=", "object", ".", "respond_to?", "(", ":to_model", ")", "?", "object", ".", "to_model", ":", "object", "key", "=", "obj", "?", "(", "obj", ".", "persisted?", "?", ":edit", ":", ":new", ")", ":", ":submit", "model", "=", "if", "obj", ".", "class", ".", "respond_to?", "(", ":model_name", ")", "obj", ".", "class", ".", "model_name", ".", "human", "else", "object_name", ".", "to_s", ".", "humanize", "end", "defaults", "=", "[", "]", "defaults", "<<", "\"helpers.submit.#{object_name}.#{key}\"", "defaults", "<<", "\"#{key.to_s.humanize} #{model}\"", "I18n", ".", "t", "(", "defaults", ".", "shift", ",", ":default", "=>", "defaults", ")", "end" ]
Basically the same as rails submit_default_value
[ "Basically", "the", "same", "as", "rails", "submit_default_value" ]
c4b134f56f4cb68cba81d583038965360c70fba4
https://github.com/agios/simple_form-dojo/blob/c4b134f56f4cb68cba81d583038965360c70fba4/lib/simple_form-dojo/form_builder.rb#L62-L76
8,325
LAS-IT/open_directory_utils
lib/open_directory_utils/connection.rb
OpenDirectoryUtils.Connection.run
def run(command:, params:, output: nil) answer = {} params[:format] = output # just in case clear record_name and calculate later params[:record_name] = nil ssh_cmds = send(command, params, dir_info) # pp ssh_cmds results = send_cmds_to_od_server(ssh_cmds) # pp results answer = process_results(results, command, params, ssh_cmds ) params[:value] = nil return answer rescue ArgumentError, NoMethodError => error format_results(error.message, command, params, ssh_cmds, 'error') end
ruby
def run(command:, params:, output: nil) answer = {} params[:format] = output # just in case clear record_name and calculate later params[:record_name] = nil ssh_cmds = send(command, params, dir_info) # pp ssh_cmds results = send_cmds_to_od_server(ssh_cmds) # pp results answer = process_results(results, command, params, ssh_cmds ) params[:value] = nil return answer rescue ArgumentError, NoMethodError => error format_results(error.message, command, params, ssh_cmds, 'error') end
[ "def", "run", "(", "command", ":", ",", "params", ":", ",", "output", ":", "nil", ")", "answer", "=", "{", "}", "params", "[", ":format", "]", "=", "output", "# just in case clear record_name and calculate later", "params", "[", ":record_name", "]", "=", "nil", "ssh_cmds", "=", "send", "(", "command", ",", "params", ",", "dir_info", ")", "# pp ssh_cmds", "results", "=", "send_cmds_to_od_server", "(", "ssh_cmds", ")", "# pp results", "answer", "=", "process_results", "(", "results", ",", "command", ",", "params", ",", "ssh_cmds", ")", "params", "[", ":value", "]", "=", "nil", "return", "answer", "rescue", "ArgumentError", ",", "NoMethodError", "=>", "error", "format_results", "(", "error", ".", "message", ",", "command", ",", "params", ",", "ssh_cmds", ",", "'error'", ")", "end" ]
after configuring a connection with .new - send commands via ssh to open directory @command [Symbol] - required -- to choose the action wanted @params [Hash] - required -- necessary information to accomplish action @output [String] - optional -- 'xml' or 'plist' will return responses using xml format response [Hash] - { response: results, status: status, command: command, attributes: params, dscl_cmds: ssh_clean }
[ "after", "configuring", "a", "connection", "with", ".", "new", "-", "send", "commands", "via", "ssh", "to", "open", "directory" ]
dd29b04728fa261c755577af066c9f817642998a
https://github.com/LAS-IT/open_directory_utils/blob/dd29b04728fa261c755577af066c9f817642998a/lib/open_directory_utils/connection.rb#L50-L64
8,326
octoai/gem-octocore-mongo
lib/octocore-mongo/counter.rb
Octo.Counter.local_count
def local_count(duration, type) aggr = {} Octo::Enterprise.each do |enterprise| args = { enterprise_id: enterprise.id, ts: duration, type: type } aggr[enterprise.id.to_s] = {} unless aggr.has_key?(enterprise.id.to_s) results = where(args) results_group = results.group_by { |x| x.uid } results_group.each do |uid, counters| _sum = counters.inject(0) do |sum, counter| sum + counter.count end aggr[enterprise.id.to_s][uid] = _sum end end aggr end
ruby
def local_count(duration, type) aggr = {} Octo::Enterprise.each do |enterprise| args = { enterprise_id: enterprise.id, ts: duration, type: type } aggr[enterprise.id.to_s] = {} unless aggr.has_key?(enterprise.id.to_s) results = where(args) results_group = results.group_by { |x| x.uid } results_group.each do |uid, counters| _sum = counters.inject(0) do |sum, counter| sum + counter.count end aggr[enterprise.id.to_s][uid] = _sum end end aggr end
[ "def", "local_count", "(", "duration", ",", "type", ")", "aggr", "=", "{", "}", "Octo", "::", "Enterprise", ".", "each", "do", "|", "enterprise", "|", "args", "=", "{", "enterprise_id", ":", "enterprise", ".", "id", ",", "ts", ":", "duration", ",", "type", ":", "type", "}", "aggr", "[", "enterprise", ".", "id", ".", "to_s", "]", "=", "{", "}", "unless", "aggr", ".", "has_key?", "(", "enterprise", ".", "id", ".", "to_s", ")", "results", "=", "where", "(", "args", ")", "results_group", "=", "results", ".", "group_by", "{", "|", "x", "|", "x", ".", "uid", "}", "results_group", ".", "each", "do", "|", "uid", ",", "counters", "|", "_sum", "=", "counters", ".", "inject", "(", "0", ")", "do", "|", "sum", ",", "counter", "|", "sum", "+", "counter", ".", "count", "end", "aggr", "[", "enterprise", ".", "id", ".", "to_s", "]", "[", "uid", "]", "=", "_sum", "end", "end", "aggr", "end" ]
Does the counting from DB. Unlike the other counter that uses Redis. Hence the name local_count @param [Time] duration A time/time range object @param [Fixnum] type The type of counter to look for
[ "Does", "the", "counting", "from", "DB", ".", "Unlike", "the", "other", "counter", "that", "uses", "Redis", ".", "Hence", "the", "name", "local_count" ]
bf7fa833fd7e08947697d0341ab5e80e89c8d05a
https://github.com/octoai/gem-octocore-mongo/blob/bf7fa833fd7e08947697d0341ab5e80e89c8d05a/lib/octocore-mongo/counter.rb#L128-L147
8,327
jarrett/ichiban
lib/ichiban/scripts.rb
Ichiban.ScriptRunner.script_file_changed
def script_file_changed(path) Ichiban.logger.script_run(path) script = Ichiban::Script.new(path).run end
ruby
def script_file_changed(path) Ichiban.logger.script_run(path) script = Ichiban::Script.new(path).run end
[ "def", "script_file_changed", "(", "path", ")", "Ichiban", ".", "logger", ".", "script_run", "(", "path", ")", "script", "=", "Ichiban", "::", "Script", ".", "new", "(", "path", ")", ".", "run", "end" ]
Takes an absolute path
[ "Takes", "an", "absolute", "path" ]
310f96b0981ea19bf01246995f3732c986915d5b
https://github.com/jarrett/ichiban/blob/310f96b0981ea19bf01246995f3732c986915d5b/lib/ichiban/scripts.rb#L8-L11
8,328
aub/tumble
lib/tumble/blog.rb
Tumble.Blog.reblog_post
def reblog_post(id, reblog_key, options={}) @connection.post("/blog/#{name}/post/reblog", options.merge('id' => id, 'reblog_key' => reblog_key)).response end
ruby
def reblog_post(id, reblog_key, options={}) @connection.post("/blog/#{name}/post/reblog", options.merge('id' => id, 'reblog_key' => reblog_key)).response end
[ "def", "reblog_post", "(", "id", ",", "reblog_key", ",", "options", "=", "{", "}", ")", "@connection", ".", "post", "(", "\"/blog/#{name}/post/reblog\"", ",", "options", ".", "merge", "(", "'id'", "=>", "id", ",", "'reblog_key'", "=>", "reblog_key", ")", ")", ".", "response", "end" ]
Reblog a Post @see http://www.tumblr.com/docs/en/api/v2#reblogging @requires_authentication Yes @param id [Integer] The ID of the reblogged post on tumblelog @param reblog_key [Integer] The reblog key for the reblogged post – get the reblog key with a /posts request @param options [Hash] A customizable set of options @option options [String] :comment A comment added to the reblogged post
[ "Reblog", "a", "Post" ]
dad342fabd2dfc30031d94392927f3fe86953cc1
https://github.com/aub/tumble/blob/dad342fabd2dfc30031d94392927f3fe86953cc1/lib/tumble/blog.rb#L181-L183
8,329
pwnall/file_blobs_rails
lib/file_blobs_rails/active_record_migration_extensions.rb
FileBlobs.ActiveRecordMigrationExtensions.create_file_blobs_table
def create_file_blobs_table(table_name = :file_blobs, options = {}, &block) blob_limit = options[:blob_limit] || 1.megabyte create_table table_name, id: false do |t| t.primary_key :id, :string, null: false, limit: 48 t.binary :data, null: false, limit: blob_limit # Block capturing and calling is a bit slower than using yield. This is # not a concern because migrations aren't run in tight loops. block.call t end end
ruby
def create_file_blobs_table(table_name = :file_blobs, options = {}, &block) blob_limit = options[:blob_limit] || 1.megabyte create_table table_name, id: false do |t| t.primary_key :id, :string, null: false, limit: 48 t.binary :data, null: false, limit: blob_limit # Block capturing and calling is a bit slower than using yield. This is # not a concern because migrations aren't run in tight loops. block.call t end end
[ "def", "create_file_blobs_table", "(", "table_name", "=", ":file_blobs", ",", "options", "=", "{", "}", ",", "&", "block", ")", "blob_limit", "=", "options", "[", ":blob_limit", "]", "||", "1", ".", "megabyte", "create_table", "table_name", ",", "id", ":", "false", "do", "|", "t", "|", "t", ".", "primary_key", ":id", ",", ":string", ",", "null", ":", "false", ",", "limit", ":", "48", "t", ".", "binary", ":data", ",", "null", ":", "false", ",", "limit", ":", "blob_limit", "# Block capturing and calling is a bit slower than using yield. This is", "# not a concern because migrations aren't run in tight loops.", "block", ".", "call", "t", "end", "end" ]
Creates the table used to hold file blobs. @param [Symbol] table_name the name of the table used to hold file data @param [Hash<Symbol, Object>] options @option options [Integer] blob_limit the maximum file size that can be stored in the table; defaults to 1 megabyte
[ "Creates", "the", "table", "used", "to", "hold", "file", "blobs", "." ]
688d43ec8547856f3572b0e6716e6faeff56345b
https://github.com/pwnall/file_blobs_rails/blob/688d43ec8547856f3572b0e6716e6faeff56345b/lib/file_blobs_rails/active_record_migration_extensions.rb#L13-L24
8,330
culturecode/s3_asset
lib/s3_asset/acts_as_s3_asset.rb
S3Asset.ActsAsS3Asset.crop_resized
def crop_resized(image, size, gravity = "Center") size =~ /(\d+)x(\d+)/ width = $1.to_i height = $2.to_i # Grab the width and height of the current image in one go. cols, rows = image[:dimensions] # Only do anything if needs be. Who knows, maybe it's already the exact # dimensions we're looking for. if(width != cols && height != rows) image.combine_options do |c| # Scale the image down to the widest dimension. if(width != cols || height != rows) scale = [width / cols.to_f, height / rows.to_f].max * 100 c.resize("#{scale}%") end # Align how things will be cropped. c.gravity(gravity) # Crop the image to size. c.crop("#{width}x#{height}+0+0") end end end
ruby
def crop_resized(image, size, gravity = "Center") size =~ /(\d+)x(\d+)/ width = $1.to_i height = $2.to_i # Grab the width and height of the current image in one go. cols, rows = image[:dimensions] # Only do anything if needs be. Who knows, maybe it's already the exact # dimensions we're looking for. if(width != cols && height != rows) image.combine_options do |c| # Scale the image down to the widest dimension. if(width != cols || height != rows) scale = [width / cols.to_f, height / rows.to_f].max * 100 c.resize("#{scale}%") end # Align how things will be cropped. c.gravity(gravity) # Crop the image to size. c.crop("#{width}x#{height}+0+0") end end end
[ "def", "crop_resized", "(", "image", ",", "size", ",", "gravity", "=", "\"Center\"", ")", "size", "=~", "/", "\\d", "\\d", "/", "width", "=", "$1", ".", "to_i", "height", "=", "$2", ".", "to_i", "# Grab the width and height of the current image in one go.", "cols", ",", "rows", "=", "image", "[", ":dimensions", "]", "# Only do anything if needs be. Who knows, maybe it's already the exact", "# dimensions we're looking for.", "if", "(", "width", "!=", "cols", "&&", "height", "!=", "rows", ")", "image", ".", "combine_options", "do", "|", "c", "|", "# Scale the image down to the widest dimension.", "if", "(", "width", "!=", "cols", "||", "height", "!=", "rows", ")", "scale", "=", "[", "width", "/", "cols", ".", "to_f", ",", "height", "/", "rows", ".", "to_f", "]", ".", "max", "*", "100", "c", ".", "resize", "(", "\"#{scale}%\"", ")", "end", "# Align how things will be cropped.", "c", ".", "gravity", "(", "gravity", ")", "# Crop the image to size.", "c", ".", "crop", "(", "\"#{width}x#{height}+0+0\"", ")", "end", "end", "end" ]
Scale an image down and crop away any extra to achieve a certain size. This is handy for creating thumbnails of the same dimensions without changing the aspect ratio.
[ "Scale", "an", "image", "down", "and", "crop", "away", "any", "extra", "to", "achieve", "a", "certain", "size", ".", "This", "is", "handy", "for", "creating", "thumbnails", "of", "the", "same", "dimensions", "without", "changing", "the", "aspect", "ratio", "." ]
9db578f316e110592ac47f0371214c3daf58f55f
https://github.com/culturecode/s3_asset/blob/9db578f316e110592ac47f0371214c3daf58f55f/lib/s3_asset/acts_as_s3_asset.rb#L183-L208
8,331
megamsys/megam_api
lib/megam/core/rest_adapter.rb
Megam.RestAdapter.megam_rest
def megam_rest options = { :email => email, :api_key => api_key, :org_id => org_id, :password_hash => password_hash, :master_key => master_key, :host => host } if headers options[:headers] = headers end Megam::API.new(options) end
ruby
def megam_rest options = { :email => email, :api_key => api_key, :org_id => org_id, :password_hash => password_hash, :master_key => master_key, :host => host } if headers options[:headers] = headers end Megam::API.new(options) end
[ "def", "megam_rest", "options", "=", "{", ":email", "=>", "email", ",", ":api_key", "=>", "api_key", ",", ":org_id", "=>", "org_id", ",", ":password_hash", "=>", "password_hash", ",", ":master_key", "=>", "master_key", ",", ":host", "=>", "host", "}", "if", "headers", "options", "[", ":headers", "]", "=", "headers", "end", "Megam", "::", "API", ".", "new", "(", "options", ")", "end" ]
clean up this module later. Build a megam api client === Parameters api:: The Megam::API client
[ "clean", "up", "this", "module", "later", ".", "Build", "a", "megam", "api", "client" ]
c28e743311706dfef9c7745ae64058a468f5b1a4
https://github.com/megamsys/megam_api/blob/c28e743311706dfef9c7745ae64058a468f5b1a4/lib/megam/core/rest_adapter.rb#L29-L42
8,332
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.add_attribute
def add_attribute(name, type, metadata={}) attr_reader name attributes << (metadata || {}).merge(:name => name.to_sym, :type => type.to_sym) end
ruby
def add_attribute(name, type, metadata={}) attr_reader name attributes << (metadata || {}).merge(:name => name.to_sym, :type => type.to_sym) end
[ "def", "add_attribute", "(", "name", ",", "type", ",", "metadata", "=", "{", "}", ")", "attr_reader", "name", "attributes", "<<", "(", "metadata", "||", "{", "}", ")", ".", "merge", "(", ":name", "=>", "name", ".", "to_sym", ",", ":type", "=>", "type", ".", "to_sym", ")", "end" ]
Attribute macros Defines an attribute @param [String] name The name of the attribute @param [Symbol] type The type of the attribute @param [Hash{Symbol => Object}] metadata The metadata for the attribute
[ "Attribute", "macros", "Defines", "an", "attribute" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L80-L83
8,333
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.string
def string(attr, metadata={}) add_attribute(attr, :string, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : arg.to_s) end end
ruby
def string(attr, metadata={}) add_attribute(attr, :string, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : arg.to_s) end end
[ "def", "string", "(", "attr", ",", "metadata", "=", "{", "}", ")", "add_attribute", "(", "attr", ",", ":string", ",", "metadata", ")", "define_method", "(", "\"#{attr}=\"", ")", "do", "|", "arg", "|", "instance_variable_set", "(", "\"@#{attr}\"", ",", "arg", ".", "nil?", "?", "nil", ":", "arg", ".", "to_s", ")", "end", "end" ]
Defines a string attribute @param [Symbol] attr The name of the attribute @param [Hash{Symbol => Object}] metadata The metadata for the attribute
[ "Defines", "a", "string", "attribute" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L89-L94
8,334
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.boolean
def boolean(attr, metadata={}) add_attribute(attr, :boolean, metadata) define_method("#{attr}=") do |arg| v = case arg when String then BOOLEAN_TRUE_STRINGS.include?(arg.downcase) when Numeric then arg == 1 when nil then nil else !!arg end instance_variable_set("@#{attr}", v) end alias_method "#{attr}?", attr end
ruby
def boolean(attr, metadata={}) add_attribute(attr, :boolean, metadata) define_method("#{attr}=") do |arg| v = case arg when String then BOOLEAN_TRUE_STRINGS.include?(arg.downcase) when Numeric then arg == 1 when nil then nil else !!arg end instance_variable_set("@#{attr}", v) end alias_method "#{attr}?", attr end
[ "def", "boolean", "(", "attr", ",", "metadata", "=", "{", "}", ")", "add_attribute", "(", "attr", ",", ":boolean", ",", "metadata", ")", "define_method", "(", "\"#{attr}=\"", ")", "do", "|", "arg", "|", "v", "=", "case", "arg", "when", "String", "then", "BOOLEAN_TRUE_STRINGS", ".", "include?", "(", "arg", ".", "downcase", ")", "when", "Numeric", "then", "arg", "==", "1", "when", "nil", "then", "nil", "else", "!", "!", "arg", "end", "instance_variable_set", "(", "\"@#{attr}\"", ",", "v", ")", "end", "alias_method", "\"#{attr}?\"", ",", "attr", "end" ]
Defines a boolean attribute @param [Symbol] attr The name of the attribute @param [Hash{Symbol => Object}] metadata The metadata for the attribute
[ "Defines", "a", "boolean", "attribute" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L100-L112
8,335
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.integer
def integer(attr, metadata={}) add_attribute(attr, :integer, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : arg.to_i) end end
ruby
def integer(attr, metadata={}) add_attribute(attr, :integer, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : arg.to_i) end end
[ "def", "integer", "(", "attr", ",", "metadata", "=", "{", "}", ")", "add_attribute", "(", "attr", ",", ":integer", ",", "metadata", ")", "define_method", "(", "\"#{attr}=\"", ")", "do", "|", "arg", "|", "instance_variable_set", "(", "\"@#{attr}\"", ",", "arg", ".", "nil?", "?", "nil", ":", "arg", ".", "to_i", ")", "end", "end" ]
Defines a integer attribute @param [Symbol] attr The name of the attribute @param [Hash{Symbol => Object}] metadata The metadata for the attribute
[ "Defines", "a", "integer", "attribute" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L118-L123
8,336
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.float
def float(attr, metadata={}) add_attribute(attr, :float, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : arg.to_f) end end
ruby
def float(attr, metadata={}) add_attribute(attr, :float, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : arg.to_f) end end
[ "def", "float", "(", "attr", ",", "metadata", "=", "{", "}", ")", "add_attribute", "(", "attr", ",", ":float", ",", "metadata", ")", "define_method", "(", "\"#{attr}=\"", ")", "do", "|", "arg", "|", "instance_variable_set", "(", "\"@#{attr}\"", ",", "arg", ".", "nil?", "?", "nil", ":", "arg", ".", "to_f", ")", "end", "end" ]
Defines a float attribute @param [Symbol] attr The name of the attribute @param [Hash{Symbol => Object}] metadata The metadata for the attribute
[ "Defines", "a", "float", "attribute" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L129-L134
8,337
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.decimal
def decimal(attr, metadata={}) add_attribute(attr, :decimal, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : BigDecimal.new(arg.to_s)) end end
ruby
def decimal(attr, metadata={}) add_attribute(attr, :decimal, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : BigDecimal.new(arg.to_s)) end end
[ "def", "decimal", "(", "attr", ",", "metadata", "=", "{", "}", ")", "add_attribute", "(", "attr", ",", ":decimal", ",", "metadata", ")", "define_method", "(", "\"#{attr}=\"", ")", "do", "|", "arg", "|", "instance_variable_set", "(", "\"@#{attr}\"", ",", "arg", ".", "nil?", "?", "nil", ":", "BigDecimal", ".", "new", "(", "arg", ".", "to_s", ")", ")", "end", "end" ]
Defines a decimal attribute @param [Symbol] attr The name of the attribute @param [Hash{Symbol => Object}] metadata The metadata for the attribute
[ "Defines", "a", "decimal", "attribute" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L140-L145
8,338
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.date
def date(attr, metadata={}) add_attribute(attr, :date, metadata) define_method("#{attr}=") do |arg| v = case arg when Date then arg when Time, DateTime then arg.to_date when String then Date.parse(arg) when Hash args = Util.extract_values(arg, :year, :month, :day) args.present? ? Date.new(*args.map(&:to_i)) : nil when nil then nil else raise ArgumentError.new("can't convert #{arg.class} to Date") end instance_variable_set("@#{attr}", v) end end
ruby
def date(attr, metadata={}) add_attribute(attr, :date, metadata) define_method("#{attr}=") do |arg| v = case arg when Date then arg when Time, DateTime then arg.to_date when String then Date.parse(arg) when Hash args = Util.extract_values(arg, :year, :month, :day) args.present? ? Date.new(*args.map(&:to_i)) : nil when nil then nil else raise ArgumentError.new("can't convert #{arg.class} to Date") end instance_variable_set("@#{attr}", v) end end
[ "def", "date", "(", "attr", ",", "metadata", "=", "{", "}", ")", "add_attribute", "(", "attr", ",", ":date", ",", "metadata", ")", "define_method", "(", "\"#{attr}=\"", ")", "do", "|", "arg", "|", "v", "=", "case", "arg", "when", "Date", "then", "arg", "when", "Time", ",", "DateTime", "then", "arg", ".", "to_date", "when", "String", "then", "Date", ".", "parse", "(", "arg", ")", "when", "Hash", "args", "=", "Util", ".", "extract_values", "(", "arg", ",", ":year", ",", ":month", ",", ":day", ")", "args", ".", "present?", "?", "Date", ".", "new", "(", "args", ".", "map", "(", ":to_i", ")", ")", ":", "nil", "when", "nil", "then", "nil", "else", "raise", "ArgumentError", ".", "new", "(", "\"can't convert #{arg.class} to Date\"", ")", "end", "instance_variable_set", "(", "\"@#{attr}\"", ",", "v", ")", "end", "end" ]
Defines a date attribute @param [Symbol] attr The name of the attribute @param [Hash{Symbol => Object}] metadata The metadata for the attribute
[ "Defines", "a", "date", "attribute" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L151-L166
8,339
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.array
def array(attr, metadata={}) add_attribute(attr, :array, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", Array(arg)) end end
ruby
def array(attr, metadata={}) add_attribute(attr, :array, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", Array(arg)) end end
[ "def", "array", "(", "attr", ",", "metadata", "=", "{", "}", ")", "add_attribute", "(", "attr", ",", ":array", ",", "metadata", ")", "define_method", "(", "\"#{attr}=\"", ")", "do", "|", "arg", "|", "instance_variable_set", "(", "\"@#{attr}\"", ",", "Array", "(", "arg", ")", ")", "end", "end" ]
Defines an array attribute @param [Symbol] attr The name of the attribute @param [Hash{Symbol => Object}] metadata The metadata for the attribute
[ "Defines", "an", "array", "attribute" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L204-L209
8,340
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.add_association
def add_association(name, type, metadata={}) associations << (metadata || {}).merge(:name => name.to_sym, :type => type.to_sym) end
ruby
def add_association(name, type, metadata={}) associations << (metadata || {}).merge(:name => name.to_sym, :type => type.to_sym) end
[ "def", "add_association", "(", "name", ",", "type", ",", "metadata", "=", "{", "}", ")", "associations", "<<", "(", "metadata", "||", "{", "}", ")", ".", "merge", "(", ":name", "=>", "name", ".", "to_sym", ",", ":type", "=>", "type", ".", "to_sym", ")", "end" ]
Defines an association @param [String] name The name of the association @param [Symbol] type The type of the association @param [Hash{Symbol => Object}] metadata The metadata for the association
[ "Defines", "an", "association" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L239-L241
8,341
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.has_many
def has_many(association_name, metadata={}) add_association association_name, :has_many, metadata association_class_name = metadata.try(:fetch, :class_name, [name.split('::')[0..-2].join('::'), association_name.to_s.classify].reject(&:blank?).join('::')) # foos define_method(association_name) do |*query| association_class = association_class_name.constantize # TODO: Support a more generic version of lazy-loading if query.empty? # Ex: Books.all, so we want to cache it. ivar = "@#{association_name}" if instance_variable_defined?(ivar) instance_variable_get(ivar) elsif self.class.autoload_associations? && association_class.respond_to?(:all) instance_variable_set(ivar, Array(association_class.all("#{self.class.name.underscore}_id" => id))) else [] end else # Ex: Book.all(:name => "The..."), so we do not want to cache it if self.class.autoload_associations? && association_class.respond_to?(:all) Array(association_class.all({"#{self.class.name.demodulize.underscore}_id" => id}.merge(query.first))) end end end # foos= define_method("#{association_name}=") do |arg| association_class = association_class_name.constantize attr_name = self.class.name.demodulize.underscore objs = (arg.is_a?(Hash) ? arg.values : Array(arg)).map do |obj| o = association_class.cast(obj) if o.respond_to?("#{attr_name}=") o.send("#{attr_name}=", self) end if o.respond_to?("#{attr_name}_id=") && respond_to?(:id) o.send("#{attr_name}_id=", id) end o end instance_variable_set("@#{association_name}", objs) end end
ruby
def has_many(association_name, metadata={}) add_association association_name, :has_many, metadata association_class_name = metadata.try(:fetch, :class_name, [name.split('::')[0..-2].join('::'), association_name.to_s.classify].reject(&:blank?).join('::')) # foos define_method(association_name) do |*query| association_class = association_class_name.constantize # TODO: Support a more generic version of lazy-loading if query.empty? # Ex: Books.all, so we want to cache it. ivar = "@#{association_name}" if instance_variable_defined?(ivar) instance_variable_get(ivar) elsif self.class.autoload_associations? && association_class.respond_to?(:all) instance_variable_set(ivar, Array(association_class.all("#{self.class.name.underscore}_id" => id))) else [] end else # Ex: Book.all(:name => "The..."), so we do not want to cache it if self.class.autoload_associations? && association_class.respond_to?(:all) Array(association_class.all({"#{self.class.name.demodulize.underscore}_id" => id}.merge(query.first))) end end end # foos= define_method("#{association_name}=") do |arg| association_class = association_class_name.constantize attr_name = self.class.name.demodulize.underscore objs = (arg.is_a?(Hash) ? arg.values : Array(arg)).map do |obj| o = association_class.cast(obj) if o.respond_to?("#{attr_name}=") o.send("#{attr_name}=", self) end if o.respond_to?("#{attr_name}_id=") && respond_to?(:id) o.send("#{attr_name}_id=", id) end o end instance_variable_set("@#{association_name}", objs) end end
[ "def", "has_many", "(", "association_name", ",", "metadata", "=", "{", "}", ")", "add_association", "association_name", ",", ":has_many", ",", "metadata", "association_class_name", "=", "metadata", ".", "try", "(", ":fetch", ",", ":class_name", ",", "[", "name", ".", "split", "(", "'::'", ")", "[", "0", "..", "-", "2", "]", ".", "join", "(", "'::'", ")", ",", "association_name", ".", "to_s", ".", "classify", "]", ".", "reject", "(", ":blank?", ")", ".", "join", "(", "'::'", ")", ")", "# foos", "define_method", "(", "association_name", ")", "do", "|", "*", "query", "|", "association_class", "=", "association_class_name", ".", "constantize", "# TODO: Support a more generic version of lazy-loading", "if", "query", ".", "empty?", "# Ex: Books.all, so we want to cache it.", "ivar", "=", "\"@#{association_name}\"", "if", "instance_variable_defined?", "(", "ivar", ")", "instance_variable_get", "(", "ivar", ")", "elsif", "self", ".", "class", ".", "autoload_associations?", "&&", "association_class", ".", "respond_to?", "(", ":all", ")", "instance_variable_set", "(", "ivar", ",", "Array", "(", "association_class", ".", "all", "(", "\"#{self.class.name.underscore}_id\"", "=>", "id", ")", ")", ")", "else", "[", "]", "end", "else", "# Ex: Book.all(:name => \"The...\"), so we do not want to cache it", "if", "self", ".", "class", ".", "autoload_associations?", "&&", "association_class", ".", "respond_to?", "(", ":all", ")", "Array", "(", "association_class", ".", "all", "(", "{", "\"#{self.class.name.demodulize.underscore}_id\"", "=>", "id", "}", ".", "merge", "(", "query", ".", "first", ")", ")", ")", "end", "end", "end", "# foos=", "define_method", "(", "\"#{association_name}=\"", ")", "do", "|", "arg", "|", "association_class", "=", "association_class_name", ".", "constantize", "attr_name", "=", "self", ".", "class", ".", "name", ".", "demodulize", ".", "underscore", "objs", "=", "(", "arg", ".", "is_a?", "(", "Hash", ")", "?", "arg", ".", "values", ":", "Array", "(", "arg", ")", ")", ".", "map", "do", "|", "obj", "|", "o", "=", "association_class", ".", "cast", "(", "obj", ")", "if", "o", ".", "respond_to?", "(", "\"#{attr_name}=\"", ")", "o", ".", "send", "(", "\"#{attr_name}=\"", ",", "self", ")", "end", "if", "o", ".", "respond_to?", "(", "\"#{attr_name}_id=\"", ")", "&&", "respond_to?", "(", ":id", ")", "o", ".", "send", "(", "\"#{attr_name}_id=\"", ",", "id", ")", "end", "o", "end", "instance_variable_set", "(", "\"@#{association_name}\"", ",", "objs", ")", "end", "end" ]
Defines an association that is a reference to an Array of another Attribution class. @param [Symbol] association_name The name of the association @param [Hash] metadata Extra information about the association. @option metadata [String] :class_name Class of the association, defaults to a class name based on the association name
[ "Defines", "an", "association", "that", "is", "a", "reference", "to", "an", "Array", "of", "another", "Attribution", "class", "." ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L326-L373
8,342
sinsoku/ponytail
lib/ponytail/config.rb
Ponytail.Configuration.update_schema
def update_schema config.update_schema = config.update_schema.call if config.update_schema.respond_to?(:call) config.update_schema end
ruby
def update_schema config.update_schema = config.update_schema.call if config.update_schema.respond_to?(:call) config.update_schema end
[ "def", "update_schema", "config", ".", "update_schema", "=", "config", ".", "update_schema", ".", "call", "if", "config", ".", "update_schema", ".", "respond_to?", "(", ":call", ")", "config", ".", "update_schema", "end" ]
for lazy load
[ "for", "lazy", "load" ]
0025018a9e0531df3aa04cee7bcc8318c605ae21
https://github.com/sinsoku/ponytail/blob/0025018a9e0531df3aa04cee7bcc8318c605ae21/lib/ponytail/config.rb#L28-L31
8,343
jeffwilliams/quartz-flow
lib/quartz_flow/wrappers.rb
QuartzTorrent.TorrentDataDelegate.to_h
def to_h result = {} ## Extra fields added by this method: # Length of the torrent result[:dataLength] = @info ? @info.dataLength : 0 # Percent complete pct = withCurrentAndTotalBytes{ |cur, total| (cur.to_f / total.to_f * 100.0).round 1 } result[:percentComplete] = pct # Time left secondsLeft = withCurrentAndTotalBytes do |cur, total| if @downloadRateDataOnly && @downloadRateDataOnly > 0 (total.to_f - cur.to_f) / @downloadRateDataOnly else 0 end end # Cap estimated time at 9999 hours secondsLeft = 35996400 if secondsLeft > 35996400 result[:timeLeft] = Formatter.formatTime(secondsLeft) ## Regular fields result[:info] = @info ? @info.to_h : nil result[:infoHash] = @infoHash result[:recommendedName] = @recommendedName result[:downloadRate] = @downloadRate result[:uploadRate] = @uploadRate result[:downloadRateDataOnly] = @downloadRateDataOnly result[:uploadRateDataOnly] = @uploadRateDataOnly result[:completedBytes] = @completedBytes result[:peers] = @peers.collect{ |p| p.to_h } result[:state] = @state #result[:completePieceBitfield] = @completePieceBitfield result[:metainfoLength] = @metainfoLength result[:metainfoCompletedLength] = @metainfoCompletedLength result[:paused] = @paused result[:queued] = @queued result[:uploadRateLimit] = @uploadRateLimit result[:downloadRateLimit] = @downloadRateLimit result[:ratio] = @ratio result[:uploadDuration] = @uploadDuration result[:bytesUploaded] = @bytesUploaded result[:bytesDownloaded] = @bytesDownloaded result[:alarms] = @alarms.collect{ |a| a.to_h } result end
ruby
def to_h result = {} ## Extra fields added by this method: # Length of the torrent result[:dataLength] = @info ? @info.dataLength : 0 # Percent complete pct = withCurrentAndTotalBytes{ |cur, total| (cur.to_f / total.to_f * 100.0).round 1 } result[:percentComplete] = pct # Time left secondsLeft = withCurrentAndTotalBytes do |cur, total| if @downloadRateDataOnly && @downloadRateDataOnly > 0 (total.to_f - cur.to_f) / @downloadRateDataOnly else 0 end end # Cap estimated time at 9999 hours secondsLeft = 35996400 if secondsLeft > 35996400 result[:timeLeft] = Formatter.formatTime(secondsLeft) ## Regular fields result[:info] = @info ? @info.to_h : nil result[:infoHash] = @infoHash result[:recommendedName] = @recommendedName result[:downloadRate] = @downloadRate result[:uploadRate] = @uploadRate result[:downloadRateDataOnly] = @downloadRateDataOnly result[:uploadRateDataOnly] = @uploadRateDataOnly result[:completedBytes] = @completedBytes result[:peers] = @peers.collect{ |p| p.to_h } result[:state] = @state #result[:completePieceBitfield] = @completePieceBitfield result[:metainfoLength] = @metainfoLength result[:metainfoCompletedLength] = @metainfoCompletedLength result[:paused] = @paused result[:queued] = @queued result[:uploadRateLimit] = @uploadRateLimit result[:downloadRateLimit] = @downloadRateLimit result[:ratio] = @ratio result[:uploadDuration] = @uploadDuration result[:bytesUploaded] = @bytesUploaded result[:bytesDownloaded] = @bytesDownloaded result[:alarms] = @alarms.collect{ |a| a.to_h } result end
[ "def", "to_h", "result", "=", "{", "}", "## Extra fields added by this method:", "# Length of the torrent", "result", "[", ":dataLength", "]", "=", "@info", "?", "@info", ".", "dataLength", ":", "0", "# Percent complete", "pct", "=", "withCurrentAndTotalBytes", "{", "|", "cur", ",", "total", "|", "(", "cur", ".", "to_f", "/", "total", ".", "to_f", "*", "100.0", ")", ".", "round", "1", "}", "result", "[", ":percentComplete", "]", "=", "pct", "# Time left", "secondsLeft", "=", "withCurrentAndTotalBytes", "do", "|", "cur", ",", "total", "|", "if", "@downloadRateDataOnly", "&&", "@downloadRateDataOnly", ">", "0", "(", "total", ".", "to_f", "-", "cur", ".", "to_f", ")", "/", "@downloadRateDataOnly", "else", "0", "end", "end", "# Cap estimated time at 9999 hours", "secondsLeft", "=", "35996400", "if", "secondsLeft", ">", "35996400", "result", "[", ":timeLeft", "]", "=", "Formatter", ".", "formatTime", "(", "secondsLeft", ")", "## Regular fields", "result", "[", ":info", "]", "=", "@info", "?", "@info", ".", "to_h", ":", "nil", "result", "[", ":infoHash", "]", "=", "@infoHash", "result", "[", ":recommendedName", "]", "=", "@recommendedName", "result", "[", ":downloadRate", "]", "=", "@downloadRate", "result", "[", ":uploadRate", "]", "=", "@uploadRate", "result", "[", ":downloadRateDataOnly", "]", "=", "@downloadRateDataOnly", "result", "[", ":uploadRateDataOnly", "]", "=", "@uploadRateDataOnly", "result", "[", ":completedBytes", "]", "=", "@completedBytes", "result", "[", ":peers", "]", "=", "@peers", ".", "collect", "{", "|", "p", "|", "p", ".", "to_h", "}", "result", "[", ":state", "]", "=", "@state", "#result[:completePieceBitfield] = @completePieceBitfield", "result", "[", ":metainfoLength", "]", "=", "@metainfoLength", "result", "[", ":metainfoCompletedLength", "]", "=", "@metainfoCompletedLength", "result", "[", ":paused", "]", "=", "@paused", "result", "[", ":queued", "]", "=", "@queued", "result", "[", ":uploadRateLimit", "]", "=", "@uploadRateLimit", "result", "[", ":downloadRateLimit", "]", "=", "@downloadRateLimit", "result", "[", ":ratio", "]", "=", "@ratio", "result", "[", ":uploadDuration", "]", "=", "@uploadDuration", "result", "[", ":bytesUploaded", "]", "=", "@bytesUploaded", "result", "[", ":bytesDownloaded", "]", "=", "@bytesDownloaded", "result", "[", ":alarms", "]", "=", "@alarms", ".", "collect", "{", "|", "a", "|", "a", ".", "to_h", "}", "result", "end" ]
Convert to a hash. Also flattens some of the data into new fields.
[ "Convert", "to", "a", "hash", ".", "Also", "flattens", "some", "of", "the", "data", "into", "new", "fields", "." ]
775c40c597e608baf7e7eade3e20bcdc99c702a7
https://github.com/jeffwilliams/quartz-flow/blob/775c40c597e608baf7e7eade3e20bcdc99c702a7/lib/quartz_flow/wrappers.rb#L65-L111
8,344
woodruffw/dreck
lib/dreck/result.rb
Dreck.Result.list
def list(type, sym, count: nil) if count raise BadCountError unless count.positive? end @expected << [:list, type, sym, count] end
ruby
def list(type, sym, count: nil) if count raise BadCountError unless count.positive? end @expected << [:list, type, sym, count] end
[ "def", "list", "(", "type", ",", "sym", ",", "count", ":", "nil", ")", "if", "count", "raise", "BadCountError", "unless", "count", ".", "positive?", "end", "@expected", "<<", "[", ":list", ",", "type", ",", "sym", ",", "count", "]", "end" ]
Specifies a list of arguments of a given type to be parsed. @param type [Symbol] the type of the arguments @param sym [Symbol] the name of the argument in {results} @param count [Integer] the number of arguments in the list
[ "Specifies", "a", "list", "of", "arguments", "of", "a", "given", "type", "to", "be", "parsed", "." ]
9a9d79810b3b193583396cc2bf4801f236fc2f76
https://github.com/woodruffw/dreck/blob/9a9d79810b3b193583396cc2bf4801f236fc2f76/lib/dreck/result.rb#L45-L51
8,345
woodruffw/dreck
lib/dreck/result.rb
Dreck.Result.parse!
def parse! check_absorption! @expected.each do |type, *rest| case type when :list parse_list!(*rest) else parse_type!(type, *rest) end end self end
ruby
def parse! check_absorption! @expected.each do |type, *rest| case type when :list parse_list!(*rest) else parse_type!(type, *rest) end end self end
[ "def", "parse!", "check_absorption!", "@expected", ".", "each", "do", "|", "type", ",", "*", "rest", "|", "case", "type", "when", ":list", "parse_list!", "(", "rest", ")", "else", "parse_type!", "(", "type", ",", "rest", ")", "end", "end", "self", "end" ]
Perform the actual parsing. @return [Result] this instance @api private
[ "Perform", "the", "actual", "parsing", "." ]
9a9d79810b3b193583396cc2bf4801f236fc2f76
https://github.com/woodruffw/dreck/blob/9a9d79810b3b193583396cc2bf4801f236fc2f76/lib/dreck/result.rb#L56-L69
8,346
woodruffw/dreck
lib/dreck/result.rb
Dreck.Result.check_absorption!
def check_absorption! count, greedy = count_expected return unless strict? raise GreedyAbsorptionError.new(count, @args.size) if count >= @args.size && greedy raise AbsorptionError.new(count, @args.size) if count != @args.size && !greedy end
ruby
def check_absorption! count, greedy = count_expected return unless strict? raise GreedyAbsorptionError.new(count, @args.size) if count >= @args.size && greedy raise AbsorptionError.new(count, @args.size) if count != @args.size && !greedy end
[ "def", "check_absorption!", "count", ",", "greedy", "=", "count_expected", "return", "unless", "strict?", "raise", "GreedyAbsorptionError", ".", "new", "(", "count", ",", "@args", ".", "size", ")", "if", "count", ">=", "@args", ".", "size", "&&", "greedy", "raise", "AbsorptionError", ".", "new", "(", "count", ",", "@args", ".", "size", ")", "if", "count", "!=", "@args", ".", "size", "&&", "!", "greedy", "end" ]
Check whether the expected arguments absorb all supplied arguments. @raise [AbsoptionError] if absorption fails and {strict?} is not true @api private
[ "Check", "whether", "the", "expected", "arguments", "absorb", "all", "supplied", "arguments", "." ]
9a9d79810b3b193583396cc2bf4801f236fc2f76
https://github.com/woodruffw/dreck/blob/9a9d79810b3b193583396cc2bf4801f236fc2f76/lib/dreck/result.rb#L74-L81
8,347
woodruffw/dreck
lib/dreck/result.rb
Dreck.Result.count_expected
def count_expected count = @expected.inject(0) do |n, exp| case exp.first when :list # if the list is greedy, all arguments have to be absorbed return [n, true] unless exp[3] n + exp[3] else n + 1 end end [count, false] end
ruby
def count_expected count = @expected.inject(0) do |n, exp| case exp.first when :list # if the list is greedy, all arguments have to be absorbed return [n, true] unless exp[3] n + exp[3] else n + 1 end end [count, false] end
[ "def", "count_expected", "count", "=", "@expected", ".", "inject", "(", "0", ")", "do", "|", "n", ",", "exp", "|", "case", "exp", ".", "first", "when", ":list", "# if the list is greedy, all arguments have to be absorbed", "return", "[", "n", ",", "true", "]", "unless", "exp", "[", "3", "]", "n", "+", "exp", "[", "3", "]", "else", "n", "+", "1", "end", "end", "[", "count", ",", "false", "]", "end" ]
Count the number of arguments expected to be supplied. @raise [Integer, nil] the number of expected arguments, or nil if a list of indeterminate size is specified @api private
[ "Count", "the", "number", "of", "arguments", "expected", "to", "be", "supplied", "." ]
9a9d79810b3b193583396cc2bf4801f236fc2f76
https://github.com/woodruffw/dreck/blob/9a9d79810b3b193583396cc2bf4801f236fc2f76/lib/dreck/result.rb#L87-L101
8,348
woodruffw/dreck
lib/dreck/result.rb
Dreck.Result.parse_list!
def parse_list!(type, sym, count) args = if count @args.shift count else @args end @results[sym] = Parser.parse_list type, args end
ruby
def parse_list!(type, sym, count) args = if count @args.shift count else @args end @results[sym] = Parser.parse_list type, args end
[ "def", "parse_list!", "(", "type", ",", "sym", ",", "count", ")", "args", "=", "if", "count", "@args", ".", "shift", "count", "else", "@args", "end", "@results", "[", "sym", "]", "=", "Parser", ".", "parse_list", "type", ",", "args", "end" ]
Parse a one or more expected arguments of a given type and add them to the results. @param type [Symbol] the type of the individual elements of the list @param sym [Symbol] the key to store the results under in {results} @param count [Integer, nil] the size of the list, or nil if the list absorbs all following arguments @api private
[ "Parse", "a", "one", "or", "more", "expected", "arguments", "of", "a", "given", "type", "and", "add", "them", "to", "the", "results", "." ]
9a9d79810b3b193583396cc2bf4801f236fc2f76
https://github.com/woodruffw/dreck/blob/9a9d79810b3b193583396cc2bf4801f236fc2f76/lib/dreck/result.rb#L110-L118
8,349
toshipon/ean3
lib/ean3/hotels.rb
Ean3.Hotels.getReservation
def getReservation response = conncetion.post do |req| req.url "res", options end return_error_or_body(response, response.body) end
ruby
def getReservation response = conncetion.post do |req| req.url "res", options end return_error_or_body(response, response.body) end
[ "def", "getReservation", "response", "=", "conncetion", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"res\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ")", "end" ]
Book a Reservation
[ "Book", "a", "Reservation" ]
d1aefbaf9b3ddf3e9da694e832314cd9ab615868
https://github.com/toshipon/ean3/blob/d1aefbaf9b3ddf3e9da694e832314cd9ab615868/lib/ean3/hotels.rb#L79-L84
8,350
toshipon/ean3
lib/ean3/hotels.rb
Ean3.Hotels.getAlternateProperties
def getAlternateProperties response = conncetion.get do |req| req.url "altProps", options end return_error_or_body(response, response.body) end
ruby
def getAlternateProperties response = conncetion.get do |req| req.url "altProps", options end return_error_or_body(response, response.body) end
[ "def", "getAlternateProperties", "response", "=", "conncetion", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"altProps\"", ",", "options", "end", "return_error_or_body", "(", "response", ",", "response", ".", "body", ")", "end" ]
Request Alternate Properties
[ "Request", "Alternate", "Properties" ]
d1aefbaf9b3ddf3e9da694e832314cd9ab615868
https://github.com/toshipon/ean3/blob/d1aefbaf9b3ddf3e9da694e832314cd9ab615868/lib/ean3/hotels.rb#L89-L94
8,351
starpeak/gricer
app/controllers/gricer/dashboard_controller.rb
Gricer.DashboardController.index
def index @sessions = Gricer.config.session_model.browsers.between_dates(@stat_from, @stat_thru) @requests = Gricer.config.request_model.browsers.between_dates(@stat_from, @stat_thru) end
ruby
def index @sessions = Gricer.config.session_model.browsers.between_dates(@stat_from, @stat_thru) @requests = Gricer.config.request_model.browsers.between_dates(@stat_from, @stat_thru) end
[ "def", "index", "@sessions", "=", "Gricer", ".", "config", ".", "session_model", ".", "browsers", ".", "between_dates", "(", "@stat_from", ",", "@stat_thru", ")", "@requests", "=", "Gricer", ".", "config", ".", "request_model", ".", "browsers", ".", "between_dates", "(", "@stat_from", ",", "@stat_thru", ")", "end" ]
This action renders the frame for the statistics tool
[ "This", "action", "renders", "the", "frame", "for", "the", "statistics", "tool" ]
46bb77bd4fc7074ce294d0310ad459fef068f507
https://github.com/starpeak/gricer/blob/46bb77bd4fc7074ce294d0310ad459fef068f507/app/controllers/gricer/dashboard_controller.rb#L5-L8
8,352
starpeak/gricer
app/controllers/gricer/dashboard_controller.rb
Gricer.DashboardController.overview
def overview @sessions = Gricer.config.session_model.browsers.between_dates(@stat_from, @stat_thru) @requests = Gricer.config.request_model.browsers.between_dates(@stat_from, @stat_thru) render partial: 'overview', formats: [:html], locals: {sessions: @sessions, requests: @requests} end
ruby
def overview @sessions = Gricer.config.session_model.browsers.between_dates(@stat_from, @stat_thru) @requests = Gricer.config.request_model.browsers.between_dates(@stat_from, @stat_thru) render partial: 'overview', formats: [:html], locals: {sessions: @sessions, requests: @requests} end
[ "def", "overview", "@sessions", "=", "Gricer", ".", "config", ".", "session_model", ".", "browsers", ".", "between_dates", "(", "@stat_from", ",", "@stat_thru", ")", "@requests", "=", "Gricer", ".", "config", ".", "request_model", ".", "browsers", ".", "between_dates", "(", "@stat_from", ",", "@stat_thru", ")", "render", "partial", ":", "'overview'", ",", "formats", ":", "[", ":html", "]", ",", "locals", ":", "{", "sessions", ":", "@sessions", ",", "requests", ":", "@requests", "}", "end" ]
This action renderes the overview of some data in the statistics tool
[ "This", "action", "renderes", "the", "overview", "of", "some", "data", "in", "the", "statistics", "tool" ]
46bb77bd4fc7074ce294d0310ad459fef068f507
https://github.com/starpeak/gricer/blob/46bb77bd4fc7074ce294d0310ad459fef068f507/app/controllers/gricer/dashboard_controller.rb#L11-L16
8,353
redding/enumeration
lib/enumeration/collection.rb
Enumeration.Collection.[]
def [](key) if self.map? && @data.has_key?(key) @data[key] elsif (self.map? && @data.has_value?(key)) || (self.list? && @data.include?(key)) key else nil end end
ruby
def [](key) if self.map? && @data.has_key?(key) @data[key] elsif (self.map? && @data.has_value?(key)) || (self.list? && @data.include?(key)) key else nil end end
[ "def", "[]", "(", "key", ")", "if", "self", ".", "map?", "&&", "@data", ".", "has_key?", "(", "key", ")", "@data", "[", "key", "]", "elsif", "(", "self", ".", "map?", "&&", "@data", ".", "has_value?", "(", "key", ")", ")", "||", "(", "self", ".", "list?", "&&", "@data", ".", "include?", "(", "key", ")", ")", "key", "else", "nil", "end", "end" ]
lookup collection value by a key
[ "lookup", "collection", "value", "by", "a", "key" ]
816d6993c3a05e538a45f65529ccef6dbc9c6bf1
https://github.com/redding/enumeration/blob/816d6993c3a05e538a45f65529ccef6dbc9c6bf1/lib/enumeration/collection.rb#L15-L24
8,354
redding/enumeration
lib/enumeration/collection.rb
Enumeration.Collection.key
def key(value) if self.map? && @data.has_value?(value) @data.invert[value] elsif (self.map? && @data.has_key?(value)) || (self.list? && @data.include?(value)) value else nil end end
ruby
def key(value) if self.map? && @data.has_value?(value) @data.invert[value] elsif (self.map? && @data.has_key?(value)) || (self.list? && @data.include?(value)) value else nil end end
[ "def", "key", "(", "value", ")", "if", "self", ".", "map?", "&&", "@data", ".", "has_value?", "(", "value", ")", "@data", ".", "invert", "[", "value", "]", "elsif", "(", "self", ".", "map?", "&&", "@data", ".", "has_key?", "(", "value", ")", ")", "||", "(", "self", ".", "list?", "&&", "@data", ".", "include?", "(", "value", ")", ")", "value", "else", "nil", "end", "end" ]
lookup collection key by a value
[ "lookup", "collection", "key", "by", "a", "value" ]
816d6993c3a05e538a45f65529ccef6dbc9c6bf1
https://github.com/redding/enumeration/blob/816d6993c3a05e538a45f65529ccef6dbc9c6bf1/lib/enumeration/collection.rb#L27-L36
8,355
brianpattison/motion-loco
lib/motion-loco/observable.rb
Loco.Observable.initialize_bindings
def initialize_bindings bindings = self.class.get_class_bindings bindings.each do |binding| binding[:proc].observed_properties.each do |key_path| register_observer(self, key_path) do new_value = binding[:proc].call(self) if binding[:name] self.setValue(new_value, forKey:binding[:name]) end end end end end
ruby
def initialize_bindings bindings = self.class.get_class_bindings bindings.each do |binding| binding[:proc].observed_properties.each do |key_path| register_observer(self, key_path) do new_value = binding[:proc].call(self) if binding[:name] self.setValue(new_value, forKey:binding[:name]) end end end end end
[ "def", "initialize_bindings", "bindings", "=", "self", ".", "class", ".", "get_class_bindings", "bindings", ".", "each", "do", "|", "binding", "|", "binding", "[", ":proc", "]", ".", "observed_properties", ".", "each", "do", "|", "key_path", "|", "register_observer", "(", "self", ",", "key_path", ")", "do", "new_value", "=", "binding", "[", ":proc", "]", ".", "call", "(", "self", ")", "if", "binding", "[", ":name", "]", "self", ".", "setValue", "(", "new_value", ",", "forKey", ":", "binding", "[", ":name", "]", ")", "end", "end", "end", "end", "end" ]
Create the bindings for the computed properties and observers
[ "Create", "the", "bindings", "for", "the", "computed", "properties", "and", "observers" ]
d6f4ca32d6e13dc4d325d2838c0e2685fa0fa4f6
https://github.com/brianpattison/motion-loco/blob/d6f4ca32d6e13dc4d325d2838c0e2685fa0fa4f6/lib/motion-loco/observable.rb#L97-L110
8,356
mmb/tinyatom
lib/tinyatom/feed.rb
TinyAtom.Feed.add_entry
def add_entry(id, title, updated, link, options={}) entries << { :id => id, :title => title, :updated => updated, :link => link }.merge(options) end
ruby
def add_entry(id, title, updated, link, options={}) entries << { :id => id, :title => title, :updated => updated, :link => link }.merge(options) end
[ "def", "add_entry", "(", "id", ",", "title", ",", "updated", ",", "link", ",", "options", "=", "{", "}", ")", "entries", "<<", "{", ":id", "=>", "id", ",", ":title", "=>", "title", ",", ":updated", "=>", "updated", ",", ":link", "=>", "link", "}", ".", "merge", "(", "options", ")", "end" ]
Add an entry to the feed
[ "Add", "an", "entry", "to", "the", "feed" ]
ae2d95a41729fc19f2b85d2df071ec7fa062184c
https://github.com/mmb/tinyatom/blob/ae2d95a41729fc19f2b85d2df071ec7fa062184c/lib/tinyatom/feed.rb#L19-L26
8,357
petebrowne/machined
spec/support/helpers.rb
Machined.SpecHelpers.machined
def machined(config = {}) @machined = nil if config.delete(:reload) @machined ||= Machined::Environment.new(config.reverse_merge(:skip_bundle => true, :skip_autoloading => true)) end
ruby
def machined(config = {}) @machined = nil if config.delete(:reload) @machined ||= Machined::Environment.new(config.reverse_merge(:skip_bundle => true, :skip_autoloading => true)) end
[ "def", "machined", "(", "config", "=", "{", "}", ")", "@machined", "=", "nil", "if", "config", ".", "delete", "(", ":reload", ")", "@machined", "||=", "Machined", "::", "Environment", ".", "new", "(", "config", ".", "reverse_merge", "(", ":skip_bundle", "=>", "true", ",", ":skip_autoloading", "=>", "true", ")", ")", "end" ]
Convenience method for creating a new Machined environment
[ "Convenience", "method", "for", "creating", "a", "new", "Machined", "environment" ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/spec/support/helpers.rb#L7-L10
8,358
petebrowne/machined
spec/support/helpers.rb
Machined.SpecHelpers.build_context
def build_context(logical_path = 'application.js', options = {}) pathname = options[:pathname] || Pathname.new('assets').join(logical_path).expand_path env = options[:env] || machined.assets env.context_class.new env, logical_path, pathname end
ruby
def build_context(logical_path = 'application.js', options = {}) pathname = options[:pathname] || Pathname.new('assets').join(logical_path).expand_path env = options[:env] || machined.assets env.context_class.new env, logical_path, pathname end
[ "def", "build_context", "(", "logical_path", "=", "'application.js'", ",", "options", "=", "{", "}", ")", "pathname", "=", "options", "[", ":pathname", "]", "||", "Pathname", ".", "new", "(", "'assets'", ")", ".", "join", "(", "logical_path", ")", ".", "expand_path", "env", "=", "options", "[", ":env", "]", "||", "machined", ".", "assets", "env", ".", "context_class", ".", "new", "env", ",", "logical_path", ",", "pathname", "end" ]
Returns a fresh context, that can be used to test helpers.
[ "Returns", "a", "fresh", "context", "that", "can", "be", "used", "to", "test", "helpers", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/spec/support/helpers.rb#L20-L25
8,359
petebrowne/machined
spec/support/helpers.rb
Machined.SpecHelpers.machined_cli
def machined_cli(args, silence = true) capture(:stdout) { Machined::CLI.start args.split(' ') } end
ruby
def machined_cli(args, silence = true) capture(:stdout) { Machined::CLI.start args.split(' ') } end
[ "def", "machined_cli", "(", "args", ",", "silence", "=", "true", ")", "capture", "(", ":stdout", ")", "{", "Machined", "::", "CLI", ".", "start", "args", ".", "split", "(", "' '", ")", "}", "end" ]
Runs the CLI with the given args.
[ "Runs", "the", "CLI", "with", "the", "given", "args", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/spec/support/helpers.rb#L28-L32
8,360
petebrowne/machined
spec/support/helpers.rb
Machined.SpecHelpers.modify
def modify(file, content = nil) Pathname.new(file).tap do |file| file.open('w') { |f| f.write(content) } if content future = Time.now + 60 file.utime future, future end end
ruby
def modify(file, content = nil) Pathname.new(file).tap do |file| file.open('w') { |f| f.write(content) } if content future = Time.now + 60 file.utime future, future end end
[ "def", "modify", "(", "file", ",", "content", "=", "nil", ")", "Pathname", ".", "new", "(", "file", ")", ".", "tap", "do", "|", "file", "|", "file", ".", "open", "(", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "content", ")", "}", "if", "content", "future", "=", "Time", ".", "now", "+", "60", "file", ".", "utime", "future", ",", "future", "end", "end" ]
Modifies the given file
[ "Modifies", "the", "given", "file" ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/spec/support/helpers.rb#L35-L41
8,361
redding/osheet
lib/osheet/workbook_element.rb
Osheet.WorkbookElement::PartialSet.verify
def verify(partial) unless partial.kind_of?(Partial) raise ArgumentError, 'you can only push Osheet::Partial objs to the partial set' end pkey = partial_key(partial) self[pkey] ||= nil pkey end
ruby
def verify(partial) unless partial.kind_of?(Partial) raise ArgumentError, 'you can only push Osheet::Partial objs to the partial set' end pkey = partial_key(partial) self[pkey] ||= nil pkey end
[ "def", "verify", "(", "partial", ")", "unless", "partial", ".", "kind_of?", "(", "Partial", ")", "raise", "ArgumentError", ",", "'you can only push Osheet::Partial objs to the partial set'", "end", "pkey", "=", "partial_key", "(", "partial", ")", "self", "[", "pkey", "]", "||=", "nil", "pkey", "end" ]
verify the partial, init and return the key otherwise ArgumentError it up
[ "verify", "the", "partial", "init", "and", "return", "the", "key", "otherwise", "ArgumentError", "it", "up" ]
207cc7bf29ddcb290f1614136f17a53686a7932e
https://github.com/redding/osheet/blob/207cc7bf29ddcb290f1614136f17a53686a7932e/lib/osheet/workbook_element.rb#L97-L104
8,362
redding/osheet
lib/osheet/workbook_element.rb
Osheet.WorkbookElement::TemplateSet.verify
def verify(template) unless template.kind_of?(Template) raise ArgumentError, 'you can only push Osheet::Template objs to the template set' end key = template_key(template) self[key.first] ||= {} self[key.first][key.last] ||= nil key end
ruby
def verify(template) unless template.kind_of?(Template) raise ArgumentError, 'you can only push Osheet::Template objs to the template set' end key = template_key(template) self[key.first] ||= {} self[key.first][key.last] ||= nil key end
[ "def", "verify", "(", "template", ")", "unless", "template", ".", "kind_of?", "(", "Template", ")", "raise", "ArgumentError", ",", "'you can only push Osheet::Template objs to the template set'", "end", "key", "=", "template_key", "(", "template", ")", "self", "[", "key", ".", "first", "]", "||=", "{", "}", "self", "[", "key", ".", "first", "]", "[", "key", ".", "last", "]", "||=", "nil", "key", "end" ]
verify the template, init the key set, and return the key string otherwise ArgumentError it up
[ "verify", "the", "template", "init", "the", "key", "set", "and", "return", "the", "key", "string", "otherwise", "ArgumentError", "it", "up" ]
207cc7bf29ddcb290f1614136f17a53686a7932e
https://github.com/redding/osheet/blob/207cc7bf29ddcb290f1614136f17a53686a7932e/lib/osheet/workbook_element.rb#L144-L152
8,363
linrock/favicon_party
lib/favicon_party/http_client.rb
FaviconParty.HTTPClient.get
def get(url) stdin, stdout, stderr, t = Open3.popen3(curl_get_cmd(url)) output = encode_utf8(stdout.read).strip error = encode_utf8(stderr.read).strip if !error.nil? && !error.empty? if error.include? "SSL" raise FaviconParty::Curl::SSLError.new(error) elsif error.include? "Couldn't resolve host" raise FaviconParty::Curl::DNSError.new(error) else raise FaviconParty::CurlError.new(error) end end output end
ruby
def get(url) stdin, stdout, stderr, t = Open3.popen3(curl_get_cmd(url)) output = encode_utf8(stdout.read).strip error = encode_utf8(stderr.read).strip if !error.nil? && !error.empty? if error.include? "SSL" raise FaviconParty::Curl::SSLError.new(error) elsif error.include? "Couldn't resolve host" raise FaviconParty::Curl::DNSError.new(error) else raise FaviconParty::CurlError.new(error) end end output end
[ "def", "get", "(", "url", ")", "stdin", ",", "stdout", ",", "stderr", ",", "t", "=", "Open3", ".", "popen3", "(", "curl_get_cmd", "(", "url", ")", ")", "output", "=", "encode_utf8", "(", "stdout", ".", "read", ")", ".", "strip", "error", "=", "encode_utf8", "(", "stderr", ".", "read", ")", ".", "strip", "if", "!", "error", ".", "nil?", "&&", "!", "error", ".", "empty?", "if", "error", ".", "include?", "\"SSL\"", "raise", "FaviconParty", "::", "Curl", "::", "SSLError", ".", "new", "(", "error", ")", "elsif", "error", ".", "include?", "\"Couldn't resolve host\"", "raise", "FaviconParty", "::", "Curl", "::", "DNSError", ".", "new", "(", "error", ")", "else", "raise", "FaviconParty", "::", "CurlError", ".", "new", "(", "error", ")", "end", "end", "output", "end" ]
Encodes output as utf8 - Not for binary http responses
[ "Encodes", "output", "as", "utf8", "-", "Not", "for", "binary", "http", "responses" ]
645d3c6f4a7152bf705ac092976a74f405f83ca1
https://github.com/linrock/favicon_party/blob/645d3c6f4a7152bf705ac092976a74f405f83ca1/lib/favicon_party/http_client.rb#L16-L30
8,364
plangrade/plangrade-ruby
lib/plangrade/oauth2_client.rb
Plangrade.OAuth2Client.exchange_auth_code_for_token
def exchange_auth_code_for_token(opts={}) unless (opts[:params] && opts[:params][:code]) raise ArgumentError.new("You must include an authorization code as a parameter") end opts[:authenticate] ||= :body code = opts[:params].delete(:code) authorization_code.get_token(code, opts) end
ruby
def exchange_auth_code_for_token(opts={}) unless (opts[:params] && opts[:params][:code]) raise ArgumentError.new("You must include an authorization code as a parameter") end opts[:authenticate] ||= :body code = opts[:params].delete(:code) authorization_code.get_token(code, opts) end
[ "def", "exchange_auth_code_for_token", "(", "opts", "=", "{", "}", ")", "unless", "(", "opts", "[", ":params", "]", "&&", "opts", "[", ":params", "]", "[", ":code", "]", ")", "raise", "ArgumentError", ".", "new", "(", "\"You must include an authorization code as a parameter\"", ")", "end", "opts", "[", ":authenticate", "]", "||=", ":body", "code", "=", "opts", "[", ":params", "]", ".", "delete", "(", ":code", ")", "authorization_code", ".", "get_token", "(", "code", ",", "opts", ")", "end" ]
Makes a request to Plangrade server that will swap your authorization code for an access token @see http://docs.plangrade.com/#finish-authorization @opts [Hash] may include redirect uri and other query parameters >> client = PlangradeClient.new(config) >> client.exchange_auth_code_for_token({ :code => '123456789' :redirect_uri => 'http://localhost:3000/auth/plangrade/callback', }) POST /oauth/token HTTP/1.1 Host: www.plangrade.com Content-Type: application/x-www-form-urlencoded client_id={client_id}&code=G3Y6jU3a&grant_type=authorization_code& redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fplangrade%2Fcallback&client_secret={client_secret}
[ "Makes", "a", "request", "to", "Plangrade", "server", "that", "will", "swap", "your", "authorization", "code", "for", "an", "access", "token" ]
fe7240753825358c9b3c6887b51b5858a984c5f8
https://github.com/plangrade/plangrade-ruby/blob/fe7240753825358c9b3c6887b51b5858a984c5f8/lib/plangrade/oauth2_client.rb#L57-L64
8,365
26fe/sem4r
lib/sem4r_soap/soap_dumper.rb
Sem4rSoap.SoapDumper.dump_soap_options
def dump_soap_options(options) @soap_dump = true @soap_dump_log = nil if options[:directory] @soap_dump_dir = options[:directory] else @soap_dump_log = File.open(options[:file], "w") end @soap_dump_format = false || options[:format] @soap_dump_interceptor = options[:interceptor] if options[:interceptor] end
ruby
def dump_soap_options(options) @soap_dump = true @soap_dump_log = nil if options[:directory] @soap_dump_dir = options[:directory] else @soap_dump_log = File.open(options[:file], "w") end @soap_dump_format = false || options[:format] @soap_dump_interceptor = options[:interceptor] if options[:interceptor] end
[ "def", "dump_soap_options", "(", "options", ")", "@soap_dump", "=", "true", "@soap_dump_log", "=", "nil", "if", "options", "[", ":directory", "]", "@soap_dump_dir", "=", "options", "[", ":directory", "]", "else", "@soap_dump_log", "=", "File", ".", "open", "(", "options", "[", ":file", "]", ",", "\"w\"", ")", "end", "@soap_dump_format", "=", "false", "||", "options", "[", ":format", "]", "@soap_dump_interceptor", "=", "options", "[", ":interceptor", "]", "if", "options", "[", ":interceptor", "]", "end" ]
set the options for the dumping soap message @param [Hash] options @option options [String] :directory @option options [String] :file @option options [String] :format @option options [String] :interceptor
[ "set", "the", "options", "for", "the", "dumping", "soap", "message" ]
2326404f98b9c2833549fcfda078d39c9954a0fa
https://github.com/26fe/sem4r/blob/2326404f98b9c2833549fcfda078d39c9954a0fa/lib/sem4r_soap/soap_dumper.rb#L43-L55
8,366
redding/deas
lib/deas/logging.rb
Deas.BaseLogging.call!
def call!(env) env['rack.logger'] = @logger status, headers, body = nil, nil, nil benchmark = Benchmark.measure do status, headers, body = @app.call(env) end log_error(env['deas.error']) env['deas.time_taken'] = RoundedTime.new(benchmark.real) [status, headers, body] end
ruby
def call!(env) env['rack.logger'] = @logger status, headers, body = nil, nil, nil benchmark = Benchmark.measure do status, headers, body = @app.call(env) end log_error(env['deas.error']) env['deas.time_taken'] = RoundedTime.new(benchmark.real) [status, headers, body] end
[ "def", "call!", "(", "env", ")", "env", "[", "'rack.logger'", "]", "=", "@logger", "status", ",", "headers", ",", "body", "=", "nil", ",", "nil", ",", "nil", "benchmark", "=", "Benchmark", ".", "measure", "do", "status", ",", "headers", ",", "body", "=", "@app", ".", "call", "(", "env", ")", "end", "log_error", "(", "env", "[", "'deas.error'", "]", ")", "env", "[", "'deas.time_taken'", "]", "=", "RoundedTime", ".", "new", "(", "benchmark", ".", "real", ")", "[", "status", ",", "headers", ",", "body", "]", "end" ]
The real Rack call interface. This is the common behavior for both the verbose and summary logging middlewares. It sets rack's logger, times the response and returns it as is.
[ "The", "real", "Rack", "call", "interface", ".", "This", "is", "the", "common", "behavior", "for", "both", "the", "verbose", "and", "summary", "logging", "middlewares", ".", "It", "sets", "rack", "s", "logger", "times", "the", "response", "and", "returns", "it", "as", "is", "." ]
865dbfa210a10f974552c2b92325306d98755283
https://github.com/redding/deas/blob/865dbfa210a10f974552c2b92325306d98755283/lib/deas/logging.rb#L34-L45
8,367
redding/deas
lib/deas/logging.rb
Deas.VerboseLogging.call!
def call!(env) log "===== Received request =====" Rack::Request.new(env).tap do |request| log " Method: #{request.request_method.inspect}" log " Path: #{request.path.inspect}" end env['deas.logging'] = Proc.new{ |msg| log(msg) } status, headers, body = super(env) log " Redir: #{headers['Location']}" if headers.key?('Location') log "===== Completed in #{env['deas.time_taken']}ms (#{response_display(status)}) =====" [status, headers, body] end
ruby
def call!(env) log "===== Received request =====" Rack::Request.new(env).tap do |request| log " Method: #{request.request_method.inspect}" log " Path: #{request.path.inspect}" end env['deas.logging'] = Proc.new{ |msg| log(msg) } status, headers, body = super(env) log " Redir: #{headers['Location']}" if headers.key?('Location') log "===== Completed in #{env['deas.time_taken']}ms (#{response_display(status)}) =====" [status, headers, body] end
[ "def", "call!", "(", "env", ")", "log", "\"===== Received request =====\"", "Rack", "::", "Request", ".", "new", "(", "env", ")", ".", "tap", "do", "|", "request", "|", "log", "\" Method: #{request.request_method.inspect}\"", "log", "\" Path: #{request.path.inspect}\"", "end", "env", "[", "'deas.logging'", "]", "=", "Proc", ".", "new", "{", "|", "msg", "|", "log", "(", "msg", ")", "}", "status", ",", "headers", ",", "body", "=", "super", "(", "env", ")", "log", "\" Redir: #{headers['Location']}\"", "if", "headers", ".", "key?", "(", "'Location'", ")", "log", "\"===== Completed in #{env['deas.time_taken']}ms (#{response_display(status)}) =====\"", "[", "status", ",", "headers", ",", "body", "]", "end" ]
This the real Rack call interface. It adds logging before and after super-ing to the common logging behavior.
[ "This", "the", "real", "Rack", "call", "interface", ".", "It", "adds", "logging", "before", "and", "after", "super", "-", "ing", "to", "the", "common", "logging", "behavior", "." ]
865dbfa210a10f974552c2b92325306d98755283
https://github.com/redding/deas/blob/865dbfa210a10f974552c2b92325306d98755283/lib/deas/logging.rb#L74-L85
8,368
redding/deas
lib/deas/logging.rb
Deas.SummaryLogging.call!
def call!(env) env['deas.logging'] = Proc.new{ |msg| } # no-op status, headers, body = super(env) request = Rack::Request.new(env) line_attrs = { 'method' => request.request_method, 'path' => request.path, 'params' => env['deas.params'], 'splat' => env['deas.splat'], 'time' => env['deas.time_taken'], 'status' => status } if env['deas.handler_class'] line_attrs['handler'] = env['deas.handler_class'].name end if headers.key?('Location') line_attrs['redir'] = headers['Location'] end log SummaryLine.new(line_attrs) [status, headers, body] end
ruby
def call!(env) env['deas.logging'] = Proc.new{ |msg| } # no-op status, headers, body = super(env) request = Rack::Request.new(env) line_attrs = { 'method' => request.request_method, 'path' => request.path, 'params' => env['deas.params'], 'splat' => env['deas.splat'], 'time' => env['deas.time_taken'], 'status' => status } if env['deas.handler_class'] line_attrs['handler'] = env['deas.handler_class'].name end if headers.key?('Location') line_attrs['redir'] = headers['Location'] end log SummaryLine.new(line_attrs) [status, headers, body] end
[ "def", "call!", "(", "env", ")", "env", "[", "'deas.logging'", "]", "=", "Proc", ".", "new", "{", "|", "msg", "|", "}", "# no-op", "status", ",", "headers", ",", "body", "=", "super", "(", "env", ")", "request", "=", "Rack", "::", "Request", ".", "new", "(", "env", ")", "line_attrs", "=", "{", "'method'", "=>", "request", ".", "request_method", ",", "'path'", "=>", "request", ".", "path", ",", "'params'", "=>", "env", "[", "'deas.params'", "]", ",", "'splat'", "=>", "env", "[", "'deas.splat'", "]", ",", "'time'", "=>", "env", "[", "'deas.time_taken'", "]", ",", "'status'", "=>", "status", "}", "if", "env", "[", "'deas.handler_class'", "]", "line_attrs", "[", "'handler'", "]", "=", "env", "[", "'deas.handler_class'", "]", ".", "name", "end", "if", "headers", ".", "key?", "(", "'Location'", ")", "line_attrs", "[", "'redir'", "]", "=", "headers", "[", "'Location'", "]", "end", "log", "SummaryLine", ".", "new", "(", "line_attrs", ")", "[", "status", ",", "headers", ",", "body", "]", "end" ]
This the real Rack call interface. It adds logging after super-ing to the common logging behavior.
[ "This", "the", "real", "Rack", "call", "interface", ".", "It", "adds", "logging", "after", "super", "-", "ing", "to", "the", "common", "logging", "behavior", "." ]
865dbfa210a10f974552c2b92325306d98755283
https://github.com/redding/deas/blob/865dbfa210a10f974552c2b92325306d98755283/lib/deas/logging.rb#L97-L117
8,369
jrissler/wafflemix
app/models/wafflemix/asset.rb
Wafflemix.Asset.to_jq_upload
def to_jq_upload { "name" => read_attribute(:asset_name), "size" => asset_size, "url" => asset_url, "thumbnail_url" => asset.thumb('80x80#').url, "delete_url" => Wafflemix::Engine::routes.url_helpers.admin_asset_path(:id => id), "delete_type" => "DELETE" } end
ruby
def to_jq_upload { "name" => read_attribute(:asset_name), "size" => asset_size, "url" => asset_url, "thumbnail_url" => asset.thumb('80x80#').url, "delete_url" => Wafflemix::Engine::routes.url_helpers.admin_asset_path(:id => id), "delete_type" => "DELETE" } end
[ "def", "to_jq_upload", "{", "\"name\"", "=>", "read_attribute", "(", ":asset_name", ")", ",", "\"size\"", "=>", "asset_size", ",", "\"url\"", "=>", "asset_url", ",", "\"thumbnail_url\"", "=>", "asset", ".", "thumb", "(", "'80x80#'", ")", ".", "url", ",", "\"delete_url\"", "=>", "Wafflemix", "::", "Engine", "::", "routes", ".", "url_helpers", ".", "admin_asset_path", "(", ":id", "=>", "id", ")", ",", "\"delete_type\"", "=>", "\"DELETE\"", "}", "end" ]
one convenient method to pass jq_upload the necessary information
[ "one", "convenient", "method", "to", "pass", "jq_upload", "the", "necessary", "information" ]
050db4c321319ff4dee425c79a25b4bd859f67c0
https://github.com/jrissler/wafflemix/blob/050db4c321319ff4dee425c79a25b4bd859f67c0/app/models/wafflemix/asset.rb#L11-L20
8,370
bumbleworks/bumbleworks
lib/bumbleworks/user.rb
Bumbleworks.User.claim
def claim(task, force = false) raise UnauthorizedClaimAttempt unless has_role?(task.role) release!(task) if force task.claim(claim_token) end
ruby
def claim(task, force = false) raise UnauthorizedClaimAttempt unless has_role?(task.role) release!(task) if force task.claim(claim_token) end
[ "def", "claim", "(", "task", ",", "force", "=", "false", ")", "raise", "UnauthorizedClaimAttempt", "unless", "has_role?", "(", "task", ".", "role", ")", "release!", "(", "task", ")", "if", "force", "task", ".", "claim", "(", "claim_token", ")", "end" ]
Attempts to set self as the claimant of the given task. If not authorized to claim the task, raises exception. Also bubbles exception from Task when task is already claimed by a different claimant.
[ "Attempts", "to", "set", "self", "as", "the", "claimant", "of", "the", "given", "task", ".", "If", "not", "authorized", "to", "claim", "the", "task", "raises", "exception", ".", "Also", "bubbles", "exception", "from", "Task", "when", "task", "is", "already", "claimed", "by", "a", "different", "claimant", "." ]
6f63992e921dcf8371d4453ef9e7b4e3322cc360
https://github.com/bumbleworks/bumbleworks/blob/6f63992e921dcf8371d4453ef9e7b4e3322cc360/lib/bumbleworks/user.rb#L52-L56
8,371
bumbleworks/bumbleworks
lib/bumbleworks/user.rb
Bumbleworks.User.release
def release(task, force = false) return unless task.claimed? raise UnauthorizedReleaseAttempt unless force || task.claimant == claim_token task.release end
ruby
def release(task, force = false) return unless task.claimed? raise UnauthorizedReleaseAttempt unless force || task.claimant == claim_token task.release end
[ "def", "release", "(", "task", ",", "force", "=", "false", ")", "return", "unless", "task", ".", "claimed?", "raise", "UnauthorizedReleaseAttempt", "unless", "force", "||", "task", ".", "claimant", "==", "claim_token", "task", ".", "release", "end" ]
If we are the current claimant of the given task, release the task. Does nothing if the task is not claimed, but raises exception if the task is currently claimed by someone else.
[ "If", "we", "are", "the", "current", "claimant", "of", "the", "given", "task", "release", "the", "task", ".", "Does", "nothing", "if", "the", "task", "is", "not", "claimed", "but", "raises", "exception", "if", "the", "task", "is", "currently", "claimed", "by", "someone", "else", "." ]
6f63992e921dcf8371d4453ef9e7b4e3322cc360
https://github.com/bumbleworks/bumbleworks/blob/6f63992e921dcf8371d4453ef9e7b4e3322cc360/lib/bumbleworks/user.rb#L70-L74
8,372
cbrumelle/blueprintr
lib/blueprint-css/lib/blueprint/validator.rb
Blueprint.Validator.validate
def validate java_path = `which java`.rstrip raise "You do not have a Java installed, but it is required." if java_path.blank? output_header Blueprint::CSS_FILES.keys.each do |file_name| css_output_path = File.join(Blueprint::BLUEPRINT_ROOT_PATH, file_name) puts "\n\n Testing #{css_output_path}" puts " Output ============================================================\n\n" @error_count += 1 if !system("#{java_path} -jar '#{Blueprint::VALIDATOR_FILE}' -e '#{css_output_path}'") end output_footer end
ruby
def validate java_path = `which java`.rstrip raise "You do not have a Java installed, but it is required." if java_path.blank? output_header Blueprint::CSS_FILES.keys.each do |file_name| css_output_path = File.join(Blueprint::BLUEPRINT_ROOT_PATH, file_name) puts "\n\n Testing #{css_output_path}" puts " Output ============================================================\n\n" @error_count += 1 if !system("#{java_path} -jar '#{Blueprint::VALIDATOR_FILE}' -e '#{css_output_path}'") end output_footer end
[ "def", "validate", "java_path", "=", "`", "`", ".", "rstrip", "raise", "\"You do not have a Java installed, but it is required.\"", "if", "java_path", ".", "blank?", "output_header", "Blueprint", "::", "CSS_FILES", ".", "keys", ".", "each", "do", "|", "file_name", "|", "css_output_path", "=", "File", ".", "join", "(", "Blueprint", "::", "BLUEPRINT_ROOT_PATH", ",", "file_name", ")", "puts", "\"\\n\\n Testing #{css_output_path}\"", "puts", "\" Output ============================================================\\n\\n\"", "@error_count", "+=", "1", "if", "!", "system", "(", "\"#{java_path} -jar '#{Blueprint::VALIDATOR_FILE}' -e '#{css_output_path}'\"", ")", "end", "output_footer", "end" ]
Validates all three CSS files
[ "Validates", "all", "three", "CSS", "files" ]
b414436f614a8d97d77b47b588ddcf3f5e61b6bd
https://github.com/cbrumelle/blueprintr/blob/b414436f614a8d97d77b47b588ddcf3f5e61b6bd/lib/blueprint-css/lib/blueprint/validator.rb#L11-L25
8,373
charypar/cyclical
lib/cyclical/schedule.rb
Cyclical.Schedule.occurrences_between
def occurrences_between(t1, t2) return ((start_time < t1 || @start_time >= t2) ? [] : [start_time]) if @occurrence.nil? @occurrence.occurrences_between(t1, t2) end
ruby
def occurrences_between(t1, t2) return ((start_time < t1 || @start_time >= t2) ? [] : [start_time]) if @occurrence.nil? @occurrence.occurrences_between(t1, t2) end
[ "def", "occurrences_between", "(", "t1", ",", "t2", ")", "return", "(", "(", "start_time", "<", "t1", "||", "@start_time", ">=", "t2", ")", "?", "[", "]", ":", "[", "start_time", "]", ")", "if", "@occurrence", ".", "nil?", "@occurrence", ".", "occurrences_between", "(", "t1", ",", "t2", ")", "end" ]
occurrences in [t1, t2)
[ "occurrences", "in", "[", "t1", "t2", ")" ]
8e45b8f83e2dd59fcad01e220412bb361867f5c6
https://github.com/charypar/cyclical/blob/8e45b8f83e2dd59fcad01e220412bb361867f5c6/lib/cyclical/schedule.rb#L75-L79
8,374
brianmichel/Crate-API
lib/crate_api/crate.rb
CrateAPI.Crate.destroy
def destroy response = JSON.parse(CrateAPI::Base.call("#{CrateAPI::Base::CRATES_URL}/#{CrateAPI::Crates::CRATE_ACTIONS[:destroy] % ["#{self.id}"]}", :post)) raise CrateDestroyError, response["message"] unless response["status"] != "failure" end
ruby
def destroy response = JSON.parse(CrateAPI::Base.call("#{CrateAPI::Base::CRATES_URL}/#{CrateAPI::Crates::CRATE_ACTIONS[:destroy] % ["#{self.id}"]}", :post)) raise CrateDestroyError, response["message"] unless response["status"] != "failure" end
[ "def", "destroy", "response", "=", "JSON", ".", "parse", "(", "CrateAPI", "::", "Base", ".", "call", "(", "\"#{CrateAPI::Base::CRATES_URL}/#{CrateAPI::Crates::CRATE_ACTIONS[:destroy] % [\"#{self.id}\"]}\"", ",", ":post", ")", ")", "raise", "CrateDestroyError", ",", "response", "[", "\"message\"", "]", "unless", "response", "[", "\"status\"", "]", "!=", "\"failure\"", "end" ]
Destroys the given crate object. @return [CrateDestroyError, nil] if there is an issue destroying the crate, an error will be raised with the message explaining why.
[ "Destroys", "the", "given", "crate", "object", "." ]
722fcbd08a40c5e0a622a2bdaa3687a753cc7970
https://github.com/brianmichel/Crate-API/blob/722fcbd08a40c5e0a622a2bdaa3687a753cc7970/lib/crate_api/crate.rb#L25-L28
8,375
brianmichel/Crate-API
lib/crate_api/crate.rb
CrateAPI.Crate.rename
def rename(name) response = JSON.parse(CrateAPI::Base.call("#{CrateAPI::Base::CRATES_URL}/#{CrateAPI::Crates::CRATE_ACTIONS[:rename] % ["#{self.id}"]}", :post, {:body => {:name => name}})) raise CrateRenameError, response["message"] unless response["status"] != "failure" end
ruby
def rename(name) response = JSON.parse(CrateAPI::Base.call("#{CrateAPI::Base::CRATES_URL}/#{CrateAPI::Crates::CRATE_ACTIONS[:rename] % ["#{self.id}"]}", :post, {:body => {:name => name}})) raise CrateRenameError, response["message"] unless response["status"] != "failure" end
[ "def", "rename", "(", "name", ")", "response", "=", "JSON", ".", "parse", "(", "CrateAPI", "::", "Base", ".", "call", "(", "\"#{CrateAPI::Base::CRATES_URL}/#{CrateAPI::Crates::CRATE_ACTIONS[:rename] % [\"#{self.id}\"]}\"", ",", ":post", ",", "{", ":body", "=>", "{", ":name", "=>", "name", "}", "}", ")", ")", "raise", "CrateRenameError", ",", "response", "[", "\"message\"", "]", "unless", "response", "[", "\"status\"", "]", "!=", "\"failure\"", "end" ]
Renamed the given crate object. @return [CrateRenameError, nil] if there is an issue with renaming the crate, an error will be raised with the message explaining why.
[ "Renamed", "the", "given", "crate", "object", "." ]
722fcbd08a40c5e0a622a2bdaa3687a753cc7970
https://github.com/brianmichel/Crate-API/blob/722fcbd08a40c5e0a622a2bdaa3687a753cc7970/lib/crate_api/crate.rb#L33-L36
8,376
brianmichel/Crate-API
lib/crate_api/crate.rb
CrateAPI.Crate.add_file
def add_file(path) file = File.new(path) response = CrateAPI::Base.call("#{CrateAPI::Base::ITEMS_URL}/#{CrateAPI::Items::ITEM_ACTIONS[:upload]}", :post, {:body => {:file => file, :crate_id => @id}}) raise CrateFileAlreadyExistsError, response["message"] unless response["status"] != "failure" end
ruby
def add_file(path) file = File.new(path) response = CrateAPI::Base.call("#{CrateAPI::Base::ITEMS_URL}/#{CrateAPI::Items::ITEM_ACTIONS[:upload]}", :post, {:body => {:file => file, :crate_id => @id}}) raise CrateFileAlreadyExistsError, response["message"] unless response["status"] != "failure" end
[ "def", "add_file", "(", "path", ")", "file", "=", "File", ".", "new", "(", "path", ")", "response", "=", "CrateAPI", "::", "Base", ".", "call", "(", "\"#{CrateAPI::Base::ITEMS_URL}/#{CrateAPI::Items::ITEM_ACTIONS[:upload]}\"", ",", ":post", ",", "{", ":body", "=>", "{", ":file", "=>", "file", ",", ":crate_id", "=>", "@id", "}", "}", ")", "raise", "CrateFileAlreadyExistsError", ",", "response", "[", "\"message\"", "]", "unless", "response", "[", "\"status\"", "]", "!=", "\"failure\"", "end" ]
Add a file to the given crate object. @param [String] This is the path to the file that you wish to upload. @return [CrateFileAlreadyExistsError, nil] if there is an issue uploading the file to the crate, an error will be raised with the message explaining why.
[ "Add", "a", "file", "to", "the", "given", "crate", "object", "." ]
722fcbd08a40c5e0a622a2bdaa3687a753cc7970
https://github.com/brianmichel/Crate-API/blob/722fcbd08a40c5e0a622a2bdaa3687a753cc7970/lib/crate_api/crate.rb#L42-L46
8,377
humpyard/humpyard
app/models/humpyard/element.rb
Humpyard.Element.last_modified
def last_modified rails_root_mtime = Time.zone.at(::File.new("#{Rails.root}").mtime) timestamps = [rails_root_mtime, self.updated_at] timestamps.sort.last end
ruby
def last_modified rails_root_mtime = Time.zone.at(::File.new("#{Rails.root}").mtime) timestamps = [rails_root_mtime, self.updated_at] timestamps.sort.last end
[ "def", "last_modified", "rails_root_mtime", "=", "Time", ".", "zone", ".", "at", "(", "::", "File", ".", "new", "(", "\"#{Rails.root}\"", ")", ".", "mtime", ")", "timestamps", "=", "[", "rails_root_mtime", ",", "self", ".", "updated_at", "]", "timestamps", ".", "sort", ".", "last", "end" ]
Return the logical modification time for the element.
[ "Return", "the", "logical", "modification", "time", "for", "the", "element", "." ]
f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd
https://github.com/humpyard/humpyard/blob/f344ab851f1dfd824c1e4cb4b92f7c62ac0acefd/app/models/humpyard/element.rb#L48-L52
8,378
boxgrinder/boxgrinder-core
lib/boxgrinder-core/helpers/appliance-config-helper.rb
BoxGrinder.ApplianceConfigHelper.substitute
def substitute(init, value, depth) if depth > VAR_SUBSTITUTION_MAX_DEPTH raise SystemStackError, "Maximal recursive depth (#{VAR_SUBSTITUTION_MAX_DEPTH}) reached for resolving variable #{init}, reached #{value} before stopping." end original = value.clone value.gsub!(/(#(.*?)#)+?/) do # 1. Match pre-defined variable, or variable defined in appliance definition. next @appliance_config.variables[$2] if @appliance_config.variables.has_key?($2) # 2. Match from environment variables. next ENV[$2] unless ENV[$2].nil? # 3. No match, replace the original string. $1 end substitute(init, value, depth+1) unless original == value end
ruby
def substitute(init, value, depth) if depth > VAR_SUBSTITUTION_MAX_DEPTH raise SystemStackError, "Maximal recursive depth (#{VAR_SUBSTITUTION_MAX_DEPTH}) reached for resolving variable #{init}, reached #{value} before stopping." end original = value.clone value.gsub!(/(#(.*?)#)+?/) do # 1. Match pre-defined variable, or variable defined in appliance definition. next @appliance_config.variables[$2] if @appliance_config.variables.has_key?($2) # 2. Match from environment variables. next ENV[$2] unless ENV[$2].nil? # 3. No match, replace the original string. $1 end substitute(init, value, depth+1) unless original == value end
[ "def", "substitute", "(", "init", ",", "value", ",", "depth", ")", "if", "depth", ">", "VAR_SUBSTITUTION_MAX_DEPTH", "raise", "SystemStackError", ",", "\"Maximal recursive depth (#{VAR_SUBSTITUTION_MAX_DEPTH})\n reached for resolving variable #{init}, reached #{value} before stopping.\"", "end", "original", "=", "value", ".", "clone", "value", ".", "gsub!", "(", "/", "/", ")", "do", "# 1. Match pre-defined variable, or variable defined in appliance definition.", "next", "@appliance_config", ".", "variables", "[", "$2", "]", "if", "@appliance_config", ".", "variables", ".", "has_key?", "(", "$2", ")", "# 2. Match from environment variables.", "next", "ENV", "[", "$2", "]", "unless", "ENV", "[", "$2", "]", ".", "nil?", "# 3. No match, replace the original string.", "$1", "end", "substitute", "(", "init", ",", "value", ",", "depth", "+", "1", ")", "unless", "original", "==", "value", "end" ]
Replace variables with values. This will occur recursively upto a limited depth if the resolved values themselves contain variables.
[ "Replace", "variables", "with", "values", ".", "This", "will", "occur", "recursively", "upto", "a", "limited", "depth", "if", "the", "resolved", "values", "themselves", "contain", "variables", "." ]
7d54ad1ddf040078b6bab0a4dc94392b2492bde5
https://github.com/boxgrinder/boxgrinder-core/blob/7d54ad1ddf040078b6bab0a4dc94392b2492bde5/lib/boxgrinder-core/helpers/appliance-config-helper.rb#L106-L121
8,379
boxgrinder/boxgrinder-core
lib/boxgrinder-core/helpers/appliance-config-helper.rb
BoxGrinder.ApplianceConfigHelper.merge_partitions
def merge_partitions partitions = {} merge_field('hardware.partitions') do |parts| parts.each do |root, partition| if partitions.keys.include?(root) partitions[root]['size'] = partition['size'] if partitions[root]['size'] < partition['size'] unless partition['type'].nil? partitions[root].delete('options') if partitions[root]['type'] != partition['type'] partitions[root]['type'] = partition['type'] else partitions[root]['type'] = @appliance_config.default_filesystem_type end else partitions[root] = {} partitions[root]['size'] = partition['size'] unless partition['type'].nil? partitions[root]['type'] = partition['type'] else partitions[root]['type'] = @appliance_config.default_filesystem_type end end partitions[root]['passphrase'] = partition['passphrase'] unless partition['passphrase'].nil? partitions[root]['options'] = partition['options'] unless partition['options'].nil? end end # https://bugzilla.redhat.com/show_bug.cgi?id=466275 partitions['/boot'] = {'type' => 'ext3', 'size' => 0.1} if partitions['/boot'].nil? and (@appliance_config.os.name == 'sl' or @appliance_config.os.name == 'centos' or @appliance_config.os.name == 'rhel') and @appliance_config.os.version == '5' @appliance_config.hardware.partitions = partitions end
ruby
def merge_partitions partitions = {} merge_field('hardware.partitions') do |parts| parts.each do |root, partition| if partitions.keys.include?(root) partitions[root]['size'] = partition['size'] if partitions[root]['size'] < partition['size'] unless partition['type'].nil? partitions[root].delete('options') if partitions[root]['type'] != partition['type'] partitions[root]['type'] = partition['type'] else partitions[root]['type'] = @appliance_config.default_filesystem_type end else partitions[root] = {} partitions[root]['size'] = partition['size'] unless partition['type'].nil? partitions[root]['type'] = partition['type'] else partitions[root]['type'] = @appliance_config.default_filesystem_type end end partitions[root]['passphrase'] = partition['passphrase'] unless partition['passphrase'].nil? partitions[root]['options'] = partition['options'] unless partition['options'].nil? end end # https://bugzilla.redhat.com/show_bug.cgi?id=466275 partitions['/boot'] = {'type' => 'ext3', 'size' => 0.1} if partitions['/boot'].nil? and (@appliance_config.os.name == 'sl' or @appliance_config.os.name == 'centos' or @appliance_config.os.name == 'rhel') and @appliance_config.os.version == '5' @appliance_config.hardware.partitions = partitions end
[ "def", "merge_partitions", "partitions", "=", "{", "}", "merge_field", "(", "'hardware.partitions'", ")", "do", "|", "parts", "|", "parts", ".", "each", "do", "|", "root", ",", "partition", "|", "if", "partitions", ".", "keys", ".", "include?", "(", "root", ")", "partitions", "[", "root", "]", "[", "'size'", "]", "=", "partition", "[", "'size'", "]", "if", "partitions", "[", "root", "]", "[", "'size'", "]", "<", "partition", "[", "'size'", "]", "unless", "partition", "[", "'type'", "]", ".", "nil?", "partitions", "[", "root", "]", ".", "delete", "(", "'options'", ")", "if", "partitions", "[", "root", "]", "[", "'type'", "]", "!=", "partition", "[", "'type'", "]", "partitions", "[", "root", "]", "[", "'type'", "]", "=", "partition", "[", "'type'", "]", "else", "partitions", "[", "root", "]", "[", "'type'", "]", "=", "@appliance_config", ".", "default_filesystem_type", "end", "else", "partitions", "[", "root", "]", "=", "{", "}", "partitions", "[", "root", "]", "[", "'size'", "]", "=", "partition", "[", "'size'", "]", "unless", "partition", "[", "'type'", "]", ".", "nil?", "partitions", "[", "root", "]", "[", "'type'", "]", "=", "partition", "[", "'type'", "]", "else", "partitions", "[", "root", "]", "[", "'type'", "]", "=", "@appliance_config", ".", "default_filesystem_type", "end", "end", "partitions", "[", "root", "]", "[", "'passphrase'", "]", "=", "partition", "[", "'passphrase'", "]", "unless", "partition", "[", "'passphrase'", "]", ".", "nil?", "partitions", "[", "root", "]", "[", "'options'", "]", "=", "partition", "[", "'options'", "]", "unless", "partition", "[", "'options'", "]", ".", "nil?", "end", "end", "# https://bugzilla.redhat.com/show_bug.cgi?id=466275", "partitions", "[", "'/boot'", "]", "=", "{", "'type'", "=>", "'ext3'", ",", "'size'", "=>", "0.1", "}", "if", "partitions", "[", "'/boot'", "]", ".", "nil?", "and", "(", "@appliance_config", ".", "os", ".", "name", "==", "'sl'", "or", "@appliance_config", ".", "os", ".", "name", "==", "'centos'", "or", "@appliance_config", ".", "os", ".", "name", "==", "'rhel'", ")", "and", "@appliance_config", ".", "os", ".", "version", "==", "'5'", "@appliance_config", ".", "hardware", ".", "partitions", "=", "partitions", "end" ]
This will merge partitions from multiple appliances.
[ "This", "will", "merge", "partitions", "from", "multiple", "appliances", "." ]
7d54ad1ddf040078b6bab0a4dc94392b2492bde5
https://github.com/boxgrinder/boxgrinder-core/blob/7d54ad1ddf040078b6bab0a4dc94392b2492bde5/lib/boxgrinder-core/helpers/appliance-config-helper.rb#L134-L168
8,380
redding/logsly
lib/logsly/logging182/appenders/rolling_file.rb
Logsly::Logging182::Appenders.RollingFile.copy_truncate
def copy_truncate return unless ::File.exist?(@fn) FileUtils.concat @fn, @fn_copy @io.truncate 0 # touch the age file if needed if @age FileUtils.touch @age_fn @age_fn_mtime = nil end @roller.roll = true end
ruby
def copy_truncate return unless ::File.exist?(@fn) FileUtils.concat @fn, @fn_copy @io.truncate 0 # touch the age file if needed if @age FileUtils.touch @age_fn @age_fn_mtime = nil end @roller.roll = true end
[ "def", "copy_truncate", "return", "unless", "::", "File", ".", "exist?", "(", "@fn", ")", "FileUtils", ".", "concat", "@fn", ",", "@fn_copy", "@io", ".", "truncate", "0", "# touch the age file if needed", "if", "@age", "FileUtils", ".", "touch", "@age_fn", "@age_fn_mtime", "=", "nil", "end", "@roller", ".", "roll", "=", "true", "end" ]
Copy the contents of the logfile to another file. Truncate the logfile to zero length. This method will set the roll flag so that all the current logfiles will be rolled along with the copied file.
[ "Copy", "the", "contents", "of", "the", "logfile", "to", "another", "file", ".", "Truncate", "the", "logfile", "to", "zero", "length", ".", "This", "method", "will", "set", "the", "roll", "flag", "so", "that", "all", "the", "current", "logfiles", "will", "be", "rolled", "along", "with", "the", "copied", "file", "." ]
a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf
https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/appenders/rolling_file.rb#L232-L244
8,381
ketan/diff-display
lib/diff/display/unified/generator.rb
Diff::Display.Unified::Generator.inline_diff
def inline_diff(line, start, ending) if start != 0 || ending != 0 last = ending + line.length str = line[0...start] + '\0' + line[start...last] + '\1' + line[last...line.length] end str || line end
ruby
def inline_diff(line, start, ending) if start != 0 || ending != 0 last = ending + line.length str = line[0...start] + '\0' + line[start...last] + '\1' + line[last...line.length] end str || line end
[ "def", "inline_diff", "(", "line", ",", "start", ",", "ending", ")", "if", "start", "!=", "0", "||", "ending", "!=", "0", "last", "=", "ending", "+", "line", ".", "length", "str", "=", "line", "[", "0", "...", "start", "]", "+", "'\\0'", "+", "line", "[", "start", "...", "last", "]", "+", "'\\1'", "+", "line", "[", "last", "...", "line", ".", "length", "]", "end", "str", "||", "line", "end" ]
Inserts string formating characters around the section of a string that differs internally from another line so that the Line class can insert the desired formating
[ "Inserts", "string", "formating", "characters", "around", "the", "section", "of", "a", "string", "that", "differs", "internally", "from", "another", "line", "so", "that", "the", "Line", "class", "can", "insert", "the", "desired", "formating" ]
39a75568148bcd1ee386189d6b46af3126a3a785
https://github.com/ketan/diff-display/blob/39a75568148bcd1ee386189d6b46af3126a3a785/lib/diff/display/unified/generator.rb#L160-L166
8,382
edmundhighcock/gsl_extras
lib/gsl_extras.rb
GSL.ScatterInterp.function
def function(vec1, vec2) case @func when :linear return normalized_radius(vec1, vec2) when :cubic_alt return normalized_radius(vec1, vec2)**(1.5) when :thin_plate_splines return 0.0 if radius(vec1, vec2) == 0.0 return normalized_radius(vec1, vec2)**2.0 * Math.log(normalized_radius(vec1, vec2)) when :thin_plate_splines_alt rnorm = ((@r0.prod.abs)**(2.0/@r0.size)*(((vec1-vec2).square / @r0.square).sum + 1.0)) return rnorm * Math.log(rnorm) when :multiquadratic # return Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum)) (@r0.prod.abs)**(1.0/@r0.size)*Math.sqrt(((vec1-vec2).square / @r0.square).sum + 1.0) when :inverse_multiquadratic 1.0 / ((@r0.prod.abs)**(1.0/@r0.size)*Math.sqrt(((vec1-vec2).square / @r0.square).sum + 1.0)) when :cubic ((@r0.prod.abs)**(2.0/@r0.size)*(((vec1-vec2).square / @r0.square).sum + 1.0))**(1.5) # invs = ((vec1-vec2).square + @r0.square).sqrt**(-1) # invs.sum # p @ro # return 1.0 / Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum)) # when :inverse_multiquadratic # # p @ro # return 1.0 / Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum)) else raise ArgumentError.new("Bad radial basis function: #{@func}") end end
ruby
def function(vec1, vec2) case @func when :linear return normalized_radius(vec1, vec2) when :cubic_alt return normalized_radius(vec1, vec2)**(1.5) when :thin_plate_splines return 0.0 if radius(vec1, vec2) == 0.0 return normalized_radius(vec1, vec2)**2.0 * Math.log(normalized_radius(vec1, vec2)) when :thin_plate_splines_alt rnorm = ((@r0.prod.abs)**(2.0/@r0.size)*(((vec1-vec2).square / @r0.square).sum + 1.0)) return rnorm * Math.log(rnorm) when :multiquadratic # return Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum)) (@r0.prod.abs)**(1.0/@r0.size)*Math.sqrt(((vec1-vec2).square / @r0.square).sum + 1.0) when :inverse_multiquadratic 1.0 / ((@r0.prod.abs)**(1.0/@r0.size)*Math.sqrt(((vec1-vec2).square / @r0.square).sum + 1.0)) when :cubic ((@r0.prod.abs)**(2.0/@r0.size)*(((vec1-vec2).square / @r0.square).sum + 1.0))**(1.5) # invs = ((vec1-vec2).square + @r0.square).sqrt**(-1) # invs.sum # p @ro # return 1.0 / Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum)) # when :inverse_multiquadratic # # p @ro # return 1.0 / Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum)) else raise ArgumentError.new("Bad radial basis function: #{@func}") end end
[ "def", "function", "(", "vec1", ",", "vec2", ")", "case", "@func", "when", ":linear", "return", "normalized_radius", "(", "vec1", ",", "vec2", ")", "when", ":cubic_alt", "return", "normalized_radius", "(", "vec1", ",", "vec2", ")", "**", "(", "1.5", ")", "when", ":thin_plate_splines", "return", "0.0", "if", "radius", "(", "vec1", ",", "vec2", ")", "==", "0.0", "return", "normalized_radius", "(", "vec1", ",", "vec2", ")", "**", "2.0", "*", "Math", ".", "log", "(", "normalized_radius", "(", "vec1", ",", "vec2", ")", ")", "when", ":thin_plate_splines_alt", "rnorm", "=", "(", "(", "@r0", ".", "prod", ".", "abs", ")", "**", "(", "2.0", "/", "@r0", ".", "size", ")", "*", "(", "(", "(", "vec1", "-", "vec2", ")", ".", "square", "/", "@r0", ".", "square", ")", ".", "sum", "+", "1.0", ")", ")", "return", "rnorm", "*", "Math", ".", "log", "(", "rnorm", ")", "when", ":multiquadratic", "# \t\t\treturn Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum))", "(", "@r0", ".", "prod", ".", "abs", ")", "**", "(", "1.0", "/", "@r0", ".", "size", ")", "*", "Math", ".", "sqrt", "(", "(", "(", "vec1", "-", "vec2", ")", ".", "square", "/", "@r0", ".", "square", ")", ".", "sum", "+", "1.0", ")", "when", ":inverse_multiquadratic", "1.0", "/", "(", "(", "@r0", ".", "prod", ".", "abs", ")", "**", "(", "1.0", "/", "@r0", ".", "size", ")", "*", "Math", ".", "sqrt", "(", "(", "(", "vec1", "-", "vec2", ")", ".", "square", "/", "@r0", ".", "square", ")", ".", "sum", "+", "1.0", ")", ")", "when", ":cubic", "(", "(", "@r0", ".", "prod", ".", "abs", ")", "**", "(", "2.0", "/", "@r0", ".", "size", ")", "*", "(", "(", "(", "vec1", "-", "vec2", ")", ".", "square", "/", "@r0", ".", "square", ")", ".", "sum", "+", "1.0", ")", ")", "**", "(", "1.5", ")", "# \t\t\tinvs = ((vec1-vec2).square + @r0.square).sqrt**(-1)", "# \t\t\tinvs.sum", "# \t\t\t\tp @ro", "# \t\t\treturn 1.0 / Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum))", "# \t\twhen :inverse_multiquadratic", "# # \t\t\t\tp @ro", "# \t\t\treturn 1.0 / Math.sqrt(radius(vec1, vec2)**2 + Math.sqrt(@r0.square.sum))", "else", "raise", "ArgumentError", ".", "new", "(", "\"Bad radial basis function: #{@func}\"", ")", "end", "end" ]
Return the value of the interpolation kernel for the separation between the two given vectors. If linear was chosen this will just be the normalised distance between the two points.
[ "Return", "the", "value", "of", "the", "interpolation", "kernel", "for", "the", "separation", "between", "the", "two", "given", "vectors", ".", "If", "linear", "was", "chosen", "this", "will", "just", "be", "the", "normalised", "distance", "between", "the", "two", "points", "." ]
e38dd98544e12dbf8dee4b384d9ae81ea4900c2a
https://github.com/edmundhighcock/gsl_extras/blob/e38dd98544e12dbf8dee4b384d9ae81ea4900c2a/lib/gsl_extras.rb#L176-L205
8,383
edmundhighcock/gsl_extras
lib/gsl_extras.rb
GSL.ScatterInterp.eval
def eval(*pars) raise ArgumentError("wrong number of points") if pars.size != @dim # p vals pars = GSL::Vector.alloc(pars) return @npoints.times.inject(0.0) do |sum, i| # sum + function(radius(vals, @gridpoints.row(i)))*@weights[i] sum + function(pars, @gridpoints.row(i))*@weights[i] end end
ruby
def eval(*pars) raise ArgumentError("wrong number of points") if pars.size != @dim # p vals pars = GSL::Vector.alloc(pars) return @npoints.times.inject(0.0) do |sum, i| # sum + function(radius(vals, @gridpoints.row(i)))*@weights[i] sum + function(pars, @gridpoints.row(i))*@weights[i] end end
[ "def", "eval", "(", "*", "pars", ")", "raise", "ArgumentError", "(", "\"wrong number of points\"", ")", "if", "pars", ".", "size", "!=", "@dim", "# \t\t\tp vals", "pars", "=", "GSL", "::", "Vector", ".", "alloc", "(", "pars", ")", "return", "@npoints", ".", "times", ".", "inject", "(", "0.0", ")", "do", "|", "sum", ",", "i", "|", "# \t\t\tsum + function(radius(vals, @gridpoints.row(i)))*@weights[i]", "sum", "+", "function", "(", "pars", ",", "@gridpoints", ".", "row", "(", "i", ")", ")", "*", "@weights", "[", "i", "]", "end", "end" ]
Return the interpolated value for the given parameters.
[ "Return", "the", "interpolated", "value", "for", "the", "given", "parameters", "." ]
e38dd98544e12dbf8dee4b384d9ae81ea4900c2a
https://github.com/edmundhighcock/gsl_extras/blob/e38dd98544e12dbf8dee4b384d9ae81ea4900c2a/lib/gsl_extras.rb#L209-L217
8,384
edmundhighcock/gsl_extras
lib/gsl_extras.rb
GSL.ScatterInterp.gaussian_smooth_eval
def gaussian_smooth_eval(*vals, sigma_vec) npix = 7 raise "npix must be odd" if npix%2==0 case vals.size when 2 # delt0 = 3.0*0.999999*sigma_vec[0] / (npix-1) # delt1 = 3.0*0.999999*sigma_vec[1] / (npix-1) # sig3 = 3.0*sigma vals0 = GSL::Vector.linspace(vals[0] - 3.0* sigma_vec[0], vals[0] + 3.0* sigma_vec[0], npix) vals1 = GSL::Vector.linspace(vals[1] - 3.0* sigma_vec[1], vals[1] + 3.0* sigma_vec[1], npix) mat = GSL::Matrix.alloc(vals0.size, vals1.size) for i in 0...vals0.size for j in 0...vals1.size mat[i,j] = eval(vals0[i], vals1[j]) end end mat.gaussian_smooth(*sigma_vec.to_a) cent = (npix - 1) / 2 return mat[cent, cent] else raise 'Not supported for this number of dimensions yet' end end
ruby
def gaussian_smooth_eval(*vals, sigma_vec) npix = 7 raise "npix must be odd" if npix%2==0 case vals.size when 2 # delt0 = 3.0*0.999999*sigma_vec[0] / (npix-1) # delt1 = 3.0*0.999999*sigma_vec[1] / (npix-1) # sig3 = 3.0*sigma vals0 = GSL::Vector.linspace(vals[0] - 3.0* sigma_vec[0], vals[0] + 3.0* sigma_vec[0], npix) vals1 = GSL::Vector.linspace(vals[1] - 3.0* sigma_vec[1], vals[1] + 3.0* sigma_vec[1], npix) mat = GSL::Matrix.alloc(vals0.size, vals1.size) for i in 0...vals0.size for j in 0...vals1.size mat[i,j] = eval(vals0[i], vals1[j]) end end mat.gaussian_smooth(*sigma_vec.to_a) cent = (npix - 1) / 2 return mat[cent, cent] else raise 'Not supported for this number of dimensions yet' end end
[ "def", "gaussian_smooth_eval", "(", "*", "vals", ",", "sigma_vec", ")", "npix", "=", "7", "raise", "\"npix must be odd\"", "if", "npix", "%", "2", "==", "0", "case", "vals", ".", "size", "when", "2", "# \t\t\tdelt0 = 3.0*0.999999*sigma_vec[0] / (npix-1)", "# \t\t\tdelt1 = 3.0*0.999999*sigma_vec[1] / (npix-1)", "# \t\t\tsig3 = 3.0*sigma", "vals0", "=", "GSL", "::", "Vector", ".", "linspace", "(", "vals", "[", "0", "]", "-", "3.0", "*", "sigma_vec", "[", "0", "]", ",", "vals", "[", "0", "]", "+", "3.0", "*", "sigma_vec", "[", "0", "]", ",", "npix", ")", "vals1", "=", "GSL", "::", "Vector", ".", "linspace", "(", "vals", "[", "1", "]", "-", "3.0", "*", "sigma_vec", "[", "1", "]", ",", "vals", "[", "1", "]", "+", "3.0", "*", "sigma_vec", "[", "1", "]", ",", "npix", ")", "mat", "=", "GSL", "::", "Matrix", ".", "alloc", "(", "vals0", ".", "size", ",", "vals1", ".", "size", ")", "for", "i", "in", "0", "...", "vals0", ".", "size", "for", "j", "in", "0", "...", "vals1", ".", "size", "mat", "[", "i", ",", "j", "]", "=", "eval", "(", "vals0", "[", "i", "]", ",", "vals1", "[", "j", "]", ")", "end", "end", "mat", ".", "gaussian_smooth", "(", "sigma_vec", ".", "to_a", ")", "cent", "=", "(", "npix", "-", "1", ")", "/", "2", "return", "mat", "[", "cent", ",", "cent", "]", "else", "raise", "'Not supported for this number of dimensions yet'", "end", "end" ]
Evaluate the function,
[ "Evaluate", "the", "function" ]
e38dd98544e12dbf8dee4b384d9ae81ea4900c2a
https://github.com/edmundhighcock/gsl_extras/blob/e38dd98544e12dbf8dee4b384d9ae81ea4900c2a/lib/gsl_extras.rb#L221-L244
8,385
edmundhighcock/gsl_extras
lib/gsl_extras.rb
GSL.Contour.graphkit
def graphkit(*args) if args.size == 0 conts = @last_contours else conts = contours(*args) end graphs = conts.map do |val, cons| unless cons[0] nil else (cons.map do |con| # p con contour = con.transpose kit = CodeRunner::GraphKit.autocreate({x: {data: contour[0]}, y: {data: contour[1], title: val.to_s}}) kit.data[0].with = "l" kit end).sum end end graphs.compact.reverse.sum end
ruby
def graphkit(*args) if args.size == 0 conts = @last_contours else conts = contours(*args) end graphs = conts.map do |val, cons| unless cons[0] nil else (cons.map do |con| # p con contour = con.transpose kit = CodeRunner::GraphKit.autocreate({x: {data: contour[0]}, y: {data: contour[1], title: val.to_s}}) kit.data[0].with = "l" kit end).sum end end graphs.compact.reverse.sum end
[ "def", "graphkit", "(", "*", "args", ")", "if", "args", ".", "size", "==", "0", "conts", "=", "@last_contours", "else", "conts", "=", "contours", "(", "args", ")", "end", "graphs", "=", "conts", ".", "map", "do", "|", "val", ",", "cons", "|", "unless", "cons", "[", "0", "]", "nil", "else", "(", "cons", ".", "map", "do", "|", "con", "|", "# \t\t\t\tp con", "contour", "=", "con", ".", "transpose", "kit", "=", "CodeRunner", "::", "GraphKit", ".", "autocreate", "(", "{", "x", ":", "{", "data", ":", "contour", "[", "0", "]", "}", ",", "y", ":", "{", "data", ":", "contour", "[", "1", "]", ",", "title", ":", "val", ".", "to_s", "}", "}", ")", "kit", ".", "data", "[", "0", "]", ".", "with", "=", "\"l\"", "kit", "end", ")", ".", "sum", "end", "end", "graphs", ".", "compact", ".", "reverse", ".", "sum", "end" ]
Create a GraphKit object of the contours.
[ "Create", "a", "GraphKit", "object", "of", "the", "contours", "." ]
e38dd98544e12dbf8dee4b384d9ae81ea4900c2a
https://github.com/edmundhighcock/gsl_extras/blob/e38dd98544e12dbf8dee4b384d9ae81ea4900c2a/lib/gsl_extras.rb#L325-L345
8,386
NYULibraries/citero-jruby
lib/citero-jruby/CSF.rb
Citero.CSF.method_missing
def method_missing(meth, *args, &block) # Check to see if it can be evaluated if(matches? meth) #Defines the method and caches it to the class self.class.send(:define_method, meth) do # Splits the method and parameter. See formatize and directionize @csf::config()::getStringArray(meth.to_s.to_java_name).to_a end # calls the method send meth, *args, &block else super end end
ruby
def method_missing(meth, *args, &block) # Check to see if it can be evaluated if(matches? meth) #Defines the method and caches it to the class self.class.send(:define_method, meth) do # Splits the method and parameter. See formatize and directionize @csf::config()::getStringArray(meth.to_s.to_java_name).to_a end # calls the method send meth, *args, &block else super end end
[ "def", "method_missing", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "# Check to see if it can be evaluated", "if", "(", "matches?", "meth", ")", "#Defines the method and caches it to the class", "self", ".", "class", ".", "send", "(", ":define_method", ",", "meth", ")", "do", "# Splits the method and parameter. See formatize and directionize", "@csf", "::", "config", "(", ")", "::", "getStringArray", "(", "meth", ".", "to_s", ".", "to_java_name", ")", ".", "to_a", "end", "# calls the method", "send", "meth", ",", "args", ",", "block", "else", "super", "end", "end" ]
Initialize the CSF object with data The method_missing override checks to see if the called method can be evaluated to a key, then stores it and calls it if it can. For example, .itemType or .authors.
[ "Initialize", "the", "CSF", "object", "with", "data", "The", "method_missing", "override", "checks", "to", "see", "if", "the", "called", "method", "can", "be", "evaluated", "to", "a", "key", "then", "stores", "it", "and", "calls", "it", "if", "it", "can", ".", "For", "example", ".", "itemType", "or", ".", "authors", "." ]
ddf1142a8a05cb1e7153d1887239fe913df563ce
https://github.com/NYULibraries/citero-jruby/blob/ddf1142a8a05cb1e7153d1887239fe913df563ce/lib/citero-jruby/CSF.rb#L21-L34
8,387
yipdw/analysand
lib/analysand/http.rb
Analysand.Http.set_credentials
def set_credentials(req, creds) return unless creds if String === creds req.add_field('Cookie', creds) elsif creds[:username] && creds[:password] req.basic_auth(creds[:username], creds[:password]) end end
ruby
def set_credentials(req, creds) return unless creds if String === creds req.add_field('Cookie', creds) elsif creds[:username] && creds[:password] req.basic_auth(creds[:username], creds[:password]) end end
[ "def", "set_credentials", "(", "req", ",", "creds", ")", "return", "unless", "creds", "if", "String", "===", "creds", "req", ".", "add_field", "(", "'Cookie'", ",", "creds", ")", "elsif", "creds", "[", ":username", "]", "&&", "creds", "[", ":password", "]", "req", ".", "basic_auth", "(", "creds", "[", ":username", "]", ",", "creds", "[", ":password", "]", ")", "end", "end" ]
Sets credentials on a request object. If creds is a hash containing :username and :password keys, HTTP basic authorization is used. If creds is a string, the string is added as a cookie.
[ "Sets", "credentials", "on", "a", "request", "object", "." ]
bc62e67031bf7e813e49538669f7434f2efd9ee9
https://github.com/yipdw/analysand/blob/bc62e67031bf7e813e49538669f7434f2efd9ee9/lib/analysand/http.rb#L80-L88
8,388
zpatten/ztk
lib/ztk/parallel.rb
ZTK.Parallel.wait
def wait(flags=0) config.ui.logger.debug { "wait" } config.ui.logger.debug { "forks(#{@forks.inspect})" } return nil if @forks.count <= 0 pid, status = (Process.wait2(-1, Process::WUNTRACED) rescue nil) if !pid.nil? && !status.nil? && !(fork = @forks.select{ |f| f[:pid] == pid }.first).nil? data = nil begin data = Marshal.load(Zlib::Inflate.inflate(Base64.decode64(fork[:reader].read).to_s)) rescue Zlib::BufError config.ui.logger.fatal { "Encountered Zlib::BufError when reading child pipe." } end config.ui.logger.debug { "read(#{data.inspect})" } data = process_data(data) !data.nil? and @results.push(data) fork[:reader].close fork[:writer].close @forks -= [fork] return [pid, status, data] end nil end
ruby
def wait(flags=0) config.ui.logger.debug { "wait" } config.ui.logger.debug { "forks(#{@forks.inspect})" } return nil if @forks.count <= 0 pid, status = (Process.wait2(-1, Process::WUNTRACED) rescue nil) if !pid.nil? && !status.nil? && !(fork = @forks.select{ |f| f[:pid] == pid }.first).nil? data = nil begin data = Marshal.load(Zlib::Inflate.inflate(Base64.decode64(fork[:reader].read).to_s)) rescue Zlib::BufError config.ui.logger.fatal { "Encountered Zlib::BufError when reading child pipe." } end config.ui.logger.debug { "read(#{data.inspect})" } data = process_data(data) !data.nil? and @results.push(data) fork[:reader].close fork[:writer].close @forks -= [fork] return [pid, status, data] end nil end
[ "def", "wait", "(", "flags", "=", "0", ")", "config", ".", "ui", ".", "logger", ".", "debug", "{", "\"wait\"", "}", "config", ".", "ui", ".", "logger", ".", "debug", "{", "\"forks(#{@forks.inspect})\"", "}", "return", "nil", "if", "@forks", ".", "count", "<=", "0", "pid", ",", "status", "=", "(", "Process", ".", "wait2", "(", "-", "1", ",", "Process", "::", "WUNTRACED", ")", "rescue", "nil", ")", "if", "!", "pid", ".", "nil?", "&&", "!", "status", ".", "nil?", "&&", "!", "(", "fork", "=", "@forks", ".", "select", "{", "|", "f", "|", "f", "[", ":pid", "]", "==", "pid", "}", ".", "first", ")", ".", "nil?", "data", "=", "nil", "begin", "data", "=", "Marshal", ".", "load", "(", "Zlib", "::", "Inflate", ".", "inflate", "(", "Base64", ".", "decode64", "(", "fork", "[", ":reader", "]", ".", "read", ")", ".", "to_s", ")", ")", "rescue", "Zlib", "::", "BufError", "config", ".", "ui", ".", "logger", ".", "fatal", "{", "\"Encountered Zlib::BufError when reading child pipe.\"", "}", "end", "config", ".", "ui", ".", "logger", ".", "debug", "{", "\"read(#{data.inspect})\"", "}", "data", "=", "process_data", "(", "data", ")", "!", "data", ".", "nil?", "and", "@results", ".", "push", "(", "data", ")", "fork", "[", ":reader", "]", ".", "close", "fork", "[", ":writer", "]", ".", "close", "@forks", "-=", "[", "fork", "]", "return", "[", "pid", ",", "status", ",", "data", "]", "end", "nil", "end" ]
Wait for a single fork to finish. If a fork successfully finishes, it's return value from the *process* block is stored into the main result set. @return [Array<pid, status, data>] An array containing the pid, status and data returned from the process block. If wait2() fails nil is returned.
[ "Wait", "for", "a", "single", "fork", "to", "finish", "." ]
9b0f35bef36f38428e1a57b36f25a806c240b3fb
https://github.com/zpatten/ztk/blob/9b0f35bef36f38428e1a57b36f25a806c240b3fb/lib/ztk/parallel.rb#L205-L232
8,389
zpatten/ztk
lib/ztk/parallel.rb
ZTK.Parallel.signal_all
def signal_all(signal="KILL") signaled = 0 if (!@forks.nil? && (@forks.count > 0)) @forks.each do |fork| begin Process.kill(signal, fork[:pid]) signaled += 1 rescue nil end end end signaled end
ruby
def signal_all(signal="KILL") signaled = 0 if (!@forks.nil? && (@forks.count > 0)) @forks.each do |fork| begin Process.kill(signal, fork[:pid]) signaled += 1 rescue nil end end end signaled end
[ "def", "signal_all", "(", "signal", "=", "\"KILL\"", ")", "signaled", "=", "0", "if", "(", "!", "@forks", ".", "nil?", "&&", "(", "@forks", ".", "count", ">", "0", ")", ")", "@forks", ".", "each", "do", "|", "fork", "|", "begin", "Process", ".", "kill", "(", "signal", ",", "fork", "[", ":pid", "]", ")", "signaled", "+=", "1", "rescue", "nil", "end", "end", "end", "signaled", "end" ]
Signals all forks. @return [Integer] The number of processes signaled.
[ "Signals", "all", "forks", "." ]
9b0f35bef36f38428e1a57b36f25a806c240b3fb
https://github.com/zpatten/ztk/blob/9b0f35bef36f38428e1a57b36f25a806c240b3fb/lib/ztk/parallel.rb#L248-L261
8,390
tylerflint/vli
lib/vli/registry.rb
Vli.Registry.register
def register(key, value=nil, &block) block = lambda { value } if value @actions[key] = block end
ruby
def register(key, value=nil, &block) block = lambda { value } if value @actions[key] = block end
[ "def", "register", "(", "key", ",", "value", "=", "nil", ",", "&", "block", ")", "block", "=", "lambda", "{", "value", "}", "if", "value", "@actions", "[", "key", "]", "=", "block", "end" ]
Register a callable by key. The callable should be given in a block which will be lazily evaluated when the action is needed. If an action by the given name already exists then it will be overwritten.
[ "Register", "a", "callable", "by", "key", "." ]
7509ae2df7fcac0325edb819866a4b3be37edede
https://github.com/tylerflint/vli/blob/7509ae2df7fcac0325edb819866a4b3be37edede/lib/vli/registry.rb#L23-L26
8,391
tylerflint/vli
lib/vli/registry.rb
Vli.Registry.get
def get(key) return nil if !@actions.has_key?(key) return @results_cache[key] if @results_cache.has_key?(key) @results_cache[key] = @actions[key].call end
ruby
def get(key) return nil if !@actions.has_key?(key) return @results_cache[key] if @results_cache.has_key?(key) @results_cache[key] = @actions[key].call end
[ "def", "get", "(", "key", ")", "return", "nil", "if", "!", "@actions", ".", "has_key?", "(", "key", ")", "return", "@results_cache", "[", "key", "]", "if", "@results_cache", ".", "has_key?", "(", "key", ")", "@results_cache", "[", "key", "]", "=", "@actions", "[", "key", "]", ".", "call", "end" ]
Get an action by the given key. This will evaluate the block given to `register` and return the resulting action stack.
[ "Get", "an", "action", "by", "the", "given", "key", "." ]
7509ae2df7fcac0325edb819866a4b3be37edede
https://github.com/tylerflint/vli/blob/7509ae2df7fcac0325edb819866a4b3be37edede/lib/vli/registry.rb#L32-L36
8,392
rixth/tay
lib/tay/specification_validator.rb
Tay.SpecificationValidator.check_file_presence
def check_file_presence spec.icons.values.each do |path| fail_if_not_exist "Icon", path end if spec.browser_action fail_if_not_exist "Browser action popup", spec.browser_action.popup fail_if_not_exist "Browser action icon", spec.browser_action.icon end if spec.page_action fail_if_not_exist "Page action popup", spec.page_action.popup fail_if_not_exist "Page action icon", spec.page_action.icon end if spec.packaged_app fail_if_not_exist "App launch page", spec.packaged_app.page end spec.content_scripts.each do |content_script| content_script.javascripts.each do |script_path| fail_if_not_exist "Content script javascript", script_path end content_script.stylesheets.each do |style_path| fail_if_not_exist "Content script style", style_path end end spec.background_scripts.each do |script_path| fail_if_not_exist "Background script style", script_path end fail_if_not_exist "Background page", spec.background_page fail_if_not_exist "Options page", spec.options_page spec.web_intents.each do |web_intent| fail_if_not_exist "Web intent href", web_intent.href end spec.nacl_modules.each do |nacl_module| fail_if_not_exist "NaCl module", nacl_module.path end spec.web_accessible_resources.each do |path| fail_if_not_exist "Web accessible resource", path end end
ruby
def check_file_presence spec.icons.values.each do |path| fail_if_not_exist "Icon", path end if spec.browser_action fail_if_not_exist "Browser action popup", spec.browser_action.popup fail_if_not_exist "Browser action icon", spec.browser_action.icon end if spec.page_action fail_if_not_exist "Page action popup", spec.page_action.popup fail_if_not_exist "Page action icon", spec.page_action.icon end if spec.packaged_app fail_if_not_exist "App launch page", spec.packaged_app.page end spec.content_scripts.each do |content_script| content_script.javascripts.each do |script_path| fail_if_not_exist "Content script javascript", script_path end content_script.stylesheets.each do |style_path| fail_if_not_exist "Content script style", style_path end end spec.background_scripts.each do |script_path| fail_if_not_exist "Background script style", script_path end fail_if_not_exist "Background page", spec.background_page fail_if_not_exist "Options page", spec.options_page spec.web_intents.each do |web_intent| fail_if_not_exist "Web intent href", web_intent.href end spec.nacl_modules.each do |nacl_module| fail_if_not_exist "NaCl module", nacl_module.path end spec.web_accessible_resources.each do |path| fail_if_not_exist "Web accessible resource", path end end
[ "def", "check_file_presence", "spec", ".", "icons", ".", "values", ".", "each", "do", "|", "path", "|", "fail_if_not_exist", "\"Icon\"", ",", "path", "end", "if", "spec", ".", "browser_action", "fail_if_not_exist", "\"Browser action popup\"", ",", "spec", ".", "browser_action", ".", "popup", "fail_if_not_exist", "\"Browser action icon\"", ",", "spec", ".", "browser_action", ".", "icon", "end", "if", "spec", ".", "page_action", "fail_if_not_exist", "\"Page action popup\"", ",", "spec", ".", "page_action", ".", "popup", "fail_if_not_exist", "\"Page action icon\"", ",", "spec", ".", "page_action", ".", "icon", "end", "if", "spec", ".", "packaged_app", "fail_if_not_exist", "\"App launch page\"", ",", "spec", ".", "packaged_app", ".", "page", "end", "spec", ".", "content_scripts", ".", "each", "do", "|", "content_script", "|", "content_script", ".", "javascripts", ".", "each", "do", "|", "script_path", "|", "fail_if_not_exist", "\"Content script javascript\"", ",", "script_path", "end", "content_script", ".", "stylesheets", ".", "each", "do", "|", "style_path", "|", "fail_if_not_exist", "\"Content script style\"", ",", "style_path", "end", "end", "spec", ".", "background_scripts", ".", "each", "do", "|", "script_path", "|", "fail_if_not_exist", "\"Background script style\"", ",", "script_path", "end", "fail_if_not_exist", "\"Background page\"", ",", "spec", ".", "background_page", "fail_if_not_exist", "\"Options page\"", ",", "spec", ".", "options_page", "spec", ".", "web_intents", ".", "each", "do", "|", "web_intent", "|", "fail_if_not_exist", "\"Web intent href\"", ",", "web_intent", ".", "href", "end", "spec", ".", "nacl_modules", ".", "each", "do", "|", "nacl_module", "|", "fail_if_not_exist", "\"NaCl module\"", ",", "nacl_module", ".", "path", "end", "spec", ".", "web_accessible_resources", ".", "each", "do", "|", "path", "|", "fail_if_not_exist", "\"Web accessible resource\"", ",", "path", "end", "end" ]
Go through the specification checking that files that are pointed to actually exist
[ "Go", "through", "the", "specification", "checking", "that", "files", "that", "are", "pointed", "to", "actually", "exist" ]
60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5
https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/specification_validator.rb#L62-L108
8,393
kellysutton/bliptv
lib/bliptv/request.rb
BlipTV.Request.set
def set(container, &declarations) struct = OpenStruct.new declarations.call(struct) send("#{container}=", struct.table) end
ruby
def set(container, &declarations) struct = OpenStruct.new declarations.call(struct) send("#{container}=", struct.table) end
[ "def", "set", "(", "container", ",", "&", "declarations", ")", "struct", "=", "OpenStruct", ".", "new", "declarations", ".", "call", "(", "struct", ")", "send", "(", "\"#{container}=\"", ",", "struct", ".", "table", ")", "end" ]
Use this method to setup your request's payload and headers. Example: request.set :headers do |h| h.content_type = 'application/ufo' end request.set :params do |p| p.sessionid = '12323' p.api_key = '13123 end
[ "Use", "this", "method", "to", "setup", "your", "request", "s", "payload", "and", "headers", "." ]
4fd0d6132ded3069401d0fdf2f35726b71d3c64d
https://github.com/kellysutton/bliptv/blob/4fd0d6132ded3069401d0fdf2f35726b71d3c64d/lib/bliptv/request.rb#L45-L49
8,394
kellysutton/bliptv
lib/bliptv/request.rb
BlipTV.Request.run
def run(&block) if block_given? set(:params, &block) end if post? and multipart? put_multipart_params_into_body else put_params_into_url end request = RestClient::Request.execute( :method => http_method, :url => url, :headers => headers, :payload => body ) self.response = parse_response(request) end
ruby
def run(&block) if block_given? set(:params, &block) end if post? and multipart? put_multipart_params_into_body else put_params_into_url end request = RestClient::Request.execute( :method => http_method, :url => url, :headers => headers, :payload => body ) self.response = parse_response(request) end
[ "def", "run", "(", "&", "block", ")", "if", "block_given?", "set", "(", ":params", ",", "block", ")", "end", "if", "post?", "and", "multipart?", "put_multipart_params_into_body", "else", "put_params_into_url", "end", "request", "=", "RestClient", "::", "Request", ".", "execute", "(", ":method", "=>", "http_method", ",", ":url", "=>", "url", ",", ":headers", "=>", "headers", ",", ":payload", "=>", "body", ")", "self", ".", "response", "=", "parse_response", "(", "request", ")", "end" ]
Send http request to Viddler API.
[ "Send", "http", "request", "to", "Viddler", "API", "." ]
4fd0d6132ded3069401d0fdf2f35726b71d3c64d
https://github.com/kellysutton/bliptv/blob/4fd0d6132ded3069401d0fdf2f35726b71d3c64d/lib/bliptv/request.rb#L52-L70
8,395
nerab/pwl
lib/pwl/locker.rb
Pwl.Locker.authenticate
def authenticate begin @backend.transaction(true){ raise NotInitializedError.new(@backend.path.path) unless @backend[:user] && @backend[:system] && @backend[:system][:created] check_salt! } rescue OpenSSL::Cipher::CipherError raise WrongMasterPasswordError end end
ruby
def authenticate begin @backend.transaction(true){ raise NotInitializedError.new(@backend.path.path) unless @backend[:user] && @backend[:system] && @backend[:system][:created] check_salt! } rescue OpenSSL::Cipher::CipherError raise WrongMasterPasswordError end end
[ "def", "authenticate", "begin", "@backend", ".", "transaction", "(", "true", ")", "{", "raise", "NotInitializedError", ".", "new", "(", "@backend", ".", "path", ".", "path", ")", "unless", "@backend", "[", ":user", "]", "&&", "@backend", "[", ":system", "]", "&&", "@backend", "[", ":system", "]", "[", ":created", "]", "check_salt!", "}", "rescue", "OpenSSL", "::", "Cipher", "::", "CipherError", "raise", "WrongMasterPasswordError", "end", "end" ]
Check that the master password is correct. This is done to prevent opening an existing but blank locker with the wrong password.
[ "Check", "that", "the", "master", "password", "is", "correct", ".", "This", "is", "done", "to", "prevent", "opening", "an", "existing", "but", "blank", "locker", "with", "the", "wrong", "password", "." ]
ef22d0f43be90c63d0a30564122c31c49148f89c
https://github.com/nerab/pwl/blob/ef22d0f43be90c63d0a30564122c31c49148f89c/lib/pwl/locker.rb#L116-L125
8,396
nerab/pwl
lib/pwl/locker.rb
Pwl.Locker.get
def get(key) raise BlankKeyError if key.blank? @backend.transaction{ timestamp!(:last_accessed) value = @backend[:user][encrypt(key)] raise KeyNotFoundError.new(key) unless value EntryMapper.from_json(decrypt(value)) } end
ruby
def get(key) raise BlankKeyError if key.blank? @backend.transaction{ timestamp!(:last_accessed) value = @backend[:user][encrypt(key)] raise KeyNotFoundError.new(key) unless value EntryMapper.from_json(decrypt(value)) } end
[ "def", "get", "(", "key", ")", "raise", "BlankKeyError", "if", "key", ".", "blank?", "@backend", ".", "transaction", "{", "timestamp!", "(", ":last_accessed", ")", "value", "=", "@backend", "[", ":user", "]", "[", "encrypt", "(", "key", ")", "]", "raise", "KeyNotFoundError", ".", "new", "(", "key", ")", "unless", "value", "EntryMapper", ".", "from_json", "(", "decrypt", "(", "value", ")", ")", "}", "end" ]
Return the value stored under key
[ "Return", "the", "value", "stored", "under", "key" ]
ef22d0f43be90c63d0a30564122c31c49148f89c
https://github.com/nerab/pwl/blob/ef22d0f43be90c63d0a30564122c31c49148f89c/lib/pwl/locker.rb#L130-L138
8,397
nerab/pwl
lib/pwl/locker.rb
Pwl.Locker.add
def add(entry_or_key, value = nil) if value.nil? and entry_or_key.is_a?(Entry) # treat as entry entry = entry_or_key else entry = Entry.new(entry_or_key) entry.password = value end entry.validate! @backend.transaction{ timestamp!(:last_modified) @backend[:user][encrypt(entry.name)] = encrypt(EntryMapper.to_json(entry)) } end
ruby
def add(entry_or_key, value = nil) if value.nil? and entry_or_key.is_a?(Entry) # treat as entry entry = entry_or_key else entry = Entry.new(entry_or_key) entry.password = value end entry.validate! @backend.transaction{ timestamp!(:last_modified) @backend[:user][encrypt(entry.name)] = encrypt(EntryMapper.to_json(entry)) } end
[ "def", "add", "(", "entry_or_key", ",", "value", "=", "nil", ")", "if", "value", ".", "nil?", "and", "entry_or_key", ".", "is_a?", "(", "Entry", ")", "# treat as entry", "entry", "=", "entry_or_key", "else", "entry", "=", "Entry", ".", "new", "(", "entry_or_key", ")", "entry", ".", "password", "=", "value", "end", "entry", ".", "validate!", "@backend", ".", "transaction", "{", "timestamp!", "(", ":last_modified", ")", "@backend", "[", ":user", "]", "[", "encrypt", "(", "entry", ".", "name", ")", "]", "=", "encrypt", "(", "EntryMapper", ".", "to_json", "(", "entry", ")", ")", "}", "end" ]
Store entry or value under key
[ "Store", "entry", "or", "value", "under", "key" ]
ef22d0f43be90c63d0a30564122c31c49148f89c
https://github.com/nerab/pwl/blob/ef22d0f43be90c63d0a30564122c31c49148f89c/lib/pwl/locker.rb#L143-L157
8,398
nerab/pwl
lib/pwl/locker.rb
Pwl.Locker.delete
def delete(key) raise BlankKeyError if key.blank? @backend.transaction{ timestamp!(:last_modified) old_value = @backend[:user].delete(encrypt(key)) raise KeyNotFoundError.new(key) unless old_value EntryMapper.from_json(decrypt(old_value)) } end
ruby
def delete(key) raise BlankKeyError if key.blank? @backend.transaction{ timestamp!(:last_modified) old_value = @backend[:user].delete(encrypt(key)) raise KeyNotFoundError.new(key) unless old_value EntryMapper.from_json(decrypt(old_value)) } end
[ "def", "delete", "(", "key", ")", "raise", "BlankKeyError", "if", "key", ".", "blank?", "@backend", ".", "transaction", "{", "timestamp!", "(", ":last_modified", ")", "old_value", "=", "@backend", "[", ":user", "]", ".", "delete", "(", "encrypt", "(", "key", ")", ")", "raise", "KeyNotFoundError", ".", "new", "(", "key", ")", "unless", "old_value", "EntryMapper", ".", "from_json", "(", "decrypt", "(", "old_value", ")", ")", "}", "end" ]
Delete the value that is stored under key and return it
[ "Delete", "the", "value", "that", "is", "stored", "under", "key", "and", "return", "it" ]
ef22d0f43be90c63d0a30564122c31c49148f89c
https://github.com/nerab/pwl/blob/ef22d0f43be90c63d0a30564122c31c49148f89c/lib/pwl/locker.rb#L162-L170
8,399
nerab/pwl
lib/pwl/locker.rb
Pwl.Locker.all
def all result = [] @backend.transaction(true){ @backend[:user].each{|k,v| result << EntryMapper.from_json(decrypt(v))} } result end
ruby
def all result = [] @backend.transaction(true){ @backend[:user].each{|k,v| result << EntryMapper.from_json(decrypt(v))} } result end
[ "def", "all", "result", "=", "[", "]", "@backend", ".", "transaction", "(", "true", ")", "{", "@backend", "[", ":user", "]", ".", "each", "{", "|", "k", ",", "v", "|", "result", "<<", "EntryMapper", ".", "from_json", "(", "decrypt", "(", "v", ")", ")", "}", "}", "result", "end" ]
Return all entries as array
[ "Return", "all", "entries", "as", "array" ]
ef22d0f43be90c63d0a30564122c31c49148f89c
https://github.com/nerab/pwl/blob/ef22d0f43be90c63d0a30564122c31c49148f89c/lib/pwl/locker.rb#L190-L196