repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
vojto/active_harmony
lib/active_harmony/synchronizer_configuration.rb
ActiveHarmony.SynchronizerConfiguration.synchronizable_for_types
def synchronizable_for_types(types) @synchronizable_fields.select do |field_description| types.include?(field_description[:type]) end.collect do |field_description| field_description[:field] end end
ruby
def synchronizable_for_types(types) @synchronizable_fields.select do |field_description| types.include?(field_description[:type]) end.collect do |field_description| field_description[:field] end end
[ "def", "synchronizable_for_types", "(", "types", ")", "@synchronizable_fields", ".", "select", "do", "|", "field_description", "|", "types", ".", "include?", "(", "field_description", "[", ":type", "]", ")", "end", ".", "collect", "do", "|", "field_description", "|", "field_description", "[", ":field", "]", "end", "end" ]
Fields that should be synchronized on types specified in argument @param [Array<Symbol>] Types @return [Array<Symbol>] Fields
[ "Fields", "that", "should", "be", "synchronized", "on", "types", "specified", "in", "argument" ]
03e5c67ea7a1f986c729001c4fec944bf116640f
https://github.com/vojto/active_harmony/blob/03e5c67ea7a1f986c729001c4fec944bf116640f/lib/active_harmony/synchronizer_configuration.rb#L63-L69
train
jemmyw/measurement
lib/measurement.rb
Measurement.Base.to_s
def to_s(unit = nil, precision = 0) if unit.to_s =~ /_and_/ units = unit.to_s.split('_and_').map do |unit| self.class.fetch_scale(unit) end UnitGroup.new(units).format(@amount, precision) else unit = self.class.fetch_scale(unit) unit.format(@amount, precision) end end
ruby
def to_s(unit = nil, precision = 0) if unit.to_s =~ /_and_/ units = unit.to_s.split('_and_').map do |unit| self.class.fetch_scale(unit) end UnitGroup.new(units).format(@amount, precision) else unit = self.class.fetch_scale(unit) unit.format(@amount, precision) end end
[ "def", "to_s", "(", "unit", "=", "nil", ",", "precision", "=", "0", ")", "if", "unit", ".", "to_s", "=~", "/", "/", "units", "=", "unit", ".", "to_s", ".", "split", "(", "'_and_'", ")", ".", "map", "do", "|", "unit", "|", "self", ".", "class", ".", "fetch_scale", "(", "unit", ")", "end", "UnitGroup", ".", "new", "(", "units", ")", ".", "format", "(", "@amount", ",", "precision", ")", "else", "unit", "=", "self", ".", "class", ".", "fetch_scale", "(", "unit", ")", "unit", ".", "format", "(", "@amount", ",", "precision", ")", "end", "end" ]
Format the measurement and return as a string. This will format using the base unit if no unit is specified. Example: Length.new(1.8034).to_s(:feet) => 6' Multiple units can be specified allowing for a more naturally formatted measurement. For example: Length.new(1.8034).to_s(:feet_and_inches) => 5' 11" Naturally formatted measurements can be returned using shorthand functions: Length.new(1.8034).in_feet_and_inches => 5' 11" The unit group can also be specified to get a similar effect: Length.new(1.8034).to_s(:metric) => '1m 80cm 3mm' A precision can be specified, otherwise the measurement is rounded to the nearest integer.
[ "Format", "the", "measurement", "and", "return", "as", "a", "string", ".", "This", "will", "format", "using", "the", "base", "unit", "if", "no", "unit", "is", "specified", "." ]
dfa192875e014ed56acfd496bcc12b00da15b540
https://github.com/jemmyw/measurement/blob/dfa192875e014ed56acfd496bcc12b00da15b540/lib/measurement.rb#L284-L295
train
fauxparse/matchy_matchy
lib/matchy_matchy/match_list.rb
MatchyMatchy.MatchList.<<
def <<(match) if include?(match) match.reject! else @matches << match @matches.sort! @matches.pop.reject! if @matches.size > @capacity end self end
ruby
def <<(match) if include?(match) match.reject! else @matches << match @matches.sort! @matches.pop.reject! if @matches.size > @capacity end self end
[ "def", "<<", "(", "match", ")", "if", "include?", "(", "match", ")", "match", ".", "reject!", "else", "@matches", "<<", "match", "@matches", ".", "sort!", "@matches", ".", "pop", ".", "reject!", "if", "@matches", ".", "size", ">", "@capacity", "end", "self", "end" ]
Initializes the list. @param capacity [Integer] The maximum number of matches this list can hold Pushes a match into the list. The list is re-sorted and any matches that don’t fit are rejected. @param match [MatchyMatchy::Match] @return [MatchyMatchy::MatchList] Self
[ "Initializes", "the", "list", "." ]
4e11ea438e08c0cc4d04836ffe0c61f196a70b94
https://github.com/fauxparse/matchy_matchy/blob/4e11ea438e08c0cc4d04836ffe0c61f196a70b94/lib/matchy_matchy/match_list.rb#L19-L28
train
tomtt/method_info
lib/method_info/ancestor_method_structure.rb
MethodInfo.AncestorMethodStructure.method_owner
def method_owner(method_symbol) # Under normal circumstances just calling @object.method(method_symbol) would work, # but this will go wrong if the object has redefined the method method. method = Object.instance_method(:method).bind(@object).call(method_symbol) method.owner rescue NameError poor_mans_method_owner(method, method_symbol.to_s) end
ruby
def method_owner(method_symbol) # Under normal circumstances just calling @object.method(method_symbol) would work, # but this will go wrong if the object has redefined the method method. method = Object.instance_method(:method).bind(@object).call(method_symbol) method.owner rescue NameError poor_mans_method_owner(method, method_symbol.to_s) end
[ "def", "method_owner", "(", "method_symbol", ")", "# Under normal circumstances just calling @object.method(method_symbol) would work,", "# but this will go wrong if the object has redefined the method method.", "method", "=", "Object", ".", "instance_method", "(", ":method", ")", ".", "bind", "(", "@object", ")", ".", "call", "(", "method_symbol", ")", "method", ".", "owner", "rescue", "NameError", "poor_mans_method_owner", "(", "method", ",", "method_symbol", ".", "to_s", ")", "end" ]
Returns the class or module where method is defined
[ "Returns", "the", "class", "or", "module", "where", "method", "is", "defined" ]
c9436535dc9d2314cb6d6914ba072554ac956c5c
https://github.com/tomtt/method_info/blob/c9436535dc9d2314cb6d6914ba072554ac956c5c/lib/method_info/ancestor_method_structure.rb#L163-L171
train
simonswine/php_fpm_docker
lib/php_fpm_docker/launcher.rb
PhpFpmDocker.Launcher.parse_config
def parse_config # rubocop:disable MethodLength # Test for file usability fail "Config file '#{@config_path}' not found"\ unless @config_path.file? fail "Config file '#{@config_path}' not readable"\ unless @config_path.readable? @ini_file = IniFile.load(@config_path) begin docker_image = @ini_file[:main]['docker_image'] @docker_image = Docker::Image.get(docker_image) @logger.info(to_s) do "Docker image id=#{@docker_image.id[0..11]} name=#{docker_image}" end rescue NoMethodError raise 'No docker_image in section main in config found' rescue Docker::Error::NotFoundError raise "Docker_image '#{docker_image}' not found" rescue Excon::Errors::SocketError => e raise "Docker connection could not be established: #{e.message}" end end
ruby
def parse_config # rubocop:disable MethodLength # Test for file usability fail "Config file '#{@config_path}' not found"\ unless @config_path.file? fail "Config file '#{@config_path}' not readable"\ unless @config_path.readable? @ini_file = IniFile.load(@config_path) begin docker_image = @ini_file[:main]['docker_image'] @docker_image = Docker::Image.get(docker_image) @logger.info(to_s) do "Docker image id=#{@docker_image.id[0..11]} name=#{docker_image}" end rescue NoMethodError raise 'No docker_image in section main in config found' rescue Docker::Error::NotFoundError raise "Docker_image '#{docker_image}' not found" rescue Excon::Errors::SocketError => e raise "Docker connection could not be established: #{e.message}" end end
[ "def", "parse_config", "# rubocop:disable MethodLength", "# Test for file usability", "fail", "\"Config file '#{@config_path}' not found\"", "unless", "@config_path", ".", "file?", "fail", "\"Config file '#{@config_path}' not readable\"", "unless", "@config_path", ".", "readable?", "@ini_file", "=", "IniFile", ".", "load", "(", "@config_path", ")", "begin", "docker_image", "=", "@ini_file", "[", ":main", "]", "[", "'docker_image'", "]", "@docker_image", "=", "Docker", "::", "Image", ".", "get", "(", "docker_image", ")", "@logger", ".", "info", "(", "to_s", ")", "do", "\"Docker image id=#{@docker_image.id[0..11]} name=#{docker_image}\"", "end", "rescue", "NoMethodError", "raise", "'No docker_image in section main in config found'", "rescue", "Docker", "::", "Error", "::", "NotFoundError", "raise", "\"Docker_image '#{docker_image}' not found\"", "rescue", "Excon", "::", "Errors", "::", "SocketError", "=>", "e", "raise", "\"Docker connection could not be established: #{e.message}\"", "end", "end" ]
Parse the config file for all pools
[ "Parse", "the", "config", "file", "for", "all", "pools" ]
2d7ab79fb6394a6a3f90457f58fb584cd916ffcd
https://github.com/simonswine/php_fpm_docker/blob/2d7ab79fb6394a6a3f90457f58fb584cd916ffcd/lib/php_fpm_docker/launcher.rb#L174-L196
train
simonswine/php_fpm_docker
lib/php_fpm_docker/launcher.rb
PhpFpmDocker.Launcher.pools_config_content_from_file
def pools_config_content_from_file(config_path) ini_file = IniFile.load(config_path) ret_val = [] ini_file.each_section do |section| ret_val << [section, ini_file[section]] end ret_val end
ruby
def pools_config_content_from_file(config_path) ini_file = IniFile.load(config_path) ret_val = [] ini_file.each_section do |section| ret_val << [section, ini_file[section]] end ret_val end
[ "def", "pools_config_content_from_file", "(", "config_path", ")", "ini_file", "=", "IniFile", ".", "load", "(", "config_path", ")", "ret_val", "=", "[", "]", "ini_file", ".", "each_section", "do", "|", "section", "|", "ret_val", "<<", "[", "section", ",", "ini_file", "[", "section", "]", "]", "end", "ret_val", "end" ]
Reads config sections from a inifile
[ "Reads", "config", "sections", "from", "a", "inifile" ]
2d7ab79fb6394a6a3f90457f58fb584cd916ffcd
https://github.com/simonswine/php_fpm_docker/blob/2d7ab79fb6394a6a3f90457f58fb584cd916ffcd/lib/php_fpm_docker/launcher.rb#L205-L213
train
simonswine/php_fpm_docker
lib/php_fpm_docker/launcher.rb
PhpFpmDocker.Launcher.pools_config_contents
def pools_config_contents ret_val = [] # Loop over Dir[@pools_directory.join('*.conf').to_s].each do |config_path| ret_val += pools_config_content_from_file(config_path) end ret_val end
ruby
def pools_config_contents ret_val = [] # Loop over Dir[@pools_directory.join('*.conf').to_s].each do |config_path| ret_val += pools_config_content_from_file(config_path) end ret_val end
[ "def", "pools_config_contents", "ret_val", "=", "[", "]", "# Loop over", "Dir", "[", "@pools_directory", ".", "join", "(", "'*.conf'", ")", ".", "to_s", "]", ".", "each", "do", "|", "config_path", "|", "ret_val", "+=", "pools_config_content_from_file", "(", "config_path", ")", "end", "ret_val", "end" ]
Merges config sections form all inifiles
[ "Merges", "config", "sections", "form", "all", "inifiles" ]
2d7ab79fb6394a6a3f90457f58fb584cd916ffcd
https://github.com/simonswine/php_fpm_docker/blob/2d7ab79fb6394a6a3f90457f58fb584cd916ffcd/lib/php_fpm_docker/launcher.rb#L216-L224
train
simonswine/php_fpm_docker
lib/php_fpm_docker/launcher.rb
PhpFpmDocker.Launcher.pools_from_config
def pools_from_config configs = {} pools_config_contents.each do |section| # Hash section name and content d = Digest::SHA2.new(256) hash = d.reset.update(section[0]).update(section[1].to_s).to_s configs[hash] = { name: section[0], config: section[1] } end configs end
ruby
def pools_from_config configs = {} pools_config_contents.each do |section| # Hash section name and content d = Digest::SHA2.new(256) hash = d.reset.update(section[0]).update(section[1].to_s).to_s configs[hash] = { name: section[0], config: section[1] } end configs end
[ "def", "pools_from_config", "configs", "=", "{", "}", "pools_config_contents", ".", "each", "do", "|", "section", "|", "# Hash section name and content", "d", "=", "Digest", "::", "SHA2", ".", "new", "(", "256", ")", "hash", "=", "d", ".", "reset", ".", "update", "(", "section", "[", "0", "]", ")", ".", "update", "(", "section", "[", "1", "]", ".", "to_s", ")", ".", "to_s", "configs", "[", "hash", "]", "=", "{", "name", ":", "section", "[", "0", "]", ",", "config", ":", "section", "[", "1", "]", "}", "end", "configs", "end" ]
Hashes configs to detect changes
[ "Hashes", "configs", "to", "detect", "changes" ]
2d7ab79fb6394a6a3f90457f58fb584cd916ffcd
https://github.com/simonswine/php_fpm_docker/blob/2d7ab79fb6394a6a3f90457f58fb584cd916ffcd/lib/php_fpm_docker/launcher.rb#L227-L241
train
vjoel/tkar
lib/tkar/primitives.rb
Tkar.Primitives.polybox
def polybox args, key_args dx, dy = args # return a proc to make the info needed to instantiate/update proc do |tkaroid, cos_r, sin_r| x = tkaroid.x y = tkaroid.y params = tkaroid.params ex = dx[params] rescue dx ey = dy[params] rescue dy points = [ [ ex, ey], [ ex, -ey], [-ex, -ey], [-ex, ey] ] coords = [] points.each do |xv, yv| coords << x + xv * cos_r - yv * sin_r coords << y + xv * sin_r + yv * cos_r end ## possible to skip below if no changes? config = {} handle_generic_config(config, params, key_args) [TkcPolygon, coords, config] end end
ruby
def polybox args, key_args dx, dy = args # return a proc to make the info needed to instantiate/update proc do |tkaroid, cos_r, sin_r| x = tkaroid.x y = tkaroid.y params = tkaroid.params ex = dx[params] rescue dx ey = dy[params] rescue dy points = [ [ ex, ey], [ ex, -ey], [-ex, -ey], [-ex, ey] ] coords = [] points.each do |xv, yv| coords << x + xv * cos_r - yv * sin_r coords << y + xv * sin_r + yv * cos_r end ## possible to skip below if no changes? config = {} handle_generic_config(config, params, key_args) [TkcPolygon, coords, config] end end
[ "def", "polybox", "args", ",", "key_args", "dx", ",", "dy", "=", "args", "# return a proc to make the info needed to instantiate/update", "proc", "do", "|", "tkaroid", ",", "cos_r", ",", "sin_r", "|", "x", "=", "tkaroid", ".", "x", "y", "=", "tkaroid", ".", "y", "params", "=", "tkaroid", ".", "params", "ex", "=", "dx", "[", "params", "]", "rescue", "dx", "ey", "=", "dy", "[", "params", "]", "rescue", "dy", "points", "=", "[", "[", "ex", ",", "ey", "]", ",", "[", "ex", ",", "-", "ey", "]", ",", "[", "-", "ex", ",", "-", "ey", "]", ",", "[", "-", "ex", ",", "ey", "]", "]", "coords", "=", "[", "]", "points", ".", "each", "do", "|", "xv", ",", "yv", "|", "coords", "<<", "x", "+", "xv", "*", "cos_r", "-", "yv", "*", "sin_r", "coords", "<<", "y", "+", "xv", "*", "sin_r", "+", "yv", "*", "cos_r", "end", "## possible to skip below if no changes?", "config", "=", "{", "}", "handle_generic_config", "(", "config", ",", "params", ",", "key_args", ")", "[", "TkcPolygon", ",", "coords", ",", "config", "]", "end", "end" ]
bitmap anchor anchorPos height pixels width pixels window pathName def window args, key_args x, y = args end An embedded window that shows a list of key-value pairs. def proplist args, key_args end just a very simple example!
[ "bitmap", "anchor", "anchorPos", "height", "pixels", "width", "pixels", "window", "pathName", "def", "window", "args", "key_args", "x", "y", "=", "args" ]
4c446bdcc028c0ec2fb858ea882717bd9908d9d0
https://github.com/vjoel/tkar/blob/4c446bdcc028c0ec2fb858ea882717bd9908d9d0/lib/tkar/primitives.rb#L344-L374
train
cordawyn/redlander
lib/redlander/model_proxy.rb
Redlander.ModelProxy.delete_all
def delete_all(pattern = {}) result = true each(pattern) { |st| result &&= delete(st) } result end
ruby
def delete_all(pattern = {}) result = true each(pattern) { |st| result &&= delete(st) } result end
[ "def", "delete_all", "(", "pattern", "=", "{", "}", ")", "result", "=", "true", "each", "(", "pattern", ")", "{", "|", "st", "|", "result", "&&=", "delete", "(", "st", ")", "}", "result", "end" ]
Delete all statements from the model, matching the given pattern @param [Statement, Hash] pattern (see {#find}) @return [Boolean]
[ "Delete", "all", "statements", "from", "the", "model", "matching", "the", "given", "pattern" ]
a5c84e15a7602c674606e531bda6a616b1237c44
https://github.com/cordawyn/redlander/blob/a5c84e15a7602c674606e531bda6a616b1237c44/lib/redlander/model_proxy.rb#L52-L56
train
cordawyn/redlander
lib/redlander/model_proxy.rb
Redlander.ModelProxy.find
def find(scope, pattern = {}) case scope when :first each(pattern).first when :all each(pattern).to_a else raise RedlandError, "Invalid search scope '#{scope}' specified." end end
ruby
def find(scope, pattern = {}) case scope when :first each(pattern).first when :all each(pattern).to_a else raise RedlandError, "Invalid search scope '#{scope}' specified." end end
[ "def", "find", "(", "scope", ",", "pattern", "=", "{", "}", ")", "case", "scope", "when", ":first", "each", "(", "pattern", ")", ".", "first", "when", ":all", "each", "(", "pattern", ")", ".", "to_a", "else", "raise", "RedlandError", ",", "\"Invalid search scope '#{scope}' specified.\"", "end", "end" ]
Find statements satisfying the given criteria. @param [:first, :all] scope find just one or all matches @param [Hash, Statement] pattern matching pattern made of: - Hash with :subject, :predicate or :object nodes, or - "patternized" Statement (nil nodes are matching anything). @return [Statement, Array, nil]
[ "Find", "statements", "satisfying", "the", "given", "criteria", "." ]
a5c84e15a7602c674606e531bda6a616b1237c44
https://github.com/cordawyn/redlander/blob/a5c84e15a7602c674606e531bda6a616b1237c44/lib/redlander/model_proxy.rb#L127-L136
train
bbc/code_cache
lib/code_cache/repo.rb
CodeCache.Repo.location_in_cache
def location_in_cache( revision = nil ) begin elements = [cache, repo_type, split_url, revision].flatten.compact.collect { |i| i.to_s } File.join( elements ) rescue => e raise CacheCalculationError.new(e.msg + e.backtrace.to_s) end end
ruby
def location_in_cache( revision = nil ) begin elements = [cache, repo_type, split_url, revision].flatten.compact.collect { |i| i.to_s } File.join( elements ) rescue => e raise CacheCalculationError.new(e.msg + e.backtrace.to_s) end end
[ "def", "location_in_cache", "(", "revision", "=", "nil", ")", "begin", "elements", "=", "[", "cache", ",", "repo_type", ",", "split_url", ",", "revision", "]", ".", "flatten", ".", "compact", ".", "collect", "{", "|", "i", "|", "i", ".", "to_s", "}", "File", ".", "join", "(", "elements", ")", "rescue", "=>", "e", "raise", "CacheCalculationError", ".", "new", "(", "e", ".", "msg", "+", "e", ".", "backtrace", ".", "to_s", ")", "end", "end" ]
Calculates the location of a cached checkout
[ "Calculates", "the", "location", "of", "a", "cached", "checkout" ]
69ab998898f9b0953da17117e8ee33e8e15dfc97
https://github.com/bbc/code_cache/blob/69ab998898f9b0953da17117e8ee33e8e15dfc97/lib/code_cache/repo.rb#L26-L33
train
ryansobol/mango
lib/mango/content_page.rb
Mango.ContentPage.method_missing
def method_missing(method_name, *args, &block) key = method_name.to_s attributes.has_key?(key) ? attributes[key] : super end
ruby
def method_missing(method_name, *args, &block) key = method_name.to_s attributes.has_key?(key) ? attributes[key] : super end
[ "def", "method_missing", "(", "method_name", ",", "*", "args", ",", "&", "block", ")", "key", "=", "method_name", ".", "to_s", "attributes", ".", "has_key?", "(", "key", ")", "?", "attributes", "[", "key", "]", ":", "super", "end" ]
Adds syntactic suger for reading attributes. @example page.title == page.attributes["title"] @param [Symbol] method_name @param [Array] args @param [Proc] block @raise [NoMethodError] Raised when there is no method name key in attributes @return [Object] Value of the method name attribute
[ "Adds", "syntactic", "suger", "for", "reading", "attributes", "." ]
f28f1fb9ff2820f11e6b9f96cdd92576774da12f
https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/content_page.rb#L159-L162
train
eriksk/kawaii
lib/kawaii/content_manager.rb
Kawaii.ContentManager.load_image
def load_image(path, tileable = false) if !@images[path] @images[path] = Gosu::Image.new(@window, "#{@root}/#{path}", tileable) end @images[path] end
ruby
def load_image(path, tileable = false) if !@images[path] @images[path] = Gosu::Image.new(@window, "#{@root}/#{path}", tileable) end @images[path] end
[ "def", "load_image", "(", "path", ",", "tileable", "=", "false", ")", "if", "!", "@images", "[", "path", "]", "@images", "[", "path", "]", "=", "Gosu", "::", "Image", ".", "new", "(", "@window", ",", "\"#{@root}/#{path}\"", ",", "tileable", ")", "end", "@images", "[", "path", "]", "end" ]
loads an image and caches it for further use if an image has been loaded it is just being returned
[ "loads", "an", "image", "and", "caches", "it", "for", "further", "use", "if", "an", "image", "has", "been", "loaded", "it", "is", "just", "being", "returned" ]
6779a50657a816f014d33b61314eaa3991982d13
https://github.com/eriksk/kawaii/blob/6779a50657a816f014d33b61314eaa3991982d13/lib/kawaii/content_manager.rb#L20-L25
train
xiuxian123/loyals
projects/mustache_render/lib/mustache_render/mustache.rb
MustacheRender.Mustache.partial
def partial(name) name = self.class.generate_template_name name, config.file_template_extension # return self.read_template_from_media name, media @_cached_partials ||= {} (@_cached_partials[media] ||= {})[name] ||= self.read_template_from_media name, media end
ruby
def partial(name) name = self.class.generate_template_name name, config.file_template_extension # return self.read_template_from_media name, media @_cached_partials ||= {} (@_cached_partials[media] ||= {})[name] ||= self.read_template_from_media name, media end
[ "def", "partial", "(", "name", ")", "name", "=", "self", ".", "class", ".", "generate_template_name", "name", ",", "config", ".", "file_template_extension", "# return self.read_template_from_media name, media", "@_cached_partials", "||=", "{", "}", "(", "@_cached_partials", "[", "media", "]", "||=", "{", "}", ")", "[", "name", "]", "||=", "self", ".", "read_template_from_media", "name", ",", "media", "end" ]
Override this in your subclass if you want to do fun things like reading templates from a database. It will be rendered by the context, so all you need to do is return a string.
[ "Override", "this", "in", "your", "subclass", "if", "you", "want", "to", "do", "fun", "things", "like", "reading", "templates", "from", "a", "database", ".", "It", "will", "be", "rendered", "by", "the", "context", "so", "all", "you", "need", "to", "do", "is", "return", "a", "string", "." ]
41f586ca1551f64e5375ad32a406d5fca0afae43
https://github.com/xiuxian123/loyals/blob/41f586ca1551f64e5375ad32a406d5fca0afae43/projects/mustache_render/lib/mustache_render/mustache.rb#L124-L130
train
maxim/has_price
lib/has_price/has_price.rb
HasPrice.HasPrice.has_price
def has_price(options = {}, &block) attribute = options[:attribute] || :price free = !block_given? && options[:free] define_method attribute.to_sym do builder = PriceBuilder.new self builder.instance_eval &block unless free builder.price end end
ruby
def has_price(options = {}, &block) attribute = options[:attribute] || :price free = !block_given? && options[:free] define_method attribute.to_sym do builder = PriceBuilder.new self builder.instance_eval &block unless free builder.price end end
[ "def", "has_price", "(", "options", "=", "{", "}", ",", "&", "block", ")", "attribute", "=", "options", "[", ":attribute", "]", "||", ":price", "free", "=", "!", "block_given?", "&&", "options", "[", ":free", "]", "define_method", "attribute", ".", "to_sym", "do", "builder", "=", "PriceBuilder", ".", "new", "self", "builder", ".", "instance_eval", "block", "unless", "free", "builder", ".", "price", "end", "end" ]
Provides a simple DSL to defines price instance method on the receiver. @param [Hash] options the options for creating price method. @option options [Symbol] :attribute (:price) Name of the price method. @option options [Boolean] :free (false) Set `:free => true` to use null object pattern. @yield The yielded block provides method `item` for declaring price entries, and method `group` for declaring price groups. @example Normal usage class Product < ActiveRecord::Base has_price do item base_price, "base" item discount, "discount" group "taxes" do item federal_tax, "federal tax" item state_tax, "state tax" end group "shipment" do # Notice that delivery_method is an instance method. # You can call instance methods anywhere in has_price block. item delivery_price, delivery_method end end end @example Null object pattern class Product < ActiveRecord::Base # Creates method #price which returns empty Price. has_price :free => true end @see PriceBuilder#item @see PriceBuilder#group
[ "Provides", "a", "simple", "DSL", "to", "defines", "price", "instance", "method", "on", "the", "receiver", "." ]
671c5c7463b0e6540cbb8ac3114da08b99c697bd
https://github.com/maxim/has_price/blob/671c5c7463b0e6540cbb8ac3114da08b99c697bd/lib/has_price/has_price.rb#L41-L50
train
octoai/gem-octocore-cassandra
lib/octocore-cassandra/scheduler.rb
Octo.Scheduler.schedule_counters
def schedule_counters counter_classes = [ Octo::ProductHit, Octo::CategoryHit, Octo::TagHit, Octo::ApiHit, Octo::NewsfeedHit ] counter_classes.each do |clazz| clazz.send(:get_typecounters).each do |counter| name = [clazz, counter].join('::') config = { class: clazz.to_s, args: [counter], cron: '* * * * *', persist: true, queue: 'high' } Resque.set_schedule name, config end end # Schedules the processing of baselines def schedule_baseline baseline_classes = [ Octo::ProductBaseline, Octo::CategoryBaseline, Octo::TagBaseline ] baseline_classes.each do |clazz| clazz.send(:get_typecounters).each do |counter| name = [clazz, counter].join('::') config = { class: clazz.to_s, args: [counter], cron: '* * * * *', persists: true, queue: 'baseline_processing' } Resque.set_schedule name, config end end end # Schedules the daily mail, to be sent at noon def schedule_subscribermail name = 'SubscriberDailyMailer' config = { class: Octo::Mailer::SubscriberMailer, args: [], cron: '0 0 * * *', persist: true, queue: 'subscriber_notifier' } Resque.set_schedule name, config end end
ruby
def schedule_counters counter_classes = [ Octo::ProductHit, Octo::CategoryHit, Octo::TagHit, Octo::ApiHit, Octo::NewsfeedHit ] counter_classes.each do |clazz| clazz.send(:get_typecounters).each do |counter| name = [clazz, counter].join('::') config = { class: clazz.to_s, args: [counter], cron: '* * * * *', persist: true, queue: 'high' } Resque.set_schedule name, config end end # Schedules the processing of baselines def schedule_baseline baseline_classes = [ Octo::ProductBaseline, Octo::CategoryBaseline, Octo::TagBaseline ] baseline_classes.each do |clazz| clazz.send(:get_typecounters).each do |counter| name = [clazz, counter].join('::') config = { class: clazz.to_s, args: [counter], cron: '* * * * *', persists: true, queue: 'baseline_processing' } Resque.set_schedule name, config end end end # Schedules the daily mail, to be sent at noon def schedule_subscribermail name = 'SubscriberDailyMailer' config = { class: Octo::Mailer::SubscriberMailer, args: [], cron: '0 0 * * *', persist: true, queue: 'subscriber_notifier' } Resque.set_schedule name, config end end
[ "def", "schedule_counters", "counter_classes", "=", "[", "Octo", "::", "ProductHit", ",", "Octo", "::", "CategoryHit", ",", "Octo", "::", "TagHit", ",", "Octo", "::", "ApiHit", ",", "Octo", "::", "NewsfeedHit", "]", "counter_classes", ".", "each", "do", "|", "clazz", "|", "clazz", ".", "send", "(", ":get_typecounters", ")", ".", "each", "do", "|", "counter", "|", "name", "=", "[", "clazz", ",", "counter", "]", ".", "join", "(", "'::'", ")", "config", "=", "{", "class", ":", "clazz", ".", "to_s", ",", "args", ":", "[", "counter", "]", ",", "cron", ":", "'* * * * *'", ",", "persist", ":", "true", ",", "queue", ":", "'high'", "}", "Resque", ".", "set_schedule", "name", ",", "config", "end", "end", "# Schedules the processing of baselines", "def", "schedule_baseline", "baseline_classes", "=", "[", "Octo", "::", "ProductBaseline", ",", "Octo", "::", "CategoryBaseline", ",", "Octo", "::", "TagBaseline", "]", "baseline_classes", ".", "each", "do", "|", "clazz", "|", "clazz", ".", "send", "(", ":get_typecounters", ")", ".", "each", "do", "|", "counter", "|", "name", "=", "[", "clazz", ",", "counter", "]", ".", "join", "(", "'::'", ")", "config", "=", "{", "class", ":", "clazz", ".", "to_s", ",", "args", ":", "[", "counter", "]", ",", "cron", ":", "'* * * * *'", ",", "persists", ":", "true", ",", "queue", ":", "'baseline_processing'", "}", "Resque", ".", "set_schedule", "name", ",", "config", "end", "end", "end", "# Schedules the daily mail, to be sent at noon", "def", "schedule_subscribermail", "name", "=", "'SubscriberDailyMailer'", "config", "=", "{", "class", ":", "Octo", "::", "Mailer", "::", "SubscriberMailer", ",", "args", ":", "[", "]", ",", "cron", ":", "'0 0 * * *'", ",", "persist", ":", "true", ",", "queue", ":", "'subscriber_notifier'", "}", "Resque", ".", "set_schedule", "name", ",", "config", "end", "end" ]
Setup the schedules for counters.
[ "Setup", "the", "schedules", "for", "counters", "." ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/scheduler.rb#L13-L70
train
influenza/hosties
lib/hosties/definitions.rb
Hosties.HasAttributes.have_attributes
def have_attributes(attr, *more) sum = (more << attr) sum.each do |name| raise ArgumentError, "Reserved attribute name #{name}" if @verbotten.include?(name) end @attributes += sum end
ruby
def have_attributes(attr, *more) sum = (more << attr) sum.each do |name| raise ArgumentError, "Reserved attribute name #{name}" if @verbotten.include?(name) end @attributes += sum end
[ "def", "have_attributes", "(", "attr", ",", "*", "more", ")", "sum", "=", "(", "more", "<<", "attr", ")", "sum", ".", "each", "do", "|", "name", "|", "raise", "ArgumentError", ",", "\"Reserved attribute name #{name}\"", "if", "@verbotten", ".", "include?", "(", "name", ")", "end", "@attributes", "+=", "sum", "end" ]
Specify symbols that will later be reified into attributes
[ "Specify", "symbols", "that", "will", "later", "be", "reified", "into", "attributes" ]
a3030cd4a23a23a0fcc2664c01a497b31e6e49fe
https://github.com/influenza/hosties/blob/a3030cd4a23a23a0fcc2664c01a497b31e6e49fe/lib/hosties/definitions.rb#L38-L44
train
influenza/hosties
lib/hosties/definitions.rb
Hosties.HasAttributes.where
def where(name) # Must define the attributes before constraining them raise ArgumentError, "Unknown attribute: #{name}" unless @attributes.include? name @constraints[name] = AttributeConstraint.new(name) end
ruby
def where(name) # Must define the attributes before constraining them raise ArgumentError, "Unknown attribute: #{name}" unless @attributes.include? name @constraints[name] = AttributeConstraint.new(name) end
[ "def", "where", "(", "name", ")", "# Must define the attributes before constraining them", "raise", "ArgumentError", ",", "\"Unknown attribute: #{name}\"", "unless", "@attributes", ".", "include?", "name", "@constraints", "[", "name", "]", "=", "AttributeConstraint", ".", "new", "(", "name", ")", "end" ]
Helpful method to define constraints
[ "Helpful", "method", "to", "define", "constraints" ]
a3030cd4a23a23a0fcc2664c01a497b31e6e49fe
https://github.com/influenza/hosties/blob/a3030cd4a23a23a0fcc2664c01a497b31e6e49fe/lib/hosties/definitions.rb#L51-L55
train
influenza/hosties
lib/hosties/definitions.rb
Hosties.HasAttributes.valid?
def valid?(name, value) if @constraints.include? name then constraints[name].possible_vals.include? value else true end end
ruby
def valid?(name, value) if @constraints.include? name then constraints[name].possible_vals.include? value else true end end
[ "def", "valid?", "(", "name", ",", "value", ")", "if", "@constraints", ".", "include?", "name", "then", "constraints", "[", "name", "]", ".", "possible_vals", ".", "include?", "value", "else", "true", "end", "end" ]
Check if a given name-value pair is valid given the constraints
[ "Check", "if", "a", "given", "name", "-", "value", "pair", "is", "valid", "given", "the", "constraints" ]
a3030cd4a23a23a0fcc2664c01a497b31e6e49fe
https://github.com/influenza/hosties/blob/a3030cd4a23a23a0fcc2664c01a497b31e6e49fe/lib/hosties/definitions.rb#L58-L62
train
grappendorf/xbee-ruby
lib/xbee-ruby/xbee.rb
XBeeRuby.XBee.open
def open @serial ||= SerialPort.new @port, @rate @serial_input = Enumerator.new { |y| loop do y.yield @serial.readbyte end } @connected = true end
ruby
def open @serial ||= SerialPort.new @port, @rate @serial_input = Enumerator.new { |y| loop do y.yield @serial.readbyte end } @connected = true end
[ "def", "open", "@serial", "||=", "SerialPort", ".", "new", "@port", ",", "@rate", "@serial_input", "=", "Enumerator", ".", "new", "{", "|", "y", "|", "loop", "do", "y", ".", "yield", "@serial", ".", "readbyte", "end", "}", "@connected", "=", "true", "end" ]
Either specify the port and serial parameters xbee = XBeeRuby::Xbee.new port: '/dev/ttyUSB0', rate: 9600 or pass in a SerialPort like object xbee = XBeeRuby::XBee.new serial: some_serial_mockup_for_testing
[ "Either", "specify", "the", "port", "and", "serial", "parameters" ]
dece2da12b7cd2973f82286c6659671b953030b8
https://github.com/grappendorf/xbee-ruby/blob/dece2da12b7cd2973f82286c6659671b953030b8/lib/xbee-ruby/xbee.rb#L33-L39
train
goncalvesjoao/usecasing_validations
lib/usecasing_validations.rb
UseCaseValidations.ClassMethods.inherited
def inherited(base) dup = _validators.dup base._validators = dup.each { |k, v| dup[k] = v.dup } super end
ruby
def inherited(base) dup = _validators.dup base._validators = dup.each { |k, v| dup[k] = v.dup } super end
[ "def", "inherited", "(", "base", ")", "dup", "=", "_validators", ".", "dup", "base", ".", "_validators", "=", "dup", ".", "each", "{", "|", "k", ",", "v", "|", "dup", "[", "k", "]", "=", "v", ".", "dup", "}", "super", "end" ]
Copy validators on inheritance.
[ "Copy", "validators", "on", "inheritance", "." ]
97375b7ade94eaa7c138f4fd9e0cf24e56db343f
https://github.com/goncalvesjoao/usecasing_validations/blob/97375b7ade94eaa7c138f4fd9e0cf24e56db343f/lib/usecasing_validations.rb#L116-L120
train
michaeledgar/amp-front
lib/amp-front/third_party/maruku/toc.rb
MaRuKu.Section.numerate
def numerate(a=[]) self.section_number = a section_children.each_with_index do |c,i| c.numerate(a.clone.push(i+1)) end if h = self.header_element h.attributes[:section_number] = self.section_number end end
ruby
def numerate(a=[]) self.section_number = a section_children.each_with_index do |c,i| c.numerate(a.clone.push(i+1)) end if h = self.header_element h.attributes[:section_number] = self.section_number end end
[ "def", "numerate", "(", "a", "=", "[", "]", ")", "self", ".", "section_number", "=", "a", "section_children", ".", "each_with_index", "do", "|", "c", ",", "i", "|", "c", ".", "numerate", "(", "a", ".", "clone", ".", "push", "(", "i", "+", "1", ")", ")", "end", "if", "h", "=", "self", ".", "header_element", "h", ".", "attributes", "[", ":section_number", "]", "=", "self", ".", "section_number", "end", "end" ]
Numerate this section and its children
[ "Numerate", "this", "section", "and", "its", "children" ]
d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9
https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/toc.rb#L70-L78
train
bclennox/acts_as_featured
lib/acts_as_featured.rb
ActsAsFeatured.ClassMethods.acts_as_featured
def acts_as_featured(attribute, options = {}) cattr_accessor :featured_attribute cattr_accessor :featured_attribute_scope self.featured_attribute = attribute self.featured_attribute_scope = options[:scope] || false if scope_name = options[:create_scope] scope_name = attribute if scope_name == true scope scope_name, -> { where(attribute => true).limit(1) } end before_save :remove_featured_from_other_records after_save :add_featured_to_first_record before_destroy :add_featured_to_first_record_if_featured end
ruby
def acts_as_featured(attribute, options = {}) cattr_accessor :featured_attribute cattr_accessor :featured_attribute_scope self.featured_attribute = attribute self.featured_attribute_scope = options[:scope] || false if scope_name = options[:create_scope] scope_name = attribute if scope_name == true scope scope_name, -> { where(attribute => true).limit(1) } end before_save :remove_featured_from_other_records after_save :add_featured_to_first_record before_destroy :add_featured_to_first_record_if_featured end
[ "def", "acts_as_featured", "(", "attribute", ",", "options", "=", "{", "}", ")", "cattr_accessor", ":featured_attribute", "cattr_accessor", ":featured_attribute_scope", "self", ".", "featured_attribute", "=", "attribute", "self", ".", "featured_attribute_scope", "=", "options", "[", ":scope", "]", "||", "false", "if", "scope_name", "=", "options", "[", ":create_scope", "]", "scope_name", "=", "attribute", "if", "scope_name", "==", "true", "scope", "scope_name", ",", "->", "{", "where", "(", "attribute", "=>", "true", ")", ".", "limit", "(", "1", ")", "}", "end", "before_save", ":remove_featured_from_other_records", "after_save", ":add_featured_to_first_record", "before_destroy", ":add_featured_to_first_record_if_featured", "end" ]
Designates an attribute on this model to indicate "featuredness," where only one record within a given scope may be featured at a time. Pass in the name of the attribute and an options hash: * <tt>:scope</tt> - If given, designates the scope in which this model is featured. This would typically be a <tt>belongs_to</tt> association. * <tt>:create_scope</tt> - If <tt>true</tt>, creates a named scope using the name of the attribute given here. If it's a symbol, creates a named scope using that symbol. class Project < ActiveRecord::Base # no two Projects will ever have their @featured attributes set simultaneously acts_as_featured :featured end class Photo < ActiveRecord::Base # each account gets a favorite photo belongs_to :account acts_as_featured :favorite, :scope => :account end class Article < ActiveRecord::Base # creates a named scope called Article.featured to return the featured article acts_as_featured :main, :create_scope => :featured end
[ "Designates", "an", "attribute", "on", "this", "model", "to", "indicate", "featuredness", "where", "only", "one", "record", "within", "a", "given", "scope", "may", "be", "featured", "at", "a", "time", "." ]
69f033dafa8a143f9cd90c90eaca39912f0a4ddc
https://github.com/bclennox/acts_as_featured/blob/69f033dafa8a143f9cd90c90eaca39912f0a4ddc/lib/acts_as_featured.rb#L31-L46
train
maxjacobson/todo_lint
lib/todo_lint/judge.rb
TodoLint.Judge.make_charge
def make_charge if !todo.annotated? "Missing due date annotation" elsif todo.due_date.overdue? && todo.tag? "Overdue due date #{todo.due_date.to_date} via tag" elsif todo.due_date.overdue? "Overdue due date" end end
ruby
def make_charge if !todo.annotated? "Missing due date annotation" elsif todo.due_date.overdue? && todo.tag? "Overdue due date #{todo.due_date.to_date} via tag" elsif todo.due_date.overdue? "Overdue due date" end end
[ "def", "make_charge", "if", "!", "todo", ".", "annotated?", "\"Missing due date annotation\"", "elsif", "todo", ".", "due_date", ".", "overdue?", "&&", "todo", ".", "tag?", "\"Overdue due date #{todo.due_date.to_date} via tag\"", "elsif", "todo", ".", "due_date", ".", "overdue?", "\"Overdue due date\"", "end", "end" ]
What is the problem with this todo? @return [String] if there's a problem @return [NilClass] if no charge needed @api private
[ "What", "is", "the", "problem", "with", "this", "todo?" ]
0d1061383ea205ef4c74edc64568e308ac1af990
https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/judge.rb#L35-L43
train
jwtd/xively-rb-connector
lib/xively-rb-connector/datastream.rb
XivelyConnector.Datastream.<<
def <<(measurement) # Make sure the value provided is a datapoint datapoint = cast_to_datapoint(measurement) # If only_save_changes is true, ignore datapoints whose value is the same as the current value if only_save_changes and BigDecimal.new(datapoint.value) == BigDecimal.new(current_value) @logger.debug "Ignoring datapoint from #{datapoint.at} because value did not change from #{current_value}" else @current_value = datapoint.value datapoints << datapoint @logger.debug "Queuing datapoint from #{datapoint.at} with value #{current_value}" end # See if the buffer is full check_datapoints_buffer end
ruby
def <<(measurement) # Make sure the value provided is a datapoint datapoint = cast_to_datapoint(measurement) # If only_save_changes is true, ignore datapoints whose value is the same as the current value if only_save_changes and BigDecimal.new(datapoint.value) == BigDecimal.new(current_value) @logger.debug "Ignoring datapoint from #{datapoint.at} because value did not change from #{current_value}" else @current_value = datapoint.value datapoints << datapoint @logger.debug "Queuing datapoint from #{datapoint.at} with value #{current_value}" end # See if the buffer is full check_datapoints_buffer end
[ "def", "<<", "(", "measurement", ")", "# Make sure the value provided is a datapoint", "datapoint", "=", "cast_to_datapoint", "(", "measurement", ")", "# If only_save_changes is true, ignore datapoints whose value is the same as the current value", "if", "only_save_changes", "and", "BigDecimal", ".", "new", "(", "datapoint", ".", "value", ")", "==", "BigDecimal", ".", "new", "(", "current_value", ")", "@logger", ".", "debug", "\"Ignoring datapoint from #{datapoint.at} because value did not change from #{current_value}\"", "else", "@current_value", "=", "datapoint", ".", "value", "datapoints", "<<", "datapoint", "@logger", ".", "debug", "\"Queuing datapoint from #{datapoint.at} with value #{current_value}\"", "end", "# See if the buffer is full", "check_datapoints_buffer", "end" ]
Have shift operator load the datapoint into the datastream's datapoints array
[ "Have", "shift", "operator", "load", "the", "datapoint", "into", "the", "datastream", "s", "datapoints", "array" ]
014c2e08d2857e67d65103b84ba23a91569baecb
https://github.com/jwtd/xively-rb-connector/blob/014c2e08d2857e67d65103b84ba23a91569baecb/lib/xively-rb-connector/datastream.rb#L52-L67
train
jwtd/xively-rb-connector
lib/xively-rb-connector/datastream.rb
XivelyConnector.Datastream.cast_to_datapoint
def cast_to_datapoint(measurement, at=Time.now()) @logger.debug "cast_to_datapoint(#{measurement.inspect})" if measurement.is_a?(Xively::Datapoint) return measurement elsif measurement.is_a?(Hash) raise "The datapoint hash does not contain :at" unless measurement[:at] raise "The datapoint hash does not contain :value" unless measurement[:value] return Xively::Datapoint.new(measurement) else return Xively::Datapoint.new(:at => at, :value => measurement.to_s) end end
ruby
def cast_to_datapoint(measurement, at=Time.now()) @logger.debug "cast_to_datapoint(#{measurement.inspect})" if measurement.is_a?(Xively::Datapoint) return measurement elsif measurement.is_a?(Hash) raise "The datapoint hash does not contain :at" unless measurement[:at] raise "The datapoint hash does not contain :value" unless measurement[:value] return Xively::Datapoint.new(measurement) else return Xively::Datapoint.new(:at => at, :value => measurement.to_s) end end
[ "def", "cast_to_datapoint", "(", "measurement", ",", "at", "=", "Time", ".", "now", "(", ")", ")", "@logger", ".", "debug", "\"cast_to_datapoint(#{measurement.inspect})\"", "if", "measurement", ".", "is_a?", "(", "Xively", "::", "Datapoint", ")", "return", "measurement", "elsif", "measurement", ".", "is_a?", "(", "Hash", ")", "raise", "\"The datapoint hash does not contain :at\"", "unless", "measurement", "[", ":at", "]", "raise", "\"The datapoint hash does not contain :value\"", "unless", "measurement", "[", ":value", "]", "return", "Xively", "::", "Datapoint", ".", "new", "(", "measurement", ")", "else", "return", "Xively", "::", "Datapoint", ".", "new", "(", ":at", "=>", "at", ",", ":value", "=>", "measurement", ".", "to_s", ")", "end", "end" ]
Converts a measurement to a Datapoint
[ "Converts", "a", "measurement", "to", "a", "Datapoint" ]
014c2e08d2857e67d65103b84ba23a91569baecb
https://github.com/jwtd/xively-rb-connector/blob/014c2e08d2857e67d65103b84ba23a91569baecb/lib/xively-rb-connector/datastream.rb#L70-L81
train
jwtd/xively-rb-connector
lib/xively-rb-connector/datastream.rb
XivelyConnector.Datastream.save_datapoints
def save_datapoints @logger.debug "Saving #{datapoints.size} datapoints to the #{id} datastream" response = XivelyConnector.connection.post("/v2/feeds/#{device.id}/datastreams/#{id}/datapoints", :body => {:datapoints => datapoints}.to_json) # If the response succeeded, clear the datapoint buffer and return the response object if response.success? clear_datapoints_buffer response else logger.error response.response raise response.response end end
ruby
def save_datapoints @logger.debug "Saving #{datapoints.size} datapoints to the #{id} datastream" response = XivelyConnector.connection.post("/v2/feeds/#{device.id}/datastreams/#{id}/datapoints", :body => {:datapoints => datapoints}.to_json) # If the response succeeded, clear the datapoint buffer and return the response object if response.success? clear_datapoints_buffer response else logger.error response.response raise response.response end end
[ "def", "save_datapoints", "@logger", ".", "debug", "\"Saving #{datapoints.size} datapoints to the #{id} datastream\"", "response", "=", "XivelyConnector", ".", "connection", ".", "post", "(", "\"/v2/feeds/#{device.id}/datastreams/#{id}/datapoints\"", ",", ":body", "=>", "{", ":datapoints", "=>", "datapoints", "}", ".", "to_json", ")", "# If the response succeeded, clear the datapoint buffer and return the response object", "if", "response", ".", "success?", "clear_datapoints_buffer", "response", "else", "logger", ".", "error", "response", ".", "response", "raise", "response", ".", "response", "end", "end" ]
Send the queued datapoints array to Xively
[ "Send", "the", "queued", "datapoints", "array", "to", "Xively" ]
014c2e08d2857e67d65103b84ba23a91569baecb
https://github.com/jwtd/xively-rb-connector/blob/014c2e08d2857e67d65103b84ba23a91569baecb/lib/xively-rb-connector/datastream.rb#L84-L96
train
lexruee/coach4rb
lib/coach4rb/client.rb
Coach4rb.Client.put
def put(url, payload, options={}, &block) http_options = options.merge(@basic_options) if block_given? RestClient.put(url, payload, http_options, &block) else RestClient.put(url, payload, http_options) end end
ruby
def put(url, payload, options={}, &block) http_options = options.merge(@basic_options) if block_given? RestClient.put(url, payload, http_options, &block) else RestClient.put(url, payload, http_options) end end
[ "def", "put", "(", "url", ",", "payload", ",", "options", "=", "{", "}", ",", "&", "block", ")", "http_options", "=", "options", ".", "merge", "(", "@basic_options", ")", "if", "block_given?", "RestClient", ".", "put", "(", "url", ",", "payload", ",", "http_options", ",", "block", ")", "else", "RestClient", ".", "put", "(", "url", ",", "payload", ",", "http_options", ")", "end", "end" ]
Performs a put request. @param [String] url @param [String] payload @param [Block] block @return [String] the payload of the response as string
[ "Performs", "a", "put", "request", "." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/client.rb#L70-L78
train
lexruee/coach4rb
lib/coach4rb/client.rb
Coach4rb.Client.delete
def delete(url, options={}, &block) http_options = options.merge(@basic_options) if block_given? RestClient.delete(url, http_options, &block) else RestClient.delete(url, http_options) end end
ruby
def delete(url, options={}, &block) http_options = options.merge(@basic_options) if block_given? RestClient.delete(url, http_options, &block) else RestClient.delete(url, http_options) end end
[ "def", "delete", "(", "url", ",", "options", "=", "{", "}", ",", "&", "block", ")", "http_options", "=", "options", ".", "merge", "(", "@basic_options", ")", "if", "block_given?", "RestClient", ".", "delete", "(", "url", ",", "http_options", ",", "block", ")", "else", "RestClient", ".", "delete", "(", "url", ",", "http_options", ")", "end", "end" ]
Performs a delete request. @param [String] url @param [Hash] options @param [Block] block @return [String] the payload of the response as string
[ "Performs", "a", "delete", "request", "." ]
59105bfe45a0717e655e0deff4d1540d511f6b02
https://github.com/lexruee/coach4rb/blob/59105bfe45a0717e655e0deff4d1540d511f6b02/lib/coach4rb/client.rb#L105-L112
train
goncalvesjoao/object_attorney
lib/object_attorney/class_methods.rb
ObjectAttorney.ClassMethods.inherited
def inherited(base) base.allegations = allegations.clone base.defendant_options = defendant_options.clone super end
ruby
def inherited(base) base.allegations = allegations.clone base.defendant_options = defendant_options.clone super end
[ "def", "inherited", "(", "base", ")", "base", ".", "allegations", "=", "allegations", ".", "clone", "base", ".", "defendant_options", "=", "defendant_options", ".", "clone", "super", "end" ]
Copy allegations on inheritance.
[ "Copy", "allegations", "on", "inheritance", "." ]
d3e3f3916460010c793d7e3b4cb89eb974d4e88d
https://github.com/goncalvesjoao/object_attorney/blob/d3e3f3916460010c793d7e3b4cb89eb974d4e88d/lib/object_attorney/class_methods.rb#L39-L44
train
wwidea/rexport
lib/rexport/export_methods.rb
Rexport.ExportMethods.to_s
def to_s String.new.tap do |result| result << header * '|' << "\n" records.each do |record| result << record * '|' << "\n" end end end
ruby
def to_s String.new.tap do |result| result << header * '|' << "\n" records.each do |record| result << record * '|' << "\n" end end end
[ "def", "to_s", "String", ".", "new", ".", "tap", "do", "|", "result", "|", "result", "<<", "header", "*", "'|'", "<<", "\"\\n\"", "records", ".", "each", "do", "|", "record", "|", "result", "<<", "record", "*", "'|'", "<<", "\"\\n\"", "end", "end", "end" ]
Returns a string with the export data
[ "Returns", "a", "string", "with", "the", "export", "data" ]
f4f978dd0327ddba3a4318dd24090fbc6d4e4e59
https://github.com/wwidea/rexport/blob/f4f978dd0327ddba3a4318dd24090fbc6d4e4e59/lib/rexport/export_methods.rb#L30-L37
train
wwidea/rexport
lib/rexport/export_methods.rb
Rexport.ExportMethods.to_csv
def to_csv(objects = nil) seed_records(objects) unless objects.nil? CSV.generate do |csv| csv << header records.each do |record| csv << record end end end
ruby
def to_csv(objects = nil) seed_records(objects) unless objects.nil? CSV.generate do |csv| csv << header records.each do |record| csv << record end end end
[ "def", "to_csv", "(", "objects", "=", "nil", ")", "seed_records", "(", "objects", ")", "unless", "objects", ".", "nil?", "CSV", ".", "generate", "do", "|", "csv", "|", "csv", "<<", "header", "records", ".", "each", "do", "|", "record", "|", "csv", "<<", "record", "end", "end", "end" ]
Returns a csv string with the export data
[ "Returns", "a", "csv", "string", "with", "the", "export", "data" ]
f4f978dd0327ddba3a4318dd24090fbc6d4e4e59
https://github.com/wwidea/rexport/blob/f4f978dd0327ddba3a4318dd24090fbc6d4e4e59/lib/rexport/export_methods.rb#L40-L48
train
wwidea/rexport
lib/rexport/export_methods.rb
Rexport.ExportMethods.get_klass_from_path
def get_klass_from_path(path, klass = export_model) return klass unless (association_name = path.shift) get_klass_from_path(path, klass.reflect_on_association(association_name.to_sym).klass) end
ruby
def get_klass_from_path(path, klass = export_model) return klass unless (association_name = path.shift) get_klass_from_path(path, klass.reflect_on_association(association_name.to_sym).klass) end
[ "def", "get_klass_from_path", "(", "path", ",", "klass", "=", "export_model", ")", "return", "klass", "unless", "(", "association_name", "=", "path", ".", "shift", ")", "get_klass_from_path", "(", "path", ",", "klass", ".", "reflect_on_association", "(", "association_name", ".", "to_sym", ")", ".", "klass", ")", "end" ]
Returns a class based on a path array
[ "Returns", "a", "class", "based", "on", "a", "path", "array" ]
f4f978dd0327ddba3a4318dd24090fbc6d4e4e59
https://github.com/wwidea/rexport/blob/f4f978dd0327ddba3a4318dd24090fbc6d4e4e59/lib/rexport/export_methods.rb#L76-L79
train
lizconlan/diffable
lib/diffable.rb
Diffable.InstanceMethods.diff
def diff(other) check_class_compatibility(self, other) self_attribs = self.get_attributes(self.class.excluded_fields) other_attribs = other.get_attributes(other.class.excluded_fields) change = compare_objects(self_attribs, other_attribs, self, other) #the last bit - no change, no report; simples if other.class.conditional_fields other.class.conditional_fields.each do |key| change[key.to_sym] = eval("other.#{key}") unless change.empty? end end change end
ruby
def diff(other) check_class_compatibility(self, other) self_attribs = self.get_attributes(self.class.excluded_fields) other_attribs = other.get_attributes(other.class.excluded_fields) change = compare_objects(self_attribs, other_attribs, self, other) #the last bit - no change, no report; simples if other.class.conditional_fields other.class.conditional_fields.each do |key| change[key.to_sym] = eval("other.#{key}") unless change.empty? end end change end
[ "def", "diff", "(", "other", ")", "check_class_compatibility", "(", "self", ",", "other", ")", "self_attribs", "=", "self", ".", "get_attributes", "(", "self", ".", "class", ".", "excluded_fields", ")", "other_attribs", "=", "other", ".", "get_attributes", "(", "other", ".", "class", ".", "excluded_fields", ")", "change", "=", "compare_objects", "(", "self_attribs", ",", "other_attribs", ",", "self", ",", "other", ")", "#the last bit - no change, no report; simples", "if", "other", ".", "class", ".", "conditional_fields", "other", ".", "class", ".", "conditional_fields", ".", "each", "do", "|", "key", "|", "change", "[", "key", ".", "to_sym", "]", "=", "eval", "(", "\"other.#{key}\"", ")", "unless", "change", ".", "empty?", "end", "end", "change", "end" ]
Produces a Hash containing the differences between the calling object and the object passed in as a parameter
[ "Produces", "a", "Hash", "containing", "the", "differences", "between", "the", "calling", "object", "and", "the", "object", "passed", "in", "as", "a", "parameter" ]
c9920a97841205b856c720777eb2bab43793a9ed
https://github.com/lizconlan/diffable/blob/c9920a97841205b856c720777eb2bab43793a9ed/lib/diffable.rb#L22-L37
train
lizconlan/diffable
lib/diffable.rb
Diffable.InstanceMethods.get_attributes
def get_attributes(excluded) attribs = attributes.dup attribs.delete_if { |key, value| (!excluded.nil? and excluded.include?(key)) or key == "id" } end
ruby
def get_attributes(excluded) attribs = attributes.dup attribs.delete_if { |key, value| (!excluded.nil? and excluded.include?(key)) or key == "id" } end
[ "def", "get_attributes", "(", "excluded", ")", "attribs", "=", "attributes", ".", "dup", "attribs", ".", "delete_if", "{", "|", "key", ",", "value", "|", "(", "!", "excluded", ".", "nil?", "and", "excluded", ".", "include?", "(", "key", ")", ")", "or", "key", "==", "\"id\"", "}", "end" ]
Fetches the attributes of the calling object, exluding the +id+ field and any fields specified passed as an array of symbols via the +excluded+ parameter
[ "Fetches", "the", "attributes", "of", "the", "calling", "object", "exluding", "the", "+", "id", "+", "field", "and", "any", "fields", "specified", "passed", "as", "an", "array", "of", "symbols", "via", "the", "+", "excluded", "+", "parameter" ]
c9920a97841205b856c720777eb2bab43793a9ed
https://github.com/lizconlan/diffable/blob/c9920a97841205b856c720777eb2bab43793a9ed/lib/diffable.rb#L43-L47
train
lizconlan/diffable
lib/diffable.rb
Diffable.InstanceMethods.reflected_names
def reflected_names(obj) classes = obj.reflections class_names = [] classes.each do |key, cl| if eval(cl.class_name).respond_to?("diffable") \ and cl.association_class != ActiveRecord::Associations::BelongsToAssociation class_names << key end end class_names end
ruby
def reflected_names(obj) classes = obj.reflections class_names = [] classes.each do |key, cl| if eval(cl.class_name).respond_to?("diffable") \ and cl.association_class != ActiveRecord::Associations::BelongsToAssociation class_names << key end end class_names end
[ "def", "reflected_names", "(", "obj", ")", "classes", "=", "obj", ".", "reflections", "class_names", "=", "[", "]", "classes", ".", "each", "do", "|", "key", ",", "cl", "|", "if", "eval", "(", "cl", ".", "class_name", ")", ".", "respond_to?", "(", "\"diffable\"", ")", "and", "cl", ".", "association_class", "!=", "ActiveRecord", "::", "Associations", "::", "BelongsToAssociation", "class_names", "<<", "key", "end", "end", "class_names", "end" ]
Uses reflection to fetch the eligible associated objects for the current object, excluding parent objects and child objects that do not include the Diffable mixin
[ "Uses", "reflection", "to", "fetch", "the", "eligible", "associated", "objects", "for", "the", "current", "object", "excluding", "parent", "objects", "and", "child", "objects", "that", "do", "not", "include", "the", "Diffable", "mixin" ]
c9920a97841205b856c720777eb2bab43793a9ed
https://github.com/lizconlan/diffable/blob/c9920a97841205b856c720777eb2bab43793a9ed/lib/diffable.rb#L53-L63
train
MakarovCode/EasyPayULatam
lib/easy_pay_u_latam/r_api/subscription_service.rb
PayuLatam.SubscriptionService.plan
def plan # si el usuario no tiene plan_id en su modelo, se le asigna el plan_id seleccionado en el formulario # recordar que ese plan_id llega en los params del contexto y por tanto tenemos acceso a el # como variable de clase @plan_id if @current_user.plan_id.nil? if @plan_id.nil? raise StandardError, 'Error creando plan, plan_id null' end # se almacena en el user @current_user.update_attribute(:plan_id, @plan_id) # despues de tenerlo almacenado en la bd, llamamos nuevamente este metodo plan plan else # el usuario tiene un plan_id asignado, se le actualiza el plan_id en caso de que haya seleccionado uno # diferente al que tiene actualmente @current_user.update_attribute(:plan_id, @plan_id) # obtener informacion del plan de la BD plan_db = @current_user.plan # # NOTA: los planes deben tener un plan_code es OBLIGATORIO para el buen funcionamiento # if plan_db.plan_code.nil? || plan_db.plan_code.empty? raise StandardError, 'Error creando plan, code null' end # con el plan_code lo buscamos en payu plan_payu = PayuLatam::Plan.new(plan_db.plan_code) # si existe? if plan_payu.success? # llenar la variable plan con la instancia de clase PayuLatam:Plan @plan = plan_payu else # si no existe en pyu, crearlo con el metodo del modelo plan plan_db.create_payu_plan # llamado recursivo plan end end end
ruby
def plan # si el usuario no tiene plan_id en su modelo, se le asigna el plan_id seleccionado en el formulario # recordar que ese plan_id llega en los params del contexto y por tanto tenemos acceso a el # como variable de clase @plan_id if @current_user.plan_id.nil? if @plan_id.nil? raise StandardError, 'Error creando plan, plan_id null' end # se almacena en el user @current_user.update_attribute(:plan_id, @plan_id) # despues de tenerlo almacenado en la bd, llamamos nuevamente este metodo plan plan else # el usuario tiene un plan_id asignado, se le actualiza el plan_id en caso de que haya seleccionado uno # diferente al que tiene actualmente @current_user.update_attribute(:plan_id, @plan_id) # obtener informacion del plan de la BD plan_db = @current_user.plan # # NOTA: los planes deben tener un plan_code es OBLIGATORIO para el buen funcionamiento # if plan_db.plan_code.nil? || plan_db.plan_code.empty? raise StandardError, 'Error creando plan, code null' end # con el plan_code lo buscamos en payu plan_payu = PayuLatam::Plan.new(plan_db.plan_code) # si existe? if plan_payu.success? # llenar la variable plan con la instancia de clase PayuLatam:Plan @plan = plan_payu else # si no existe en pyu, crearlo con el metodo del modelo plan plan_db.create_payu_plan # llamado recursivo plan end end end
[ "def", "plan", "# si el usuario no tiene plan_id en su modelo, se le asigna el plan_id seleccionado en el formulario", "# recordar que ese plan_id llega en los params del contexto y por tanto tenemos acceso a el", "# como variable de clase @plan_id", "if", "@current_user", ".", "plan_id", ".", "nil?", "if", "@plan_id", ".", "nil?", "raise", "StandardError", ",", "'Error creando plan, plan_id null'", "end", "# se almacena en el user", "@current_user", ".", "update_attribute", "(", ":plan_id", ",", "@plan_id", ")", "# despues de tenerlo almacenado en la bd, llamamos nuevamente este metodo plan", "plan", "else", "# el usuario tiene un plan_id asignado, se le actualiza el plan_id en caso de que haya seleccionado uno", "# diferente al que tiene actualmente", "@current_user", ".", "update_attribute", "(", ":plan_id", ",", "@plan_id", ")", "# obtener informacion del plan de la BD", "plan_db", "=", "@current_user", ".", "plan", "#", "# NOTA: los planes deben tener un plan_code es OBLIGATORIO para el buen funcionamiento", "#", "if", "plan_db", ".", "plan_code", ".", "nil?", "||", "plan_db", ".", "plan_code", ".", "empty?", "raise", "StandardError", ",", "'Error creando plan, code null'", "end", "# con el plan_code lo buscamos en payu", "plan_payu", "=", "PayuLatam", "::", "Plan", ".", "new", "(", "plan_db", ".", "plan_code", ")", "# si existe?", "if", "plan_payu", ".", "success?", "# llenar la variable plan con la instancia de clase PayuLatam:Plan", "@plan", "=", "plan_payu", "else", "# si no existe en pyu, crearlo con el metodo del modelo plan", "plan_db", ".", "create_payu_plan", "# llamado recursivo", "plan", "end", "end", "end" ]
crea o carga un plan en un cliente de payu se utiliza el current_user, el payu_id del cliente y el plan_code del plan
[ "crea", "o", "carga", "un", "plan", "en", "un", "cliente", "de", "payu", "se", "utiliza", "el", "current_user", "el", "payu_id", "del", "cliente", "y", "el", "plan_code", "del", "plan" ]
c412b36fc316eabc338ce9cd152b8fea7316983d
https://github.com/MakarovCode/EasyPayULatam/blob/c412b36fc316eabc338ce9cd152b8fea7316983d/lib/easy_pay_u_latam/r_api/subscription_service.rb#L47-L85
train
MakarovCode/EasyPayULatam
lib/easy_pay_u_latam/r_api/subscription_service.rb
PayuLatam.SubscriptionService.create_card
def create_card raise StandardError, 'Cliente null' if @client.nil? # la instancia de card recibe como parametro el @client al que se le va asociar la tarjeta card = PayuLatam::Card.new(@client) # hay un metodo card_params que genera el objeto a enviar con los datos correctos # se asignan los params correctos para la peticion card.params.merge! card_params # intento de creacion de tarjeta card.create! # si todo bien if card.success? # se llena la variable @card con la instancia de la clase PayuLatam::Card @card = card # no me acuerdo XD @client.remove_cards # se agrega la tarjeta al array de tarjetas del usuario. Ojo este array esta en memoria no necesariamente # es el mismo array de payu @client.add_card( card.response ) # la respuesta de creacion de payu solo incluye el token de la tarjeta, entonces # volvemos a consultar la info almacenada en payu para recibier un poco mas de detalle y almacenarlo _card = card.load(card.response['token']) # se crea un registro de payu_card con la info publica de la tarjeta y el token de payu de la tarjeta @current_user.payu_cards.create(token: @card.response['token'], last_4: _card['number'], brand: _card['type']) else raise StandardError, "Error generando token de tarjeta: #{card.error}" end end
ruby
def create_card raise StandardError, 'Cliente null' if @client.nil? # la instancia de card recibe como parametro el @client al que se le va asociar la tarjeta card = PayuLatam::Card.new(@client) # hay un metodo card_params que genera el objeto a enviar con los datos correctos # se asignan los params correctos para la peticion card.params.merge! card_params # intento de creacion de tarjeta card.create! # si todo bien if card.success? # se llena la variable @card con la instancia de la clase PayuLatam::Card @card = card # no me acuerdo XD @client.remove_cards # se agrega la tarjeta al array de tarjetas del usuario. Ojo este array esta en memoria no necesariamente # es el mismo array de payu @client.add_card( card.response ) # la respuesta de creacion de payu solo incluye el token de la tarjeta, entonces # volvemos a consultar la info almacenada en payu para recibier un poco mas de detalle y almacenarlo _card = card.load(card.response['token']) # se crea un registro de payu_card con la info publica de la tarjeta y el token de payu de la tarjeta @current_user.payu_cards.create(token: @card.response['token'], last_4: _card['number'], brand: _card['type']) else raise StandardError, "Error generando token de tarjeta: #{card.error}" end end
[ "def", "create_card", "raise", "StandardError", ",", "'Cliente null'", "if", "@client", ".", "nil?", "# la instancia de card recibe como parametro el @client al que se le va asociar la tarjeta", "card", "=", "PayuLatam", "::", "Card", ".", "new", "(", "@client", ")", "# hay un metodo card_params que genera el objeto a enviar con los datos correctos", "# se asignan los params correctos para la peticion", "card", ".", "params", ".", "merge!", "card_params", "# intento de creacion de tarjeta", "card", ".", "create!", "# si todo bien", "if", "card", ".", "success?", "# se llena la variable @card con la instancia de la clase PayuLatam::Card", "@card", "=", "card", "# no me acuerdo XD", "@client", ".", "remove_cards", "# se agrega la tarjeta al array de tarjetas del usuario. Ojo este array esta en memoria no necesariamente", "# es el mismo array de payu", "@client", ".", "add_card", "(", "card", ".", "response", ")", "# la respuesta de creacion de payu solo incluye el token de la tarjeta, entonces", "# volvemos a consultar la info almacenada en payu para recibier un poco mas de detalle y almacenarlo", "_card", "=", "card", ".", "load", "(", "card", ".", "response", "[", "'token'", "]", ")", "# se crea un registro de payu_card con la info publica de la tarjeta y el token de payu de la tarjeta", "@current_user", ".", "payu_cards", ".", "create", "(", "token", ":", "@card", ".", "response", "[", "'token'", "]", ",", "last_4", ":", "_card", "[", "'number'", "]", ",", "brand", ":", "_card", "[", "'type'", "]", ")", "else", "raise", "StandardError", ",", "\"Error generando token de tarjeta: #{card.error}\"", "end", "end" ]
crear tarjeta de credito en payu utiliza los params recibidos
[ "crear", "tarjeta", "de", "credito", "en", "payu", "utiliza", "los", "params", "recibidos" ]
c412b36fc316eabc338ce9cd152b8fea7316983d
https://github.com/MakarovCode/EasyPayULatam/blob/c412b36fc316eabc338ce9cd152b8fea7316983d/lib/easy_pay_u_latam/r_api/subscription_service.rb#L94-L124
train
MakarovCode/EasyPayULatam
lib/easy_pay_u_latam/r_api/subscription_service.rb
PayuLatam.SubscriptionService.find_card
def find_card @client.remove_cards card = PayuLatam::Card.new(@client) # info de payu card.load( PayuCard.find(@selected_card).token ) @client.add_card({token: card.resource['token']}) end
ruby
def find_card @client.remove_cards card = PayuLatam::Card.new(@client) # info de payu card.load( PayuCard.find(@selected_card).token ) @client.add_card({token: card.resource['token']}) end
[ "def", "find_card", "@client", ".", "remove_cards", "card", "=", "PayuLatam", "::", "Card", ".", "new", "(", "@client", ")", "# info de payu", "card", ".", "load", "(", "PayuCard", ".", "find", "(", "@selected_card", ")", ".", "token", ")", "@client", ".", "add_card", "(", "{", "token", ":", "card", ".", "resource", "[", "'token'", "]", "}", ")", "end" ]
busca la info de una tarjeta de payu
[ "busca", "la", "info", "de", "una", "tarjeta", "de", "payu" ]
c412b36fc316eabc338ce9cd152b8fea7316983d
https://github.com/MakarovCode/EasyPayULatam/blob/c412b36fc316eabc338ce9cd152b8fea7316983d/lib/easy_pay_u_latam/r_api/subscription_service.rb#L144-L149
train
nebiros/dm-paginator
lib/dm-paginator/paginator.rb
DataMapper.Paginator.limit
def limit options = {} # Remove this key if we come from limit_page method. page = options.delete :page query = options.dup collection = new_collection scoped_query( options = { :limit => options[:limit], :offset => options[:offset], :order => [options[:order]] }.merge( query ) ) options.merge! :count => calculate_total_records( query ), :page => page collection.paginator = DataMapper::Paginator::Main.new options collection end
ruby
def limit options = {} # Remove this key if we come from limit_page method. page = options.delete :page query = options.dup collection = new_collection scoped_query( options = { :limit => options[:limit], :offset => options[:offset], :order => [options[:order]] }.merge( query ) ) options.merge! :count => calculate_total_records( query ), :page => page collection.paginator = DataMapper::Paginator::Main.new options collection end
[ "def", "limit", "options", "=", "{", "}", "# Remove this key if we come from limit_page method.", "page", "=", "options", ".", "delete", ":page", "query", "=", "options", ".", "dup", "collection", "=", "new_collection", "scoped_query", "(", "options", "=", "{", ":limit", "=>", "options", "[", ":limit", "]", ",", ":offset", "=>", "options", "[", ":offset", "]", ",", ":order", "=>", "[", "options", "[", ":order", "]", "]", "}", ".", "merge", "(", "query", ")", ")", "options", ".", "merge!", ":count", "=>", "calculate_total_records", "(", "query", ")", ",", ":page", "=>", "page", "collection", ".", "paginator", "=", "DataMapper", "::", "Paginator", "::", "Main", ".", "new", "options", "collection", "end" ]
Limit results. @param [Hash] options @return [Collection]
[ "Limit", "results", "." ]
e7486cce5c3712227b7eeef3ff76c1025c70d146
https://github.com/nebiros/dm-paginator/blob/e7486cce5c3712227b7eeef3ff76c1025c70d146/lib/dm-paginator/paginator.rb#L10-L22
train
nebiros/dm-paginator
lib/dm-paginator/paginator.rb
DataMapper.Paginator.limit_page
def limit_page page = nil, options = {} if page.is_a?( Hash ) options = page else options[:page] = page.to_i end options[:page] = options[:page].to_i > 0 ? options[:page] : DataMapper::Paginator.default[:page] options[:limit] = options[:limit].to_i || DataMapper::Paginator.default[:limit] options[:offset] = options[:limit] * ( options[:page] - 1 ) options[:order] = options[:order] || DataMapper::Paginator.default[:order] limit options end
ruby
def limit_page page = nil, options = {} if page.is_a?( Hash ) options = page else options[:page] = page.to_i end options[:page] = options[:page].to_i > 0 ? options[:page] : DataMapper::Paginator.default[:page] options[:limit] = options[:limit].to_i || DataMapper::Paginator.default[:limit] options[:offset] = options[:limit] * ( options[:page] - 1 ) options[:order] = options[:order] || DataMapper::Paginator.default[:order] limit options end
[ "def", "limit_page", "page", "=", "nil", ",", "options", "=", "{", "}", "if", "page", ".", "is_a?", "(", "Hash", ")", "options", "=", "page", "else", "options", "[", ":page", "]", "=", "page", ".", "to_i", "end", "options", "[", ":page", "]", "=", "options", "[", ":page", "]", ".", "to_i", ">", "0", "?", "options", "[", ":page", "]", ":", "DataMapper", "::", "Paginator", ".", "default", "[", ":page", "]", "options", "[", ":limit", "]", "=", "options", "[", ":limit", "]", ".", "to_i", "||", "DataMapper", "::", "Paginator", ".", "default", "[", ":limit", "]", "options", "[", ":offset", "]", "=", "options", "[", ":limit", "]", "*", "(", "options", "[", ":page", "]", "-", "1", ")", "options", "[", ":order", "]", "=", "options", "[", ":order", "]", "||", "DataMapper", "::", "Paginator", ".", "default", "[", ":order", "]", "limit", "options", "end" ]
Limit results by page. @param [Integer, Hash] page @param [Hash] options @return [Collection]
[ "Limit", "results", "by", "page", "." ]
e7486cce5c3712227b7eeef3ff76c1025c70d146
https://github.com/nebiros/dm-paginator/blob/e7486cce5c3712227b7eeef3ff76c1025c70d146/lib/dm-paginator/paginator.rb#L30-L42
train
nebiros/dm-paginator
lib/dm-paginator/paginator.rb
DataMapper.Paginator.calculate_total_records
def calculate_total_records query # Remove those keys from the query query.delete :page query.delete :limit query.delete :offset collection = new_collection scoped_query( query ) collection.count.to_i end
ruby
def calculate_total_records query # Remove those keys from the query query.delete :page query.delete :limit query.delete :offset collection = new_collection scoped_query( query ) collection.count.to_i end
[ "def", "calculate_total_records", "query", "# Remove those keys from the query", "query", ".", "delete", ":page", "query", ".", "delete", ":limit", "query", ".", "delete", ":offset", "collection", "=", "new_collection", "scoped_query", "(", "query", ")", "collection", ".", "count", ".", "to_i", "end" ]
Calculate total records @param [Hash] query @return [Integer]
[ "Calculate", "total", "records" ]
e7486cce5c3712227b7eeef3ff76c1025c70d146
https://github.com/nebiros/dm-paginator/blob/e7486cce5c3712227b7eeef3ff76c1025c70d146/lib/dm-paginator/paginator.rb#L51-L58
train
dlindahl/network_executive
lib/network_executive/scheduled_program.rb
NetworkExecutive.ScheduledProgram.+
def +( other_program ) raise ArgumentError if @program.class != other_program.class additional_duration = other_program.duration + 1 program.duration += additional_duration occurrence.duration += additional_duration occurrence.end_time += additional_duration self end
ruby
def +( other_program ) raise ArgumentError if @program.class != other_program.class additional_duration = other_program.duration + 1 program.duration += additional_duration occurrence.duration += additional_duration occurrence.end_time += additional_duration self end
[ "def", "+", "(", "other_program", ")", "raise", "ArgumentError", "if", "@program", ".", "class", "!=", "other_program", ".", "class", "additional_duration", "=", "other_program", ".", "duration", "+", "1", "program", ".", "duration", "+=", "additional_duration", "occurrence", ".", "duration", "+=", "additional_duration", "occurrence", ".", "end_time", "+=", "additional_duration", "self", "end" ]
Extends this scheduled program with another program of the same type.
[ "Extends", "this", "scheduled", "program", "with", "another", "program", "of", "the", "same", "type", "." ]
4802e8b20225d7058c82f5ded05bfa6c84918e3d
https://github.com/dlindahl/network_executive/blob/4802e8b20225d7058c82f5ded05bfa6c84918e3d/lib/network_executive/scheduled_program.rb#L14-L24
train
babausse/kharon
lib/kharon/processor.rb
Kharon.Processor.before_all
def before_all(key, options) required(key) if (options.has_key?(:required) and options[:required] == true) if options.has_key?(:dependencies) dependencies(key, options[:dependencies]) elsif options.has_key?(:dependency) dependency(key, options[:dependency]) end end
ruby
def before_all(key, options) required(key) if (options.has_key?(:required) and options[:required] == true) if options.has_key?(:dependencies) dependencies(key, options[:dependencies]) elsif options.has_key?(:dependency) dependency(key, options[:dependency]) end end
[ "def", "before_all", "(", "key", ",", "options", ")", "required", "(", "key", ")", "if", "(", "options", ".", "has_key?", "(", ":required", ")", "and", "options", "[", ":required", "]", "==", "true", ")", "if", "options", ".", "has_key?", "(", ":dependencies", ")", "dependencies", "(", "key", ",", "options", "[", ":dependencies", "]", ")", "elsif", "options", ".", "has_key?", "(", ":dependency", ")", "dependency", "(", "key", ",", "options", "[", ":dependency", "]", ")", "end", "end" ]
This method is executed before any call to a public method. @param [Object] key the key associated with the value currently filteres in the filtered datas. @param [Hash] options the options applied to the initial value.
[ "This", "method", "is", "executed", "before", "any", "call", "to", "a", "public", "method", "." ]
bfd3d90cbc229db70f2ed1762f5f1743259154cd
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L27-L34
train
babausse/kharon
lib/kharon/processor.rb
Kharon.Processor.store
def store(key, process, options = {}) unless (options.has_key?(:extract) and options[:extract] == false) if validator.datas.has_key?(key) value = ((options.has_key?(:cast) and options[:cast] == false) ? validator.datas[key] : process.call(validator.datas[key])) if(options.has_key?(:in)) in_array?(key, options[:in]) elsif(options.has_key?(:equals)) equals_to?(key, options[:equals]) elsif(options.has_key?(:equals_key)) equals_key?(key, options[:equals_key]) end options.has_key?(:rename) ? (validator.filtered[options[:rename]] = value) : (validator.filtered[key] = value) end end end
ruby
def store(key, process, options = {}) unless (options.has_key?(:extract) and options[:extract] == false) if validator.datas.has_key?(key) value = ((options.has_key?(:cast) and options[:cast] == false) ? validator.datas[key] : process.call(validator.datas[key])) if(options.has_key?(:in)) in_array?(key, options[:in]) elsif(options.has_key?(:equals)) equals_to?(key, options[:equals]) elsif(options.has_key?(:equals_key)) equals_key?(key, options[:equals_key]) end options.has_key?(:rename) ? (validator.filtered[options[:rename]] = value) : (validator.filtered[key] = value) end end end
[ "def", "store", "(", "key", ",", "process", ",", "options", "=", "{", "}", ")", "unless", "(", "options", ".", "has_key?", "(", ":extract", ")", "and", "options", "[", ":extract", "]", "==", "false", ")", "if", "validator", ".", "datas", ".", "has_key?", "(", "key", ")", "value", "=", "(", "(", "options", ".", "has_key?", "(", ":cast", ")", "and", "options", "[", ":cast", "]", "==", "false", ")", "?", "validator", ".", "datas", "[", "key", "]", ":", "process", ".", "call", "(", "validator", ".", "datas", "[", "key", "]", ")", ")", "if", "(", "options", ".", "has_key?", "(", ":in", ")", ")", "in_array?", "(", "key", ",", "options", "[", ":in", "]", ")", "elsif", "(", "options", ".", "has_key?", "(", ":equals", ")", ")", "equals_to?", "(", "key", ",", "options", "[", ":equals", "]", ")", "elsif", "(", "options", ".", "has_key?", "(", ":equals_key", ")", ")", "equals_key?", "(", "key", ",", "options", "[", ":equals_key", "]", ")", "end", "options", ".", "has_key?", "(", ":rename", ")", "?", "(", "validator", ".", "filtered", "[", "options", "[", ":rename", "]", "]", "=", "value", ")", ":", "(", "validator", ".", "filtered", "[", "key", "]", "=", "value", ")", "end", "end", "end" ]
Tries to store the associated key in the filtered key, transforming it with the given process. @param [Object] key the key associated with the value to store in the filtered datas. @param [Proc] process a process (lambda) to execute on the initial value. Must contain strictly one argument. @param [Hash] options the options applied to the initial value.
[ "Tries", "to", "store", "the", "associated", "key", "in", "the", "filtered", "key", "transforming", "it", "with", "the", "given", "process", "." ]
bfd3d90cbc229db70f2ed1762f5f1743259154cd
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L40-L54
train
babausse/kharon
lib/kharon/processor.rb
Kharon.Processor.raise_type_error
def raise_type_error(key, type) raise_error(type: "type", key: key, supposed: type, found: key.class) end
ruby
def raise_type_error(key, type) raise_error(type: "type", key: key, supposed: type, found: key.class) end
[ "def", "raise_type_error", "(", "key", ",", "type", ")", "raise_error", "(", "type", ":", "\"type\"", ",", "key", ":", "key", ",", "supposed", ":", "type", ",", "found", ":", "key", ".", "class", ")", "end" ]
Raises a type error with a generic message. @param [Object] key the key associated from the value triggering the error. @param [Class] type the expected type, not respected by the initial value. @raise [ArgumentError] the chosen type error.
[ "Raises", "a", "type", "error", "with", "a", "generic", "message", "." ]
bfd3d90cbc229db70f2ed1762f5f1743259154cd
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L60-L62
train
babausse/kharon
lib/kharon/processor.rb
Kharon.Processor.required
def required(key) raise_error(type: "required", key: key) unless validator.datas.has_key?(key) end
ruby
def required(key) raise_error(type: "required", key: key) unless validator.datas.has_key?(key) end
[ "def", "required", "(", "key", ")", "raise_error", "(", "type", ":", "\"required\"", ",", "key", ":", "key", ")", "unless", "validator", ".", "datas", ".", "has_key?", "(", "key", ")", "end" ]
Checks if a required key is present in provided datas. @param [Object] key the key of which check the presence. @raise [ArgumentError] if the key is not present.
[ "Checks", "if", "a", "required", "key", "is", "present", "in", "provided", "datas", "." ]
bfd3d90cbc229db70f2ed1762f5f1743259154cd
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L80-L82
train
babausse/kharon
lib/kharon/processor.rb
Kharon.Processor.dependency
def dependency(key, dependency) raise_error(type: "dependency", key: "key", needed: dependency) unless validator.datas.has_key?(dependency) end
ruby
def dependency(key, dependency) raise_error(type: "dependency", key: "key", needed: dependency) unless validator.datas.has_key?(dependency) end
[ "def", "dependency", "(", "key", ",", "dependency", ")", "raise_error", "(", "type", ":", "\"dependency\"", ",", "key", ":", "\"key\"", ",", "needed", ":", "dependency", ")", "unless", "validator", ".", "datas", ".", "has_key?", "(", "dependency", ")", "end" ]
Checks if a dependency is respected. A dependency is a key openly needed by another key. @param [Object] key the key needing another key to properly work. @param [Object] dependency the key needed by another key for it to properly work. @raise [ArgumentError] if the required dependency is not present.
[ "Checks", "if", "a", "dependency", "is", "respected", ".", "A", "dependency", "is", "a", "key", "openly", "needed", "by", "another", "key", "." ]
bfd3d90cbc229db70f2ed1762f5f1743259154cd
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L97-L99
train
babausse/kharon
lib/kharon/processor.rb
Kharon.Processor.is_typed?
def is_typed?(key, type) return (!validator.datas.has_key?(key) or validator.datas[key].kind_of?(type)) end
ruby
def is_typed?(key, type) return (!validator.datas.has_key?(key) or validator.datas[key].kind_of?(type)) end
[ "def", "is_typed?", "(", "key", ",", "type", ")", "return", "(", "!", "validator", ".", "datas", ".", "has_key?", "(", "key", ")", "or", "validator", ".", "datas", "[", "key", "]", ".", "kind_of?", "(", "type", ")", ")", "end" ]
Check if the value associated with the given key is typed with the given type, or with a type inheriting from it. @param [Object] key the key of the value to check the type from. @param [Class] type the type with which check the initial value. @return [Boolean] true if the initial value is from the right type, false if not.
[ "Check", "if", "the", "value", "associated", "with", "the", "given", "key", "is", "typed", "with", "the", "given", "type", "or", "with", "a", "type", "inheriting", "from", "it", "." ]
bfd3d90cbc229db70f2ed1762f5f1743259154cd
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L105-L107
train
babausse/kharon
lib/kharon/processor.rb
Kharon.Processor.in_array?
def in_array?(key, values) raise_error(type: "array.in", key: key, supposed: values, value: validator.datas[key]) unless (values.empty? or values.include?(validator.datas[key])) end
ruby
def in_array?(key, values) raise_error(type: "array.in", key: key, supposed: values, value: validator.datas[key]) unless (values.empty? or values.include?(validator.datas[key])) end
[ "def", "in_array?", "(", "key", ",", "values", ")", "raise_error", "(", "type", ":", "\"array.in\"", ",", "key", ":", "key", ",", "supposed", ":", "values", ",", "value", ":", "validator", ".", "datas", "[", "key", "]", ")", "unless", "(", "values", ".", "empty?", "or", "values", ".", "include?", "(", "validator", ".", "datas", "[", "key", "]", ")", ")", "end" ]
Checks if the value associated with the given key is included in the given array of values. @param [Object] key the key associated with the value to check. @param [Array] values the values in which the initial value should be contained. @raise [ArgumentError] if the initial value is not included in the given possible values.
[ "Checks", "if", "the", "value", "associated", "with", "the", "given", "key", "is", "included", "in", "the", "given", "array", "of", "values", "." ]
bfd3d90cbc229db70f2ed1762f5f1743259154cd
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L113-L115
train
babausse/kharon
lib/kharon/processor.rb
Kharon.Processor.equals_to?
def equals_to?(key, value) raise_error(type: "equals", key: key, supposed: value, found: validator.datas[key]) unless validator.datas[key] == value end
ruby
def equals_to?(key, value) raise_error(type: "equals", key: key, supposed: value, found: validator.datas[key]) unless validator.datas[key] == value end
[ "def", "equals_to?", "(", "key", ",", "value", ")", "raise_error", "(", "type", ":", "\"equals\"", ",", "key", ":", "key", ",", "supposed", ":", "value", ",", "found", ":", "validator", ".", "datas", "[", "key", "]", ")", "unless", "validator", ".", "datas", "[", "key", "]", "==", "value", "end" ]
Checks if the value associated with the given key is equal to the given value. @param [Object] key the key associated with the value to check. @param [Object] value the values with which the initial value should be compared. @raise [ArgumentError] if the initial value is not equal to the given value.
[ "Checks", "if", "the", "value", "associated", "with", "the", "given", "key", "is", "equal", "to", "the", "given", "value", "." ]
bfd3d90cbc229db70f2ed1762f5f1743259154cd
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L121-L123
train
babausse/kharon
lib/kharon/processor.rb
Kharon.Processor.match?
def match?(key, regex) return (!validator.datas.has_key?(key) or validator.datas[key].to_s.match(regex)) end
ruby
def match?(key, regex) return (!validator.datas.has_key?(key) or validator.datas[key].to_s.match(regex)) end
[ "def", "match?", "(", "key", ",", "regex", ")", "return", "(", "!", "validator", ".", "datas", ".", "has_key?", "(", "key", ")", "or", "validator", ".", "datas", "[", "key", "]", ".", "to_s", ".", "match", "(", "regex", ")", ")", "end" ]
Check if the value associated with the given key matches the given regular expression. @param [Object] key the key of the value to compare with the given regexp. @param [Regexp] regex the regex with which match the initial value. @return [Boolean] true if the initial value matches the regex, false if not.
[ "Check", "if", "the", "value", "associated", "with", "the", "given", "key", "matches", "the", "given", "regular", "expression", "." ]
bfd3d90cbc229db70f2ed1762f5f1743259154cd
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L137-L139
train
babausse/kharon
lib/kharon/processor.rb
Kharon.Processor.contains?
def contains?(key, values, required_values) raise_error(type: "contains.values", required: required_values, key: key) if (values & required_values) != required_values end
ruby
def contains?(key, values, required_values) raise_error(type: "contains.values", required: required_values, key: key) if (values & required_values) != required_values end
[ "def", "contains?", "(", "key", ",", "values", ",", "required_values", ")", "raise_error", "(", "type", ":", "\"contains.values\"", ",", "required", ":", "required_values", ",", "key", ":", "key", ")", "if", "(", "values", "&", "required_values", ")", "!=", "required_values", "end" ]
Checks if the value associated with the given key has the given required values. @param [Object] key the key associated with the value to check. @param [Array] required_values the values that the initial Enumerable typed value should contain. @raise [ArgumentError] if the initial value has not each and every one of the given values.
[ "Checks", "if", "the", "value", "associated", "with", "the", "given", "key", "has", "the", "given", "required", "values", "." ]
bfd3d90cbc229db70f2ed1762f5f1743259154cd
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L150-L152
train
babausse/kharon
lib/kharon/processor.rb
Kharon.Processor.has_keys?
def has_keys?(key, required_keys) raise_error(type: "contains.keys", required: required_keys, key: key) if (validator.datas[key].keys & required_keys) != required_keys end
ruby
def has_keys?(key, required_keys) raise_error(type: "contains.keys", required: required_keys, key: key) if (validator.datas[key].keys & required_keys) != required_keys end
[ "def", "has_keys?", "(", "key", ",", "required_keys", ")", "raise_error", "(", "type", ":", "\"contains.keys\"", ",", "required", ":", "required_keys", ",", "key", ":", "key", ")", "if", "(", "validator", ".", "datas", "[", "key", "]", ".", "keys", "&", "required_keys", ")", "!=", "required_keys", "end" ]
Checks if the value associated with the given key has the given required keys. @param [Object] key the key associated with the value to check. @param [Array] required_keys the keys that the initial Hash typed value should contain. @raise [ArgumentError] if the initial value has not each and every one of the given keys.
[ "Checks", "if", "the", "value", "associated", "with", "the", "given", "key", "has", "the", "given", "required", "keys", "." ]
bfd3d90cbc229db70f2ed1762f5f1743259154cd
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L158-L160
train
ideonetwork/lato-blog
lib/lato_blog/interfaces/tags.rb
LatoBlog.Interface::Tags.blog__clean_tag_parents
def blog__clean_tag_parents tag_parents = LatoBlog::TagParent.all tag_parents.map { |tp| tp.destroy if tp.tags.empty? } end
ruby
def blog__clean_tag_parents tag_parents = LatoBlog::TagParent.all tag_parents.map { |tp| tp.destroy if tp.tags.empty? } end
[ "def", "blog__clean_tag_parents", "tag_parents", "=", "LatoBlog", "::", "TagParent", ".", "all", "tag_parents", ".", "map", "{", "|", "tp", "|", "tp", ".", "destroy", "if", "tp", ".", "tags", ".", "empty?", "}", "end" ]
This function cleans all old tag parents without any child.
[ "This", "function", "cleans", "all", "old", "tag", "parents", "without", "any", "child", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/tags.rb#L7-L10
train
ideonetwork/lato-blog
lib/lato_blog/interfaces/tags.rb
LatoBlog.Interface::Tags.blog__get_tags
def blog__get_tags( order: nil, language: nil, search: nil, page: nil, per_page: nil ) tags = LatoBlog::Tag.all # apply filters order = order && order == 'ASC' ? 'ASC' : 'DESC' tags = _tags_filter_by_order(tags, order) tags = _tags_filter_by_language(tags, language) tags = _tags_filter_search(tags, search) # take tags uniqueness tags = tags.uniq(&:id) # save total tags total = tags.length # manage pagination page = page&.to_i || 1 per_page = per_page&.to_i || 20 tags = core__paginate_array(tags, per_page, page) # return result { tags: tags && !tags.empty? ? tags.map(&:serialize) : [], page: page, per_page: per_page, order: order, total: total } end
ruby
def blog__get_tags( order: nil, language: nil, search: nil, page: nil, per_page: nil ) tags = LatoBlog::Tag.all # apply filters order = order && order == 'ASC' ? 'ASC' : 'DESC' tags = _tags_filter_by_order(tags, order) tags = _tags_filter_by_language(tags, language) tags = _tags_filter_search(tags, search) # take tags uniqueness tags = tags.uniq(&:id) # save total tags total = tags.length # manage pagination page = page&.to_i || 1 per_page = per_page&.to_i || 20 tags = core__paginate_array(tags, per_page, page) # return result { tags: tags && !tags.empty? ? tags.map(&:serialize) : [], page: page, per_page: per_page, order: order, total: total } end
[ "def", "blog__get_tags", "(", "order", ":", "nil", ",", "language", ":", "nil", ",", "search", ":", "nil", ",", "page", ":", "nil", ",", "per_page", ":", "nil", ")", "tags", "=", "LatoBlog", "::", "Tag", ".", "all", "# apply filters", "order", "=", "order", "&&", "order", "==", "'ASC'", "?", "'ASC'", ":", "'DESC'", "tags", "=", "_tags_filter_by_order", "(", "tags", ",", "order", ")", "tags", "=", "_tags_filter_by_language", "(", "tags", ",", "language", ")", "tags", "=", "_tags_filter_search", "(", "tags", ",", "search", ")", "# take tags uniqueness", "tags", "=", "tags", ".", "uniq", "(", ":id", ")", "# save total tags", "total", "=", "tags", ".", "length", "# manage pagination", "page", "=", "page", "&.", "to_i", "||", "1", "per_page", "=", "per_page", "&.", "to_i", "||", "20", "tags", "=", "core__paginate_array", "(", "tags", ",", "per_page", ",", "page", ")", "# return result", "{", "tags", ":", "tags", "&&", "!", "tags", ".", "empty?", "?", "tags", ".", "map", "(", ":serialize", ")", ":", "[", "]", ",", "page", ":", "page", ",", "per_page", ":", "per_page", ",", "order", ":", "order", ",", "total", ":", "total", "}", "end" ]
This function returns an object with the list of tags with some filters.
[ "This", "function", "returns", "an", "object", "with", "the", "list", "of", "tags", "with", "some", "filters", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/tags.rb#L13-L47
train
ideonetwork/lato-blog
lib/lato_blog/interfaces/tags.rb
LatoBlog.Interface::Tags.blog__get_category
def blog__get_category(id: nil, permalink: nil) return {} unless id || permalink if id category = LatoBlog::Category.find_by(id: id.to_i) else category = LatoBlog::Category.find_by(meta_permalink: permalink) end category.serialize end
ruby
def blog__get_category(id: nil, permalink: nil) return {} unless id || permalink if id category = LatoBlog::Category.find_by(id: id.to_i) else category = LatoBlog::Category.find_by(meta_permalink: permalink) end category.serialize end
[ "def", "blog__get_category", "(", "id", ":", "nil", ",", "permalink", ":", "nil", ")", "return", "{", "}", "unless", "id", "||", "permalink", "if", "id", "category", "=", "LatoBlog", "::", "Category", ".", "find_by", "(", "id", ":", "id", ".", "to_i", ")", "else", "category", "=", "LatoBlog", "::", "Category", ".", "find_by", "(", "meta_permalink", ":", "permalink", ")", "end", "category", ".", "serialize", "end" ]
This function returns a single category searched by id or permalink.
[ "This", "function", "returns", "a", "single", "category", "searched", "by", "id", "or", "permalink", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/tags.rb#L50-L60
train
npepinpe/redstruct
lib/redstruct/set.rb
Redstruct.Set.random
def random(count: 1) list = self.connection.srandmember(@key, count) return nil if list.nil? return count == 1 ? list[0] : ::Set.new(list) end
ruby
def random(count: 1) list = self.connection.srandmember(@key, count) return nil if list.nil? return count == 1 ? list[0] : ::Set.new(list) end
[ "def", "random", "(", "count", ":", "1", ")", "list", "=", "self", ".", "connection", ".", "srandmember", "(", "@key", ",", "count", ")", "return", "nil", "if", "list", ".", "nil?", "return", "count", "==", "1", "?", "list", "[", "0", "]", ":", "::", "Set", ".", "new", "(", "list", ")", "end" ]
Returns random items from the set @param [Integer] count the number of items to return @return [String, Set] if count is one, then return the item; otherwise returns a set
[ "Returns", "random", "items", "from", "the", "set" ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/set.rb#L22-L27
train
npepinpe/redstruct
lib/redstruct/set.rb
Redstruct.Set.difference
def difference(other, dest: nil) destination = coerce_destination(dest) results = if destination.nil? ::Set.new(self.connection.sdiff(@key, other.key)) else self.connection.sdiffstore(destination.key, @key, other.key) end return results end
ruby
def difference(other, dest: nil) destination = coerce_destination(dest) results = if destination.nil? ::Set.new(self.connection.sdiff(@key, other.key)) else self.connection.sdiffstore(destination.key, @key, other.key) end return results end
[ "def", "difference", "(", "other", ",", "dest", ":", "nil", ")", "destination", "=", "coerce_destination", "(", "dest", ")", "results", "=", "if", "destination", ".", "nil?", "::", "Set", ".", "new", "(", "self", ".", "connection", ".", "sdiff", "(", "@key", ",", "other", ".", "key", ")", ")", "else", "self", ".", "connection", ".", "sdiffstore", "(", "destination", ".", "key", ",", "@key", ",", "other", ".", "key", ")", "end", "return", "results", "end" ]
Computes the difference of the two sets and stores the result in `dest`. If no destination provided, computes the results in memory. @param [Redstruct::Set] other set the set to subtract @param [Redstruct::Set, String] dest if nil, results are computed in memory. if a string, a new Redstruct::Set is constructed with the string as the key, and results are stored there. if already a Redstruct::Set, results are stored there. @return [::Set, Integer] if dest was provided, returns the number of elements in the destination; otherwise a standard Ruby set containing the difference
[ "Computes", "the", "difference", "of", "the", "two", "sets", "and", "stores", "the", "result", "in", "dest", ".", "If", "no", "destination", "provided", "computes", "the", "results", "in", "memory", "." ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/set.rb#L77-L86
train
npepinpe/redstruct
lib/redstruct/set.rb
Redstruct.Set.intersection
def intersection(other, dest: nil) destination = coerce_destination(dest) results = if destination.nil? ::Set.new(self.connection.sinter(@key, other.key)) else self.connection.sinterstore(destination.key, @key, other.key) end return results end
ruby
def intersection(other, dest: nil) destination = coerce_destination(dest) results = if destination.nil? ::Set.new(self.connection.sinter(@key, other.key)) else self.connection.sinterstore(destination.key, @key, other.key) end return results end
[ "def", "intersection", "(", "other", ",", "dest", ":", "nil", ")", "destination", "=", "coerce_destination", "(", "dest", ")", "results", "=", "if", "destination", ".", "nil?", "::", "Set", ".", "new", "(", "self", ".", "connection", ".", "sinter", "(", "@key", ",", "other", ".", "key", ")", ")", "else", "self", ".", "connection", ".", "sinterstore", "(", "destination", ".", "key", ",", "@key", ",", "other", ".", "key", ")", "end", "return", "results", "end" ]
Computes the interesection of the two sets and stores the result in `dest`. If no destination provided, computes the results in memory. @param [Redstruct::Set] other set the set to intersect @param [Redstruct::Set, String] dest if nil, results are computed in memory. if a string, a new Redstruct::Set is constructed with the string as the key, and results are stored there. if already a Redstruct::Set, results are stored there. @return [::Set, Integer] if dest was provided, returns the number of elements in the destination; otherwise a standard Ruby set containing the intersection
[ "Computes", "the", "interesection", "of", "the", "two", "sets", "and", "stores", "the", "result", "in", "dest", ".", "If", "no", "destination", "provided", "computes", "the", "results", "in", "memory", "." ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/set.rb#L95-L104
train
npepinpe/redstruct
lib/redstruct/set.rb
Redstruct.Set.union
def union(other, dest: nil) destination = coerce_destination(dest) results = if destination.nil? ::Set.new(self.connection.sunion(@key, other.key)) else self.connection.sunionstore(destination.key, @key, other.key) end return results end
ruby
def union(other, dest: nil) destination = coerce_destination(dest) results = if destination.nil? ::Set.new(self.connection.sunion(@key, other.key)) else self.connection.sunionstore(destination.key, @key, other.key) end return results end
[ "def", "union", "(", "other", ",", "dest", ":", "nil", ")", "destination", "=", "coerce_destination", "(", "dest", ")", "results", "=", "if", "destination", ".", "nil?", "::", "Set", ".", "new", "(", "self", ".", "connection", ".", "sunion", "(", "@key", ",", "other", ".", "key", ")", ")", "else", "self", ".", "connection", ".", "sunionstore", "(", "destination", ".", "key", ",", "@key", ",", "other", ".", "key", ")", "end", "return", "results", "end" ]
Computes the union of the two sets and stores the result in `dest`. If no destination provided, computes the results in memory. @param [Redstruct::Set] other set the set to add @param [Redstruct::Set, String] dest if nil, results are computed in memory. if a string, a new Redstruct::Set is constructed with the string as the key, and results are stored there. if already a Redstruct::Set, results are stored there. @return [::Set, Integer] if dest was provided, returns the number of elements in the destination; otherwise a standard Ruby set containing the union
[ "Computes", "the", "union", "of", "the", "two", "sets", "and", "stores", "the", "result", "in", "dest", ".", "If", "no", "destination", "provided", "computes", "the", "results", "in", "memory", "." ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/set.rb#L113-L122
train
cqql/exec_env
lib/exec_env/env.rb
ExecEnv.Env.exec
def exec (*args, &block) if @scope @scope.instance_variables.each do |name| instance_variable_set(name, @scope.instance_variable_get(name)) end end @ivars.each do |name, value| instance_variable_set(name, value) end instance_exec(*args, &block) end
ruby
def exec (*args, &block) if @scope @scope.instance_variables.each do |name| instance_variable_set(name, @scope.instance_variable_get(name)) end end @ivars.each do |name, value| instance_variable_set(name, value) end instance_exec(*args, &block) end
[ "def", "exec", "(", "*", "args", ",", "&", "block", ")", "if", "@scope", "@scope", ".", "instance_variables", ".", "each", "do", "|", "name", "|", "instance_variable_set", "(", "name", ",", "@scope", ".", "instance_variable_get", "(", "name", ")", ")", "end", "end", "@ivars", ".", "each", "do", "|", "name", ",", "value", "|", "instance_variable_set", "(", "name", ",", "value", ")", "end", "instance_exec", "(", "args", ",", "block", ")", "end" ]
Execute a block in the manipulated environment. Additional arguments will be passed to the block. Returns the return value of the block
[ "Execute", "a", "block", "in", "the", "manipulated", "environment", "." ]
288e109c3be390349ddb73dee74897f49479824f
https://github.com/cqql/exec_env/blob/288e109c3be390349ddb73dee74897f49479824f/lib/exec_env/env.rb#L57-L69
train
ZirconCode/Scrapah
lib/scrapah/scraper.rb
Scrapah.Scraper.process_appropriate
def process_appropriate(doc,cmd) return process_regex(doc,cmd) if(cmd.is_a? Regexp) return process_proc(doc,cmd) if(cmd.is_a? Proc) if cmd.is_a?(String) return process_xpath(doc,cmd) if cmd.start_with?("x|") return process_css(doc,cmd) if cmd.start_with?("c|") end nil end
ruby
def process_appropriate(doc,cmd) return process_regex(doc,cmd) if(cmd.is_a? Regexp) return process_proc(doc,cmd) if(cmd.is_a? Proc) if cmd.is_a?(String) return process_xpath(doc,cmd) if cmd.start_with?("x|") return process_css(doc,cmd) if cmd.start_with?("c|") end nil end
[ "def", "process_appropriate", "(", "doc", ",", "cmd", ")", "return", "process_regex", "(", "doc", ",", "cmd", ")", "if", "(", "cmd", ".", "is_a?", "Regexp", ")", "return", "process_proc", "(", "doc", ",", "cmd", ")", "if", "(", "cmd", ".", "is_a?", "Proc", ")", "if", "cmd", ".", "is_a?", "(", "String", ")", "return", "process_xpath", "(", "doc", ",", "cmd", ")", "if", "cmd", ".", "start_with?", "(", "\"x|\"", ")", "return", "process_css", "(", "doc", ",", "cmd", ")", "if", "cmd", ".", "start_with?", "(", "\"c|\"", ")", "end", "nil", "end" ]
accepts nokogiri doc's only atm
[ "accepts", "nokogiri", "doc", "s", "only", "atm" ]
5adcc92da1f7d7634f91c717f6f28e0daf0129b7
https://github.com/ZirconCode/Scrapah/blob/5adcc92da1f7d7634f91c717f6f28e0daf0129b7/lib/scrapah/scraper.rb#L103-L115
train
bradfeehan/derelict
lib/derelict/connection.rb
Derelict.Connection.validate!
def validate! logger.debug "Starting validation for #{description}" raise NotFound.new path unless File.exists? path logger.info "Successfully validated #{description}" self end
ruby
def validate! logger.debug "Starting validation for #{description}" raise NotFound.new path unless File.exists? path logger.info "Successfully validated #{description}" self end
[ "def", "validate!", "logger", ".", "debug", "\"Starting validation for #{description}\"", "raise", "NotFound", ".", "new", "path", "unless", "File", ".", "exists?", "path", "logger", ".", "info", "\"Successfully validated #{description}\"", "self", "end" ]
Initializes a Connection for use in a particular directory * instance: The Derelict::Instance to use to control Vagrant * path: The project path, which contains the Vagrantfile Validates the data used for this connection Raises exceptions on failure: * +Derelict::Connection::NotFound+ if the path is not found
[ "Initializes", "a", "Connection", "for", "use", "in", "a", "particular", "directory" ]
c9d70f04562280a34083dd060b0e4099e6f32d8d
https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/connection.rb#L28-L33
train
adriancuadros/seedsv
lib/seedsv/csv_seed.rb
Seedsv.CsvSeed.seed_model
def seed_model(model_class, options={}) if model_class.count == 0 or options[:force] table_name = options[:file_name] || model_class.table_name puts "Seeding #{model_class.to_s.pluralize}..." csv_file = @@csv_class.open(Rails.root + "db/csv/#{table_name}.csv", :headers => true) seed_from_csv(model_class, csv_file) end end
ruby
def seed_model(model_class, options={}) if model_class.count == 0 or options[:force] table_name = options[:file_name] || model_class.table_name puts "Seeding #{model_class.to_s.pluralize}..." csv_file = @@csv_class.open(Rails.root + "db/csv/#{table_name}.csv", :headers => true) seed_from_csv(model_class, csv_file) end end
[ "def", "seed_model", "(", "model_class", ",", "options", "=", "{", "}", ")", "if", "model_class", ".", "count", "==", "0", "or", "options", "[", ":force", "]", "table_name", "=", "options", "[", ":file_name", "]", "||", "model_class", ".", "table_name", "puts", "\"Seeding #{model_class.to_s.pluralize}...\"", "csv_file", "=", "@@csv_class", ".", "open", "(", "Rails", ".", "root", "+", "\"db/csv/#{table_name}.csv\"", ",", ":headers", "=>", "true", ")", "seed_from_csv", "(", "model_class", ",", "csv_file", ")", "end", "end" ]
Receives the reference to the model class to seed. Seeds only when there are no records in the table or if the +force+ option is set to true. Also optionally it can receive the +file_name+ to use.
[ "Receives", "the", "reference", "to", "the", "model", "class", "to", "seed", ".", "Seeds", "only", "when", "there", "are", "no", "records", "in", "the", "table", "or", "if", "the", "+", "force", "+", "option", "is", "set", "to", "true", ".", "Also", "optionally", "it", "can", "receive", "the", "+", "file_name", "+", "to", "use", "." ]
db01147a5ece722389120230247c5f0ee111ea9e
https://github.com/adriancuadros/seedsv/blob/db01147a5ece722389120230247c5f0ee111ea9e/lib/seedsv/csv_seed.rb#L20-L27
train
adriancuadros/seedsv
lib/seedsv/csv_seed.rb
Seedsv.CsvSeed.seed_from_csv
def seed_from_csv(migration_class, csv_file) migration_class.transaction do csv_file.each do |line_values| record = migration_class.new line_values.to_hash.keys.map{|attribute| record.send("#{attribute.strip}=",line_values[attribute].strip) rescue nil} record.save(:validate => false) end end end
ruby
def seed_from_csv(migration_class, csv_file) migration_class.transaction do csv_file.each do |line_values| record = migration_class.new line_values.to_hash.keys.map{|attribute| record.send("#{attribute.strip}=",line_values[attribute].strip) rescue nil} record.save(:validate => false) end end end
[ "def", "seed_from_csv", "(", "migration_class", ",", "csv_file", ")", "migration_class", ".", "transaction", "do", "csv_file", ".", "each", "do", "|", "line_values", "|", "record", "=", "migration_class", ".", "new", "line_values", ".", "to_hash", ".", "keys", ".", "map", "{", "|", "attribute", "|", "record", ".", "send", "(", "\"#{attribute.strip}=\"", ",", "line_values", "[", "attribute", "]", ".", "strip", ")", "rescue", "nil", "}", "record", ".", "save", "(", ":validate", "=>", "false", ")", "end", "end", "end" ]
Receives the class reference and csv file and creates all thre records inside one transaction
[ "Receives", "the", "class", "reference", "and", "csv", "file", "and", "creates", "all", "thre", "records", "inside", "one", "transaction" ]
db01147a5ece722389120230247c5f0ee111ea9e
https://github.com/adriancuadros/seedsv/blob/db01147a5ece722389120230247c5f0ee111ea9e/lib/seedsv/csv_seed.rb#L33-L41
train
jeremyz/edoors-ruby
lib/edoors/particle.rb
Edoors.Particle.add_dsts
def add_dsts *dsts dsts.each do |dst| if dst.empty? or dst==Edoors::ACT_SEP or dst[0]==Edoors::PATH_SEP \ or dst=~/\/\?/ or dst=~/\/{2,}/ or dst=~/\s+/ raise Edoors::Exception.new "destination #{dst} is not acceptable" end @dsts << dst end end
ruby
def add_dsts *dsts dsts.each do |dst| if dst.empty? or dst==Edoors::ACT_SEP or dst[0]==Edoors::PATH_SEP \ or dst=~/\/\?/ or dst=~/\/{2,}/ or dst=~/\s+/ raise Edoors::Exception.new "destination #{dst} is not acceptable" end @dsts << dst end end
[ "def", "add_dsts", "*", "dsts", "dsts", ".", "each", "do", "|", "dst", "|", "if", "dst", ".", "empty?", "or", "dst", "==", "Edoors", "::", "ACT_SEP", "or", "dst", "[", "0", "]", "==", "Edoors", "::", "PATH_SEP", "or", "dst", "=~", "/", "\\/", "\\?", "/", "or", "dst", "=~", "/", "\\/", "/", "or", "dst", "=~", "/", "\\s", "/", "raise", "Edoors", "::", "Exception", ".", "new", "\"destination #{dst} is not acceptable\"", "end", "@dsts", "<<", "dst", "end", "end" ]
adds destinations to the destination list @param [Array] dsts destinations to add @raise Edoors::Exception if a destination is not acceptable The parameters are checked before beeing added. they must not be empty or be '?' or start with '/' or contain '/?' or '//' or '\s+'
[ "adds", "destinations", "to", "the", "destination", "list" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/particle.rb#L162-L170
train
jeremyz/edoors-ruby
lib/edoors/particle.rb
Edoors.Particle.set_dst!
def set_dst! a, d @action = a if d.is_a? Edoors::Iota @dst = d else @dst = nil _split_path! d end end
ruby
def set_dst! a, d @action = a if d.is_a? Edoors::Iota @dst = d else @dst = nil _split_path! d end end
[ "def", "set_dst!", "a", ",", "d", "@action", "=", "a", "if", "d", ".", "is_a?", "Edoors", "::", "Iota", "@dst", "=", "d", "else", "@dst", "=", "nil", "_split_path!", "d", "end", "end" ]
sets the current destination @param [String] a the action @param [String Iota] d the destination
[ "sets", "the", "current", "destination" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/particle.rb#L186-L194
train
jeremyz/edoors-ruby
lib/edoors/particle.rb
Edoors.Particle.apply_link!
def apply_link! lnk init! lnk.door clear_dsts! add_dsts *lnk.dsts set_link_keys *lnk.keys end
ruby
def apply_link! lnk init! lnk.door clear_dsts! add_dsts *lnk.dsts set_link_keys *lnk.keys end
[ "def", "apply_link!", "lnk", "init!", "lnk", ".", "door", "clear_dsts!", "add_dsts", "lnk", ".", "dsts", "set_link_keys", "lnk", ".", "keys", "end" ]
applies the effects of the given Link @param [Link] lnk the link to apply effects updates @src with Link @src, clears the destination list adds the Link destinations to @dsts, sets the @link_keys
[ "applies", "the", "effects", "of", "the", "given", "Link" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/particle.rb#L257-L262
train
jeremyz/edoors-ruby
lib/edoors/particle.rb
Edoors.Particle.set_link_keys
def set_link_keys *args @link_keys.clear if not @link_keys.empty? args.compact! args.each do |lf| @link_keys << lf end @link_value = @payload.select { |k,v| @link_keys.include? k } end
ruby
def set_link_keys *args @link_keys.clear if not @link_keys.empty? args.compact! args.each do |lf| @link_keys << lf end @link_value = @payload.select { |k,v| @link_keys.include? k } end
[ "def", "set_link_keys", "*", "args", "@link_keys", ".", "clear", "if", "not", "@link_keys", ".", "empty?", "args", ".", "compact!", "args", ".", "each", "do", "|", "lf", "|", "@link_keys", "<<", "lf", "end", "@link_value", "=", "@payload", ".", "select", "{", "|", "k", ",", "v", "|", "@link_keys", ".", "include?", "k", "}", "end" ]
sets the links keys @param [Array] args list of keys to set \@link_value attribute will be updated
[ "sets", "the", "links", "keys" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/particle.rb#L315-L322
train
jeremyz/edoors-ruby
lib/edoors/particle.rb
Edoors.Particle.link_with?
def link_with? link return true if link.value.nil? link.value.keys.inject({}) { |h,k| h[k]=@payload[k] if @payload.has_key?(k); h }.eql? link.value end
ruby
def link_with? link return true if link.value.nil? link.value.keys.inject({}) { |h,k| h[k]=@payload[k] if @payload.has_key?(k); h }.eql? link.value end
[ "def", "link_with?", "link", "return", "true", "if", "link", ".", "value", ".", "nil?", "link", ".", "value", ".", "keys", ".", "inject", "(", "{", "}", ")", "{", "|", "h", ",", "k", "|", "h", "[", "k", "]", "=", "@payload", "[", "k", "]", "if", "@payload", ".", "has_key?", "(", "k", ")", ";", "h", "}", ".", "eql?", "link", ".", "value", "end" ]
tries to link the Particle with the given Link @param [Link] link the link to try to link with returns true if the value of the Link is nil otherwise checks if the extracted key values pairs from the Particle payload using the Link value keys as selectors, equals the Link value @return [Boolean] true if the Link links with the Particle
[ "tries", "to", "link", "the", "Particle", "with", "the", "given", "Link" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/particle.rb#L334-L337
train
jeremyz/edoors-ruby
lib/edoors/particle.rb
Edoors.Particle.clear_merged!
def clear_merged! r=false @merged.each do |p| p.clear_merged! r r.release_p p if r end @merged.clear end
ruby
def clear_merged! r=false @merged.each do |p| p.clear_merged! r r.release_p p if r end @merged.clear end
[ "def", "clear_merged!", "r", "=", "false", "@merged", ".", "each", "do", "|", "p", "|", "p", ".", "clear_merged!", "r", "r", ".", "release_p", "p", "if", "r", "end", "@merged", ".", "clear", "end" ]
recursively clears the merged Particle list @param [Boolean] r releases the cleared Particle if true
[ "recursively", "clears", "the", "merged", "Particle", "list" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/particle.rb#L365-L371
train
bottleneckco/playoverwatch-scraper
lib/playoverwatch-scraper/scraper.rb
PlayOverwatch.Scraper.sr
def sr comp_div = @player_page.css('.competitive-rank > .h5') return -1 if comp_div.empty? content = comp_div.first.content content.to_i if Integer(content) rescue -1 end
ruby
def sr comp_div = @player_page.css('.competitive-rank > .h5') return -1 if comp_div.empty? content = comp_div.first.content content.to_i if Integer(content) rescue -1 end
[ "def", "sr", "comp_div", "=", "@player_page", ".", "css", "(", "'.competitive-rank > .h5'", ")", "return", "-", "1", "if", "comp_div", ".", "empty?", "content", "=", "comp_div", ".", "first", ".", "content", "content", ".", "to_i", "if", "Integer", "(", "content", ")", "rescue", "-", "1", "end" ]
Retrieve a player's current competitive season ranking. Returns -1 if player did not complete placements.
[ "Retrieve", "a", "player", "s", "current", "competitive", "season", "ranking", ".", "Returns", "-", "1", "if", "player", "did", "not", "complete", "placements", "." ]
7909bdda3cefe15a5f4718e122943146365a01e1
https://github.com/bottleneckco/playoverwatch-scraper/blob/7909bdda3cefe15a5f4718e122943146365a01e1/lib/playoverwatch-scraper/scraper.rb#L40-L45
train
bottleneckco/playoverwatch-scraper
lib/playoverwatch-scraper/scraper.rb
PlayOverwatch.Scraper.main_qp
def main_qp hero_img = hidden_mains_style.content.scan(/\.quickplay {.+?url\((.+?)\);/mis).flatten.first hero_img.scan(/\/hero\/(.+?)\/career/i).flatten.first end
ruby
def main_qp hero_img = hidden_mains_style.content.scan(/\.quickplay {.+?url\((.+?)\);/mis).flatten.first hero_img.scan(/\/hero\/(.+?)\/career/i).flatten.first end
[ "def", "main_qp", "hero_img", "=", "hidden_mains_style", ".", "content", ".", "scan", "(", "/", "\\.", "\\(", "\\)", "/mis", ")", ".", "flatten", ".", "first", "hero_img", ".", "scan", "(", "/", "\\/", "\\/", "\\/", "/i", ")", ".", "flatten", ".", "first", "end" ]
Retrieve player's main Quick Play hero, in lowercase form.
[ "Retrieve", "player", "s", "main", "Quick", "Play", "hero", "in", "lowercase", "form", "." ]
7909bdda3cefe15a5f4718e122943146365a01e1
https://github.com/bottleneckco/playoverwatch-scraper/blob/7909bdda3cefe15a5f4718e122943146365a01e1/lib/playoverwatch-scraper/scraper.rb#L49-L52
train
bottleneckco/playoverwatch-scraper
lib/playoverwatch-scraper/scraper.rb
PlayOverwatch.Scraper.main_comp
def main_comp hero_img = hidden_mains_style.content.scan(/\.competitive {.+?url\((.+?)\);/mis).flatten.first hero_img.scan(/\/hero\/(.+?)\/career/i).flatten.first end
ruby
def main_comp hero_img = hidden_mains_style.content.scan(/\.competitive {.+?url\((.+?)\);/mis).flatten.first hero_img.scan(/\/hero\/(.+?)\/career/i).flatten.first end
[ "def", "main_comp", "hero_img", "=", "hidden_mains_style", ".", "content", ".", "scan", "(", "/", "\\.", "\\(", "\\)", "/mis", ")", ".", "flatten", ".", "first", "hero_img", ".", "scan", "(", "/", "\\/", "\\/", "\\/", "/i", ")", ".", "flatten", ".", "first", "end" ]
Retrieve player's main Competitive hero, in lowercase form. You should check if the sr is -1 before attempting to call this.
[ "Retrieve", "player", "s", "main", "Competitive", "hero", "in", "lowercase", "form", ".", "You", "should", "check", "if", "the", "sr", "is", "-", "1", "before", "attempting", "to", "call", "this", "." ]
7909bdda3cefe15a5f4718e122943146365a01e1
https://github.com/bottleneckco/playoverwatch-scraper/blob/7909bdda3cefe15a5f4718e122943146365a01e1/lib/playoverwatch-scraper/scraper.rb#L57-L60
train
hilotus/spear-cb-api
lib/spear/request.rb
Spear.Request.to_xml
def to_xml(body) root = @api_options[:root_element].nil? ? 'Request' : @api_options[:root_element] body.to_xml(root: root, skip_instruct: true, skip_types: true) end
ruby
def to_xml(body) root = @api_options[:root_element].nil? ? 'Request' : @api_options[:root_element] body.to_xml(root: root, skip_instruct: true, skip_types: true) end
[ "def", "to_xml", "(", "body", ")", "root", "=", "@api_options", "[", ":root_element", "]", ".", "nil?", "?", "'Request'", ":", "@api_options", "[", ":root_element", "]", "body", ".", "to_xml", "(", "root", ":", "root", ",", "skip_instruct", ":", "true", ",", "skip_types", ":", "true", ")", "end" ]
parse body from hash to xml format
[ "parse", "body", "from", "hash", "to", "xml", "format" ]
a0fd264556b3532ee61961cbb2abf990fe855f47
https://github.com/hilotus/spear-cb-api/blob/a0fd264556b3532ee61961cbb2abf990fe855f47/lib/spear/request.rb#L74-L77
train
janlelis/ripl-profiles
lib/ripl/profiles.rb
Ripl::Profiles.Runner.parse_option
def parse_option( option, argv ) if option =~ /(?:-p|--profile)=?(.*)/ Ripl::Profiles.load( ($1.empty? ? argv.shift.to_s : $1).split(':') ) else super end end
ruby
def parse_option( option, argv ) if option =~ /(?:-p|--profile)=?(.*)/ Ripl::Profiles.load( ($1.empty? ? argv.shift.to_s : $1).split(':') ) else super end end
[ "def", "parse_option", "(", "option", ",", "argv", ")", "if", "option", "=~", "/", "/", "Ripl", "::", "Profiles", ".", "load", "(", "(", "$1", ".", "empty?", "?", "argv", ".", "shift", ".", "to_s", ":", "$1", ")", ".", "split", "(", "':'", ")", ")", "else", "super", "end", "end" ]
add command line option
[ "add", "command", "line", "option" ]
0f8d64d9650b2917fdb59b6846263578218f375f
https://github.com/janlelis/ripl-profiles/blob/0f8d64d9650b2917fdb59b6846263578218f375f/lib/ripl/profiles.rb#L59-L65
train
mlandauer/new_time
lib/new_time.rb
NewTime.NewTime.convert
def convert(point) today = Date.new(year, month, day) new_seconds = seconds + fractional + (minutes + hours * 60) * 60 # During daylight hours? if hours >= 6 && hours < 18 start = NewTime.sunrise(today, point) finish = NewTime.sunset(today, point) new_start_hour = 6 else # Is it before sunrise or after sunset? if hours < 6 start = NewTime.sunset(today - 1, point) finish = NewTime.sunrise(today, point) new_start_hour = 18 - 24 else start = NewTime.sunset(today, point) finish = NewTime.sunrise(today + 1, point) new_start_hour = 18 end end start + (new_seconds.to_f / (60 * 60) - new_start_hour) * (finish - start) / 12 end
ruby
def convert(point) today = Date.new(year, month, day) new_seconds = seconds + fractional + (minutes + hours * 60) * 60 # During daylight hours? if hours >= 6 && hours < 18 start = NewTime.sunrise(today, point) finish = NewTime.sunset(today, point) new_start_hour = 6 else # Is it before sunrise or after sunset? if hours < 6 start = NewTime.sunset(today - 1, point) finish = NewTime.sunrise(today, point) new_start_hour = 18 - 24 else start = NewTime.sunset(today, point) finish = NewTime.sunrise(today + 1, point) new_start_hour = 18 end end start + (new_seconds.to_f / (60 * 60) - new_start_hour) * (finish - start) / 12 end
[ "def", "convert", "(", "point", ")", "today", "=", "Date", ".", "new", "(", "year", ",", "month", ",", "day", ")", "new_seconds", "=", "seconds", "+", "fractional", "+", "(", "minutes", "+", "hours", "*", "60", ")", "*", "60", "# During daylight hours?", "if", "hours", ">=", "6", "&&", "hours", "<", "18", "start", "=", "NewTime", ".", "sunrise", "(", "today", ",", "point", ")", "finish", "=", "NewTime", ".", "sunset", "(", "today", ",", "point", ")", "new_start_hour", "=", "6", "else", "# Is it before sunrise or after sunset?", "if", "hours", "<", "6", "start", "=", "NewTime", ".", "sunset", "(", "today", "-", "1", ",", "point", ")", "finish", "=", "NewTime", ".", "sunrise", "(", "today", ",", "point", ")", "new_start_hour", "=", "18", "-", "24", "else", "start", "=", "NewTime", ".", "sunset", "(", "today", ",", "point", ")", "finish", "=", "NewTime", ".", "sunrise", "(", "today", "+", "1", ",", "point", ")", "new_start_hour", "=", "18", "end", "end", "start", "+", "(", "new_seconds", ".", "to_f", "/", "(", "60", "*", "60", ")", "-", "new_start_hour", ")", "*", "(", "finish", "-", "start", ")", "/", "12", "end" ]
Convert back to "normal" time
[ "Convert", "back", "to", "normal", "time" ]
0ea74c82cf59a56a03860c7d38f9058cff1f6d8b
https://github.com/mlandauer/new_time/blob/0ea74c82cf59a56a03860c7d38f9058cff1f6d8b/lib/new_time.rb#L33-L55
train
smsified/smsified-ruby
lib/smsified/reporting.rb
Smsified.Reporting.delivery_status
def delivery_status(options) raise ArgumentError, 'an options Hash is required' if !options.instance_of?(Hash) raise ArgumentError, ':sender_address is required' if options[:sender_address].nil? && @sender_address.nil? options[:sender_address] = options[:sender_address] || @sender_address Response.new self.class.get("/smsmessaging/outbound/#{options[:sender_address]}/requests/#{options[:request_id]}/deliveryInfos", :basic_auth => @auth, :headers => SMSIFIED_HTTP_HEADERS) end
ruby
def delivery_status(options) raise ArgumentError, 'an options Hash is required' if !options.instance_of?(Hash) raise ArgumentError, ':sender_address is required' if options[:sender_address].nil? && @sender_address.nil? options[:sender_address] = options[:sender_address] || @sender_address Response.new self.class.get("/smsmessaging/outbound/#{options[:sender_address]}/requests/#{options[:request_id]}/deliveryInfos", :basic_auth => @auth, :headers => SMSIFIED_HTTP_HEADERS) end
[ "def", "delivery_status", "(", "options", ")", "raise", "ArgumentError", ",", "'an options Hash is required'", "if", "!", "options", ".", "instance_of?", "(", "Hash", ")", "raise", "ArgumentError", ",", "':sender_address is required'", "if", "options", "[", ":sender_address", "]", ".", "nil?", "&&", "@sender_address", ".", "nil?", "options", "[", ":sender_address", "]", "=", "options", "[", ":sender_address", "]", "||", "@sender_address", "Response", ".", "new", "self", ".", "class", ".", "get", "(", "\"/smsmessaging/outbound/#{options[:sender_address]}/requests/#{options[:request_id]}/deliveryInfos\"", ",", ":basic_auth", "=>", "@auth", ",", ":headers", "=>", "SMSIFIED_HTTP_HEADERS", ")", "end" ]
Intantiate a new class to work with reporting @param [required, Hash] params to create the Reporting object with @option params [required, String] :username username to authenticate with @option params [required, String] :password to authenticate with @option params [optional, String] :base_uri of an alternative location of SMSified @option params [optional, String] :destination_address to use with subscriptions @option params [optional, String] :sender_address to use with subscriptions @option params [optional, Boolean] :debug to turn on the HTTparty debugging to stdout @example subscription = Subscription.new :username => 'user', :password => '123' Get the delivery status of an outstanding SMS request @param [required, Hash] params to get the delivery status @option params [required, String] :request_id to fetch the status for @option params [optional, String] :sender_address used to send the SMS, required if not provided on initialization of OneAPI @return [Object] A Response Object with http and data instance methods @raise [ArgumentError] of :sender_address is not passed here when not passed on instantiating the object @example one_api.delivery_status :request_id => 'f359193765f6a3149ca76a4508e21234', :sender_address => '14155551212'
[ "Intantiate", "a", "new", "class", "to", "work", "with", "reporting" ]
1c7a0f445ffe7fe0fb035a1faf44ac55687a4488
https://github.com/smsified/smsified-ruby/blob/1c7a0f445ffe7fe0fb035a1faf44ac55687a4488/lib/smsified/reporting.rb#L41-L48
train
jeremyvdw/disqussion
lib/disqussion/client/threads.rb
Disqussion.Threads.list
def list(*args) options = args.last.is_a?(Hash) ? args.pop : {} response = get('threads/list', options) end
ruby
def list(*args) options = args.last.is_a?(Hash) ? args.pop : {} response = get('threads/list', options) end
[ "def", "list", "(", "*", "args", ")", "options", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "response", "=", "get", "(", "'threads/list'", ",", "options", ")", "end" ]
Returns a list of threads sorted by the date created. @accessibility: public key, secret key @methods: GET @format: json, jsonp, rss @authenticated: false @limited: false @return [Hashie::Rash] List of threads. @param options [Hash] A customizable set of options. @option options [Integer] :category. Defaults to null @option options [String] :forum. Defaults to null. Looks up a forum by ID (aka short name) @option options [Integer] :thread. Defaults to null. Looks up a thread by ID. You may pass use the 'ident' or 'link' query types instead of an ID by including 'forum'. @option options [Integer, String] :author. Defaults to null. You may look up a user by username using the 'username' query type. @option options [Datetime, Timestamp] :since. Unix timestamp (or ISO datetime standard). Defaults to null @option options [String, Array] :related allows multiple. Defaults to []. You may specify relations to include with your response. Choices: forum, author, category @option options [Integer] :cursor. Defaults to null @option options [Integer] :limit. Defaults to 25. Maximum length of 100 @option options [String, Array] :include allows multiple. Defaults to ["open", "close"]. Choices: open, closed, killed. @option options [String] :order. Defaults to "asc". Choices: asc, desc @example Return extended information for forum 'myforum' Disqussion::Client.threads.list(:forum => "the88") @see: http://disqus.com/api/3.0/threads/list.json
[ "Returns", "a", "list", "of", "threads", "sorted", "by", "the", "date", "created", "." ]
5ad1b0325b7630daf41eb59fc8acbcb785cbc387
https://github.com/jeremyvdw/disqussion/blob/5ad1b0325b7630daf41eb59fc8acbcb785cbc387/lib/disqussion/client/threads.rb#L94-L97
train
jeremyvdw/disqussion
lib/disqussion/client/threads.rb
Disqussion.Threads.listPosts
def listPosts(*args) options = args.last.is_a?(Hash) ? args.pop : {} thread = args.first options.merge!(:thread => thread) if ([:ident, :link] & options.keys).empty? response = get('threads/listPosts', options) end
ruby
def listPosts(*args) options = args.last.is_a?(Hash) ? args.pop : {} thread = args.first options.merge!(:thread => thread) if ([:ident, :link] & options.keys).empty? response = get('threads/listPosts', options) end
[ "def", "listPosts", "(", "*", "args", ")", "options", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "thread", "=", "args", ".", "first", "options", ".", "merge!", "(", ":thread", "=>", "thread", ")", "if", "(", "[", ":ident", ",", ":link", "]", "&", "options", ".", "keys", ")", ".", "empty?", "response", "=", "get", "(", "'threads/listPosts'", ",", "options", ")", "end" ]
Returns a list of posts within a thread. @accessibility: public key, secret key @methods: GET @format: json, jsonp, rss @authenticated: false @limited: false @return [Hashie::Rash] List of threads post. @param thread [Integer] Looks up a thread by ID. You must be a moderator on the selected thread's forum. You may pass use the 'ident' or 'link' query types instead of an ID by including 'forum'. @param options [Hash] A customizable set of options. @option options [String] :forum. Defaults to null. Looks up a forum by ID (aka short name) @option options [Datetime, Timestamp] :since. Unix timestamp (or ISO datetime standard). Defaults to null @option options [String, Array] :related allows multiple. Defaults to []. You may specify relations to include with your response. Choices: forum @option options [Integer] :cursor. Defaults to null @option options [Integer] :limit. Defaults to 25. Maximum length of 100 @option options [Integer] :query. Defaults to null. @option options [String, Array] :include allows multiple. Defaults to ["approved"]. Choices: unapproved, approved, spam, deleted, flagged @option options [String] :order. Defaults to "desc". Choices: asc, desc @example Return extended information for forum 'myforum' Disqussion::Client.threads.list() @see: http://disqus.com/api/3.0/threads/listPosts.json
[ "Returns", "a", "list", "of", "posts", "within", "a", "thread", "." ]
5ad1b0325b7630daf41eb59fc8acbcb785cbc387
https://github.com/jeremyvdw/disqussion/blob/5ad1b0325b7630daf41eb59fc8acbcb785cbc387/lib/disqussion/client/threads.rb#L185-L190
train
jeremyvdw/disqussion
lib/disqussion/client/threads.rb
Disqussion.Threads.remove
def remove(*args) options = args.last.is_a?(Hash) ? args.pop : {} thread = args.first options.merge!(:thread => thread) if ([:ident, :link] & options.keys).empty? response = post('threads/remove', options) end
ruby
def remove(*args) options = args.last.is_a?(Hash) ? args.pop : {} thread = args.first options.merge!(:thread => thread) if ([:ident, :link] & options.keys).empty? response = post('threads/remove', options) end
[ "def", "remove", "(", "*", "args", ")", "options", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "thread", "=", "args", ".", "first", "options", ".", "merge!", "(", ":thread", "=>", "thread", ")", "if", "(", "[", ":ident", ",", ":link", "]", "&", "options", ".", "keys", ")", ".", "empty?", "response", "=", "post", "(", "'threads/remove'", ",", "options", ")", "end" ]
Removes a thread @accessibility: public key, secret key @methods: POST @format: json, jsonp @authenticated: true @limited: false @param thread [Array, Integer] allows multiple. Looks up a thread by ID. You must be a moderator on the selected thread's forum. You may pass use the 'ident' or 'link' query types instead of an ID by including 'forum'. @return [Hashie::Rash] ID of the deleted thread. @option options [String] :forum. Defaults to null. Looks up a forum by ID (aka short name). You must be a moderator on the selected forum. @example Removes thread 12345678 Disqussion::Client.threads.remove(12345678) @see: http://disqus.com/api/3.0/threads/remove.json
[ "Removes", "a", "thread" ]
5ad1b0325b7630daf41eb59fc8acbcb785cbc387
https://github.com/jeremyvdw/disqussion/blob/5ad1b0325b7630daf41eb59fc8acbcb785cbc387/lib/disqussion/client/threads.rb#L223-L228
train
PlasticLizard/ruote-mongodb
lib/ruote-mongodb/mongodb_storage.rb
Ruote.MongoDbStorage.dump
def dump(type) get_many(type).map{|d|d.to_s}.sort.join("\n") end
ruby
def dump(type) get_many(type).map{|d|d.to_s}.sort.join("\n") end
[ "def", "dump", "(", "type", ")", "get_many", "(", "type", ")", ".", "map", "{", "|", "d", "|", "d", ".", "to_s", "}", ".", "sort", ".", "join", "(", "\"\\n\"", ")", "end" ]
Returns a String containing a representation of the current content of in this storage.
[ "Returns", "a", "String", "containing", "a", "representation", "of", "the", "current", "content", "of", "in", "this", "storage", "." ]
82d9701c4eea1916c7b27768b0abd43af1bb80f6
https://github.com/PlasticLizard/ruote-mongodb/blob/82d9701c4eea1916c7b27768b0abd43af1bb80f6/lib/ruote-mongodb/mongodb_storage.rb#L174-L176
train
wapcaplet/kelp
lib/kelp/field.rb
Kelp.Field.select_or_fill
def select_or_fill(field, value) case field_type(field) when :select begin select(value, :from => field) rescue Capybara::ElementNotFound raise Kelp::OptionNotFound, "Field '#{field}' has no option '#{value}'" end when :fillable_field fill_in(field, :with => value) end end
ruby
def select_or_fill(field, value) case field_type(field) when :select begin select(value, :from => field) rescue Capybara::ElementNotFound raise Kelp::OptionNotFound, "Field '#{field}' has no option '#{value}'" end when :fillable_field fill_in(field, :with => value) end end
[ "def", "select_or_fill", "(", "field", ",", "value", ")", "case", "field_type", "(", "field", ")", "when", ":select", "begin", "select", "(", "value", ",", ":from", "=>", "field", ")", "rescue", "Capybara", "::", "ElementNotFound", "raise", "Kelp", "::", "OptionNotFound", ",", "\"Field '#{field}' has no option '#{value}'\"", "end", "when", ":fillable_field", "fill_in", "(", "field", ",", ":with", "=>", "value", ")", "end", "end" ]
Select a value from a dropdown or listbox, or fill in a text field, depending on what kind of form field is available. If `field` is a dropdown or listbox, select `value` from that; otherwise, assume `field` is a text box. @param [String] field Capybara locator for the field (name, id, or label text) @param [String] value Text to select from a dropdown or enter in a text box @raise [Kelp::AmbiguousField] If more than one field matching `field` is found @raise [Kelp::FieldNotFound] If no field matching `field` is found @raise [Kelp::OptionNotFound] If a dropdown matching `field` is found, but it has no option matching `value` @since 0.1.9
[ "Select", "a", "value", "from", "a", "dropdown", "or", "listbox", "or", "fill", "in", "a", "text", "field", "depending", "on", "what", "kind", "of", "form", "field", "is", "available", ".", "If", "field", "is", "a", "dropdown", "or", "listbox", "select", "value", "from", "that", ";", "otherwise", "assume", "field", "is", "a", "text", "box", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/field.rb#L34-L46
train
wapcaplet/kelp
lib/kelp/field.rb
Kelp.Field.field_should_be_empty
def field_should_be_empty(field, scope={}) in_scope(scope) do _field = nice_find_field(field) if !(_field.nil? || _field.value.nil? || _field.value.strip == '') raise Kelp::Unexpected, "Expected field '#{field}' to be empty, but value is '#{_field.value}'" end end end
ruby
def field_should_be_empty(field, scope={}) in_scope(scope) do _field = nice_find_field(field) if !(_field.nil? || _field.value.nil? || _field.value.strip == '') raise Kelp::Unexpected, "Expected field '#{field}' to be empty, but value is '#{_field.value}'" end end end
[ "def", "field_should_be_empty", "(", "field", ",", "scope", "=", "{", "}", ")", "in_scope", "(", "scope", ")", "do", "_field", "=", "nice_find_field", "(", "field", ")", "if", "!", "(", "_field", ".", "nil?", "||", "_field", ".", "value", ".", "nil?", "||", "_field", ".", "value", ".", "strip", "==", "''", ")", "raise", "Kelp", "::", "Unexpected", ",", "\"Expected field '#{field}' to be empty, but value is '#{_field.value}'\"", "end", "end", "end" ]
Verify that the given field is empty or nil. @param [String] field Capybara locator for the field (name, id, or label text) @param [Hash] scope Scoping keywords as understood by {#in_scope} @raise [Kelp::Unexpected] If the given field is not empty or nil
[ "Verify", "that", "the", "given", "field", "is", "empty", "or", "nil", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/field.rb#L168-L176
train
wapcaplet/kelp
lib/kelp/field.rb
Kelp.Field.field_value
def field_value(field) element = find_field(field) value = (element.tag_name == 'textarea') ? element.text : element.value # If field value is an Array, take the first item if value.class == Array value = value.first end return value.to_s end
ruby
def field_value(field) element = find_field(field) value = (element.tag_name == 'textarea') ? element.text : element.value # If field value is an Array, take the first item if value.class == Array value = value.first end return value.to_s end
[ "def", "field_value", "(", "field", ")", "element", "=", "find_field", "(", "field", ")", "value", "=", "(", "element", ".", "tag_name", "==", "'textarea'", ")", "?", "element", ".", "text", ":", "element", ".", "value", "# If field value is an Array, take the first item", "if", "value", ".", "class", "==", "Array", "value", "=", "value", ".", "first", "end", "return", "value", ".", "to_s", "end" ]
Return the string value found in the given field. If the field is `nil`, return the empty string. @param [String] field Capybara locator for the field (name, id, or label text) @return [String] The value found in the given field @since 0.2.1
[ "Return", "the", "string", "value", "found", "in", "the", "given", "field", ".", "If", "the", "field", "is", "nil", "return", "the", "empty", "string", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/field.rb#L190-L198
train
wapcaplet/kelp
lib/kelp/field.rb
Kelp.Field.fields_should_contain
def fields_should_contain(field_values, scope={}) in_scope(scope) do field_values.each do |field, value| _field = find_field(field) # For nil/empty, check for nil field or nil value if value.nil? or value.strip.empty? field_should_be_empty(field) # If field is a dropdown elsif _field.tag_name == 'select' dropdown_should_equal(field, value) # Otherwise treat as a text field else field_should_contain(field, value) end end end end
ruby
def fields_should_contain(field_values, scope={}) in_scope(scope) do field_values.each do |field, value| _field = find_field(field) # For nil/empty, check for nil field or nil value if value.nil? or value.strip.empty? field_should_be_empty(field) # If field is a dropdown elsif _field.tag_name == 'select' dropdown_should_equal(field, value) # Otherwise treat as a text field else field_should_contain(field, value) end end end end
[ "def", "fields_should_contain", "(", "field_values", ",", "scope", "=", "{", "}", ")", "in_scope", "(", "scope", ")", "do", "field_values", ".", "each", "do", "|", "field", ",", "value", "|", "_field", "=", "find_field", "(", "field", ")", "# For nil/empty, check for nil field or nil value", "if", "value", ".", "nil?", "or", "value", ".", "strip", ".", "empty?", "field_should_be_empty", "(", "field", ")", "# If field is a dropdown", "elsif", "_field", ".", "tag_name", "==", "'select'", "dropdown_should_equal", "(", "field", ",", "value", ")", "# Otherwise treat as a text field", "else", "field_should_contain", "(", "field", ",", "value", ")", "end", "end", "end", "end" ]
Verify the values of multiple fields given as a Hash. @param [Hash] field_values "field" => "value" for each field you want to verify @param [Hash] scope Scoping keywords as understood by {#in_scope} @raise [Kelp::Unexpected] If any field does not contain the expected value
[ "Verify", "the", "values", "of", "multiple", "fields", "given", "as", "a", "Hash", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/field.rb#L265-L281
train
wapcaplet/kelp
lib/kelp/field.rb
Kelp.Field.field_type
def field_type(field) select = all(:select, field).count fillable = all(:fillable_field, field).count count = select + fillable case count when 0 raise Kelp::FieldNotFound, "No field with id, name, or label '#{field}' found" when 1 return select > 0 ? :select : :fillable_field else raise Kelp::AmbiguousField, "Field '#{field}' is ambiguous" end end
ruby
def field_type(field) select = all(:select, field).count fillable = all(:fillable_field, field).count count = select + fillable case count when 0 raise Kelp::FieldNotFound, "No field with id, name, or label '#{field}' found" when 1 return select > 0 ? :select : :fillable_field else raise Kelp::AmbiguousField, "Field '#{field}' is ambiguous" end end
[ "def", "field_type", "(", "field", ")", "select", "=", "all", "(", ":select", ",", "field", ")", ".", "count", "fillable", "=", "all", "(", ":fillable_field", ",", "field", ")", ".", "count", "count", "=", "select", "+", "fillable", "case", "count", "when", "0", "raise", "Kelp", "::", "FieldNotFound", ",", "\"No field with id, name, or label '#{field}' found\"", "when", "1", "return", "select", ">", "0", "?", ":select", ":", ":fillable_field", "else", "raise", "Kelp", "::", "AmbiguousField", ",", "\"Field '#{field}' is ambiguous\"", "end", "end" ]
Figure out whether the field locator matches a single select or fillable field. @param [String] field Capybara locator for the field (name, id, or label text) @raise [Kelp::AmbiguousField] If more than one field matching `field` is found @raise [Kelp::FieldNotFound] If no field matching `field` is found @return [Symbol] `:select` or `:fillable_field` depending on the type of element
[ "Figure", "out", "whether", "the", "field", "locator", "matches", "a", "single", "select", "or", "fillable", "field", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/field.rb#L318-L333
train
octoai/gem-octocore-cassandra
lib/octocore-cassandra/kafka_bridge.rb
Octo.KafkaBridge.create_message
def create_message(message) begin @producer.produce(JSON.dump(message), topic: @topic) rescue Kafka::BufferOverflow Octo.logger.error 'Buffer Overflow. Sleeping for 1s' sleep 1 retry end end
ruby
def create_message(message) begin @producer.produce(JSON.dump(message), topic: @topic) rescue Kafka::BufferOverflow Octo.logger.error 'Buffer Overflow. Sleeping for 1s' sleep 1 retry end end
[ "def", "create_message", "(", "message", ")", "begin", "@producer", ".", "produce", "(", "JSON", ".", "dump", "(", "message", ")", ",", "topic", ":", "@topic", ")", "rescue", "Kafka", "::", "BufferOverflow", "Octo", ".", "logger", ".", "error", "'Buffer Overflow. Sleeping for 1s'", "sleep", "1", "retry", "end", "end" ]
Creates a new message. @param [Hash] message The message hash to be produced
[ "Creates", "a", "new", "message", "." ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/kafka_bridge.rb#L49-L57
train
erpe/acts_as_referred
lib/acts_as_referred/instance_methods.rb
ActsAsReferred.InstanceMethods.create_referrer
def create_referrer # will not respond to _get_reqref unless # reqref injected in application-controller # if self.respond_to?(:_get_reqref) if struct = _get_reqref self.create_referee( origin: struct.referrer_url, request: struct.request_url, visits: struct.visit_count ) end end end
ruby
def create_referrer # will not respond to _get_reqref unless # reqref injected in application-controller # if self.respond_to?(:_get_reqref) if struct = _get_reqref self.create_referee( origin: struct.referrer_url, request: struct.request_url, visits: struct.visit_count ) end end end
[ "def", "create_referrer", "# will not respond to _get_reqref unless ", "# reqref injected in application-controller", "#", "if", "self", ".", "respond_to?", "(", ":_get_reqref", ")", "if", "struct", "=", "_get_reqref", "self", ".", "create_referee", "(", "origin", ":", "struct", ".", "referrer_url", ",", "request", ":", "struct", ".", "request_url", ",", "visits", ":", "struct", ".", "visit_count", ")", "end", "end", "end" ]
after create hook to create a corresponding +Referee+
[ "after", "create", "hook", "to", "create", "a", "corresponding", "+", "Referee", "+" ]
d1ffb3208e6e358c9888cec71c7bd76d30a0fdd3
https://github.com/erpe/acts_as_referred/blob/d1ffb3208e6e358c9888cec71c7bd76d30a0fdd3/lib/acts_as_referred/instance_methods.rb#L7-L22
train
justenwalker/baha
lib/baha/config.rb
Baha.Config.init_docker!
def init_docker! Docker.options = @options set_docker_url LOG.debug { "Docker URL: #{Docker.url}"} LOG.debug { "Docker Options: #{Docker.options.inspect}"} Docker.validate_version! end
ruby
def init_docker! Docker.options = @options set_docker_url LOG.debug { "Docker URL: #{Docker.url}"} LOG.debug { "Docker Options: #{Docker.options.inspect}"} Docker.validate_version! end
[ "def", "init_docker!", "Docker", ".", "options", "=", "@options", "set_docker_url", "LOG", ".", "debug", "{", "\"Docker URL: #{Docker.url}\"", "}", "LOG", ".", "debug", "{", "\"Docker Options: #{Docker.options.inspect}\"", "}", "Docker", ".", "validate_version!", "end" ]
Initialize Docker Client
[ "Initialize", "Docker", "Client" ]
df1b57e222f4f4ebe474794d7f191f912be6d9fc
https://github.com/justenwalker/baha/blob/df1b57e222f4f4ebe474794d7f191f912be6d9fc/lib/baha/config.rb#L112-L118
train
redding/logsly
lib/logsly/logging182/appenders/buffering.rb
Logsly::Logging182::Appenders.Buffering.immediate_at=
def immediate_at=( level ) @immediate.clear # get the immediate levels -- no buffering occurs at these levels, and # a log message is written to the logging destination immediately immediate_at = case level when String; level.split(',').map {|x| x.strip} when Array; level else Array(level) end immediate_at.each do |lvl| num = ::Logsly::Logging182.level_num(lvl) next if num.nil? @immediate[num] = true end end
ruby
def immediate_at=( level ) @immediate.clear # get the immediate levels -- no buffering occurs at these levels, and # a log message is written to the logging destination immediately immediate_at = case level when String; level.split(',').map {|x| x.strip} when Array; level else Array(level) end immediate_at.each do |lvl| num = ::Logsly::Logging182.level_num(lvl) next if num.nil? @immediate[num] = true end end
[ "def", "immediate_at", "=", "(", "level", ")", "@immediate", ".", "clear", "# get the immediate levels -- no buffering occurs at these levels, and", "# a log message is written to the logging destination immediately", "immediate_at", "=", "case", "level", "when", "String", ";", "level", ".", "split", "(", "','", ")", ".", "map", "{", "|", "x", "|", "x", ".", "strip", "}", "when", "Array", ";", "level", "else", "Array", "(", "level", ")", "end", "immediate_at", ".", "each", "do", "|", "lvl", "|", "num", "=", "::", "Logsly", "::", "Logging182", ".", "level_num", "(", "lvl", ")", "next", "if", "num", ".", "nil?", "@immediate", "[", "num", "]", "=", "true", "end", "end" ]
Configure the levels that will trigger an immediate flush of the logging buffer. When a log event of the given level is seen, the buffer will be flushed immediately. Only the levels explicitly given in this assignment will flush the buffer; if an "error" message is configured to immediately flush the buffer, a "fatal" message will not even though it is a higher level. Both must be explicitly passed to this assignment. You can pass in a single level name or number, an array of level names or numbers, or a string containing a comma separated list of level names or numbers. immediate_at = :error immediate_at = [:error, :fatal] immediate_at = "warn, error"
[ "Configure", "the", "levels", "that", "will", "trigger", "an", "immediate", "flush", "of", "the", "logging", "buffer", ".", "When", "a", "log", "event", "of", "the", "given", "level", "is", "seen", "the", "buffer", "will", "be", "flushed", "immediately", ".", "Only", "the", "levels", "explicitly", "given", "in", "this", "assignment", "will", "flush", "the", "buffer", ";", "if", "an", "error", "message", "is", "configured", "to", "immediately", "flush", "the", "buffer", "a", "fatal", "message", "will", "not", "even", "though", "it", "is", "a", "higher", "level", ".", "Both", "must", "be", "explicitly", "passed", "to", "this", "assignment", "." ]
a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf
https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/appenders/buffering.rb#L102-L118
train
michaelmior/mipper
lib/mipper/expression.rb
MIPPeR.LinExpr.add
def add(other) case other when LinExpr @terms.merge!(other.terms) { |_, c1, c2| c1 + c2 } when Variable if @terms.key? other @terms[other] += 1.0 else @terms[other] = 1.0 end else fail TypeError end self end
ruby
def add(other) case other when LinExpr @terms.merge!(other.terms) { |_, c1, c2| c1 + c2 } when Variable if @terms.key? other @terms[other] += 1.0 else @terms[other] = 1.0 end else fail TypeError end self end
[ "def", "add", "(", "other", ")", "case", "other", "when", "LinExpr", "@terms", ".", "merge!", "(", "other", ".", "terms", ")", "{", "|", "_", ",", "c1", ",", "c2", "|", "c1", "+", "c2", "}", "when", "Variable", "if", "@terms", ".", "key?", "other", "@terms", "[", "other", "]", "+=", "1.0", "else", "@terms", "[", "other", "]", "=", "1.0", "end", "else", "fail", "TypeError", "end", "self", "end" ]
Add terms from the other expression to this one
[ "Add", "terms", "from", "the", "other", "expression", "to", "this", "one" ]
4ab7f8b32c27f33fc5121756554a0a28d2077e06
https://github.com/michaelmior/mipper/blob/4ab7f8b32c27f33fc5121756554a0a28d2077e06/lib/mipper/expression.rb#L25-L40
train
michaelmior/mipper
lib/mipper/expression.rb
MIPPeR.LinExpr.inspect
def inspect @terms.map do |var, coeff| # Skip if the coefficient is zero or the value is zero value = var.value next if coeff == 0 || value == 0 || value == false coeff == 1 ? var.name : "#{var.name} * #{coeff}" end.compact.join(' + ') end
ruby
def inspect @terms.map do |var, coeff| # Skip if the coefficient is zero or the value is zero value = var.value next if coeff == 0 || value == 0 || value == false coeff == 1 ? var.name : "#{var.name} * #{coeff}" end.compact.join(' + ') end
[ "def", "inspect", "@terms", ".", "map", "do", "|", "var", ",", "coeff", "|", "# Skip if the coefficient is zero or the value is zero", "value", "=", "var", ".", "value", "next", "if", "coeff", "==", "0", "||", "value", "==", "0", "||", "value", "==", "false", "coeff", "==", "1", "?", "var", ".", "name", ":", "\"#{var.name} * #{coeff}\"", "end", ".", "compact", ".", "join", "(", "' + '", ")", "end" ]
Produce a string representing the expression
[ "Produce", "a", "string", "representing", "the", "expression" ]
4ab7f8b32c27f33fc5121756554a0a28d2077e06
https://github.com/michaelmior/mipper/blob/4ab7f8b32c27f33fc5121756554a0a28d2077e06/lib/mipper/expression.rb#L43-L51
train
redding/ns-options
lib/ns-options/option.rb
NsOptions.Option.value
def value val = self.lazy_proc?(@value) ? self.coerce(@value.call) : @value val.respond_to?(:returned_value) ? val.returned_value : val end
ruby
def value val = self.lazy_proc?(@value) ? self.coerce(@value.call) : @value val.respond_to?(:returned_value) ? val.returned_value : val end
[ "def", "value", "val", "=", "self", ".", "lazy_proc?", "(", "@value", ")", "?", "self", ".", "coerce", "(", "@value", ".", "call", ")", ":", "@value", "val", ".", "respond_to?", "(", ":returned_value", ")", "?", "val", ".", "returned_value", ":", "val", "end" ]
if reading a lazy_proc, call the proc and return its coerced return val otherwise, just return the stored value
[ "if", "reading", "a", "lazy_proc", "call", "the", "proc", "and", "return", "its", "coerced", "return", "val", "otherwise", "just", "return", "the", "stored", "value" ]
63618a18e7a1d270dffc5a3cfea70ef45569e061
https://github.com/redding/ns-options/blob/63618a18e7a1d270dffc5a3cfea70ef45569e061/lib/ns-options/option.rb#L40-L43
train
geoffgarside/demolisher
lib/demolisher.rb
Demolisher.Node.method_missing
def method_missing(meth, *args, &block) # :nodoc: xpath = _xpath_for_element(meth.to_s, args.shift) return nil if xpath.empty? if block_given? xpath.each_with_index do |node, idx| @nodes.push(node) case block.arity when 1 yield idx when 2 yield self.class.new(node, @namespaces, false), idx else yield end @nodes.pop end self else node = xpath.first if node.xpath('text()').length == 1 content = node.xpath('text()').first.content case meth.to_s when /\?$/ !! Regexp.new(/(t(rue)?|y(es)?|1)/i).match(content) else content end else self.class.new(node, @namespaces, false) end end end
ruby
def method_missing(meth, *args, &block) # :nodoc: xpath = _xpath_for_element(meth.to_s, args.shift) return nil if xpath.empty? if block_given? xpath.each_with_index do |node, idx| @nodes.push(node) case block.arity when 1 yield idx when 2 yield self.class.new(node, @namespaces, false), idx else yield end @nodes.pop end self else node = xpath.first if node.xpath('text()').length == 1 content = node.xpath('text()').first.content case meth.to_s when /\?$/ !! Regexp.new(/(t(rue)?|y(es)?|1)/i).match(content) else content end else self.class.new(node, @namespaces, false) end end end
[ "def", "method_missing", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "# :nodoc:", "xpath", "=", "_xpath_for_element", "(", "meth", ".", "to_s", ",", "args", ".", "shift", ")", "return", "nil", "if", "xpath", ".", "empty?", "if", "block_given?", "xpath", ".", "each_with_index", "do", "|", "node", ",", "idx", "|", "@nodes", ".", "push", "(", "node", ")", "case", "block", ".", "arity", "when", "1", "yield", "idx", "when", "2", "yield", "self", ".", "class", ".", "new", "(", "node", ",", "@namespaces", ",", "false", ")", ",", "idx", "else", "yield", "end", "@nodes", ".", "pop", "end", "self", "else", "node", "=", "xpath", ".", "first", "if", "node", ".", "xpath", "(", "'text()'", ")", ".", "length", "==", "1", "content", "=", "node", ".", "xpath", "(", "'text()'", ")", ".", "first", ".", "content", "case", "meth", ".", "to_s", "when", "/", "\\?", "/", "!", "!", "Regexp", ".", "new", "(", "/", "/i", ")", ".", "match", "(", "content", ")", "else", "content", "end", "else", "self", ".", "class", ".", "new", "(", "node", ",", "@namespaces", ",", "false", ")", "end", "end", "end" ]
The workhorse, finds the node matching meth. Rough flow guide: If a block is given then yield to it each for each instance of the element found in the current node. If no block given then get the first element found If the node has only one text element check if the method called has a ? suffix then return true if node content looks like a boolean. Otherwise return text content Otherwise return a new Node instance
[ "The", "workhorse", "finds", "the", "node", "matching", "meth", "." ]
36e12417a35aa4e04c8bf76f7be305bb0cb0516d
https://github.com/geoffgarside/demolisher/blob/36e12417a35aa4e04c8bf76f7be305bb0cb0516d/lib/demolisher.rb#L72-L105
train
dmolesUC3/xml-mapping_extensions
lib/xml/mapping_extensions.rb
XML.Mapping.write_xml
def write_xml(options = { mapping: :_default }) xml = save_to_xml(options) formatter = REXML::Formatters::Pretty.new formatter.compact = true io = ::StringIO.new formatter.write(xml, io) io.string end
ruby
def write_xml(options = { mapping: :_default }) xml = save_to_xml(options) formatter = REXML::Formatters::Pretty.new formatter.compact = true io = ::StringIO.new formatter.write(xml, io) io.string end
[ "def", "write_xml", "(", "options", "=", "{", "mapping", ":", ":_default", "}", ")", "xml", "=", "save_to_xml", "(", "options", ")", "formatter", "=", "REXML", "::", "Formatters", "::", "Pretty", ".", "new", "formatter", ".", "compact", "=", "true", "io", "=", "::", "StringIO", ".", "new", "formatter", ".", "write", "(", "xml", ",", "io", ")", "io", ".", "string", "end" ]
Writes this mapped object as a pretty-printed XML string. @param options [Hash] the options to be passed to [XML::Mapping#save_to_xml](http://multi-io.github.io/xml-mapping/XML/Mapping.html#method-i-save_to_xml) @return [String] the XML form of the object, as a compact, pretty-printed string.
[ "Writes", "this", "mapped", "object", "as", "a", "pretty", "-", "printed", "XML", "string", "." ]
012a01aaebc920229f6af9df881717fe91b24c8e
https://github.com/dmolesUC3/xml-mapping_extensions/blob/012a01aaebc920229f6af9df881717fe91b24c8e/lib/xml/mapping_extensions.rb#L43-L50
train
stevenhaddox/cert_munger
lib/cert_munger/formatter.rb
CertMunger.ClassMethods.to_cert
def to_cert(raw_cert) logger.debug "CertMunger raw_cert:\n#{raw_cert}" new_cert = build_cert(raw_cert) logger.debug "CertMunger reformatted_cert:\n#{new_cert}" logger.debug 'Returning OpenSSL::X509::Certificate.new on new_cert' OpenSSL::X509::Certificate.new new_cert end
ruby
def to_cert(raw_cert) logger.debug "CertMunger raw_cert:\n#{raw_cert}" new_cert = build_cert(raw_cert) logger.debug "CertMunger reformatted_cert:\n#{new_cert}" logger.debug 'Returning OpenSSL::X509::Certificate.new on new_cert' OpenSSL::X509::Certificate.new new_cert end
[ "def", "to_cert", "(", "raw_cert", ")", "logger", ".", "debug", "\"CertMunger raw_cert:\\n#{raw_cert}\"", "new_cert", "=", "build_cert", "(", "raw_cert", ")", "logger", ".", "debug", "\"CertMunger reformatted_cert:\\n#{new_cert}\"", "logger", ".", "debug", "'Returning OpenSSL::X509::Certificate.new on new_cert'", "OpenSSL", "::", "X509", "::", "Certificate", ".", "new", "new_cert", "end" ]
Attempts to munge a string into a valid X509 certificate @param raw_cert [String] The string of text you wish to parse into a cert @return [OpenSSL::X509::Certificate]
[ "Attempts", "to", "munge", "a", "string", "into", "a", "valid", "X509", "certificate" ]
48a42f93f964bb47f4311d9e3f7a3ab03c7a5bee
https://github.com/stevenhaddox/cert_munger/blob/48a42f93f964bb47f4311d9e3f7a3ab03c7a5bee/lib/cert_munger/formatter.rb#L36-L43
train
stevenhaddox/cert_munger
lib/cert_munger/formatter.rb
CertMunger.ClassMethods.build_cert
def build_cert(raw_cert) tmp_cert = ['-----BEGIN CERTIFICATE-----'] cert_contents = if raw_cert.lines.count == 1 one_line_contents(raw_cert) else multi_line_contents(raw_cert) end tmp_cert << cert_contents.flatten # put mixed space lines as own elements tmp_cert << '-----END CERTIFICATE-----' tmp_cert.join("\n").rstrip end
ruby
def build_cert(raw_cert) tmp_cert = ['-----BEGIN CERTIFICATE-----'] cert_contents = if raw_cert.lines.count == 1 one_line_contents(raw_cert) else multi_line_contents(raw_cert) end tmp_cert << cert_contents.flatten # put mixed space lines as own elements tmp_cert << '-----END CERTIFICATE-----' tmp_cert.join("\n").rstrip end
[ "def", "build_cert", "(", "raw_cert", ")", "tmp_cert", "=", "[", "'-----BEGIN CERTIFICATE-----'", "]", "cert_contents", "=", "if", "raw_cert", ".", "lines", ".", "count", "==", "1", "one_line_contents", "(", "raw_cert", ")", "else", "multi_line_contents", "(", "raw_cert", ")", "end", "tmp_cert", "<<", "cert_contents", ".", "flatten", "# put mixed space lines as own elements", "tmp_cert", "<<", "'-----END CERTIFICATE-----'", "tmp_cert", ".", "join", "(", "\"\\n\"", ")", ".", "rstrip", "end" ]
Creates a temporary cert and orchestrates certificate body reformatting @param raw_cert [String] The string of text you wish to parse into a cert @return [String] reformatted and (hopefully) parseable certificate string
[ "Creates", "a", "temporary", "cert", "and", "orchestrates", "certificate", "body", "reformatting" ]
48a42f93f964bb47f4311d9e3f7a3ab03c7a5bee
https://github.com/stevenhaddox/cert_munger/blob/48a42f93f964bb47f4311d9e3f7a3ab03c7a5bee/lib/cert_munger/formatter.rb#L49-L59
train