id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
3,000
bdurand/acts_as_revisionable
lib/acts_as_revisionable.rb
ActsAsRevisionable.ClassMethods.restore_revision
def restore_revision(id, revision_number) revision_record = revision(id, revision_number) return revision_record.restore if revision_record end
ruby
def restore_revision(id, revision_number) revision_record = revision(id, revision_number) return revision_record.restore if revision_record end
[ "def", "restore_revision", "(", "id", ",", "revision_number", ")", "revision_record", "=", "revision", "(", "id", ",", "revision_number", ")", "return", "revision_record", ".", "restore", "if", "revision_record", "end" ]
Load a revision for a record with a particular id. Associations added since the revision was created will still be in the restored record. If you want to save a revision with associations properly, use restore_revision!
[ "Load", "a", "revision", "for", "a", "record", "with", "a", "particular", "id", ".", "Associations", "added", "since", "the", "revision", "was", "created", "will", "still", "be", "in", "the", "restored", "record", ".", "If", "you", "want", "to", "save", "a", "revision", "with", "associations", "properly", "use", "restore_revision!" ]
cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc
https://github.com/bdurand/acts_as_revisionable/blob/cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc/lib/acts_as_revisionable.rb#L84-L87
3,001
bdurand/acts_as_revisionable
lib/acts_as_revisionable.rb
ActsAsRevisionable.ClassMethods.restore_revision!
def restore_revision!(id, revision_number) record = restore_revision(id, revision_number) if record record.store_revision do save_restorable_associations(record, revisionable_associations) end end return record end
ruby
def restore_revision!(id, revision_number) record = restore_revision(id, revision_number) if record record.store_revision do save_restorable_associations(record, revisionable_associations) end end return record end
[ "def", "restore_revision!", "(", "id", ",", "revision_number", ")", "record", "=", "restore_revision", "(", "id", ",", "revision_number", ")", "if", "record", "record", ".", "store_revision", "do", "save_restorable_associations", "(", "record", ",", "revisionable_associations", ")", "end", "end", "return", "record", "end" ]
Load a revision for a record with a particular id and save it to the database. You should always use this method to save a revision if it has associations.
[ "Load", "a", "revision", "for", "a", "record", "with", "a", "particular", "id", "and", "save", "it", "to", "the", "database", ".", "You", "should", "always", "use", "this", "method", "to", "save", "a", "revision", "if", "it", "has", "associations", "." ]
cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc
https://github.com/bdurand/acts_as_revisionable/blob/cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc/lib/acts_as_revisionable.rb#L91-L99
3,002
bdurand/acts_as_revisionable
lib/acts_as_revisionable.rb
ActsAsRevisionable.ClassMethods.restore_last_revision!
def restore_last_revision!(id) record = restore_last_revision(id) if record record.store_revision do save_restorable_associations(record, revisionable_associations) end end return record end
ruby
def restore_last_revision!(id) record = restore_last_revision(id) if record record.store_revision do save_restorable_associations(record, revisionable_associations) end end return record end
[ "def", "restore_last_revision!", "(", "id", ")", "record", "=", "restore_last_revision", "(", "id", ")", "if", "record", "record", ".", "store_revision", "do", "save_restorable_associations", "(", "record", ",", "revisionable_associations", ")", "end", "end", "return", "record", "end" ]
Load the last revision for a record with the specified id and save it to the database. You should always use this method to save a revision if it has associations.
[ "Load", "the", "last", "revision", "for", "a", "record", "with", "the", "specified", "id", "and", "save", "it", "to", "the", "database", ".", "You", "should", "always", "use", "this", "method", "to", "save", "a", "revision", "if", "it", "has", "associations", "." ]
cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc
https://github.com/bdurand/acts_as_revisionable/blob/cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc/lib/acts_as_revisionable.rb#L111-L119
3,003
bdurand/acts_as_revisionable
lib/acts_as_revisionable.rb
ActsAsRevisionable.ClassMethods.revisionable_associations
def revisionable_associations(options = acts_as_revisionable_options[:associations]) return nil unless options options = [options] unless options.kind_of?(Array) associations = {} options.each do |association| if association.kind_of?(Symbol) associations[association] = true elsif association.kind_of?(Hash) association.each_pair do |key, value| associations[key] = revisionable_associations(value) end end end return associations end
ruby
def revisionable_associations(options = acts_as_revisionable_options[:associations]) return nil unless options options = [options] unless options.kind_of?(Array) associations = {} options.each do |association| if association.kind_of?(Symbol) associations[association] = true elsif association.kind_of?(Hash) association.each_pair do |key, value| associations[key] = revisionable_associations(value) end end end return associations end
[ "def", "revisionable_associations", "(", "options", "=", "acts_as_revisionable_options", "[", ":associations", "]", ")", "return", "nil", "unless", "options", "options", "=", "[", "options", "]", "unless", "options", ".", "kind_of?", "(", "Array", ")", "associations", "=", "{", "}", "options", ".", "each", "do", "|", "association", "|", "if", "association", ".", "kind_of?", "(", "Symbol", ")", "associations", "[", "association", "]", "=", "true", "elsif", "association", ".", "kind_of?", "(", "Hash", ")", "association", ".", "each_pair", "do", "|", "key", ",", "value", "|", "associations", "[", "key", "]", "=", "revisionable_associations", "(", "value", ")", "end", "end", "end", "return", "associations", "end" ]
Returns a hash structure used to identify the revisioned associations.
[ "Returns", "a", "hash", "structure", "used", "to", "identify", "the", "revisioned", "associations", "." ]
cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc
https://github.com/bdurand/acts_as_revisionable/blob/cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc/lib/acts_as_revisionable.rb#L122-L136
3,004
bdurand/acts_as_revisionable
lib/acts_as_revisionable.rb
ActsAsRevisionable.InstanceMethods.store_revision
def store_revision if new_record? || @revisions_disabled return yield else retval = nil revision = nil begin revision_record_class.transaction do begin read_only = self.class.first(:conditions => {self.class.primary_key => self.id}, :readonly => true) if read_only revision = read_only.create_revision! truncate_revisions! end rescue => e logger.warn(e) if logger end disable_revisioning do retval = yield end raise ActiveRecord::Rollback unless errors.empty? revision.trash! if destroyed? end rescue => e # In case the database doesn't support transactions if revision begin revision.destroy rescue => e logger.warn(e) if logger end end raise e end return retval end end
ruby
def store_revision if new_record? || @revisions_disabled return yield else retval = nil revision = nil begin revision_record_class.transaction do begin read_only = self.class.first(:conditions => {self.class.primary_key => self.id}, :readonly => true) if read_only revision = read_only.create_revision! truncate_revisions! end rescue => e logger.warn(e) if logger end disable_revisioning do retval = yield end raise ActiveRecord::Rollback unless errors.empty? revision.trash! if destroyed? end rescue => e # In case the database doesn't support transactions if revision begin revision.destroy rescue => e logger.warn(e) if logger end end raise e end return retval end end
[ "def", "store_revision", "if", "new_record?", "||", "@revisions_disabled", "return", "yield", "else", "retval", "=", "nil", "revision", "=", "nil", "begin", "revision_record_class", ".", "transaction", "do", "begin", "read_only", "=", "self", ".", "class", ".", "first", "(", ":conditions", "=>", "{", "self", ".", "class", ".", "primary_key", "=>", "self", ".", "id", "}", ",", ":readonly", "=>", "true", ")", "if", "read_only", "revision", "=", "read_only", ".", "create_revision!", "truncate_revisions!", "end", "rescue", "=>", "e", "logger", ".", "warn", "(", "e", ")", "if", "logger", "end", "disable_revisioning", "do", "retval", "=", "yield", "end", "raise", "ActiveRecord", "::", "Rollback", "unless", "errors", ".", "empty?", "revision", ".", "trash!", "if", "destroyed?", "end", "rescue", "=>", "e", "# In case the database doesn't support transactions", "if", "revision", "begin", "revision", ".", "destroy", "rescue", "=>", "e", "logger", ".", "warn", "(", "e", ")", "if", "logger", "end", "end", "raise", "e", "end", "return", "retval", "end", "end" ]
Call this method to implement revisioning. The object changes should happen inside the block.
[ "Call", "this", "method", "to", "implement", "revisioning", ".", "The", "object", "changes", "should", "happen", "inside", "the", "block", "." ]
cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc
https://github.com/bdurand/acts_as_revisionable/blob/cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc/lib/acts_as_revisionable.rb#L205-L244
3,005
bdurand/acts_as_revisionable
lib/acts_as_revisionable.rb
ActsAsRevisionable.InstanceMethods.create_revision!
def create_revision! revision_options = self.class.acts_as_revisionable_options revision = revision_record_class.new(self, revision_options[:encoding]) if revision_options[:meta].is_a?(Hash) revision_options[:meta].each do |attribute, value| set_revision_meta_attribute(revision, attribute, value) end elsif revision_options[:meta].is_a?(Array) revision_options[:meta].each do |attribute| set_revision_meta_attribute(revision, attribute, attribute.to_sym) end elsif revision_options[:meta] set_revision_meta_attribute(revision, revision_options[:meta], revision_options[:meta].to_sym) end revision.save! return revision end
ruby
def create_revision! revision_options = self.class.acts_as_revisionable_options revision = revision_record_class.new(self, revision_options[:encoding]) if revision_options[:meta].is_a?(Hash) revision_options[:meta].each do |attribute, value| set_revision_meta_attribute(revision, attribute, value) end elsif revision_options[:meta].is_a?(Array) revision_options[:meta].each do |attribute| set_revision_meta_attribute(revision, attribute, attribute.to_sym) end elsif revision_options[:meta] set_revision_meta_attribute(revision, revision_options[:meta], revision_options[:meta].to_sym) end revision.save! return revision end
[ "def", "create_revision!", "revision_options", "=", "self", ".", "class", ".", "acts_as_revisionable_options", "revision", "=", "revision_record_class", ".", "new", "(", "self", ",", "revision_options", "[", ":encoding", "]", ")", "if", "revision_options", "[", ":meta", "]", ".", "is_a?", "(", "Hash", ")", "revision_options", "[", ":meta", "]", ".", "each", "do", "|", "attribute", ",", "value", "|", "set_revision_meta_attribute", "(", "revision", ",", "attribute", ",", "value", ")", "end", "elsif", "revision_options", "[", ":meta", "]", ".", "is_a?", "(", "Array", ")", "revision_options", "[", ":meta", "]", ".", "each", "do", "|", "attribute", "|", "set_revision_meta_attribute", "(", "revision", ",", "attribute", ",", "attribute", ".", "to_sym", ")", "end", "elsif", "revision_options", "[", ":meta", "]", "set_revision_meta_attribute", "(", "revision", ",", "revision_options", "[", ":meta", "]", ",", "revision_options", "[", ":meta", "]", ".", "to_sym", ")", "end", "revision", ".", "save!", "return", "revision", "end" ]
Create a revision record based on this record and save it to the database.
[ "Create", "a", "revision", "record", "based", "on", "this", "record", "and", "save", "it", "to", "the", "database", "." ]
cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc
https://github.com/bdurand/acts_as_revisionable/blob/cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc/lib/acts_as_revisionable.rb#L247-L263
3,006
bdurand/acts_as_revisionable
lib/acts_as_revisionable.rb
ActsAsRevisionable.InstanceMethods.set_revision_meta_attribute
def set_revision_meta_attribute(revision, attribute, value) case value when Symbol value = self.send(value) when Proc value = value.call(self) end revision.send("#{attribute}=", value) end
ruby
def set_revision_meta_attribute(revision, attribute, value) case value when Symbol value = self.send(value) when Proc value = value.call(self) end revision.send("#{attribute}=", value) end
[ "def", "set_revision_meta_attribute", "(", "revision", ",", "attribute", ",", "value", ")", "case", "value", "when", "Symbol", "value", "=", "self", ".", "send", "(", "value", ")", "when", "Proc", "value", "=", "value", ".", "call", "(", "self", ")", "end", "revision", ".", "send", "(", "\"#{attribute}=\"", ",", "value", ")", "end" ]
Set an attribute based on a meta argument
[ "Set", "an", "attribute", "based", "on", "a", "meta", "argument" ]
cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc
https://github.com/bdurand/acts_as_revisionable/blob/cabc9b9e35b58463d2a942f6cd2b4ab3d4fe64fc/lib/acts_as_revisionable.rb#L305-L313
3,007
ShipCompliant/ship_compliant-ruby
lib/ship_compliant/base_result.rb
ShipCompliant.BaseResult.errors
def errors return [] if success? @errors ||= Array.wrap(response[:errors]).map do |error| ErrorResult.new(error[:error]) end end
ruby
def errors return [] if success? @errors ||= Array.wrap(response[:errors]).map do |error| ErrorResult.new(error[:error]) end end
[ "def", "errors", "return", "[", "]", "if", "success?", "@errors", "||=", "Array", ".", "wrap", "(", "response", "[", ":errors", "]", ")", ".", "map", "do", "|", "error", "|", "ErrorResult", ".", "new", "(", "error", "[", ":error", "]", ")", "end", "end" ]
An array of +ErrorResult+ items or an empty array if the response was successful. result.errors.each do |error| puts "#{error.message} [#error.key]" end
[ "An", "array", "of", "+", "ErrorResult", "+", "items", "or", "an", "empty", "array", "if", "the", "response", "was", "successful", "." ]
aa12852a58cd6cb7939eb9fbb7fdc03e46e18197
https://github.com/ShipCompliant/ship_compliant-ruby/blob/aa12852a58cd6cb7939eb9fbb7fdc03e46e18197/lib/ship_compliant/base_result.rb#L29-L34
3,008
brasten/scruffy
lib/scruffy/graph.rb
Scruffy.Graph.render
def render(options = {}) options[:theme] ||= theme options[:value_formatter] ||= value_formatter options[:key_formatter] ||= key_formatter options[:point_markers] ||= point_markers options[:point_markers_rotation] ||= point_markers_rotation options[:point_markers_ticks] ||= point_markers_ticks options[:size] ||= (options[:width] ? [options[:width], (options.delete(:width) * 0.6).to_i] : [600, 360]) options[:title] ||= title options[:x_legend] ||= x_legend options[:y_legend] ||= y_legend options[:layers] ||= layers options[:min_value] ||= bottom_value(options[:padding] ? options[:padding] : nil) options[:max_value] ||= top_value(options[:padding] ? options[:padding] : nil) options[:min_key] ||= bottom_key options[:max_key] ||= top_key options[:graph] ||= self # Removed for now. # Added for making smaller fonts more legible, but may not be needed after all. # # if options[:as] && (options[:size][0] <= 300 || options[:size][1] <= 200) # options[:actual_size] = options[:size] # options[:size] = [800, (800.to_f * (options[:actual_size][1].to_f / options[:actual_size][0].to_f))] # end svg = ( options[:renderer].nil? ? self.renderer.render( options ) : options[:renderer].render( options ) ) # SVG to file. if options[:to] && options[:as].nil? File.open(options[:to], 'w') { |file| file.write(svg) } end options[:as] ? rasterizer.rasterize(svg, options) : svg end
ruby
def render(options = {}) options[:theme] ||= theme options[:value_formatter] ||= value_formatter options[:key_formatter] ||= key_formatter options[:point_markers] ||= point_markers options[:point_markers_rotation] ||= point_markers_rotation options[:point_markers_ticks] ||= point_markers_ticks options[:size] ||= (options[:width] ? [options[:width], (options.delete(:width) * 0.6).to_i] : [600, 360]) options[:title] ||= title options[:x_legend] ||= x_legend options[:y_legend] ||= y_legend options[:layers] ||= layers options[:min_value] ||= bottom_value(options[:padding] ? options[:padding] : nil) options[:max_value] ||= top_value(options[:padding] ? options[:padding] : nil) options[:min_key] ||= bottom_key options[:max_key] ||= top_key options[:graph] ||= self # Removed for now. # Added for making smaller fonts more legible, but may not be needed after all. # # if options[:as] && (options[:size][0] <= 300 || options[:size][1] <= 200) # options[:actual_size] = options[:size] # options[:size] = [800, (800.to_f * (options[:actual_size][1].to_f / options[:actual_size][0].to_f))] # end svg = ( options[:renderer].nil? ? self.renderer.render( options ) : options[:renderer].render( options ) ) # SVG to file. if options[:to] && options[:as].nil? File.open(options[:to], 'w') { |file| file.write(svg) } end options[:as] ? rasterizer.rasterize(svg, options) : svg end
[ "def", "render", "(", "options", "=", "{", "}", ")", "options", "[", ":theme", "]", "||=", "theme", "options", "[", ":value_formatter", "]", "||=", "value_formatter", "options", "[", ":key_formatter", "]", "||=", "key_formatter", "options", "[", ":point_markers", "]", "||=", "point_markers", "options", "[", ":point_markers_rotation", "]", "||=", "point_markers_rotation", "options", "[", ":point_markers_ticks", "]", "||=", "point_markers_ticks", "options", "[", ":size", "]", "||=", "(", "options", "[", ":width", "]", "?", "[", "options", "[", ":width", "]", ",", "(", "options", ".", "delete", "(", ":width", ")", "*", "0.6", ")", ".", "to_i", "]", ":", "[", "600", ",", "360", "]", ")", "options", "[", ":title", "]", "||=", "title", "options", "[", ":x_legend", "]", "||=", "x_legend", "options", "[", ":y_legend", "]", "||=", "y_legend", "options", "[", ":layers", "]", "||=", "layers", "options", "[", ":min_value", "]", "||=", "bottom_value", "(", "options", "[", ":padding", "]", "?", "options", "[", ":padding", "]", ":", "nil", ")", "options", "[", ":max_value", "]", "||=", "top_value", "(", "options", "[", ":padding", "]", "?", "options", "[", ":padding", "]", ":", "nil", ")", "options", "[", ":min_key", "]", "||=", "bottom_key", "options", "[", ":max_key", "]", "||=", "top_key", "options", "[", ":graph", "]", "||=", "self", "# Removed for now.", "# Added for making smaller fonts more legible, but may not be needed after all.", "#", "# if options[:as] && (options[:size][0] <= 300 || options[:size][1] <= 200)", "# options[:actual_size] = options[:size]", "# options[:size] = [800, (800.to_f * (options[:actual_size][1].to_f / options[:actual_size][0].to_f))]", "# end", "svg", "=", "(", "options", "[", ":renderer", "]", ".", "nil?", "?", "self", ".", "renderer", ".", "render", "(", "options", ")", ":", "options", "[", ":renderer", "]", ".", "render", "(", "options", ")", ")", "# SVG to file.", "if", "options", "[", ":to", "]", "&&", "options", "[", ":as", "]", ".", "nil?", "File", ".", "open", "(", "options", "[", ":to", "]", ",", "'w'", ")", "{", "|", "file", "|", "file", ".", "write", "(", "svg", ")", "}", "end", "options", "[", ":as", "]", "?", "rasterizer", ".", "rasterize", "(", "svg", ",", "options", ")", ":", "svg", "end" ]
Writer defined below Returns a new Graph. You can optionally pass in a default graph type and an options hash. Graph.new # New graph Graph.new(:line) # New graph with default graph type of Line Graph.new({...}) # New graph with options. Options: title:: Graph's title x_legend :: Title for X Axis y_legend :: Title for Y Axis theme:: A theme object to use when rendering graph layers:: An array of Layers for this graph to use default_type:: A symbol indicating the default type of Layer for this graph value_formatter:: Sets a formatter used to modify marker values prior to rendering point_markers:: Sets the x-axis marker values point_markers_rotation:: Sets the angle of rotation for x-axis marker values point_markers_ticks:: Sets a small tick mark above each marker value. Helful when used with rotation. rasterizer:: Sets the rasterizer to use when rendering to an image format. Defaults to RMagick. Renders the graph in it's current state to an SVG object. Options: size:: An array indicating the size you wish to render the graph. ( [x, y] ) width:: The width of the rendered graph. A height is calculated at 3/4th of the width. theme:: Theme used to render graph for this render only. min_value:: Overrides the calculated minimum value used for the graph. max_value:: Overrides the calculated maximum value used for the graph. renderer:: Provide a Renderer object to use instead of the default. For other image formats: as:: File format to render to ('PNG', 'JPG', etc) to:: Name of file to save graph to, if desired. If not provided, image is returned as blob/string.
[ "Writer", "defined", "below", "Returns", "a", "new", "Graph", ".", "You", "can", "optionally", "pass", "in", "a", "default", "graph", "type", "and", "an", "options", "hash", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/graph.rb#L145-L181
3,009
brasten/scruffy
lib/scruffy/layers/stacked.rb
Scruffy::Layers.Stacked.render
def render(svg, options = {}) #TODO ensure this works with new points current_points = points layers.each do |layer| real_points = layer.points layer.points = current_points layer_options = options.dup layer_options[:color] = layer.preferred_color || layer.color || options[:theme].next_color layer.render(svg, layer_options) options.merge(layer_options) layer.points = real_points layer.points.each_with_index { |val, idx| current_points[idx] -= val } end end
ruby
def render(svg, options = {}) #TODO ensure this works with new points current_points = points layers.each do |layer| real_points = layer.points layer.points = current_points layer_options = options.dup layer_options[:color] = layer.preferred_color || layer.color || options[:theme].next_color layer.render(svg, layer_options) options.merge(layer_options) layer.points = real_points layer.points.each_with_index { |val, idx| current_points[idx] -= val } end end
[ "def", "render", "(", "svg", ",", "options", "=", "{", "}", ")", "#TODO ensure this works with new points", "current_points", "=", "points", "layers", ".", "each", "do", "|", "layer", "|", "real_points", "=", "layer", ".", "points", "layer", ".", "points", "=", "current_points", "layer_options", "=", "options", ".", "dup", "layer_options", "[", ":color", "]", "=", "layer", ".", "preferred_color", "||", "layer", ".", "color", "||", "options", "[", ":theme", "]", ".", "next_color", "layer", ".", "render", "(", "svg", ",", "layer_options", ")", "options", ".", "merge", "(", "layer_options", ")", "layer", ".", "points", "=", "real_points", "layer", ".", "points", ".", "each_with_index", "{", "|", "val", ",", "idx", "|", "current_points", "[", "idx", "]", "-=", "val", "}", "end", "end" ]
Returns new Stacked graph. You can provide a block for easily adding layers during (just after) initialization. Example: Stacked.new do |stacked| stacked << Scruffy::Layers::Line.new( ... ) stacked.add(:bar, 'My Bar', [...]) end The initialize method passes itself to the block, and since stacked is a LayerContainer, layers can be added just as if they were being added to Graph. Overrides Base#render to fiddle with layers' points to achieve a stacked effect.
[ "Returns", "new", "Stacked", "graph", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/stacked.rb#L32-L47
3,010
brasten/scruffy
lib/scruffy/layers/stacked.rb
Scruffy::Layers.Stacked.legend_data
def legend_data if relevant_data? retval = [] layers.each do |layer| retval << layer.legend_data end retval else nil end end
ruby
def legend_data if relevant_data? retval = [] layers.each do |layer| retval << layer.legend_data end retval else nil end end
[ "def", "legend_data", "if", "relevant_data?", "retval", "=", "[", "]", "layers", ".", "each", "do", "|", "layer", "|", "retval", "<<", "layer", ".", "legend_data", "end", "retval", "else", "nil", "end", "end" ]
A stacked graph has many data sets. Return legend information for all of them.
[ "A", "stacked", "graph", "has", "many", "data", "sets", ".", "Return", "legend", "information", "for", "all", "of", "them", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/stacked.rb#L50-L60
3,011
brasten/scruffy
lib/scruffy/renderers/base.rb
Scruffy::Renderers.Base.render
def render(options = {}) options[:graph_id] ||= 'scruffy_graph' options[:complexity] ||= (global_complexity || :normal) # Allow subclasses to muck with components prior to renders. rendertime_renderer = self.clone rendertime_renderer.instance_eval { before_render if respond_to?(:before_render) } svg = Builder::XmlMarkup.new(:indent => 2) unless options[:no_doctype_header] svg.instruct! svg.declare! :DOCTYPE, :svg, :PUBLIC, "-//W3C//DTD SVG 1.0//EN", "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd" end svg.svg(:xmlns => "http://www.w3.org/2000/svg", 'xmlns:xlink' => "http://www.w3.org/1999/xlink", :width => options[:size].first, :height => options[:size].last) { svg.g(:id => options[:graph_id]) { rendertime_renderer.components.each do |component| component.render(svg, bounds_for( options[:size], component.position, component.size ), options) end } } svg.target! end
ruby
def render(options = {}) options[:graph_id] ||= 'scruffy_graph' options[:complexity] ||= (global_complexity || :normal) # Allow subclasses to muck with components prior to renders. rendertime_renderer = self.clone rendertime_renderer.instance_eval { before_render if respond_to?(:before_render) } svg = Builder::XmlMarkup.new(:indent => 2) unless options[:no_doctype_header] svg.instruct! svg.declare! :DOCTYPE, :svg, :PUBLIC, "-//W3C//DTD SVG 1.0//EN", "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd" end svg.svg(:xmlns => "http://www.w3.org/2000/svg", 'xmlns:xlink' => "http://www.w3.org/1999/xlink", :width => options[:size].first, :height => options[:size].last) { svg.g(:id => options[:graph_id]) { rendertime_renderer.components.each do |component| component.render(svg, bounds_for( options[:size], component.position, component.size ), options) end } } svg.target! end
[ "def", "render", "(", "options", "=", "{", "}", ")", "options", "[", ":graph_id", "]", "||=", "'scruffy_graph'", "options", "[", ":complexity", "]", "||=", "(", "global_complexity", "||", ":normal", ")", "# Allow subclasses to muck with components prior to renders.", "rendertime_renderer", "=", "self", ".", "clone", "rendertime_renderer", ".", "instance_eval", "{", "before_render", "if", "respond_to?", "(", ":before_render", ")", "}", "svg", "=", "Builder", "::", "XmlMarkup", ".", "new", "(", ":indent", "=>", "2", ")", "unless", "options", "[", ":no_doctype_header", "]", "svg", ".", "instruct!", "svg", ".", "declare!", ":DOCTYPE", ",", ":svg", ",", ":PUBLIC", ",", "\"-//W3C//DTD SVG 1.0//EN\"", ",", "\"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\"", "end", "svg", ".", "svg", "(", ":xmlns", "=>", "\"http://www.w3.org/2000/svg\"", ",", "'xmlns:xlink'", "=>", "\"http://www.w3.org/1999/xlink\"", ",", ":width", "=>", "options", "[", ":size", "]", ".", "first", ",", ":height", "=>", "options", "[", ":size", "]", ".", "last", ")", "{", "svg", ".", "g", "(", ":id", "=>", "options", "[", ":graph_id", "]", ")", "{", "rendertime_renderer", ".", "components", ".", "each", "do", "|", "component", "|", "component", ".", "render", "(", "svg", ",", "bounds_for", "(", "options", "[", ":size", "]", ",", "component", ".", "position", ",", "component", ".", "size", ")", ",", "options", ")", "end", "}", "}", "svg", ".", "target!", "end" ]
Renders the graph and all components.
[ "Renders", "the", "graph", "and", "all", "components", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/renderers/base.rb#L24-L47
3,012
rossf7/elasticrawl
lib/elasticrawl/parse_job.rb
Elasticrawl.ParseJob.set_segments
def set_segments(crawl_segments, max_files = nil) self.job_name = set_job_name self.job_desc = set_job_desc(crawl_segments, max_files) self.max_files = max_files crawl_segments.each do |segment| self.job_steps.push(create_job_step(segment)) end end
ruby
def set_segments(crawl_segments, max_files = nil) self.job_name = set_job_name self.job_desc = set_job_desc(crawl_segments, max_files) self.max_files = max_files crawl_segments.each do |segment| self.job_steps.push(create_job_step(segment)) end end
[ "def", "set_segments", "(", "crawl_segments", ",", "max_files", "=", "nil", ")", "self", ".", "job_name", "=", "set_job_name", "self", ".", "job_desc", "=", "set_job_desc", "(", "crawl_segments", ",", "max_files", ")", "self", ".", "max_files", "=", "max_files", "crawl_segments", ".", "each", "do", "|", "segment", "|", "self", ".", "job_steps", ".", "push", "(", "create_job_step", "(", "segment", ")", ")", "end", "end" ]
Populates the job from the list of segments to be parsed.
[ "Populates", "the", "job", "from", "the", "list", "of", "segments", "to", "be", "parsed", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/parse_job.rb#L8-L16
3,013
rossf7/elasticrawl
lib/elasticrawl/parse_job.rb
Elasticrawl.ParseJob.run
def run emr_config = job_config['emr_config'] job_flow_id = run_job_flow(emr_config) if job_flow_id.present? self.job_flow_id = job_flow_id self.job_steps.each do |step| segment = step.crawl_segment segment.parse_time = DateTime.now segment.save end self.save self.result_message end end
ruby
def run emr_config = job_config['emr_config'] job_flow_id = run_job_flow(emr_config) if job_flow_id.present? self.job_flow_id = job_flow_id self.job_steps.each do |step| segment = step.crawl_segment segment.parse_time = DateTime.now segment.save end self.save self.result_message end end
[ "def", "run", "emr_config", "=", "job_config", "[", "'emr_config'", "]", "job_flow_id", "=", "run_job_flow", "(", "emr_config", ")", "if", "job_flow_id", ".", "present?", "self", ".", "job_flow_id", "=", "job_flow_id", "self", ".", "job_steps", ".", "each", "do", "|", "step", "|", "segment", "=", "step", ".", "crawl_segment", "segment", ".", "parse_time", "=", "DateTime", ".", "now", "segment", ".", "save", "end", "self", ".", "save", "self", ".", "result_message", "end", "end" ]
Runs the job by calling Elastic MapReduce API. If successful the parse time is set for each segment.
[ "Runs", "the", "job", "by", "calling", "Elastic", "MapReduce", "API", ".", "If", "successful", "the", "parse", "time", "is", "set", "for", "each", "segment", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/parse_job.rb#L20-L36
3,014
rossf7/elasticrawl
lib/elasticrawl/parse_job.rb
Elasticrawl.ParseJob.segment_list
def segment_list segments = ['Segments'] job_steps.each do |job_step| if job_step.crawl_segment.present? segment = job_step.crawl_segment segments.push(segment.segment_desc) end end segments.push('') end
ruby
def segment_list segments = ['Segments'] job_steps.each do |job_step| if job_step.crawl_segment.present? segment = job_step.crawl_segment segments.push(segment.segment_desc) end end segments.push('') end
[ "def", "segment_list", "segments", "=", "[", "'Segments'", "]", "job_steps", ".", "each", "do", "|", "job_step", "|", "if", "job_step", ".", "crawl_segment", ".", "present?", "segment", "=", "job_step", ".", "crawl_segment", "segments", ".", "push", "(", "segment", ".", "segment_desc", ")", "end", "end", "segments", ".", "push", "(", "''", ")", "end" ]
Return list of segment descriptions.
[ "Return", "list", "of", "segment", "descriptions", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/parse_job.rb#L45-L56
3,015
rossf7/elasticrawl
lib/elasticrawl/parse_job.rb
Elasticrawl.ParseJob.set_job_desc
def set_job_desc(segments, max_files) if segments.count > 0 crawl_name = segments[0].crawl.crawl_name if segments[0].crawl.present? file_desc = max_files.nil? ? 'all files' : "#{max_files} files per segment" end "Crawl: #{crawl_name} Segments: #{segments.count} Parsing: #{file_desc}" end
ruby
def set_job_desc(segments, max_files) if segments.count > 0 crawl_name = segments[0].crawl.crawl_name if segments[0].crawl.present? file_desc = max_files.nil? ? 'all files' : "#{max_files} files per segment" end "Crawl: #{crawl_name} Segments: #{segments.count} Parsing: #{file_desc}" end
[ "def", "set_job_desc", "(", "segments", ",", "max_files", ")", "if", "segments", ".", "count", ">", "0", "crawl_name", "=", "segments", "[", "0", "]", ".", "crawl", ".", "crawl_name", "if", "segments", "[", "0", "]", ".", "crawl", ".", "present?", "file_desc", "=", "max_files", ".", "nil?", "?", "'all files'", ":", "\"#{max_files} files per segment\"", "end", "\"Crawl: #{crawl_name} Segments: #{segments.count} Parsing: #{file_desc}\"", "end" ]
Sets the job description which forms part of the Elastic MapReduce job flow name.
[ "Sets", "the", "job", "description", "which", "forms", "part", "of", "the", "Elastic", "MapReduce", "job", "flow", "name", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/parse_job.rb#L83-L90
3,016
58bits/partial-date
lib/partial-date/date.rb
PartialDate.Date.old_to_s
def old_to_s(format = :default) format = FORMATS[format] if format.is_a?(Symbol) result = format.dup FORMAT_METHODS.each_pair do |key, value| result.gsub!( key, value.call( self )) if result.include? key end # Remove any leading "/-," chars. # Remove double white spaces. # Remove any duplicate "/-," chars and replace with the single char. # Remove any trailing "/-," chars. # Anything else - you're on your own ;-) lead_trim = (year != 0 && format.lstrip.start_with?("%Y")) ? /\A[\/\,\s]+/ : /\A[\/\,\-\s]+/ result = result.gsub(lead_trim, '').gsub(/\s\s/, ' ').gsub(/[\/\-\,]([\/\-\,])/, '\1').gsub(/[\/\,\-\s]+\z/, '') end
ruby
def old_to_s(format = :default) format = FORMATS[format] if format.is_a?(Symbol) result = format.dup FORMAT_METHODS.each_pair do |key, value| result.gsub!( key, value.call( self )) if result.include? key end # Remove any leading "/-," chars. # Remove double white spaces. # Remove any duplicate "/-," chars and replace with the single char. # Remove any trailing "/-," chars. # Anything else - you're on your own ;-) lead_trim = (year != 0 && format.lstrip.start_with?("%Y")) ? /\A[\/\,\s]+/ : /\A[\/\,\-\s]+/ result = result.gsub(lead_trim, '').gsub(/\s\s/, ' ').gsub(/[\/\-\,]([\/\-\,])/, '\1').gsub(/[\/\,\-\s]+\z/, '') end
[ "def", "old_to_s", "(", "format", "=", ":default", ")", "format", "=", "FORMATS", "[", "format", "]", "if", "format", ".", "is_a?", "(", "Symbol", ")", "result", "=", "format", ".", "dup", "FORMAT_METHODS", ".", "each_pair", "do", "|", "key", ",", "value", "|", "result", ".", "gsub!", "(", "key", ",", "value", ".", "call", "(", "self", ")", ")", "if", "result", ".", "include?", "key", "end", "# Remove any leading \"/-,\" chars.", "# Remove double white spaces.", "# Remove any duplicate \"/-,\" chars and replace with the single char.", "# Remove any trailing \"/-,\" chars.", "# Anything else - you're on your own ;-)", "lead_trim", "=", "(", "year", "!=", "0", "&&", "format", ".", "lstrip", ".", "start_with?", "(", "\"%Y\"", ")", ")", "?", "/", "\\A", "\\/", "\\,", "\\s", "/", ":", "/", "\\A", "\\/", "\\,", "\\-", "\\s", "/", "result", "=", "result", ".", "gsub", "(", "lead_trim", ",", "''", ")", ".", "gsub", "(", "/", "\\s", "\\s", "/", ",", "' '", ")", ".", "gsub", "(", "/", "\\/", "\\-", "\\,", "\\/", "\\-", "\\,", "/", ",", "'\\1'", ")", ".", "gsub", "(", "/", "\\/", "\\,", "\\-", "\\s", "\\z", "/", ",", "''", ")", "end" ]
Here for the moment for benchmark comparisons
[ "Here", "for", "the", "moment", "for", "benchmark", "comparisons" ]
1760d33bda3da42bb8c3f67fb63dd6bc5dc70bea
https://github.com/58bits/partial-date/blob/1760d33bda3da42bb8c3f67fb63dd6bc5dc70bea/lib/partial-date/date.rb#L316-L331
3,017
brasten/scruffy
lib/scruffy/layers/line.rb
Scruffy::Layers.Line.draw
def draw(svg, coords, options={}) # Include options provided when the object was created options.merge!(@options) stroke_width = (options[:relativestroke]) ? relative(options[:stroke_width]) : options[:stroke_width] style = (options[:style]) ? options[:style] : '' if options[:shadow] svg.g(:class => 'shadow', :transform => "translate(#{relative(0.5)}, #{relative(0.5)})") { svg.polyline( :points => stringify_coords(coords).join(' '), :fill => 'transparent', :stroke => 'black', 'stroke-width' => stroke_width, :style => 'fill-opacity: 0; stroke-opacity: 0.35' ) if options[:dots] coords.each { |coord| svg.circle( :cx => coord.first, :cy => coord.last + relative(0.9), :r => stroke_width, :style => "stroke-width: #{stroke_width}; stroke: black; opacity: 0.35;" ) } end } end svg.polyline( :points => stringify_coords(coords).join(' '), :fill => 'none', :stroke => @color.to_s, 'stroke-width' => stroke_width, :style => style ) if options[:dots] coords.each { |coord| svg.circle( :cx => coord.first, :cy => coord.last, :r => stroke_width, :style => "stroke-width: #{stroke_width}; stroke: #{color.to_s}; fill: #{color.to_s}" ) } end end
ruby
def draw(svg, coords, options={}) # Include options provided when the object was created options.merge!(@options) stroke_width = (options[:relativestroke]) ? relative(options[:stroke_width]) : options[:stroke_width] style = (options[:style]) ? options[:style] : '' if options[:shadow] svg.g(:class => 'shadow', :transform => "translate(#{relative(0.5)}, #{relative(0.5)})") { svg.polyline( :points => stringify_coords(coords).join(' '), :fill => 'transparent', :stroke => 'black', 'stroke-width' => stroke_width, :style => 'fill-opacity: 0; stroke-opacity: 0.35' ) if options[:dots] coords.each { |coord| svg.circle( :cx => coord.first, :cy => coord.last + relative(0.9), :r => stroke_width, :style => "stroke-width: #{stroke_width}; stroke: black; opacity: 0.35;" ) } end } end svg.polyline( :points => stringify_coords(coords).join(' '), :fill => 'none', :stroke => @color.to_s, 'stroke-width' => stroke_width, :style => style ) if options[:dots] coords.each { |coord| svg.circle( :cx => coord.first, :cy => coord.last, :r => stroke_width, :style => "stroke-width: #{stroke_width}; stroke: #{color.to_s}; fill: #{color.to_s}" ) } end end
[ "def", "draw", "(", "svg", ",", "coords", ",", "options", "=", "{", "}", ")", "# Include options provided when the object was created", "options", ".", "merge!", "(", "@options", ")", "stroke_width", "=", "(", "options", "[", ":relativestroke", "]", ")", "?", "relative", "(", "options", "[", ":stroke_width", "]", ")", ":", "options", "[", ":stroke_width", "]", "style", "=", "(", "options", "[", ":style", "]", ")", "?", "options", "[", ":style", "]", ":", "''", "if", "options", "[", ":shadow", "]", "svg", ".", "g", "(", ":class", "=>", "'shadow'", ",", ":transform", "=>", "\"translate(#{relative(0.5)}, #{relative(0.5)})\"", ")", "{", "svg", ".", "polyline", "(", ":points", "=>", "stringify_coords", "(", "coords", ")", ".", "join", "(", "' '", ")", ",", ":fill", "=>", "'transparent'", ",", ":stroke", "=>", "'black'", ",", "'stroke-width'", "=>", "stroke_width", ",", ":style", "=>", "'fill-opacity: 0; stroke-opacity: 0.35'", ")", "if", "options", "[", ":dots", "]", "coords", ".", "each", "{", "|", "coord", "|", "svg", ".", "circle", "(", ":cx", "=>", "coord", ".", "first", ",", ":cy", "=>", "coord", ".", "last", "+", "relative", "(", "0.9", ")", ",", ":r", "=>", "stroke_width", ",", ":style", "=>", "\"stroke-width: #{stroke_width}; stroke: black; opacity: 0.35;\"", ")", "}", "end", "}", "end", "svg", ".", "polyline", "(", ":points", "=>", "stringify_coords", "(", "coords", ")", ".", "join", "(", "' '", ")", ",", ":fill", "=>", "'none'", ",", ":stroke", "=>", "@color", ".", "to_s", ",", "'stroke-width'", "=>", "stroke_width", ",", ":style", "=>", "style", ")", "if", "options", "[", ":dots", "]", "coords", ".", "each", "{", "|", "coord", "|", "svg", ".", "circle", "(", ":cx", "=>", "coord", ".", "first", ",", ":cy", "=>", "coord", ".", "last", ",", ":r", "=>", "stroke_width", ",", ":style", "=>", "\"stroke-width: #{stroke_width}; stroke: #{color.to_s}; fill: #{color.to_s}\"", ")", "}", "end", "end" ]
Renders line graph. Options: See initialize()
[ "Renders", "line", "graph", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/line.rb#L14-L44
3,018
rossf7/elasticrawl
lib/elasticrawl/crawl.rb
Elasticrawl.Crawl.status
def status total = self.crawl_segments.count remaining = CrawlSegment.where(:crawl_id => self.id, :parse_time => nil).count parsed = total - remaining status = self.crawl_name status += " Segments: to parse #{remaining}, " status += "parsed #{parsed}, total #{total}" end
ruby
def status total = self.crawl_segments.count remaining = CrawlSegment.where(:crawl_id => self.id, :parse_time => nil).count parsed = total - remaining status = self.crawl_name status += " Segments: to parse #{remaining}, " status += "parsed #{parsed}, total #{total}" end
[ "def", "status", "total", "=", "self", ".", "crawl_segments", ".", "count", "remaining", "=", "CrawlSegment", ".", "where", "(", ":crawl_id", "=>", "self", ".", "id", ",", ":parse_time", "=>", "nil", ")", ".", "count", "parsed", "=", "total", "-", "remaining", "status", "=", "self", ".", "crawl_name", "status", "+=", "\" Segments: to parse #{remaining}, \"", "status", "+=", "\"parsed #{parsed}, total #{total}\"", "end" ]
Returns the status of the current crawl.
[ "Returns", "the", "status", "of", "the", "current", "crawl", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/crawl.rb#L28-L36
3,019
rossf7/elasticrawl
lib/elasticrawl/crawl.rb
Elasticrawl.Crawl.create_segments
def create_segments file_paths = warc_paths(self.crawl_name) segments = parse_segments(file_paths) save if segments.count > 0 segments.keys.each do |segment_name| file_count = segments[segment_name] CrawlSegment.create_segment(self, segment_name, file_count) end segments.count end
ruby
def create_segments file_paths = warc_paths(self.crawl_name) segments = parse_segments(file_paths) save if segments.count > 0 segments.keys.each do |segment_name| file_count = segments[segment_name] CrawlSegment.create_segment(self, segment_name, file_count) end segments.count end
[ "def", "create_segments", "file_paths", "=", "warc_paths", "(", "self", ".", "crawl_name", ")", "segments", "=", "parse_segments", "(", "file_paths", ")", "save", "if", "segments", ".", "count", ">", "0", "segments", ".", "keys", ".", "each", "do", "|", "segment_name", "|", "file_count", "=", "segments", "[", "segment_name", "]", "CrawlSegment", ".", "create_segment", "(", "self", ",", "segment_name", ",", "file_count", ")", "end", "segments", ".", "count", "end" ]
Creates crawl segments from the warc.paths file for this crawl.
[ "Creates", "crawl", "segments", "from", "the", "warc", ".", "paths", "file", "for", "this", "crawl", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/crawl.rb#L50-L62
3,020
rossf7/elasticrawl
lib/elasticrawl/crawl.rb
Elasticrawl.Crawl.reset
def reset segments = CrawlSegment.where('crawl_id = ? and parse_time is not null', self.id) segments.map { |segment| segment.update_attribute(:parse_time, nil) } status end
ruby
def reset segments = CrawlSegment.where('crawl_id = ? and parse_time is not null', self.id) segments.map { |segment| segment.update_attribute(:parse_time, nil) } status end
[ "def", "reset", "segments", "=", "CrawlSegment", ".", "where", "(", "'crawl_id = ? and parse_time is not null'", ",", "self", ".", "id", ")", "segments", ".", "map", "{", "|", "segment", "|", "segment", ".", "update_attribute", "(", ":parse_time", ",", "nil", ")", "}", "status", "end" ]
Resets parse time of all parsed segments to null so they will be parsed again. Returns the updated crawl status.
[ "Resets", "parse", "time", "of", "all", "parsed", "segments", "to", "null", "so", "they", "will", "be", "parsed", "again", ".", "Returns", "the", "updated", "crawl", "status", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/crawl.rb#L80-L86
3,021
rossf7/elasticrawl
lib/elasticrawl/crawl.rb
Elasticrawl.Crawl.warc_paths
def warc_paths(crawl_name) s3_path = [Elasticrawl::COMMON_CRAWL_PATH, crawl_name, Elasticrawl::WARC_PATHS].join('/') begin s3 = AWS::S3.new bucket = s3.buckets[Elasticrawl::COMMON_CRAWL_BUCKET] object = bucket.objects[s3_path] uncompress_file(object) rescue AWS::Errors::Base => s3e raise S3AccessError.new(s3e.http_response), 'Failed to get WARC paths' rescue Exception => e raise S3AccessError, 'Failed to get WARC paths' end end
ruby
def warc_paths(crawl_name) s3_path = [Elasticrawl::COMMON_CRAWL_PATH, crawl_name, Elasticrawl::WARC_PATHS].join('/') begin s3 = AWS::S3.new bucket = s3.buckets[Elasticrawl::COMMON_CRAWL_BUCKET] object = bucket.objects[s3_path] uncompress_file(object) rescue AWS::Errors::Base => s3e raise S3AccessError.new(s3e.http_response), 'Failed to get WARC paths' rescue Exception => e raise S3AccessError, 'Failed to get WARC paths' end end
[ "def", "warc_paths", "(", "crawl_name", ")", "s3_path", "=", "[", "Elasticrawl", "::", "COMMON_CRAWL_PATH", ",", "crawl_name", ",", "Elasticrawl", "::", "WARC_PATHS", "]", ".", "join", "(", "'/'", ")", "begin", "s3", "=", "AWS", "::", "S3", ".", "new", "bucket", "=", "s3", ".", "buckets", "[", "Elasticrawl", "::", "COMMON_CRAWL_BUCKET", "]", "object", "=", "bucket", ".", "objects", "[", "s3_path", "]", "uncompress_file", "(", "object", ")", "rescue", "AWS", "::", "Errors", "::", "Base", "=>", "s3e", "raise", "S3AccessError", ".", "new", "(", "s3e", ".", "http_response", ")", ",", "'Failed to get WARC paths'", "rescue", "Exception", "=>", "e", "raise", "S3AccessError", ",", "'Failed to get WARC paths'", "end", "end" ]
Gets the WARC file paths from S3 for this crawl if it exists.
[ "Gets", "the", "WARC", "file", "paths", "from", "S3", "for", "this", "crawl", "if", "it", "exists", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/crawl.rb#L90-L106
3,022
rossf7/elasticrawl
lib/elasticrawl/crawl.rb
Elasticrawl.Crawl.uncompress_file
def uncompress_file(s3_object) result = '' if s3_object.exists? io = StringIO.new io.write(s3_object.read) io.rewind gz = Zlib::GzipReader.new(io) result = gz.read gz.close end result end
ruby
def uncompress_file(s3_object) result = '' if s3_object.exists? io = StringIO.new io.write(s3_object.read) io.rewind gz = Zlib::GzipReader.new(io) result = gz.read gz.close end result end
[ "def", "uncompress_file", "(", "s3_object", ")", "result", "=", "''", "if", "s3_object", ".", "exists?", "io", "=", "StringIO", ".", "new", "io", ".", "write", "(", "s3_object", ".", "read", ")", "io", ".", "rewind", "gz", "=", "Zlib", "::", "GzipReader", ".", "new", "(", "io", ")", "result", "=", "gz", ".", "read", "gz", ".", "close", "end", "result", "end" ]
Takes in a S3 object and returns the contents as an uncompressed string.
[ "Takes", "in", "a", "S3", "object", "and", "returns", "the", "contents", "as", "an", "uncompressed", "string", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/crawl.rb#L109-L124
3,023
rossf7/elasticrawl
lib/elasticrawl/crawl.rb
Elasticrawl.Crawl.parse_segments
def parse_segments(warc_paths) segments = Hash.new 0 warc_paths.split.each do |warc_path| segment_name = warc_path.split('/')[3] segments[segment_name] += 1 if segment_name.present? end segments end
ruby
def parse_segments(warc_paths) segments = Hash.new 0 warc_paths.split.each do |warc_path| segment_name = warc_path.split('/')[3] segments[segment_name] += 1 if segment_name.present? end segments end
[ "def", "parse_segments", "(", "warc_paths", ")", "segments", "=", "Hash", ".", "new", "0", "warc_paths", ".", "split", ".", "each", "do", "|", "warc_path", "|", "segment_name", "=", "warc_path", ".", "split", "(", "'/'", ")", "[", "3", "]", "segments", "[", "segment_name", "]", "+=", "1", "if", "segment_name", ".", "present?", "end", "segments", "end" ]
Parses the segment names and file counts from the WARC file paths.
[ "Parses", "the", "segment", "names", "and", "file", "counts", "from", "the", "WARC", "file", "paths", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/crawl.rb#L127-L136
3,024
brasten/scruffy
lib/scruffy/layers/multi_area.rb
Scruffy::Layers.MultiArea.draw
def draw(svg, coords, options={}) # Check whether to use color from theme, or whether to use user defined colors from the area_colors array color_count = nil if @area_colors && @area_colors.size > 0 area_color = @area_colors[0] color_count = 1 else puts "Never Set Area Color" area_color = color end # Draw Bottom Level Polygons (Original Coords) draw_poly(svg, coords, area_color, options = {}) # Draw Lower Area Polygons if @baselines # Get the Color of this Area puts "Drawing Baselines" @baselines.sort! {|x,y| y <=> x } @baselines.each do |baseline| if color_count area_color = area_colors[color_count] color_count = color_count + 1 puts area_color.to_s if color_count >= area_colors.size color_count = 0 end end lower_poly_coords = create_lower_polygon_coords(translate_number(baseline), coords, options) draw_poly(svg, lower_poly_coords, area_color, options = {}) end end end
ruby
def draw(svg, coords, options={}) # Check whether to use color from theme, or whether to use user defined colors from the area_colors array color_count = nil if @area_colors && @area_colors.size > 0 area_color = @area_colors[0] color_count = 1 else puts "Never Set Area Color" area_color = color end # Draw Bottom Level Polygons (Original Coords) draw_poly(svg, coords, area_color, options = {}) # Draw Lower Area Polygons if @baselines # Get the Color of this Area puts "Drawing Baselines" @baselines.sort! {|x,y| y <=> x } @baselines.each do |baseline| if color_count area_color = area_colors[color_count] color_count = color_count + 1 puts area_color.to_s if color_count >= area_colors.size color_count = 0 end end lower_poly_coords = create_lower_polygon_coords(translate_number(baseline), coords, options) draw_poly(svg, lower_poly_coords, area_color, options = {}) end end end
[ "def", "draw", "(", "svg", ",", "coords", ",", "options", "=", "{", "}", ")", "# Check whether to use color from theme, or whether to use user defined colors from the area_colors array", "color_count", "=", "nil", "if", "@area_colors", "&&", "@area_colors", ".", "size", ">", "0", "area_color", "=", "@area_colors", "[", "0", "]", "color_count", "=", "1", "else", "puts", "\"Never Set Area Color\"", "area_color", "=", "color", "end", "# Draw Bottom Level Polygons (Original Coords)", "draw_poly", "(", "svg", ",", "coords", ",", "area_color", ",", "options", "=", "{", "}", ")", "# Draw Lower Area Polygons", "if", "@baselines", "# Get the Color of this Area", "puts", "\"Drawing Baselines\"", "@baselines", ".", "sort!", "{", "|", "x", ",", "y", "|", "y", "<=>", "x", "}", "@baselines", ".", "each", "do", "|", "baseline", "|", "if", "color_count", "area_color", "=", "area_colors", "[", "color_count", "]", "color_count", "=", "color_count", "+", "1", "puts", "area_color", ".", "to_s", "if", "color_count", ">=", "area_colors", ".", "size", "color_count", "=", "0", "end", "end", "lower_poly_coords", "=", "create_lower_polygon_coords", "(", "translate_number", "(", "baseline", ")", ",", "coords", ",", "options", ")", "draw_poly", "(", "svg", ",", "lower_poly_coords", ",", "area_color", ",", "options", "=", "{", "}", ")", "end", "end", "end" ]
Render Multi Area graph.
[ "Render", "Multi", "Area", "graph", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/multi_area.rb#L21-L54
3,025
rrrene/sparkr
lib/sparkr/sparkline.rb
Sparkr.Sparkline.normalize_numbers
def normalize_numbers(_numbers) numbers = _numbers.map(&:to_i) min = numbers.min numbers.map do |n| n - min end end
ruby
def normalize_numbers(_numbers) numbers = _numbers.map(&:to_i) min = numbers.min numbers.map do |n| n - min end end
[ "def", "normalize_numbers", "(", "_numbers", ")", "numbers", "=", "_numbers", ".", "map", "(", ":to_i", ")", "min", "=", "numbers", ".", "min", "numbers", ".", "map", "do", "|", "n", "|", "n", "-", "min", "end", "end" ]
Returns the normalized equivalent of a given list normalize_numbers([3, 4, 7]) # => [0, 1, 4] @return [Fixnum] the normalized equivalent of the given +_numbers+
[ "Returns", "the", "normalized", "equivalent", "of", "a", "given", "list" ]
2329d965ae421dfbc4743dd728884f2da501a107
https://github.com/rrrene/sparkr/blob/2329d965ae421dfbc4743dd728884f2da501a107/lib/sparkr/sparkline.rb#L62-L68
3,026
opentox/lazar
lib/nanoparticle.rb
OpenTox.Nanoparticle.parse_ambit_value
def parse_ambit_value feature, v, dataset # TODO add study id to warnings v.delete "unit" # TODO: ppm instead of weights if v.keys == ["textValue"] add_feature feature, v["textValue"], dataset elsif v.keys == ["loValue"] add_feature feature, v["loValue"], dataset elsif v.keys.size == 2 and v["errorValue"] add_feature feature, v["loValue"], dataset #warn "Ignoring errorValue '#{v["errorValue"]}' for '#{feature.name}'." elsif v.keys.size == 2 and v["loQualifier"] == "mean" add_feature feature, v["loValue"], dataset #warn "'#{feature.name}' is a mean value. Original data is not available." elsif v.keys.size == 2 and v["loQualifier"] #== ">=" #warn "Only min value available for '#{feature.name}', entry ignored" elsif v.keys.size == 2 and v["upQualifier"] #== ">=" #warn "Only max value available for '#{feature.name}', entry ignored" elsif v.keys.size == 3 and v["loValue"] and v["loQualifier"].nil? and v["upQualifier"].nil? add_feature feature, v["loValue"], dataset #warn "loQualifier and upQualifier are empty." elsif v.keys.size == 3 and v["loValue"] and v["loQualifier"] == "" and v["upQualifier"] == "" add_feature feature, v["loValue"], dataset #warn "loQualifier and upQualifier are empty." elsif v.keys.size == 4 and v["loValue"] and v["loQualifier"].nil? and v["upQualifier"].nil? add_feature feature, v["loValue"], dataset #warn "loQualifier and upQualifier are empty." elsif v.size == 4 and v["loQualifier"] and v["upQualifier"] and v["loValue"] and v["upValue"] #add_feature feature, [v["loValue"],v["upValue"]].mean, dataset #warn "Using mean value of range #{v["loValue"]} - #{v["upValue"]} for '#{feature.name}'. Original data is not available." elsif v.size == 4 and v["loQualifier"] == "mean" and v["errorValue"] #warn "'#{feature.name}' is a mean value. Original data is not available. Ignoring errorValue '#{v["errorValue"]}' for '#{feature.name}'." add_feature feature, v["loValue"], dataset elsif v == {} # do nothing else warn "Cannot parse Ambit eNanoMapper value '#{v}' for feature '#{feature.name}'." end end
ruby
def parse_ambit_value feature, v, dataset # TODO add study id to warnings v.delete "unit" # TODO: ppm instead of weights if v.keys == ["textValue"] add_feature feature, v["textValue"], dataset elsif v.keys == ["loValue"] add_feature feature, v["loValue"], dataset elsif v.keys.size == 2 and v["errorValue"] add_feature feature, v["loValue"], dataset #warn "Ignoring errorValue '#{v["errorValue"]}' for '#{feature.name}'." elsif v.keys.size == 2 and v["loQualifier"] == "mean" add_feature feature, v["loValue"], dataset #warn "'#{feature.name}' is a mean value. Original data is not available." elsif v.keys.size == 2 and v["loQualifier"] #== ">=" #warn "Only min value available for '#{feature.name}', entry ignored" elsif v.keys.size == 2 and v["upQualifier"] #== ">=" #warn "Only max value available for '#{feature.name}', entry ignored" elsif v.keys.size == 3 and v["loValue"] and v["loQualifier"].nil? and v["upQualifier"].nil? add_feature feature, v["loValue"], dataset #warn "loQualifier and upQualifier are empty." elsif v.keys.size == 3 and v["loValue"] and v["loQualifier"] == "" and v["upQualifier"] == "" add_feature feature, v["loValue"], dataset #warn "loQualifier and upQualifier are empty." elsif v.keys.size == 4 and v["loValue"] and v["loQualifier"].nil? and v["upQualifier"].nil? add_feature feature, v["loValue"], dataset #warn "loQualifier and upQualifier are empty." elsif v.size == 4 and v["loQualifier"] and v["upQualifier"] and v["loValue"] and v["upValue"] #add_feature feature, [v["loValue"],v["upValue"]].mean, dataset #warn "Using mean value of range #{v["loValue"]} - #{v["upValue"]} for '#{feature.name}'. Original data is not available." elsif v.size == 4 and v["loQualifier"] == "mean" and v["errorValue"] #warn "'#{feature.name}' is a mean value. Original data is not available. Ignoring errorValue '#{v["errorValue"]}' for '#{feature.name}'." add_feature feature, v["loValue"], dataset elsif v == {} # do nothing else warn "Cannot parse Ambit eNanoMapper value '#{v}' for feature '#{feature.name}'." end end
[ "def", "parse_ambit_value", "feature", ",", "v", ",", "dataset", "# TODO add study id to warnings", "v", ".", "delete", "\"unit\"", "# TODO: ppm instead of weights", "if", "v", ".", "keys", "==", "[", "\"textValue\"", "]", "add_feature", "feature", ",", "v", "[", "\"textValue\"", "]", ",", "dataset", "elsif", "v", ".", "keys", "==", "[", "\"loValue\"", "]", "add_feature", "feature", ",", "v", "[", "\"loValue\"", "]", ",", "dataset", "elsif", "v", ".", "keys", ".", "size", "==", "2", "and", "v", "[", "\"errorValue\"", "]", "add_feature", "feature", ",", "v", "[", "\"loValue\"", "]", ",", "dataset", "#warn \"Ignoring errorValue '#{v[\"errorValue\"]}' for '#{feature.name}'.\"", "elsif", "v", ".", "keys", ".", "size", "==", "2", "and", "v", "[", "\"loQualifier\"", "]", "==", "\"mean\"", "add_feature", "feature", ",", "v", "[", "\"loValue\"", "]", ",", "dataset", "#warn \"'#{feature.name}' is a mean value. Original data is not available.\"", "elsif", "v", ".", "keys", ".", "size", "==", "2", "and", "v", "[", "\"loQualifier\"", "]", "#== \">=\"", "#warn \"Only min value available for '#{feature.name}', entry ignored\"", "elsif", "v", ".", "keys", ".", "size", "==", "2", "and", "v", "[", "\"upQualifier\"", "]", "#== \">=\"", "#warn \"Only max value available for '#{feature.name}', entry ignored\"", "elsif", "v", ".", "keys", ".", "size", "==", "3", "and", "v", "[", "\"loValue\"", "]", "and", "v", "[", "\"loQualifier\"", "]", ".", "nil?", "and", "v", "[", "\"upQualifier\"", "]", ".", "nil?", "add_feature", "feature", ",", "v", "[", "\"loValue\"", "]", ",", "dataset", "#warn \"loQualifier and upQualifier are empty.\"", "elsif", "v", ".", "keys", ".", "size", "==", "3", "and", "v", "[", "\"loValue\"", "]", "and", "v", "[", "\"loQualifier\"", "]", "==", "\"\"", "and", "v", "[", "\"upQualifier\"", "]", "==", "\"\"", "add_feature", "feature", ",", "v", "[", "\"loValue\"", "]", ",", "dataset", "#warn \"loQualifier and upQualifier are empty.\"", "elsif", "v", ".", "keys", ".", "size", "==", "4", "and", "v", "[", "\"loValue\"", "]", "and", "v", "[", "\"loQualifier\"", "]", ".", "nil?", "and", "v", "[", "\"upQualifier\"", "]", ".", "nil?", "add_feature", "feature", ",", "v", "[", "\"loValue\"", "]", ",", "dataset", "#warn \"loQualifier and upQualifier are empty.\"", "elsif", "v", ".", "size", "==", "4", "and", "v", "[", "\"loQualifier\"", "]", "and", "v", "[", "\"upQualifier\"", "]", "and", "v", "[", "\"loValue\"", "]", "and", "v", "[", "\"upValue\"", "]", "#add_feature feature, [v[\"loValue\"],v[\"upValue\"]].mean, dataset", "#warn \"Using mean value of range #{v[\"loValue\"]} - #{v[\"upValue\"]} for '#{feature.name}'. Original data is not available.\"", "elsif", "v", ".", "size", "==", "4", "and", "v", "[", "\"loQualifier\"", "]", "==", "\"mean\"", "and", "v", "[", "\"errorValue\"", "]", "#warn \"'#{feature.name}' is a mean value. Original data is not available. Ignoring errorValue '#{v[\"errorValue\"]}' for '#{feature.name}'.\"", "add_feature", "feature", ",", "v", "[", "\"loValue\"", "]", ",", "dataset", "elsif", "v", "==", "{", "}", "# do nothing", "else", "warn", "\"Cannot parse Ambit eNanoMapper value '#{v}' for feature '#{feature.name}'.\"", "end", "end" ]
Parse values from Ambit database @param [OpenTox::Feature] @param [TrueClass,FalseClass,Float] @param [OpenTox::Dataset]
[ "Parse", "values", "from", "Ambit", "database" ]
1ee7de09c969e16fd11522d22179224e694b0161
https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/nanoparticle.rb#L77-L114
3,027
opentox/lazar
lib/dataset.rb
OpenTox.Dataset.substances
def substances @substances ||= data_entries.keys.collect{|id| OpenTox::Substance.find id}.uniq @substances end
ruby
def substances @substances ||= data_entries.keys.collect{|id| OpenTox::Substance.find id}.uniq @substances end
[ "def", "substances", "@substances", "||=", "data_entries", ".", "keys", ".", "collect", "{", "|", "id", "|", "OpenTox", "::", "Substance", ".", "find", "id", "}", ".", "uniq", "@substances", "end" ]
Get all substances @return [Array<OpenTox::Substance>]
[ "Get", "all", "substances" ]
1ee7de09c969e16fd11522d22179224e694b0161
https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/dataset.rb#L27-L30
3,028
opentox/lazar
lib/dataset.rb
OpenTox.Dataset.features
def features @features ||= data_entries.collect{|sid,data| data.keys.collect{|id| OpenTox::Feature.find(id)}}.flatten.uniq @features end
ruby
def features @features ||= data_entries.collect{|sid,data| data.keys.collect{|id| OpenTox::Feature.find(id)}}.flatten.uniq @features end
[ "def", "features", "@features", "||=", "data_entries", ".", "collect", "{", "|", "sid", ",", "data", "|", "data", ".", "keys", ".", "collect", "{", "|", "id", "|", "OpenTox", "::", "Feature", ".", "find", "(", "id", ")", "}", "}", ".", "flatten", ".", "uniq", "@features", "end" ]
Get all features @return [Array<OpenTox::Feature>]
[ "Get", "all", "features" ]
1ee7de09c969e16fd11522d22179224e694b0161
https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/dataset.rb#L34-L37
3,029
opentox/lazar
lib/dataset.rb
OpenTox.Dataset.values
def values substance,feature substance = substance.id if substance.is_a? Substance feature = feature.id if feature.is_a? Feature if data_entries[substance.to_s] and data_entries[substance.to_s][feature.to_s] data_entries[substance.to_s][feature.to_s] else [nil] end end
ruby
def values substance,feature substance = substance.id if substance.is_a? Substance feature = feature.id if feature.is_a? Feature if data_entries[substance.to_s] and data_entries[substance.to_s][feature.to_s] data_entries[substance.to_s][feature.to_s] else [nil] end end
[ "def", "values", "substance", ",", "feature", "substance", "=", "substance", ".", "id", "if", "substance", ".", "is_a?", "Substance", "feature", "=", "feature", ".", "id", "if", "feature", ".", "is_a?", "Feature", "if", "data_entries", "[", "substance", ".", "to_s", "]", "and", "data_entries", "[", "substance", ".", "to_s", "]", "[", "feature", ".", "to_s", "]", "data_entries", "[", "substance", ".", "to_s", "]", "[", "feature", ".", "to_s", "]", "else", "[", "nil", "]", "end", "end" ]
Get all values for a given substance and feature @param [OpenTox::Substance,BSON::ObjectId,String] substance or substance id @param [OpenTox::Feature,BSON::ObjectId,String] feature or feature id @return [TrueClass,FalseClass,Float]
[ "Get", "all", "values", "for", "a", "given", "substance", "and", "feature" ]
1ee7de09c969e16fd11522d22179224e694b0161
https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/dataset.rb#L43-L51
3,030
opentox/lazar
lib/dataset.rb
OpenTox.Dataset.add
def add(substance,feature,value) substance = substance.id if substance.is_a? Substance feature = feature.id if feature.is_a? Feature data_entries[substance.to_s] ||= {} data_entries[substance.to_s][feature.to_s] ||= [] data_entries[substance.to_s][feature.to_s] << value #data_entries[substance.to_s][feature.to_s].uniq! if value.numeric? # assuming that identical values come from the same source end
ruby
def add(substance,feature,value) substance = substance.id if substance.is_a? Substance feature = feature.id if feature.is_a? Feature data_entries[substance.to_s] ||= {} data_entries[substance.to_s][feature.to_s] ||= [] data_entries[substance.to_s][feature.to_s] << value #data_entries[substance.to_s][feature.to_s].uniq! if value.numeric? # assuming that identical values come from the same source end
[ "def", "add", "(", "substance", ",", "feature", ",", "value", ")", "substance", "=", "substance", ".", "id", "if", "substance", ".", "is_a?", "Substance", "feature", "=", "feature", ".", "id", "if", "feature", ".", "is_a?", "Feature", "data_entries", "[", "substance", ".", "to_s", "]", "||=", "{", "}", "data_entries", "[", "substance", ".", "to_s", "]", "[", "feature", ".", "to_s", "]", "||=", "[", "]", "data_entries", "[", "substance", ".", "to_s", "]", "[", "feature", ".", "to_s", "]", "<<", "value", "#data_entries[substance.to_s][feature.to_s].uniq! if value.numeric? # assuming that identical values come from the same source", "end" ]
Writers Add a value for a given substance and feature @param [OpenTox::Substance,BSON::ObjectId,String] substance or substance id @param [OpenTox::Feature,BSON::ObjectId,String] feature or feature id @param [TrueClass,FalseClass,Float]
[ "Writers", "Add", "a", "value", "for", "a", "given", "substance", "and", "feature" ]
1ee7de09c969e16fd11522d22179224e694b0161
https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/dataset.rb#L59-L66
3,031
opentox/lazar
lib/dataset.rb
OpenTox.Dataset.folds
def folds n len = self.substances.size indices = (0..len-1).to_a.shuffle mid = (len/n) chunks = [] start = 0 1.upto(n) do |i| last = start+mid last = last-1 unless len%n >= i test_idxs = indices[start..last] || [] test_substances = test_idxs.collect{|i| substances[i]} training_idxs = indices-test_idxs training_substances = training_idxs.collect{|i| substances[i]} chunk = [training_substances,test_substances].collect do |substances| dataset = self.class.create(:name => "#{self.name} (Fold #{i-1})",:source => self.id ) substances.each do |substance| substance.dataset_ids << dataset.id substance.dataset_ids.uniq! substance.save dataset.data_entries[substance.id.to_s] = data_entries[substance.id.to_s] ||= {} end dataset.save dataset end start = last+1 chunks << chunk end chunks end
ruby
def folds n len = self.substances.size indices = (0..len-1).to_a.shuffle mid = (len/n) chunks = [] start = 0 1.upto(n) do |i| last = start+mid last = last-1 unless len%n >= i test_idxs = indices[start..last] || [] test_substances = test_idxs.collect{|i| substances[i]} training_idxs = indices-test_idxs training_substances = training_idxs.collect{|i| substances[i]} chunk = [training_substances,test_substances].collect do |substances| dataset = self.class.create(:name => "#{self.name} (Fold #{i-1})",:source => self.id ) substances.each do |substance| substance.dataset_ids << dataset.id substance.dataset_ids.uniq! substance.save dataset.data_entries[substance.id.to_s] = data_entries[substance.id.to_s] ||= {} end dataset.save dataset end start = last+1 chunks << chunk end chunks end
[ "def", "folds", "n", "len", "=", "self", ".", "substances", ".", "size", "indices", "=", "(", "0", "..", "len", "-", "1", ")", ".", "to_a", ".", "shuffle", "mid", "=", "(", "len", "/", "n", ")", "chunks", "=", "[", "]", "start", "=", "0", "1", ".", "upto", "(", "n", ")", "do", "|", "i", "|", "last", "=", "start", "+", "mid", "last", "=", "last", "-", "1", "unless", "len", "%", "n", ">=", "i", "test_idxs", "=", "indices", "[", "start", "..", "last", "]", "||", "[", "]", "test_substances", "=", "test_idxs", ".", "collect", "{", "|", "i", "|", "substances", "[", "i", "]", "}", "training_idxs", "=", "indices", "-", "test_idxs", "training_substances", "=", "training_idxs", ".", "collect", "{", "|", "i", "|", "substances", "[", "i", "]", "}", "chunk", "=", "[", "training_substances", ",", "test_substances", "]", ".", "collect", "do", "|", "substances", "|", "dataset", "=", "self", ".", "class", ".", "create", "(", ":name", "=>", "\"#{self.name} (Fold #{i-1})\"", ",", ":source", "=>", "self", ".", "id", ")", "substances", ".", "each", "do", "|", "substance", "|", "substance", ".", "dataset_ids", "<<", "dataset", ".", "id", "substance", ".", "dataset_ids", ".", "uniq!", "substance", ".", "save", "dataset", ".", "data_entries", "[", "substance", ".", "id", ".", "to_s", "]", "=", "data_entries", "[", "substance", ".", "id", ".", "to_s", "]", "||=", "{", "}", "end", "dataset", ".", "save", "dataset", "end", "start", "=", "last", "+", "1", "chunks", "<<", "chunk", "end", "chunks", "end" ]
Dataset operations Split a dataset into n folds @param [Integer] number of folds @return [Array] Array with folds [training_dataset,test_dataset]
[ "Dataset", "operations", "Split", "a", "dataset", "into", "n", "folds" ]
1ee7de09c969e16fd11522d22179224e694b0161
https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/dataset.rb#L73-L101
3,032
opentox/lazar
lib/dataset.rb
OpenTox.Dataset.to_csv
def to_csv(inchi=false) CSV.generate() do |csv| compound = substances.first.is_a? Compound if compound csv << [inchi ? "InChI" : "SMILES"] + features.collect{|f| f.name} else csv << ["Name"] + features.collect{|f| f.name} end substances.each do |substance| if compound name = (inchi ? substance.inchi : substance.smiles) else name = substance.name end nr_measurements = features.collect{|f| data_entries[substance.id.to_s][f.id.to_s].size if data_entries[substance.id.to_s][f.id.to_s]}.compact.uniq if nr_measurements.size > 1 warn "Unequal number of measurements (#{nr_measurements}) for '#{name}'. Skipping entries." else (0..nr_measurements.first-1).each do |i| row = [name] features.each do |f| values(substance,f) ? row << values(substance,f)[i] : row << "" end csv << row end end end end end
ruby
def to_csv(inchi=false) CSV.generate() do |csv| compound = substances.first.is_a? Compound if compound csv << [inchi ? "InChI" : "SMILES"] + features.collect{|f| f.name} else csv << ["Name"] + features.collect{|f| f.name} end substances.each do |substance| if compound name = (inchi ? substance.inchi : substance.smiles) else name = substance.name end nr_measurements = features.collect{|f| data_entries[substance.id.to_s][f.id.to_s].size if data_entries[substance.id.to_s][f.id.to_s]}.compact.uniq if nr_measurements.size > 1 warn "Unequal number of measurements (#{nr_measurements}) for '#{name}'. Skipping entries." else (0..nr_measurements.first-1).each do |i| row = [name] features.each do |f| values(substance,f) ? row << values(substance,f)[i] : row << "" end csv << row end end end end end
[ "def", "to_csv", "(", "inchi", "=", "false", ")", "CSV", ".", "generate", "(", ")", "do", "|", "csv", "|", "compound", "=", "substances", ".", "first", ".", "is_a?", "Compound", "if", "compound", "csv", "<<", "[", "inchi", "?", "\"InChI\"", ":", "\"SMILES\"", "]", "+", "features", ".", "collect", "{", "|", "f", "|", "f", ".", "name", "}", "else", "csv", "<<", "[", "\"Name\"", "]", "+", "features", ".", "collect", "{", "|", "f", "|", "f", ".", "name", "}", "end", "substances", ".", "each", "do", "|", "substance", "|", "if", "compound", "name", "=", "(", "inchi", "?", "substance", ".", "inchi", ":", "substance", ".", "smiles", ")", "else", "name", "=", "substance", ".", "name", "end", "nr_measurements", "=", "features", ".", "collect", "{", "|", "f", "|", "data_entries", "[", "substance", ".", "id", ".", "to_s", "]", "[", "f", ".", "id", ".", "to_s", "]", ".", "size", "if", "data_entries", "[", "substance", ".", "id", ".", "to_s", "]", "[", "f", ".", "id", ".", "to_s", "]", "}", ".", "compact", ".", "uniq", "if", "nr_measurements", ".", "size", ">", "1", "warn", "\"Unequal number of measurements (#{nr_measurements}) for '#{name}'. Skipping entries.\"", "else", "(", "0", "..", "nr_measurements", ".", "first", "-", "1", ")", ".", "each", "do", "|", "i", "|", "row", "=", "[", "name", "]", "features", ".", "each", "do", "|", "f", "|", "values", "(", "substance", ",", "f", ")", "?", "row", "<<", "values", "(", "substance", ",", "f", ")", "[", "i", "]", ":", "row", "<<", "\"\"", "end", "csv", "<<", "row", "end", "end", "end", "end", "end" ]
Serialisation Convert dataset to csv format including compound smiles as first column, other column headers are feature names @return [String]
[ "Serialisation", "Convert", "dataset", "to", "csv", "format", "including", "compound", "smiles", "as", "first", "column", "other", "column", "headers", "are", "feature", "names" ]
1ee7de09c969e16fd11522d22179224e694b0161
https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/dataset.rb#L107-L136
3,033
botanicus/rango
lib/rango/mixins/logger.rb
Rango.LoggerMixin.inspect
def inspect(*args) if args.first.is_a?(Hash) && args.length.eql?(1) args.first.each do |name, value| self.debug("#{name}: #{value.inspect}") end else args = args.map { |arg| arg.inspect } self.debug(*args) end end
ruby
def inspect(*args) if args.first.is_a?(Hash) && args.length.eql?(1) args.first.each do |name, value| self.debug("#{name}: #{value.inspect}") end else args = args.map { |arg| arg.inspect } self.debug(*args) end end
[ "def", "inspect", "(", "*", "args", ")", "if", "args", ".", "first", ".", "is_a?", "(", "Hash", ")", "&&", "args", ".", "length", ".", "eql?", "(", "1", ")", "args", ".", "first", ".", "each", "do", "|", "name", ",", "value", "|", "self", ".", "debug", "(", "\"#{name}: #{value.inspect}\"", ")", "end", "else", "args", "=", "args", ".", "map", "{", "|", "arg", "|", "arg", ".", "inspect", "}", "self", ".", "debug", "(", "args", ")", "end", "end" ]
Project.logger.inspect(@posts, item) Project.logger.inspect("@post" => @post) @since 0.0.1
[ "Project", ".", "logger", ".", "inspect", "(" ]
b8904453f3b7d3cd65e2bcc5236bfe645aa78e8e
https://github.com/botanicus/rango/blob/b8904453f3b7d3cd65e2bcc5236bfe645aa78e8e/lib/rango/mixins/logger.rb#L8-L17
3,034
github/graphql-relay-walker
lib/graphql/relay/walker/queue.rb
GraphQL::Relay::Walker.Queue.add
def add(frame) return false if max_size && queue.length >= max_size return false if seen.include?(frame.gid) seen.add(frame.gid) idx = random_idx ? rand(queue.length + 1) : queue.length queue.insert(idx, frame) true end
ruby
def add(frame) return false if max_size && queue.length >= max_size return false if seen.include?(frame.gid) seen.add(frame.gid) idx = random_idx ? rand(queue.length + 1) : queue.length queue.insert(idx, frame) true end
[ "def", "add", "(", "frame", ")", "return", "false", "if", "max_size", "&&", "queue", ".", "length", ">=", "max_size", "return", "false", "if", "seen", ".", "include?", "(", "frame", ".", "gid", ")", "seen", ".", "add", "(", "frame", ".", "gid", ")", "idx", "=", "random_idx", "?", "rand", "(", "queue", ".", "length", "+", "1", ")", ":", "queue", ".", "length", "queue", ".", "insert", "(", "idx", ",", "frame", ")", "true", "end" ]
Initialize a new Queue. max_size: - The maximum size the queue can grow to. This helps when walking a large graph by forcing us to walk deeper. random_idx: - Add frames to the queue at random indicies. This helps when walking a large graph by forcing us to walk deeper. Returns nothing. Add a frame to the queue if its GID hasn't been seen already and the queue hasn't exceeded its max size. frame - The Frame to add to the queue. Returns true if the frame was added, false otherwise.
[ "Initialize", "a", "new", "Queue", "." ]
1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7
https://github.com/github/graphql-relay-walker/blob/1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7/lib/graphql/relay/walker/queue.rb#L28-L37
3,035
github/graphql-relay-walker
lib/graphql/relay/walker/queue.rb
GraphQL::Relay::Walker.Queue.add_gid
def add_gid(gid, parent = nil) frame = Frame.new(self, gid, parent) add(frame) end
ruby
def add_gid(gid, parent = nil) frame = Frame.new(self, gid, parent) add(frame) end
[ "def", "add_gid", "(", "gid", ",", "parent", "=", "nil", ")", "frame", "=", "Frame", ".", "new", "(", "self", ",", "gid", ",", "parent", ")", "add", "(", "frame", ")", "end" ]
Add a GID to the queue. gid - The String GID to add to the queue. parent - The frame where this GID was discovered (optional). Returns true if a frame was added, false otherwise.
[ "Add", "a", "GID", "to", "the", "queue", "." ]
1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7
https://github.com/github/graphql-relay-walker/blob/1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7/lib/graphql/relay/walker/queue.rb#L45-L48
3,036
ShipCompliant/ship_compliant-ruby
lib/ship_compliant/get_inventory_details_result.rb
ShipCompliant.GetInventoryDetailsResult.location
def location(key) location = locations.select { |l| l[:fulfillment_location] == key }.first return {} if location.nil? location end
ruby
def location(key) location = locations.select { |l| l[:fulfillment_location] == key }.first return {} if location.nil? location end
[ "def", "location", "(", "key", ")", "location", "=", "locations", ".", "select", "{", "|", "l", "|", "l", "[", ":fulfillment_location", "]", "==", "key", "}", ".", "first", "return", "{", "}", "if", "location", ".", "nil?", "location", "end" ]
Finds a location by +FulfillmentLocation+. result.location('WineShipping')[:supplier] #=> 'LOCATION-SUPPLIER'
[ "Finds", "a", "location", "by", "+", "FulfillmentLocation", "+", "." ]
aa12852a58cd6cb7939eb9fbb7fdc03e46e18197
https://github.com/ShipCompliant/ship_compliant-ruby/blob/aa12852a58cd6cb7939eb9fbb7fdc03e46e18197/lib/ship_compliant/get_inventory_details_result.rb#L21-L26
3,037
ktonon/cog
lib/cog/config.rb
Cog.Config.prepare
def prepare(opt={}) throw :ConfigInstanceAlreadyPrepared if @prepared && !opt[:force_reset] @prepared = true @fullpaths = opt[:fullpaths] @project_path = nil @project_generator_path = nil @project_plugin_path = nil @project_template_path = nil @generator_path = [] @plugin_path = [] @template_path = [] @plugins = {} @target_language = Language.new @active_languages = [Language.new] # active language stack @language = {} @language_extension_map = {} process_cogfiles opt post_cogfile_processing build_language_extension_map end
ruby
def prepare(opt={}) throw :ConfigInstanceAlreadyPrepared if @prepared && !opt[:force_reset] @prepared = true @fullpaths = opt[:fullpaths] @project_path = nil @project_generator_path = nil @project_plugin_path = nil @project_template_path = nil @generator_path = [] @plugin_path = [] @template_path = [] @plugins = {} @target_language = Language.new @active_languages = [Language.new] # active language stack @language = {} @language_extension_map = {} process_cogfiles opt post_cogfile_processing build_language_extension_map end
[ "def", "prepare", "(", "opt", "=", "{", "}", ")", "throw", ":ConfigInstanceAlreadyPrepared", "if", "@prepared", "&&", "!", "opt", "[", ":force_reset", "]", "@prepared", "=", "true", "@fullpaths", "=", "opt", "[", ":fullpaths", "]", "@project_path", "=", "nil", "@project_generator_path", "=", "nil", "@project_plugin_path", "=", "nil", "@project_template_path", "=", "nil", "@generator_path", "=", "[", "]", "@plugin_path", "=", "[", "]", "@template_path", "=", "[", "]", "@plugins", "=", "{", "}", "@target_language", "=", "Language", ".", "new", "@active_languages", "=", "[", "Language", ".", "new", "]", "# active language stack", "@language", "=", "{", "}", "@language_extension_map", "=", "{", "}", "process_cogfiles", "opt", "post_cogfile_processing", "build_language_extension_map", "end" ]
Must be called once before using cog. In the context of a command-line invocation, this method will be called automatically. Outside of that context, for example in a unit test, it will have to be called manually. @option opt [Boolean] :fullpaths (false) when listing files, full paths should be shown @option opt [Boolean] :minimal (false) only load the built-in Cogfile @option opt [String] :project_cogfile_path (nil) explicitly specify the location of the project {DSL::Cogfile}. If not provided, it will be searched for. If none can be found, {#project?} will be +false+
[ "Must", "be", "called", "once", "before", "using", "cog", ".", "In", "the", "context", "of", "a", "command", "-", "line", "invocation", "this", "method", "will", "be", "called", "automatically", ".", "Outside", "of", "that", "context", "for", "example", "in", "a", "unit", "test", "it", "will", "have", "to", "be", "called", "manually", "." ]
156c81a0873135d7dc47c79c705c477893fff74a
https://github.com/ktonon/cog/blob/156c81a0873135d7dc47c79c705c477893fff74a/lib/cog/config.rb#L61-L81
3,038
ShipCompliant/ship_compliant-ruby
lib/ship_compliant/check_compliance_result.rb
ShipCompliant.CheckComplianceResult.taxes_for_shipment
def taxes_for_shipment(shipment_key) shipment = shipment_sales_tax_rates.select { |s| s[:@shipment_key] == shipment_key }.first # convert attribute keys to symbols freight = attributes_to_symbols(shipment[:freight_sales_tax_rate]) # wrap products in ProductSalesTaxRate products = wrap_products(shipment[:product_sales_tax_rates]) ShipmentSalesTaxRate.new(shipment_key, FreightSalesTaxRate.new(freight), products) end
ruby
def taxes_for_shipment(shipment_key) shipment = shipment_sales_tax_rates.select { |s| s[:@shipment_key] == shipment_key }.first # convert attribute keys to symbols freight = attributes_to_symbols(shipment[:freight_sales_tax_rate]) # wrap products in ProductSalesTaxRate products = wrap_products(shipment[:product_sales_tax_rates]) ShipmentSalesTaxRate.new(shipment_key, FreightSalesTaxRate.new(freight), products) end
[ "def", "taxes_for_shipment", "(", "shipment_key", ")", "shipment", "=", "shipment_sales_tax_rates", ".", "select", "{", "|", "s", "|", "s", "[", ":@shipment_key", "]", "==", "shipment_key", "}", ".", "first", "# convert attribute keys to symbols", "freight", "=", "attributes_to_symbols", "(", "shipment", "[", ":freight_sales_tax_rate", "]", ")", "# wrap products in ProductSalesTaxRate", "products", "=", "wrap_products", "(", "shipment", "[", ":product_sales_tax_rates", "]", ")", "ShipmentSalesTaxRate", ".", "new", "(", "shipment_key", ",", "FreightSalesTaxRate", ".", "new", "(", "freight", ")", ",", "products", ")", "end" ]
Access the tax information for a shipment. Returns an instance of ShipmentSalesTaxRate.
[ "Access", "the", "tax", "information", "for", "a", "shipment", ".", "Returns", "an", "instance", "of", "ShipmentSalesTaxRate", "." ]
aa12852a58cd6cb7939eb9fbb7fdc03e46e18197
https://github.com/ShipCompliant/ship_compliant-ruby/blob/aa12852a58cd6cb7939eb9fbb7fdc03e46e18197/lib/ship_compliant/check_compliance_result.rb#L30-L40
3,039
ShipCompliant/ship_compliant-ruby
lib/ship_compliant/check_compliance_result.rb
ShipCompliant.CheckComplianceResult.compliance_rules_for_shipment
def compliance_rules_for_shipment(shipment_key) shipment = shipment_compliance_rules.select { |s| s[:key] == shipment_key }.first ShipmentCompliance.new(shipment) end
ruby
def compliance_rules_for_shipment(shipment_key) shipment = shipment_compliance_rules.select { |s| s[:key] == shipment_key }.first ShipmentCompliance.new(shipment) end
[ "def", "compliance_rules_for_shipment", "(", "shipment_key", ")", "shipment", "=", "shipment_compliance_rules", ".", "select", "{", "|", "s", "|", "s", "[", ":key", "]", "==", "shipment_key", "}", ".", "first", "ShipmentCompliance", ".", "new", "(", "shipment", ")", "end" ]
Finds all the compliance rules for a shipment. Returns an instance of ShipmentCompliance. shipment_compliance = compliance_result.compliance_rules_for_shipment('SHIPMENT-KEY') puts shipment_compliance.compliant? #=> false
[ "Finds", "all", "the", "compliance", "rules", "for", "a", "shipment", ".", "Returns", "an", "instance", "of", "ShipmentCompliance", "." ]
aa12852a58cd6cb7939eb9fbb7fdc03e46e18197
https://github.com/ShipCompliant/ship_compliant-ruby/blob/aa12852a58cd6cb7939eb9fbb7fdc03e46e18197/lib/ship_compliant/check_compliance_result.rb#L62-L65
3,040
poise/poise-profiler
lib/poise_profiler/config.rb
PoiseProfiler.Config.gather_from_env
def gather_from_env ENV.each do |key, value| if key.downcase =~ /^poise(_|-)profiler_(.+)$/ self[$2] = YAML.safe_load(value) end end end
ruby
def gather_from_env ENV.each do |key, value| if key.downcase =~ /^poise(_|-)profiler_(.+)$/ self[$2] = YAML.safe_load(value) end end end
[ "def", "gather_from_env", "ENV", ".", "each", "do", "|", "key", ",", "value", "|", "if", "key", ".", "downcase", "=~", "/", "/", "self", "[", "$2", "]", "=", "YAML", ".", "safe_load", "(", "value", ")", "end", "end", "end" ]
Find configuration data in environment variables. This is the only option on Chef 12.0, 12.1, and 12.2. @api private
[ "Find", "configuration", "data", "in", "environment", "variables", ".", "This", "is", "the", "only", "option", "on", "Chef", "12", ".", "0", "12", ".", "1", "and", "12", ".", "2", "." ]
a190acc6bdd4fcdac34ef43bbe4f59dddb9c0f67
https://github.com/poise/poise-profiler/blob/a190acc6bdd4fcdac34ef43bbe4f59dddb9c0f67/lib/poise_profiler/config.rb#L49-L55
3,041
poise/poise-profiler
lib/poise_profiler/config.rb
PoiseProfiler.Config.gather_from_node
def gather_from_node return unless defined?(Chef.node) (Chef.node['poise-profiler'] || {}).each do |key, value| self[key] = value end end
ruby
def gather_from_node return unless defined?(Chef.node) (Chef.node['poise-profiler'] || {}).each do |key, value| self[key] = value end end
[ "def", "gather_from_node", "return", "unless", "defined?", "(", "Chef", ".", "node", ")", "(", "Chef", ".", "node", "[", "'poise-profiler'", "]", "||", "{", "}", ")", ".", "each", "do", "|", "key", ",", "value", "|", "self", "[", "key", "]", "=", "value", "end", "end" ]
Find configuration data in node attributes. @api private
[ "Find", "configuration", "data", "in", "node", "attributes", "." ]
a190acc6bdd4fcdac34ef43bbe4f59dddb9c0f67
https://github.com/poise/poise-profiler/blob/a190acc6bdd4fcdac34ef43bbe4f59dddb9c0f67/lib/poise_profiler/config.rb#L60-L65
3,042
ShipCompliant/ship_compliant-ruby
lib/ship_compliant/inventory_product.rb
ShipCompliant.InventoryProduct.inventory_levels
def inventory_levels levels = {} product[:inventory_levels][:inventory_level].each do |level| key = level[:inventory_type].underscore.to_sym value = level[:quantity].to_f levels[key] = value end levels end
ruby
def inventory_levels levels = {} product[:inventory_levels][:inventory_level].each do |level| key = level[:inventory_type].underscore.to_sym value = level[:quantity].to_f levels[key] = value end levels end
[ "def", "inventory_levels", "levels", "=", "{", "}", "product", "[", ":inventory_levels", "]", "[", ":inventory_level", "]", ".", "each", "do", "|", "level", "|", "key", "=", "level", "[", ":inventory_type", "]", ".", "underscore", ".", "to_sym", "value", "=", "level", "[", ":quantity", "]", ".", "to_f", "levels", "[", "key", "]", "=", "value", "end", "levels", "end" ]
Returns a Hash of inventory levels. - The key is the +InventoryType+. - The value is +Quantity+ as a float. product.inventory_levels #=> { available: 2, on_hold: 2, back_order: 4 }
[ "Returns", "a", "Hash", "of", "inventory", "levels", "." ]
aa12852a58cd6cb7939eb9fbb7fdc03e46e18197
https://github.com/ShipCompliant/ship_compliant-ruby/blob/aa12852a58cd6cb7939eb9fbb7fdc03e46e18197/lib/ship_compliant/inventory_product.rb#L82-L93
3,043
rossf7/elasticrawl
lib/elasticrawl/cluster.rb
Elasticrawl.Cluster.create_job_flow
def create_job_flow(job, emr_config = nil) config = Config.new Elasticity.configure do |c| c.access_key = config.access_key_id c.secret_key = config.secret_access_key end job_flow = Elasticity::JobFlow.new job_flow.name = "Job: #{job.job_name} #{job.job_desc}" job_flow.log_uri = job.log_uri configure_job_flow(job_flow) configure_instances(job_flow) configure_bootstrap_actions(job_flow, emr_config) job_flow end
ruby
def create_job_flow(job, emr_config = nil) config = Config.new Elasticity.configure do |c| c.access_key = config.access_key_id c.secret_key = config.secret_access_key end job_flow = Elasticity::JobFlow.new job_flow.name = "Job: #{job.job_name} #{job.job_desc}" job_flow.log_uri = job.log_uri configure_job_flow(job_flow) configure_instances(job_flow) configure_bootstrap_actions(job_flow, emr_config) job_flow end
[ "def", "create_job_flow", "(", "job", ",", "emr_config", "=", "nil", ")", "config", "=", "Config", ".", "new", "Elasticity", ".", "configure", "do", "|", "c", "|", "c", ".", "access_key", "=", "config", ".", "access_key_id", "c", ".", "secret_key", "=", "config", ".", "secret_access_key", "end", "job_flow", "=", "Elasticity", "::", "JobFlow", ".", "new", "job_flow", ".", "name", "=", "\"Job: #{job.job_name} #{job.job_desc}\"", "job_flow", ".", "log_uri", "=", "job", ".", "log_uri", "configure_job_flow", "(", "job_flow", ")", "configure_instances", "(", "job_flow", ")", "configure_bootstrap_actions", "(", "job_flow", ",", "emr_config", ")", "job_flow", "end" ]
Returns a configured job flow to the calling job.
[ "Returns", "a", "configured", "job", "flow", "to", "the", "calling", "job", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/cluster.rb#L12-L29
3,044
rossf7/elasticrawl
lib/elasticrawl/cluster.rb
Elasticrawl.Cluster.configure_job_flow
def configure_job_flow(job_flow) ec2_key_name = config_setting('ec2_key_name') placement = config_setting('placement') emr_ami_version = config_setting('emr_ami_version') job_flow_role = config_setting('job_flow_role') service_role = config_setting('service_role') ec2_subnet_id = config_setting('ec2_subnet_id') job_flow.ec2_subnet_id = ec2_subnet_id if ec2_subnet_id.present? job_flow.ec2_key_name = ec2_key_name if ec2_key_name.present? job_flow.placement = placement if placement.present? job_flow.ami_version = emr_ami_version if emr_ami_version.present? job_flow.job_flow_role = job_flow_role if job_flow_role.present? job_flow.service_role = service_role if service_role.present? end
ruby
def configure_job_flow(job_flow) ec2_key_name = config_setting('ec2_key_name') placement = config_setting('placement') emr_ami_version = config_setting('emr_ami_version') job_flow_role = config_setting('job_flow_role') service_role = config_setting('service_role') ec2_subnet_id = config_setting('ec2_subnet_id') job_flow.ec2_subnet_id = ec2_subnet_id if ec2_subnet_id.present? job_flow.ec2_key_name = ec2_key_name if ec2_key_name.present? job_flow.placement = placement if placement.present? job_flow.ami_version = emr_ami_version if emr_ami_version.present? job_flow.job_flow_role = job_flow_role if job_flow_role.present? job_flow.service_role = service_role if service_role.present? end
[ "def", "configure_job_flow", "(", "job_flow", ")", "ec2_key_name", "=", "config_setting", "(", "'ec2_key_name'", ")", "placement", "=", "config_setting", "(", "'placement'", ")", "emr_ami_version", "=", "config_setting", "(", "'emr_ami_version'", ")", "job_flow_role", "=", "config_setting", "(", "'job_flow_role'", ")", "service_role", "=", "config_setting", "(", "'service_role'", ")", "ec2_subnet_id", "=", "config_setting", "(", "'ec2_subnet_id'", ")", "job_flow", ".", "ec2_subnet_id", "=", "ec2_subnet_id", "if", "ec2_subnet_id", ".", "present?", "job_flow", ".", "ec2_key_name", "=", "ec2_key_name", "if", "ec2_key_name", ".", "present?", "job_flow", ".", "placement", "=", "placement", "if", "placement", ".", "present?", "job_flow", ".", "ami_version", "=", "emr_ami_version", "if", "emr_ami_version", ".", "present?", "job_flow", ".", "job_flow_role", "=", "job_flow_role", "if", "job_flow_role", ".", "present?", "job_flow", ".", "service_role", "=", "service_role", "if", "service_role", ".", "present?", "end" ]
Set job flow properties from settings in cluster.yml.
[ "Set", "job", "flow", "properties", "from", "settings", "in", "cluster", ".", "yml", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/cluster.rb#L44-L58
3,045
rossf7/elasticrawl
lib/elasticrawl/cluster.rb
Elasticrawl.Cluster.configure_bootstrap_actions
def configure_bootstrap_actions(job_flow, emr_config = nil) bootstrap_scripts = config_setting('bootstrap_scripts') if bootstrap_scripts.present? bootstrap_scripts.each do |script_uri| action = Elasticity::BootstrapAction.new(script_uri, '', '') job_flow.add_bootstrap_action(action) end end if emr_config.present? action = Elasticity::HadoopFileBootstrapAction.new(emr_config) job_flow.add_bootstrap_action(action) end end
ruby
def configure_bootstrap_actions(job_flow, emr_config = nil) bootstrap_scripts = config_setting('bootstrap_scripts') if bootstrap_scripts.present? bootstrap_scripts.each do |script_uri| action = Elasticity::BootstrapAction.new(script_uri, '', '') job_flow.add_bootstrap_action(action) end end if emr_config.present? action = Elasticity::HadoopFileBootstrapAction.new(emr_config) job_flow.add_bootstrap_action(action) end end
[ "def", "configure_bootstrap_actions", "(", "job_flow", ",", "emr_config", "=", "nil", ")", "bootstrap_scripts", "=", "config_setting", "(", "'bootstrap_scripts'", ")", "if", "bootstrap_scripts", ".", "present?", "bootstrap_scripts", ".", "each", "do", "|", "script_uri", "|", "action", "=", "Elasticity", "::", "BootstrapAction", ".", "new", "(", "script_uri", ",", "''", ",", "''", ")", "job_flow", ".", "add_bootstrap_action", "(", "action", ")", "end", "end", "if", "emr_config", ".", "present?", "action", "=", "Elasticity", "::", "HadoopFileBootstrapAction", ".", "new", "(", "emr_config", ")", "job_flow", ".", "add_bootstrap_action", "(", "action", ")", "end", "end" ]
Configures bootstrap actions that will be run when each instance is launched. EMR config is an XML file of Hadoop settings stored on S3. There are applied to each node by a bootstrap action.
[ "Configures", "bootstrap", "actions", "that", "will", "be", "run", "when", "each", "instance", "is", "launched", ".", "EMR", "config", "is", "an", "XML", "file", "of", "Hadoop", "settings", "stored", "on", "S3", ".", "There", "are", "applied", "to", "each", "node", "by", "a", "bootstrap", "action", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/cluster.rb#L71-L85
3,046
brasten/scruffy
lib/scruffy/components/legend.rb
Scruffy::Components.Legend.relevant_legend_info
def relevant_legend_info(layers, categories=(@options[:category] ? [@options[:category]] : @options[:categories])) legend_info = layers.inject([]) do |arr, layer| if categories.nil? || (categories.include?(layer.options[:category]) || (layer.options[:categories] && (categories & layer.options[:categories]).size > 0) ) data = layer.legend_data arr << data if data.is_a?(Hash) arr = arr + data if data.is_a?(Array) end arr end end
ruby
def relevant_legend_info(layers, categories=(@options[:category] ? [@options[:category]] : @options[:categories])) legend_info = layers.inject([]) do |arr, layer| if categories.nil? || (categories.include?(layer.options[:category]) || (layer.options[:categories] && (categories & layer.options[:categories]).size > 0) ) data = layer.legend_data arr << data if data.is_a?(Hash) arr = arr + data if data.is_a?(Array) end arr end end
[ "def", "relevant_legend_info", "(", "layers", ",", "categories", "=", "(", "@options", "[", ":category", "]", "?", "[", "@options", "[", ":category", "]", "]", ":", "@options", "[", ":categories", "]", ")", ")", "legend_info", "=", "layers", ".", "inject", "(", "[", "]", ")", "do", "|", "arr", ",", "layer", "|", "if", "categories", ".", "nil?", "||", "(", "categories", ".", "include?", "(", "layer", ".", "options", "[", ":category", "]", ")", "||", "(", "layer", ".", "options", "[", ":categories", "]", "&&", "(", "categories", "&", "layer", ".", "options", "[", ":categories", "]", ")", ".", "size", ">", "0", ")", ")", "data", "=", "layer", ".", "legend_data", "arr", "<<", "data", "if", "data", ".", "is_a?", "(", "Hash", ")", "arr", "=", "arr", "+", "data", "if", "data", ".", "is_a?", "(", "Array", ")", "end", "arr", "end", "end" ]
Collects Legend Info from the provided Layers. Automatically filters by legend's categories.
[ "Collects", "Legend", "Info", "from", "the", "provided", "Layers", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/components/legend.rb#L102-L114
3,047
ShipCompliant/ship_compliant-ruby
lib/ship_compliant/order_search.rb
ShipCompliant.OrderSearch.to_h
def to_h details.reject do |key| !KEYS.include?(key) end.deep_transform_keys { |key| key.to_s.camelize } end
ruby
def to_h details.reject do |key| !KEYS.include?(key) end.deep_transform_keys { |key| key.to_s.camelize } end
[ "def", "to_h", "details", ".", "reject", "do", "|", "key", "|", "!", "KEYS", ".", "include?", "(", "key", ")", "end", ".", "deep_transform_keys", "{", "|", "key", "|", "key", ".", "to_s", ".", "camelize", "}", "end" ]
Converts hash keys to Pascal case and rejects invalid keys. :sales_order_keys #=> 'SalesOrderKeys'
[ "Converts", "hash", "keys", "to", "Pascal", "case", "and", "rejects", "invalid", "keys", "." ]
aa12852a58cd6cb7939eb9fbb7fdc03e46e18197
https://github.com/ShipCompliant/ship_compliant-ruby/blob/aa12852a58cd6cb7939eb9fbb7fdc03e46e18197/lib/ship_compliant/order_search.rb#L86-L90
3,048
brasten/scruffy
lib/scruffy/renderers/cubed3d.rb
Scruffy::Renderers.Cubed3d.graph_block
def graph_block(graph_filter) block = Proc.new { |components| components << Scruffy::Components::Grid.new(:grid, :position => [10, 0], :size => [90, 89]) components << Scruffy::Components::ValueMarkers.new(:value_markers, :position => [0, 2], :size => [8, 89]) components << Scruffy::Components::DataMarkers.new(:data_markers, :position => [10, 92], :size => [90, 8]) components << Scruffy::Components::Graphs.new(:graphs, :position => [10, 0], :size => [90, 89], :only => graph_filter) } block end
ruby
def graph_block(graph_filter) block = Proc.new { |components| components << Scruffy::Components::Grid.new(:grid, :position => [10, 0], :size => [90, 89]) components << Scruffy::Components::ValueMarkers.new(:value_markers, :position => [0, 2], :size => [8, 89]) components << Scruffy::Components::DataMarkers.new(:data_markers, :position => [10, 92], :size => [90, 8]) components << Scruffy::Components::Graphs.new(:graphs, :position => [10, 0], :size => [90, 89], :only => graph_filter) } block end
[ "def", "graph_block", "(", "graph_filter", ")", "block", "=", "Proc", ".", "new", "{", "|", "components", "|", "components", "<<", "Scruffy", "::", "Components", "::", "Grid", ".", "new", "(", ":grid", ",", ":position", "=>", "[", "10", ",", "0", "]", ",", ":size", "=>", "[", "90", ",", "89", "]", ")", "components", "<<", "Scruffy", "::", "Components", "::", "ValueMarkers", ".", "new", "(", ":value_markers", ",", ":position", "=>", "[", "0", ",", "2", "]", ",", ":size", "=>", "[", "8", ",", "89", "]", ")", "components", "<<", "Scruffy", "::", "Components", "::", "DataMarkers", ".", "new", "(", ":data_markers", ",", ":position", "=>", "[", "10", ",", "92", "]", ",", ":size", "=>", "[", "90", ",", "8", "]", ")", "components", "<<", "Scruffy", "::", "Components", "::", "Graphs", ".", "new", "(", ":graphs", ",", ":position", "=>", "[", "10", ",", "0", "]", ",", ":size", "=>", "[", "90", ",", "89", "]", ",", ":only", "=>", "graph_filter", ")", "}", "block", "end" ]
Returns a typical graph layout. These are squeezed into viewports.
[ "Returns", "a", "typical", "graph", "layout", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/renderers/cubed3d.rb#L42-L51
3,049
rossf7/elasticrawl
lib/elasticrawl/job_step.rb
Elasticrawl.JobStep.job_flow_step
def job_flow_step(job_config) jar = job_config['jar'] max_files = self.job.max_files step_args = [] step_args[0] = job_config['class'] step_args[1] = self.input_paths step_args[2] = self.output_path # All arguments must be strings. step_args[3] = max_files.to_s if max_files.present? step = Elasticity::CustomJarStep.new(jar) step.name = set_step_name step.arguments = step_args step end
ruby
def job_flow_step(job_config) jar = job_config['jar'] max_files = self.job.max_files step_args = [] step_args[0] = job_config['class'] step_args[1] = self.input_paths step_args[2] = self.output_path # All arguments must be strings. step_args[3] = max_files.to_s if max_files.present? step = Elasticity::CustomJarStep.new(jar) step.name = set_step_name step.arguments = step_args step end
[ "def", "job_flow_step", "(", "job_config", ")", "jar", "=", "job_config", "[", "'jar'", "]", "max_files", "=", "self", ".", "job", ".", "max_files", "step_args", "=", "[", "]", "step_args", "[", "0", "]", "=", "job_config", "[", "'class'", "]", "step_args", "[", "1", "]", "=", "self", ".", "input_paths", "step_args", "[", "2", "]", "=", "self", ".", "output_path", "# All arguments must be strings.", "step_args", "[", "3", "]", "=", "max_files", ".", "to_s", "if", "max_files", ".", "present?", "step", "=", "Elasticity", "::", "CustomJarStep", ".", "new", "(", "jar", ")", "step", ".", "name", "=", "set_step_name", "step", ".", "arguments", "=", "step_args", "step", "end" ]
Returns a custom jar step that is configured with the jar location, class name and input and output paths. For parse jobs optionally specifies the maximum # of Common Crawl data files to process before the job exits.
[ "Returns", "a", "custom", "jar", "step", "that", "is", "configured", "with", "the", "jar", "location", "class", "name", "and", "input", "and", "output", "paths", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/job_step.rb#L14-L30
3,050
rossf7/elasticrawl
lib/elasticrawl/job_step.rb
Elasticrawl.JobStep.set_step_name
def set_step_name case self.job.type when 'Elasticrawl::ParseJob' if self.crawl_segment.present? max_files = self.job.max_files || 'all' "#{self.crawl_segment.segment_desc} Parsing: #{max_files}" end when 'Elasticrawl::CombineJob' paths = self.input_paths.split(',') "Combining #{paths.count} jobs" end end
ruby
def set_step_name case self.job.type when 'Elasticrawl::ParseJob' if self.crawl_segment.present? max_files = self.job.max_files || 'all' "#{self.crawl_segment.segment_desc} Parsing: #{max_files}" end when 'Elasticrawl::CombineJob' paths = self.input_paths.split(',') "Combining #{paths.count} jobs" end end
[ "def", "set_step_name", "case", "self", ".", "job", ".", "type", "when", "'Elasticrawl::ParseJob'", "if", "self", ".", "crawl_segment", ".", "present?", "max_files", "=", "self", ".", "job", ".", "max_files", "||", "'all'", "\"#{self.crawl_segment.segment_desc} Parsing: #{max_files}\"", "end", "when", "'Elasticrawl::CombineJob'", "paths", "=", "self", ".", "input_paths", ".", "split", "(", "','", ")", "\"Combining #{paths.count} jobs\"", "end", "end" ]
Sets the Elastic MapReduce job flow step name based on the type of job it belongs to.
[ "Sets", "the", "Elastic", "MapReduce", "job", "flow", "step", "name", "based", "on", "the", "type", "of", "job", "it", "belongs", "to", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/job_step.rb#L35-L46
3,051
github/graphql-relay-walker
lib/graphql/relay/walker/frame.rb
GraphQL::Relay::Walker.Frame.found_gids
def found_gids(data = result) [].tap do |ids| case data when Hash ids.concat(Array(data['id'])) ids.concat(found_gids(data.values)) when Array data.each { |datum| ids.concat(found_gids(datum)) } end end end
ruby
def found_gids(data = result) [].tap do |ids| case data when Hash ids.concat(Array(data['id'])) ids.concat(found_gids(data.values)) when Array data.each { |datum| ids.concat(found_gids(datum)) } end end end
[ "def", "found_gids", "(", "data", "=", "result", ")", "[", "]", ".", "tap", "do", "|", "ids", "|", "case", "data", "when", "Hash", "ids", ".", "concat", "(", "Array", "(", "data", "[", "'id'", "]", ")", ")", "ids", ".", "concat", "(", "found_gids", "(", "data", ".", "values", ")", ")", "when", "Array", "data", ".", "each", "{", "|", "datum", "|", "ids", ".", "concat", "(", "found_gids", "(", "datum", ")", ")", "}", "end", "end", "end" ]
The GIDs from this frame's results. Returns an Array of GID Strings.
[ "The", "GIDs", "from", "this", "frame", "s", "results", "." ]
1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7
https://github.com/github/graphql-relay-walker/blob/1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7/lib/graphql/relay/walker/frame.rb#L39-L49
3,052
burtcorp/humboldt
lib/ext/rubydoop.rb
Rubydoop.JobDefinition.secondary_sort
def secondary_sort(start_index, end_index) @job.set_partitioner_class(Hadoop::Mapreduce::Lib::Partition::BinaryPartitioner) Hadoop::Mapreduce::Lib::Partition::BinaryPartitioner.set_offsets(@job.configuration, start_index, end_index) @job.set_grouping_comparator_class(Humboldt::JavaLib::BinaryComparator) Humboldt::JavaLib::BinaryComparator.set_offsets(@job.configuration, start_index, end_index) end
ruby
def secondary_sort(start_index, end_index) @job.set_partitioner_class(Hadoop::Mapreduce::Lib::Partition::BinaryPartitioner) Hadoop::Mapreduce::Lib::Partition::BinaryPartitioner.set_offsets(@job.configuration, start_index, end_index) @job.set_grouping_comparator_class(Humboldt::JavaLib::BinaryComparator) Humboldt::JavaLib::BinaryComparator.set_offsets(@job.configuration, start_index, end_index) end
[ "def", "secondary_sort", "(", "start_index", ",", "end_index", ")", "@job", ".", "set_partitioner_class", "(", "Hadoop", "::", "Mapreduce", "::", "Lib", "::", "Partition", "::", "BinaryPartitioner", ")", "Hadoop", "::", "Mapreduce", "::", "Lib", "::", "Partition", "::", "BinaryPartitioner", ".", "set_offsets", "(", "@job", ".", "configuration", ",", "start_index", ",", "end_index", ")", "@job", ".", "set_grouping_comparator_class", "(", "Humboldt", "::", "JavaLib", "::", "BinaryComparator", ")", "Humboldt", "::", "JavaLib", "::", "BinaryComparator", ".", "set_offsets", "(", "@job", ".", "configuration", ",", "start_index", ",", "end_index", ")", "end" ]
Configures the job for secondary sort on the specified slice of the mapper output key. Hadoop comes with a partitioner that can partition the map output based on a slice of the map output key. Humboldt ships with a comparator that uses the same configuration. Together they can be used to implement secondary sort. Secondary sort is a mapreduce pattern where you emit a key, but partition and group only on a subset of that key. This has the result that each reduce invocation will see values grouped by the subset, but ordered by the whole key. It is used, among other things, to efficiently count distinct values. Say you want to count the number of distinct visitors to a site. Your input is pairs of site and visitor IDs. The naïve implementation is to emit the site as key and the visitor ID as value and then, in the reducer, collect all IDs in a set, and emit the site and the size of the set of IDs. This is very memory inefficient, and impractical. For any interesting amount of data you will not be able to keep all the visitor IDs in memory. What you do, instead, is to concatenate the site and visitor ID and emit that as key, and the visitor ID as value. It might seem wasteful to emit the visitor ID twice, but it's necessary since Hadoop will only give you the key for the first value in each group. You then instruct Hadoop to partition and group on just the site part of the key. Hadoop will still sort the values by their full key, so within each group the values will be sorted by visitor ID. In the reducer it's now trivial to loop over the values and just increment a counter each time the visitor ID changes. You configure which part of the key to partition and group by specifying the start and end _indexes_. The reason why they are indexes and not a start index and a length, like Ruby's `String#slice`, is that you also can use negative indexes to count from the end. Negative indexes are useful for example when you don't know how wide the part of the key that you want use is. In the example above if you use the domain to identify sites these can be of different length. If your visitor IDs are 20 characters you can use 0 and -21 as your indexes. @param [Fixnum] start_index The first index of the slice, negative numbers are counted from the end @param [Fixnum] end_index The last index of the slice, negative numbers are counted from the end @see http://hadoop.apache.org/docs/r2.7.1/api/org/apache/hadoop/mapreduce/lib/partition/BinaryPartitioner.html Hadoop's BinaryPartitioner
[ "Configures", "the", "job", "for", "secondary", "sort", "on", "the", "specified", "slice", "of", "the", "mapper", "output", "key", "." ]
fe5d18e0f90f02a884acfa4a60e3ebddd1e574c7
https://github.com/burtcorp/humboldt/blob/fe5d18e0f90f02a884acfa4a60e3ebddd1e574c7/lib/ext/rubydoop.rb#L125-L130
3,053
brasten/scruffy
lib/scruffy/layers/base.rb
Scruffy::Layers.Base.render
def render(svg, options) setup_variables(options) coords = generate_coordinates(options) draw(svg, coords, options) end
ruby
def render(svg, options) setup_variables(options) coords = generate_coordinates(options) draw(svg, coords, options) end
[ "def", "render", "(", "svg", ",", "options", ")", "setup_variables", "(", "options", ")", "coords", "=", "generate_coordinates", "(", "options", ")", "draw", "(", "svg", ",", "coords", ",", "options", ")", "end" ]
Returns a new Base object. Any options other that those specified below are stored in the @options variable for possible later use. This would be a good place to store options needed for a custom graph. Options: title:: Name/title of data group points:: Array of data points preferred_color:: Color used to render this graph, overrides theme color. preferred_outline:: Color used to render this graph outline, overrides theme outline. relevant_data:: Rarely used - indicates the data on this graph should not included in any graph data aggregations, such as averaging data points. style:: SVG polyline style. (default: 'fill-opacity: 0; stroke-opacity: 0.35') stroke_width:: numeric value for width of line (0.1 - 10, default: 1) relativestroke:: stroke-width relative to image size? true or false (default) shadow:: Display line shadow? true or false (default) dots:: Display co-ord dots? true or false (default) Builds SVG code for this graph using the provided Builder object. This method actually generates data needed by this graph, then passes the rendering responsibilities to Base#draw. svg:: a Builder object used to create SVG code.
[ "Returns", "a", "new", "Base", "object", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/base.rb#L83-L88
3,054
brasten/scruffy
lib/scruffy/layers/base.rb
Scruffy::Layers.Base.setup_variables
def setup_variables(options = {}) @color = (preferred_color || options.delete(:color)) @outline = (preferred_outline || options.delete(:outline)) @width, @height = options.delete(:size) @min_value, @max_value = options[:min_value], options[:max_value] @opacity = options[:opacity] || 1.0 @complexity = options[:complexity] end
ruby
def setup_variables(options = {}) @color = (preferred_color || options.delete(:color)) @outline = (preferred_outline || options.delete(:outline)) @width, @height = options.delete(:size) @min_value, @max_value = options[:min_value], options[:max_value] @opacity = options[:opacity] || 1.0 @complexity = options[:complexity] end
[ "def", "setup_variables", "(", "options", "=", "{", "}", ")", "@color", "=", "(", "preferred_color", "||", "options", ".", "delete", "(", ":color", ")", ")", "@outline", "=", "(", "preferred_outline", "||", "options", ".", "delete", "(", ":outline", ")", ")", "@width", ",", "@height", "=", "options", ".", "delete", "(", ":size", ")", "@min_value", ",", "@max_value", "=", "options", "[", ":min_value", "]", ",", "options", "[", ":max_value", "]", "@opacity", "=", "options", "[", ":opacity", "]", "||", "1.0", "@complexity", "=", "options", "[", ":complexity", "]", "end" ]
Sets up several variables that almost every graph layer will need to render itself.
[ "Sets", "up", "several", "variables", "that", "almost", "every", "graph", "layer", "will", "need", "to", "render", "itself", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/base.rb#L150-L157
3,055
ShipCompliant/ship_compliant-ruby
lib/ship_compliant/product_attributes.rb
ShipCompliant.ProductAttributes.to_h
def to_h details.deep_transform_keys do |key| # handle special cases pascal_key = key.to_s.camelize if SPECIAL_CASES.has_key?(key) pascal_key = SPECIAL_CASES[key] end pascal_key end end
ruby
def to_h details.deep_transform_keys do |key| # handle special cases pascal_key = key.to_s.camelize if SPECIAL_CASES.has_key?(key) pascal_key = SPECIAL_CASES[key] end pascal_key end end
[ "def", "to_h", "details", ".", "deep_transform_keys", "do", "|", "key", "|", "# handle special cases", "pascal_key", "=", "key", ".", "to_s", ".", "camelize", "if", "SPECIAL_CASES", ".", "has_key?", "(", "key", ")", "pascal_key", "=", "SPECIAL_CASES", "[", "key", "]", "end", "pascal_key", "end", "end" ]
Converts hash keys to Pascal case and handles special cases. :bottle_size_ml #=> 'BottleSizeML'
[ "Converts", "hash", "keys", "to", "Pascal", "case", "and", "handles", "special", "cases", "." ]
aa12852a58cd6cb7939eb9fbb7fdc03e46e18197
https://github.com/ShipCompliant/ship_compliant-ruby/blob/aa12852a58cd6cb7939eb9fbb7fdc03e46e18197/lib/ship_compliant/product_attributes.rb#L86-L96
3,056
fgrehm/tiny-rails
lib/tiny-rails/actions.rb
TinyRails.Actions.gem
def gem(*args) options = extract_options!(args) name, version = args # Set the message to be shown in logs. Uses the git repo if one is given, # otherwise use name (version). parts, message = [ name.inspect ], name if version ||= options.delete(:version) parts << version.inspect message << " (#{version})" end message = options[:git] if options[:git] say_status :gemfile, message options.each do |option, value| parts << "#{option}: #{value.inspect}" end in_root do str = "gem #{parts.join(", ")}" str = "\n" + str append_file "Gemfile", str, :verbose => false end end
ruby
def gem(*args) options = extract_options!(args) name, version = args # Set the message to be shown in logs. Uses the git repo if one is given, # otherwise use name (version). parts, message = [ name.inspect ], name if version ||= options.delete(:version) parts << version.inspect message << " (#{version})" end message = options[:git] if options[:git] say_status :gemfile, message options.each do |option, value| parts << "#{option}: #{value.inspect}" end in_root do str = "gem #{parts.join(", ")}" str = "\n" + str append_file "Gemfile", str, :verbose => false end end
[ "def", "gem", "(", "*", "args", ")", "options", "=", "extract_options!", "(", "args", ")", "name", ",", "version", "=", "args", "# Set the message to be shown in logs. Uses the git repo if one is given,", "# otherwise use name (version).", "parts", ",", "message", "=", "[", "name", ".", "inspect", "]", ",", "name", "if", "version", "||=", "options", ".", "delete", "(", ":version", ")", "parts", "<<", "version", ".", "inspect", "message", "<<", "\" (#{version})\"", "end", "message", "=", "options", "[", ":git", "]", "if", "options", "[", ":git", "]", "say_status", ":gemfile", ",", "message", "options", ".", "each", "do", "|", "option", ",", "value", "|", "parts", "<<", "\"#{option}: #{value.inspect}\"", "end", "in_root", "do", "str", "=", "\"gem #{parts.join(\", \")}\"", "str", "=", "\"\\n\"", "+", "str", "append_file", "\"Gemfile\"", ",", "str", ",", ":verbose", "=>", "false", "end", "end" ]
Adds an entry into Gemfile for the supplied gem. gem "rspec", group: :test gem "technoweenie-restful-authentication", lib: "restful-authentication", source: "http://gems.github.com/" gem "rails", "3.0", git: "git://github.com/rails/rails"
[ "Adds", "an", "entry", "into", "Gemfile", "for", "the", "supplied", "gem", "." ]
a73d83d868f1466a666af7c81b5cd2ff4dabd51f
https://github.com/fgrehm/tiny-rails/blob/a73d83d868f1466a666af7c81b5cd2ff4dabd51f/lib/tiny-rails/actions.rb#L9-L33
3,057
fgrehm/tiny-rails
lib/tiny-rails/actions.rb
TinyRails.Actions.application
def application(data=nil, &block) data = block.call if !data && block_given? data = "\n#{data}" unless data =~ /^\n/ data << "\n" unless data =~ /\n$/ inject_into_file 'boot.rb', data, :after => /^ config\.secret_token = .+\n/ end
ruby
def application(data=nil, &block) data = block.call if !data && block_given? data = "\n#{data}" unless data =~ /^\n/ data << "\n" unless data =~ /\n$/ inject_into_file 'boot.rb', data, :after => /^ config\.secret_token = .+\n/ end
[ "def", "application", "(", "data", "=", "nil", ",", "&", "block", ")", "data", "=", "block", ".", "call", "if", "!", "data", "&&", "block_given?", "data", "=", "\"\\n#{data}\"", "unless", "data", "=~", "/", "\\n", "/", "data", "<<", "\"\\n\"", "unless", "data", "=~", "/", "\\n", "/", "inject_into_file", "'boot.rb'", ",", "data", ",", ":after", "=>", "/", "\\.", "\\n", "/", "end" ]
Appends a line inside the TinyRailsApp class on boot.rb. application do "config.assets.enabled = true" end
[ "Appends", "a", "line", "inside", "the", "TinyRailsApp", "class", "on", "boot", ".", "rb", "." ]
a73d83d868f1466a666af7c81b5cd2ff4dabd51f
https://github.com/fgrehm/tiny-rails/blob/a73d83d868f1466a666af7c81b5cd2ff4dabd51f/lib/tiny-rails/actions.rb#L40-L47
3,058
eladmeidar/MongoMysqlRelations
lib/mongo_mysql_relations.rb
MongoMysqlRelations.ClassMethods.to_mysql_belongs_to
def to_mysql_belongs_to(name, options = {}) field "#{name}_id", type: Integer object_class = options[:class] || name.to_s.titleize.delete(' ').constantize self.instance_eval do define_method(name) do |reload = false| if reload self.instance_variable_set("@#{name}", nil) end if self.instance_variable_get("@#{name}").blank? self.instance_variable_set("@#{name}", object_class.where(object_class.primary_key => self.send("#{name}_id")).first) end self.instance_variable_get("@#{name}") end define_method("#{name}=(new_instance)") do self.send("#{name}_id=", new_instance.id) self.instance_variable_set("@#{name}", nil) end end end
ruby
def to_mysql_belongs_to(name, options = {}) field "#{name}_id", type: Integer object_class = options[:class] || name.to_s.titleize.delete(' ').constantize self.instance_eval do define_method(name) do |reload = false| if reload self.instance_variable_set("@#{name}", nil) end if self.instance_variable_get("@#{name}").blank? self.instance_variable_set("@#{name}", object_class.where(object_class.primary_key => self.send("#{name}_id")).first) end self.instance_variable_get("@#{name}") end define_method("#{name}=(new_instance)") do self.send("#{name}_id=", new_instance.id) self.instance_variable_set("@#{name}", nil) end end end
[ "def", "to_mysql_belongs_to", "(", "name", ",", "options", "=", "{", "}", ")", "field", "\"#{name}_id\"", ",", "type", ":", "Integer", "object_class", "=", "options", "[", ":class", "]", "||", "name", ".", "to_s", ".", "titleize", ".", "delete", "(", "' '", ")", ".", "constantize", "self", ".", "instance_eval", "do", "define_method", "(", "name", ")", "do", "|", "reload", "=", "false", "|", "if", "reload", "self", ".", "instance_variable_set", "(", "\"@#{name}\"", ",", "nil", ")", "end", "if", "self", ".", "instance_variable_get", "(", "\"@#{name}\"", ")", ".", "blank?", "self", ".", "instance_variable_set", "(", "\"@#{name}\"", ",", "object_class", ".", "where", "(", "object_class", ".", "primary_key", "=>", "self", ".", "send", "(", "\"#{name}_id\"", ")", ")", ".", "first", ")", "end", "self", ".", "instance_variable_get", "(", "\"@#{name}\"", ")", "end", "define_method", "(", "\"#{name}=(new_instance)\"", ")", "do", "self", ".", "send", "(", "\"#{name}_id=\"", ",", "new_instance", ".", "id", ")", "self", ".", "instance_variable_set", "(", "\"@#{name}\"", ",", "nil", ")", "end", "end", "end" ]
Connection methods from mongoid to mysql
[ "Connection", "methods", "from", "mongoid", "to", "mysql" ]
b445be7b87120d5ce45fc1d7fd9f38ee07791fef
https://github.com/eladmeidar/MongoMysqlRelations/blob/b445be7b87120d5ce45fc1d7fd9f38ee07791fef/lib/mongo_mysql_relations.rb#L13-L34
3,059
github/graphql-relay-walker
lib/graphql/relay/walker/query_builder.rb
GraphQL::Relay::Walker.QueryBuilder.build_query
def build_query GraphQL.parse(BASE_QUERY).tap do |d_ast| selections = d_ast.definitions.first.selections.first.selections node_types.each do |type| selections << inline_fragment_ast(type) if include?(type) end selections.compact! end end
ruby
def build_query GraphQL.parse(BASE_QUERY).tap do |d_ast| selections = d_ast.definitions.first.selections.first.selections node_types.each do |type| selections << inline_fragment_ast(type) if include?(type) end selections.compact! end end
[ "def", "build_query", "GraphQL", ".", "parse", "(", "BASE_QUERY", ")", ".", "tap", "do", "|", "d_ast", "|", "selections", "=", "d_ast", ".", "definitions", ".", "first", ".", "selections", ".", "first", ".", "selections", "node_types", ".", "each", "do", "|", "type", "|", "selections", "<<", "inline_fragment_ast", "(", "type", ")", "if", "include?", "(", "type", ")", "end", "selections", ".", "compact!", "end", "end" ]
Build a query for our relay schema that selects an inline fragment for every node type. For every inline fragment, we select the ID of every node field and connection. Returns a GraphQL::Language::Nodes::Document instance.
[ "Build", "a", "query", "for", "our", "relay", "schema", "that", "selects", "an", "inline", "fragment", "for", "every", "node", "type", ".", "For", "every", "inline", "fragment", "we", "select", "the", "ID", "of", "every", "node", "field", "and", "connection", "." ]
1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7
https://github.com/github/graphql-relay-walker/blob/1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7/lib/graphql/relay/walker/query_builder.rb#L37-L47
3,060
github/graphql-relay-walker
lib/graphql/relay/walker/query_builder.rb
GraphQL::Relay::Walker.QueryBuilder.inline_fragment_ast
def inline_fragment_ast(type, with_children: true) selections = [] if with_children type.all_fields.each do |field| field_type = field.type.unwrap if node_field?(field) && include?(field_type) selections << node_field_ast(field) elsif connection_field?(field) && include?(field_type) selections << connection_field_ast(field) end end elsif id = type.get_field('id') selections << field_ast(id) end selections.compact! if selections.none? nil else GraphQL::Language::Nodes::InlineFragment.new( type: make_type_name_node(type.name), selections: selections, ) end end
ruby
def inline_fragment_ast(type, with_children: true) selections = [] if with_children type.all_fields.each do |field| field_type = field.type.unwrap if node_field?(field) && include?(field_type) selections << node_field_ast(field) elsif connection_field?(field) && include?(field_type) selections << connection_field_ast(field) end end elsif id = type.get_field('id') selections << field_ast(id) end selections.compact! if selections.none? nil else GraphQL::Language::Nodes::InlineFragment.new( type: make_type_name_node(type.name), selections: selections, ) end end
[ "def", "inline_fragment_ast", "(", "type", ",", "with_children", ":", "true", ")", "selections", "=", "[", "]", "if", "with_children", "type", ".", "all_fields", ".", "each", "do", "|", "field", "|", "field_type", "=", "field", ".", "type", ".", "unwrap", "if", "node_field?", "(", "field", ")", "&&", "include?", "(", "field_type", ")", "selections", "<<", "node_field_ast", "(", "field", ")", "elsif", "connection_field?", "(", "field", ")", "&&", "include?", "(", "field_type", ")", "selections", "<<", "connection_field_ast", "(", "field", ")", "end", "end", "elsif", "id", "=", "type", ".", "get_field", "(", "'id'", ")", "selections", "<<", "field_ast", "(", "id", ")", "end", "selections", ".", "compact!", "if", "selections", ".", "none?", "nil", "else", "GraphQL", "::", "Language", "::", "Nodes", "::", "InlineFragment", ".", "new", "(", "type", ":", "make_type_name_node", "(", "type", ".", "name", ")", ",", "selections", ":", "selections", ",", ")", "end", "end" ]
Make an inline fragment AST. type - The GraphQL::ObjectType instance to make the fragment for. with_children: - Boolean. Whether to select all children of this inline fragment, or just it's ID. Returns a GraphQL::Language::Nodes::InlineFragment instance or nil if the created AST was invalid for having no selections.
[ "Make", "an", "inline", "fragment", "AST", "." ]
1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7
https://github.com/github/graphql-relay-walker/blob/1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7/lib/graphql/relay/walker/query_builder.rb#L70-L95
3,061
github/graphql-relay-walker
lib/graphql/relay/walker/query_builder.rb
GraphQL::Relay::Walker.QueryBuilder.field_ast
def field_ast(field, arguments = {}, &blk) type = field.type.unwrap # Bail unless we have the required arguments. required_args_are_present = field.arguments.all? do |arg_name, arg| arguments.key?(arg_name) || valid_input?(arg.type, nil) end if !required_args_are_present nil else f_alias = field.name == 'id' ? nil : random_alias f_args = arguments.map do |name, value| GraphQL::Language::Nodes::Argument.new(name: name, value: value) end GraphQL::Language::Nodes::Field.new(name: field.name, alias: f_alias, arguments: f_args) end end
ruby
def field_ast(field, arguments = {}, &blk) type = field.type.unwrap # Bail unless we have the required arguments. required_args_are_present = field.arguments.all? do |arg_name, arg| arguments.key?(arg_name) || valid_input?(arg.type, nil) end if !required_args_are_present nil else f_alias = field.name == 'id' ? nil : random_alias f_args = arguments.map do |name, value| GraphQL::Language::Nodes::Argument.new(name: name, value: value) end GraphQL::Language::Nodes::Field.new(name: field.name, alias: f_alias, arguments: f_args) end end
[ "def", "field_ast", "(", "field", ",", "arguments", "=", "{", "}", ",", "&", "blk", ")", "type", "=", "field", ".", "type", ".", "unwrap", "# Bail unless we have the required arguments.", "required_args_are_present", "=", "field", ".", "arguments", ".", "all?", "do", "|", "arg_name", ",", "arg", "|", "arguments", ".", "key?", "(", "arg_name", ")", "||", "valid_input?", "(", "arg", ".", "type", ",", "nil", ")", "end", "if", "!", "required_args_are_present", "nil", "else", "f_alias", "=", "field", ".", "name", "==", "'id'", "?", "nil", ":", "random_alias", "f_args", "=", "arguments", ".", "map", "do", "|", "name", ",", "value", "|", "GraphQL", "::", "Language", "::", "Nodes", "::", "Argument", ".", "new", "(", "name", ":", "name", ",", "value", ":", "value", ")", "end", "GraphQL", "::", "Language", "::", "Nodes", "::", "Field", ".", "new", "(", "name", ":", "field", ".", "name", ",", "alias", ":", "f_alias", ",", "arguments", ":", "f_args", ")", "end", "end" ]
Make a field AST. field - The GraphQL::Field instance to make the fragment for. arguments - A Hash of arguments to include in the field. &blk - A block to call with the AST and field type before returning the AST. Returns a GraphQL::Language::Nodes::Field instance or nil if the created AST was invalid for having no selections or missing required arguments.
[ "Make", "a", "field", "AST", "." ]
1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7
https://github.com/github/graphql-relay-walker/blob/1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7/lib/graphql/relay/walker/query_builder.rb#L106-L124
3,062
github/graphql-relay-walker
lib/graphql/relay/walker/query_builder.rb
GraphQL::Relay::Walker.QueryBuilder.node_field_ast
def node_field_ast(field) f_ast = field_ast(field) return nil if f_ast.nil? type = field.type.unwrap selections = f_ast.selections.dup if type.kind.object? selections << field_ast(type.get_field('id')) else possible_node_types(type).each do |if_type| selections << inline_fragment_ast(if_type, with_children: false) end end selections.compact! if f_ast.respond_to?(:merge) # GraphQL-Ruby 1.9+ f_ast = f_ast.merge(selections: selections) else f_ast.selections = selections end f_ast end
ruby
def node_field_ast(field) f_ast = field_ast(field) return nil if f_ast.nil? type = field.type.unwrap selections = f_ast.selections.dup if type.kind.object? selections << field_ast(type.get_field('id')) else possible_node_types(type).each do |if_type| selections << inline_fragment_ast(if_type, with_children: false) end end selections.compact! if f_ast.respond_to?(:merge) # GraphQL-Ruby 1.9+ f_ast = f_ast.merge(selections: selections) else f_ast.selections = selections end f_ast end
[ "def", "node_field_ast", "(", "field", ")", "f_ast", "=", "field_ast", "(", "field", ")", "return", "nil", "if", "f_ast", ".", "nil?", "type", "=", "field", ".", "type", ".", "unwrap", "selections", "=", "f_ast", ".", "selections", ".", "dup", "if", "type", ".", "kind", ".", "object?", "selections", "<<", "field_ast", "(", "type", ".", "get_field", "(", "'id'", ")", ")", "else", "possible_node_types", "(", "type", ")", ".", "each", "do", "|", "if_type", "|", "selections", "<<", "inline_fragment_ast", "(", "if_type", ",", "with_children", ":", "false", ")", "end", "end", "selections", ".", "compact!", "if", "f_ast", ".", "respond_to?", "(", ":merge", ")", "# GraphQL-Ruby 1.9+", "f_ast", "=", "f_ast", ".", "merge", "(", "selections", ":", "selections", ")", "else", "f_ast", ".", "selections", "=", "selections", "end", "f_ast", "end" ]
Make a field AST for a node field. field - The GraphQL::Field instance to make the fragment for. Returns a GraphQL::Language::Nodes::Field instance.
[ "Make", "a", "field", "AST", "for", "a", "node", "field", "." ]
1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7
https://github.com/github/graphql-relay-walker/blob/1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7/lib/graphql/relay/walker/query_builder.rb#L131-L153
3,063
github/graphql-relay-walker
lib/graphql/relay/walker/query_builder.rb
GraphQL::Relay::Walker.QueryBuilder.edges_field_ast
def edges_field_ast(field) f_ast = field_ast(field) return nil if f_ast.nil? node_fields = [node_field_ast(field.type.unwrap.get_field('node'))] if f_ast.respond_to?(:merge) # GraphQL-Ruby 1.9+ f_ast.merge(selections: f_ast.selections + node_fields) else f_ast.selections.concat(node_fields) f_ast end end
ruby
def edges_field_ast(field) f_ast = field_ast(field) return nil if f_ast.nil? node_fields = [node_field_ast(field.type.unwrap.get_field('node'))] if f_ast.respond_to?(:merge) # GraphQL-Ruby 1.9+ f_ast.merge(selections: f_ast.selections + node_fields) else f_ast.selections.concat(node_fields) f_ast end end
[ "def", "edges_field_ast", "(", "field", ")", "f_ast", "=", "field_ast", "(", "field", ")", "return", "nil", "if", "f_ast", ".", "nil?", "node_fields", "=", "[", "node_field_ast", "(", "field", ".", "type", ".", "unwrap", ".", "get_field", "(", "'node'", ")", ")", "]", "if", "f_ast", ".", "respond_to?", "(", ":merge", ")", "# GraphQL-Ruby 1.9+", "f_ast", ".", "merge", "(", "selections", ":", "f_ast", ".", "selections", "+", "node_fields", ")", "else", "f_ast", ".", "selections", ".", "concat", "(", "node_fields", ")", "f_ast", "end", "end" ]
Make a field AST for an edges field. field - The GraphQL::Field instance to make the fragment for. Returns a GraphQL::Language::Nodes::Field instance.
[ "Make", "a", "field", "AST", "for", "an", "edges", "field", "." ]
1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7
https://github.com/github/graphql-relay-walker/blob/1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7/lib/graphql/relay/walker/query_builder.rb#L160-L170
3,064
github/graphql-relay-walker
lib/graphql/relay/walker/query_builder.rb
GraphQL::Relay::Walker.QueryBuilder.connection_field_ast
def connection_field_ast(field) f_ast = field_ast(field, connection_arguments) return nil if f_ast.nil? edges_fields = [edges_field_ast(field.type.unwrap.get_field('edges'))] if f_ast.respond_to?(:merge) # GraphQL-Ruby 1.9+ f_ast.merge(selections: f_ast.selections + edges_fields) else f_ast.selections.concat(edges_fields) f_ast end end
ruby
def connection_field_ast(field) f_ast = field_ast(field, connection_arguments) return nil if f_ast.nil? edges_fields = [edges_field_ast(field.type.unwrap.get_field('edges'))] if f_ast.respond_to?(:merge) # GraphQL-Ruby 1.9+ f_ast.merge(selections: f_ast.selections + edges_fields) else f_ast.selections.concat(edges_fields) f_ast end end
[ "def", "connection_field_ast", "(", "field", ")", "f_ast", "=", "field_ast", "(", "field", ",", "connection_arguments", ")", "return", "nil", "if", "f_ast", ".", "nil?", "edges_fields", "=", "[", "edges_field_ast", "(", "field", ".", "type", ".", "unwrap", ".", "get_field", "(", "'edges'", ")", ")", "]", "if", "f_ast", ".", "respond_to?", "(", ":merge", ")", "# GraphQL-Ruby 1.9+", "f_ast", ".", "merge", "(", "selections", ":", "f_ast", ".", "selections", "+", "edges_fields", ")", "else", "f_ast", ".", "selections", ".", "concat", "(", "edges_fields", ")", "f_ast", "end", "end" ]
Make a field AST for a connection field. field - The GraphQL::Field instance to make the fragment for. Returns a GraphQL::Language::Nodes::Field instance or nil if the created AST was invalid for missing required arguments.
[ "Make", "a", "field", "AST", "for", "a", "connection", "field", "." ]
1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7
https://github.com/github/graphql-relay-walker/blob/1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7/lib/graphql/relay/walker/query_builder.rb#L178-L188
3,065
github/graphql-relay-walker
lib/graphql/relay/walker/query_builder.rb
GraphQL::Relay::Walker.QueryBuilder.node_field?
def node_field?(field) type = field.type.unwrap kind = type.kind if kind.object? node_types.include?(type) elsif kind.interface? || kind.union? possible_node_types(type).any? end end
ruby
def node_field?(field) type = field.type.unwrap kind = type.kind if kind.object? node_types.include?(type) elsif kind.interface? || kind.union? possible_node_types(type).any? end end
[ "def", "node_field?", "(", "field", ")", "type", "=", "field", ".", "type", ".", "unwrap", "kind", "=", "type", ".", "kind", "if", "kind", ".", "object?", "node_types", ".", "include?", "(", "type", ")", "elsif", "kind", ".", "interface?", "||", "kind", ".", "union?", "possible_node_types", "(", "type", ")", ".", "any?", "end", "end" ]
Is this field for a relay node? field - A GraphQL::Field instance. Returns true if the field's type includes the `Node` interface or is a union or interface with a possible type that includes the `Node` interface Returns false otherwise.
[ "Is", "this", "field", "for", "a", "relay", "node?" ]
1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7
https://github.com/github/graphql-relay-walker/blob/1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7/lib/graphql/relay/walker/query_builder.rb#L197-L206
3,066
github/graphql-relay-walker
lib/graphql/relay/walker/query_builder.rb
GraphQL::Relay::Walker.QueryBuilder.connection_field?
def connection_field?(field) type = field.type.unwrap if edges_field = type.get_field('edges') edges = edges_field.type.unwrap if node_field = edges.get_field('node') return node_field?(node_field) end end false end
ruby
def connection_field?(field) type = field.type.unwrap if edges_field = type.get_field('edges') edges = edges_field.type.unwrap if node_field = edges.get_field('node') return node_field?(node_field) end end false end
[ "def", "connection_field?", "(", "field", ")", "type", "=", "field", ".", "type", ".", "unwrap", "if", "edges_field", "=", "type", ".", "get_field", "(", "'edges'", ")", "edges", "=", "edges_field", ".", "type", ".", "unwrap", "if", "node_field", "=", "edges", ".", "get_field", "(", "'node'", ")", "return", "node_field?", "(", "node_field", ")", "end", "end", "false", "end" ]
Is this field for a relay connection? field - A GraphQL::Field instance. Returns true if this field's type has a `edges` field whose type has a `node` field that is a relay node. Returns false otherwise.
[ "Is", "this", "field", "for", "a", "relay", "connection?" ]
1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7
https://github.com/github/graphql-relay-walker/blob/1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7/lib/graphql/relay/walker/query_builder.rb#L214-L225
3,067
github/graphql-relay-walker
lib/graphql/relay/walker/query_builder.rb
GraphQL::Relay::Walker.QueryBuilder.possible_types
def possible_types(type) if type.kind.interface? schema.possible_types(type) elsif type.kind.union? type.possible_types end end
ruby
def possible_types(type) if type.kind.interface? schema.possible_types(type) elsif type.kind.union? type.possible_types end end
[ "def", "possible_types", "(", "type", ")", "if", "type", ".", "kind", ".", "interface?", "schema", ".", "possible_types", "(", "type", ")", "elsif", "type", ".", "kind", ".", "union?", "type", ".", "possible_types", "end", "end" ]
Get the possible types of a union or interface. type - A GraphQL::UnionType or GraphQL::InterfaceType instance. Returns an Array of GraphQL::ObjectType instances.
[ "Get", "the", "possible", "types", "of", "a", "union", "or", "interface", "." ]
1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7
https://github.com/github/graphql-relay-walker/blob/1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7/lib/graphql/relay/walker/query_builder.rb#L232-L238
3,068
ShipCompliant/ship_compliant-ruby
lib/ship_compliant/shipment_compliance.rb
ShipCompliant.ShipmentCompliance.rules
def rules return [] if result[:rules].nil? Array.wrap(result[:rules][:rule_compliance_response]).map do |rule| ComplianceRule.new(rule) end end
ruby
def rules return [] if result[:rules].nil? Array.wrap(result[:rules][:rule_compliance_response]).map do |rule| ComplianceRule.new(rule) end end
[ "def", "rules", "return", "[", "]", "if", "result", "[", ":rules", "]", ".", "nil?", "Array", ".", "wrap", "(", "result", "[", ":rules", "]", "[", ":rule_compliance_response", "]", ")", ".", "map", "do", "|", "rule", "|", "ComplianceRule", ".", "new", "(", "rule", ")", "end", "end" ]
Wraps the +RuleComplianceResponse+ nodes with ComplianceRule. compliance_errors = shipment.rules.reject { |r| r.compliant? }
[ "Wraps", "the", "+", "RuleComplianceResponse", "+", "nodes", "with", "ComplianceRule", "." ]
aa12852a58cd6cb7939eb9fbb7fdc03e46e18197
https://github.com/ShipCompliant/ship_compliant-ruby/blob/aa12852a58cd6cb7939eb9fbb7fdc03e46e18197/lib/ship_compliant/shipment_compliance.rb#L20-L25
3,069
kishanio/CCAvenue-Ruby-Gem
lib/ccavenue.rb
Ccavenue.Payment.request
def request(order_Id,amount,billing_cust_name,billing_cust_address,billing_cust_city,billing_zip_code,billing_cust_state,billing_cust_country,billing_cust_email,billing_cust_tel,billing_cust_notes="",delivery_cust_name="",delivery_cust_address="",delivery_cust_city="",delivery_zip_code="",delivery_cust_state="",delivery_cust_country="",delivery_cust_email="",delivery_cust_tel="",delivery_cust_notes="") checksum = getChecksum(order_Id,amount) raw_request = "Merchant_Id=#{@merchant_Id}&Amount=#{amount}&Order_Id=#{order_Id}&Redirect_Url=#{@redirect_Url}&billing_cust_name=#{billing_cust_name}&billing_cust_address=#{billing_cust_address}&billing_cust_country=#{billing_cust_country}&billing_cust_state=#{billing_cust_state}&billing_cust_city=#{billing_cust_city}&billing_zip_code=#{billing_zip_code}&billing_cust_tel=#{billing_cust_tel}&billing_cust_email=#{billing_cust_email}&billing_cust_notes=#{billing_cust_notes}&delivery_cust_name=#{delivery_cust_name}&delivery_cust_address=#{delivery_cust_address}&delivery_cust_country=#{delivery_cust_country}&delivery_cust_state=#{delivery_cust_state}&delivery_cust_city=#{delivery_cust_city}&delivery_zip_code=#{delivery_zip_code}&delivery_cust_tel=#{delivery_cust_tel}&billing_cust_notes=#{delivery_cust_notes}&Checksum=#{checksum.to_s}" return encrypt_data(raw_request,@working_Key,"AES-128-CBC")[0] end
ruby
def request(order_Id,amount,billing_cust_name,billing_cust_address,billing_cust_city,billing_zip_code,billing_cust_state,billing_cust_country,billing_cust_email,billing_cust_tel,billing_cust_notes="",delivery_cust_name="",delivery_cust_address="",delivery_cust_city="",delivery_zip_code="",delivery_cust_state="",delivery_cust_country="",delivery_cust_email="",delivery_cust_tel="",delivery_cust_notes="") checksum = getChecksum(order_Id,amount) raw_request = "Merchant_Id=#{@merchant_Id}&Amount=#{amount}&Order_Id=#{order_Id}&Redirect_Url=#{@redirect_Url}&billing_cust_name=#{billing_cust_name}&billing_cust_address=#{billing_cust_address}&billing_cust_country=#{billing_cust_country}&billing_cust_state=#{billing_cust_state}&billing_cust_city=#{billing_cust_city}&billing_zip_code=#{billing_zip_code}&billing_cust_tel=#{billing_cust_tel}&billing_cust_email=#{billing_cust_email}&billing_cust_notes=#{billing_cust_notes}&delivery_cust_name=#{delivery_cust_name}&delivery_cust_address=#{delivery_cust_address}&delivery_cust_country=#{delivery_cust_country}&delivery_cust_state=#{delivery_cust_state}&delivery_cust_city=#{delivery_cust_city}&delivery_zip_code=#{delivery_zip_code}&delivery_cust_tel=#{delivery_cust_tel}&billing_cust_notes=#{delivery_cust_notes}&Checksum=#{checksum.to_s}" return encrypt_data(raw_request,@working_Key,"AES-128-CBC")[0] end
[ "def", "request", "(", "order_Id", ",", "amount", ",", "billing_cust_name", ",", "billing_cust_address", ",", "billing_cust_city", ",", "billing_zip_code", ",", "billing_cust_state", ",", "billing_cust_country", ",", "billing_cust_email", ",", "billing_cust_tel", ",", "billing_cust_notes", "=", "\"\"", ",", "delivery_cust_name", "=", "\"\"", ",", "delivery_cust_address", "=", "\"\"", ",", "delivery_cust_city", "=", "\"\"", ",", "delivery_zip_code", "=", "\"\"", ",", "delivery_cust_state", "=", "\"\"", ",", "delivery_cust_country", "=", "\"\"", ",", "delivery_cust_email", "=", "\"\"", ",", "delivery_cust_tel", "=", "\"\"", ",", "delivery_cust_notes", "=", "\"\"", ")", "checksum", "=", "getChecksum", "(", "order_Id", ",", "amount", ")", "raw_request", "=", "\"Merchant_Id=#{@merchant_Id}&Amount=#{amount}&Order_Id=#{order_Id}&Redirect_Url=#{@redirect_Url}&billing_cust_name=#{billing_cust_name}&billing_cust_address=#{billing_cust_address}&billing_cust_country=#{billing_cust_country}&billing_cust_state=#{billing_cust_state}&billing_cust_city=#{billing_cust_city}&billing_zip_code=#{billing_zip_code}&billing_cust_tel=#{billing_cust_tel}&billing_cust_email=#{billing_cust_email}&billing_cust_notes=#{billing_cust_notes}&delivery_cust_name=#{delivery_cust_name}&delivery_cust_address=#{delivery_cust_address}&delivery_cust_country=#{delivery_cust_country}&delivery_cust_state=#{delivery_cust_state}&delivery_cust_city=#{delivery_cust_city}&delivery_zip_code=#{delivery_zip_code}&delivery_cust_tel=#{delivery_cust_tel}&billing_cust_notes=#{delivery_cust_notes}&Checksum=#{checksum.to_s}\"", "return", "encrypt_data", "(", "raw_request", ",", "@working_Key", ",", "\"AES-128-CBC\"", ")", "[", "0", "]", "end" ]
constructer to one time initialze genric keys request CCAvenue encrypted data
[ "constructer", "to", "one", "time", "initialze", "genric", "keys", "request", "CCAvenue", "encrypted", "data" ]
d5a9371c4e1a6cbb6a4ee964455faffc31f993e7
https://github.com/kishanio/CCAvenue-Ruby-Gem/blob/d5a9371c4e1a6cbb6a4ee964455faffc31f993e7/lib/ccavenue.rb#L27-L31
3,070
kishanio/CCAvenue-Ruby-Gem
lib/ccavenue.rb
Ccavenue.Payment.response
def response(response) raw_response = CGI::parse(decrypt_data(response,@working_Key,"AES-128-CBC")) auth_desc = raw_response["AuthDesc"][0] order_id = raw_response["Order_Id"][0] amount = raw_response["Amount"][0] checksum = raw_response["Checksum"][0] verification = verifyChecksum(order_id,amount,auth_desc,checksum) return auth_desc,verification,raw_response end
ruby
def response(response) raw_response = CGI::parse(decrypt_data(response,@working_Key,"AES-128-CBC")) auth_desc = raw_response["AuthDesc"][0] order_id = raw_response["Order_Id"][0] amount = raw_response["Amount"][0] checksum = raw_response["Checksum"][0] verification = verifyChecksum(order_id,amount,auth_desc,checksum) return auth_desc,verification,raw_response end
[ "def", "response", "(", "response", ")", "raw_response", "=", "CGI", "::", "parse", "(", "decrypt_data", "(", "response", ",", "@working_Key", ",", "\"AES-128-CBC\"", ")", ")", "auth_desc", "=", "raw_response", "[", "\"AuthDesc\"", "]", "[", "0", "]", "order_id", "=", "raw_response", "[", "\"Order_Id\"", "]", "[", "0", "]", "amount", "=", "raw_response", "[", "\"Amount\"", "]", "[", "0", "]", "checksum", "=", "raw_response", "[", "\"Checksum\"", "]", "[", "0", "]", "verification", "=", "verifyChecksum", "(", "order_id", ",", "amount", ",", "auth_desc", ",", "checksum", ")", "return", "auth_desc", ",", "verification", ",", "raw_response", "end" ]
calling response method to check if everything went well
[ "calling", "response", "method", "to", "check", "if", "everything", "went", "well" ]
d5a9371c4e1a6cbb6a4ee964455faffc31f993e7
https://github.com/kishanio/CCAvenue-Ruby-Gem/blob/d5a9371c4e1a6cbb6a4ee964455faffc31f993e7/lib/ccavenue.rb#L35-L45
3,071
kishanio/CCAvenue-Ruby-Gem
lib/ccavenue.rb
Ccavenue.Payment.verifyChecksum
def verifyChecksum( order_Id, amount, authDesc, checksum) String str = @merchant_Id+"|"+order_Id+"|"+amount+"|"+authDesc+"|"+@working_Key String newChecksum = Zlib::adler32(str).to_s return (newChecksum.eql?(checksum)) ? true : false end
ruby
def verifyChecksum( order_Id, amount, authDesc, checksum) String str = @merchant_Id+"|"+order_Id+"|"+amount+"|"+authDesc+"|"+@working_Key String newChecksum = Zlib::adler32(str).to_s return (newChecksum.eql?(checksum)) ? true : false end
[ "def", "verifyChecksum", "(", "order_Id", ",", "amount", ",", "authDesc", ",", "checksum", ")", "String", "str", "=", "@merchant_Id", "+", "\"|\"", "+", "order_Id", "+", "\"|\"", "+", "amount", "+", "\"|\"", "+", "authDesc", "+", "\"|\"", "+", "@working_Key", "String", "newChecksum", "=", "Zlib", "::", "adler32", "(", "str", ")", ".", "to_s", "return", "(", "newChecksum", ".", "eql?", "(", "checksum", ")", ")", "?", "true", ":", "false", "end" ]
verify checksum response
[ "verify", "checksum", "response" ]
d5a9371c4e1a6cbb6a4ee964455faffc31f993e7
https://github.com/kishanio/CCAvenue-Ruby-Gem/blob/d5a9371c4e1a6cbb6a4ee964455faffc31f993e7/lib/ccavenue.rb#L60-L64
3,072
kishanio/CCAvenue-Ruby-Gem
lib/ccavenue.rb
Ccavenue.Payment.hextobin
def hextobin(hexstring) length = hexstring.length binString = "" count = 0 while count < length do substring = hexstring[count,2] substring = [substring] packedString = substring.pack('H*') if count == 0 binString = packedString else binString +=packedString end count+=2 end return binString end
ruby
def hextobin(hexstring) length = hexstring.length binString = "" count = 0 while count < length do substring = hexstring[count,2] substring = [substring] packedString = substring.pack('H*') if count == 0 binString = packedString else binString +=packedString end count+=2 end return binString end
[ "def", "hextobin", "(", "hexstring", ")", "length", "=", "hexstring", ".", "length", "binString", "=", "\"\"", "count", "=", "0", "while", "count", "<", "length", "do", "substring", "=", "hexstring", "[", "count", ",", "2", "]", "substring", "=", "[", "substring", "]", "packedString", "=", "substring", ".", "pack", "(", "'H*'", ")", "if", "count", "==", "0", "binString", "=", "packedString", "else", "binString", "+=", "packedString", "end", "count", "+=", "2", "end", "return", "binString", "end" ]
hex-to-bin
[ "hex", "-", "to", "-", "bin" ]
d5a9371c4e1a6cbb6a4ee964455faffc31f993e7
https://github.com/kishanio/CCAvenue-Ruby-Gem/blob/d5a9371c4e1a6cbb6a4ee964455faffc31f993e7/lib/ccavenue.rb#L97-L118
3,073
github/graphql-relay-walker
lib/graphql/relay/walker/client_ext.rb
GraphQL::Relay::Walker.ClientExt.walk
def walk(from_id:, except: nil, only: nil, variables: {}, context: {}) query_string = GraphQL::Relay::Walker.query_string(schema, except: except, only: only) walker_query = parse(query_string) GraphQL::Relay::Walker.walk(from_id: from_id) do |frame| response = query( walker_query, variables: variables.merge('id' => frame.gid), context: context ) frame.context[:response] = response frame.result = response.respond_to?(:data) && response.data ? response.data.to_h : {} frame.enqueue_found_gids yield(frame) if block_given? end end
ruby
def walk(from_id:, except: nil, only: nil, variables: {}, context: {}) query_string = GraphQL::Relay::Walker.query_string(schema, except: except, only: only) walker_query = parse(query_string) GraphQL::Relay::Walker.walk(from_id: from_id) do |frame| response = query( walker_query, variables: variables.merge('id' => frame.gid), context: context ) frame.context[:response] = response frame.result = response.respond_to?(:data) && response.data ? response.data.to_h : {} frame.enqueue_found_gids yield(frame) if block_given? end end
[ "def", "walk", "(", "from_id", ":", ",", "except", ":", "nil", ",", "only", ":", "nil", ",", "variables", ":", "{", "}", ",", "context", ":", "{", "}", ")", "query_string", "=", "GraphQL", "::", "Relay", "::", "Walker", ".", "query_string", "(", "schema", ",", "except", ":", "except", ",", "only", ":", "only", ")", "walker_query", "=", "parse", "(", "query_string", ")", "GraphQL", "::", "Relay", "::", "Walker", ".", "walk", "(", "from_id", ":", "from_id", ")", "do", "|", "frame", "|", "response", "=", "query", "(", "walker_query", ",", "variables", ":", "variables", ".", "merge", "(", "'id'", "=>", "frame", ".", "gid", ")", ",", "context", ":", "context", ")", "frame", ".", "context", "[", ":response", "]", "=", "response", "frame", ".", "result", "=", "response", ".", "respond_to?", "(", ":data", ")", "&&", "response", ".", "data", "?", "response", ".", "data", ".", "to_h", ":", "{", "}", "frame", ".", "enqueue_found_gids", "yield", "(", "frame", ")", "if", "block_given?", "end", "end" ]
Walk this client's graph from the given GID. from_id: - The String GID to start walking from. variables: - A Hash of variables to be passed to GraphQL::Client. context: - A Hash containing context to be passed to GraphQL::Client. &blk - A block to call with each Walker::Frame that is visited. Returns nothing.
[ "Walk", "this", "client", "s", "graph", "from", "the", "given", "GID", "." ]
1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7
https://github.com/github/graphql-relay-walker/blob/1095cfc4f0aa6d157cae18dcc73aa2e08295e4d7/lib/graphql/relay/walker/client_ext.rb#L11-L28
3,074
sunny/anyplayer
lib/anyplayer/selector.rb
Anyplayer.Selector.player
def player PLAYERS.each do |player| player_load(player) || next instance = player_class(player).new player_on_platform?(instance) || next return instance if player_launched?(instance) end nil end
ruby
def player PLAYERS.each do |player| player_load(player) || next instance = player_class(player).new player_on_platform?(instance) || next return instance if player_launched?(instance) end nil end
[ "def", "player", "PLAYERS", ".", "each", "do", "|", "player", "|", "player_load", "(", "player", ")", "||", "next", "instance", "=", "player_class", "(", "player", ")", ".", "new", "player_on_platform?", "(", "instance", ")", "||", "next", "return", "instance", "if", "player_launched?", "(", "instance", ")", "end", "nil", "end" ]
Returns an instance of the first music player that's launched
[ "Returns", "an", "instance", "of", "the", "first", "music", "player", "that", "s", "launched" ]
6dff74cc74c1fe2429567a6176ea59dc53b69c7c
https://github.com/sunny/anyplayer/blob/6dff74cc74c1fe2429567a6176ea59dc53b69c7c/lib/anyplayer/selector.rb#L24-L34
3,075
brasten/scruffy
lib/scruffy/helpers/canvas.rb
Scruffy::Helpers.Canvas.bounds_for
def bounds_for(canvas_size, position, size) return nil if (position.nil? || size.nil?) bounds = {} bounds[:x] = canvas_size.first * (position.first / 100.to_f) bounds[:y] = canvas_size.last * (position.last / 100.to_f) bounds[:width] = canvas_size.first * (size.first / 100.to_f) bounds[:height] = canvas_size.last * (size.last / 100.to_f) bounds end
ruby
def bounds_for(canvas_size, position, size) return nil if (position.nil? || size.nil?) bounds = {} bounds[:x] = canvas_size.first * (position.first / 100.to_f) bounds[:y] = canvas_size.last * (position.last / 100.to_f) bounds[:width] = canvas_size.first * (size.first / 100.to_f) bounds[:height] = canvas_size.last * (size.last / 100.to_f) bounds end
[ "def", "bounds_for", "(", "canvas_size", ",", "position", ",", "size", ")", "return", "nil", "if", "(", "position", ".", "nil?", "||", "size", ".", "nil?", ")", "bounds", "=", "{", "}", "bounds", "[", ":x", "]", "=", "canvas_size", ".", "first", "*", "(", "position", ".", "first", "/", "100", ".", "to_f", ")", "bounds", "[", ":y", "]", "=", "canvas_size", ".", "last", "*", "(", "position", ".", "last", "/", "100", ".", "to_f", ")", "bounds", "[", ":width", "]", "=", "canvas_size", ".", "first", "*", "(", "size", ".", "first", "/", "100", ".", "to_f", ")", "bounds", "[", ":height", "]", "=", "canvas_size", ".", "last", "*", "(", "size", ".", "last", "/", "100", ".", "to_f", ")", "bounds", "end" ]
Converts percentage values into actual pixel values based on the known render size. Returns a hash consisting of :x, :y, :width, and :height elements.
[ "Converts", "percentage", "values", "into", "actual", "pixel", "values", "based", "on", "the", "known", "render", "size", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/helpers/canvas.rb#L30-L38
3,076
brasten/scruffy
lib/scruffy/formatters.rb
Scruffy::Formatters.Base.route_format
def route_format(target, idx, options = {}) args = [target, idx, options] if respond_to?(:format) send :format, *args[0...self.method(:format).arity] elsif respond_to?(:format!) send :format!, *args[0...self.method(:format!).arity] target else raise NameError, "Formatter subclass must container either a format() method or format!() method." end end
ruby
def route_format(target, idx, options = {}) args = [target, idx, options] if respond_to?(:format) send :format, *args[0...self.method(:format).arity] elsif respond_to?(:format!) send :format!, *args[0...self.method(:format!).arity] target else raise NameError, "Formatter subclass must container either a format() method or format!() method." end end
[ "def", "route_format", "(", "target", ",", "idx", ",", "options", "=", "{", "}", ")", "args", "=", "[", "target", ",", "idx", ",", "options", "]", "if", "respond_to?", "(", ":format", ")", "send", ":format", ",", "args", "[", "0", "...", "self", ".", "method", "(", ":format", ")", ".", "arity", "]", "elsif", "respond_to?", "(", ":format!", ")", "send", ":format!", ",", "args", "[", "0", "...", "self", ".", "method", "(", ":format!", ")", ".", "arity", "]", "target", "else", "raise", "NameError", ",", "\"Formatter subclass must container either a format() method or format!() method.\"", "end", "end" ]
Called by the value marker component. Routes the format call to one of a couple possible methods. If the formatter defines a #format method, the returned value is used as the value. If the formatter defines a #format! method, the value passed is expected to be modified, and is used as the value. (This may not actually work, in hindsight.)
[ "Called", "by", "the", "value", "marker", "component", ".", "Routes", "the", "format", "call", "to", "one", "of", "a", "couple", "possible", "methods", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/formatters.rb#L31-L41
3,077
brasten/scruffy
lib/scruffy/formatters.rb
Scruffy::Formatters.Number.format
def format(target, idx, options) my_precision = @precision if @precision == :auto my_precision = options[:all_values].inject(0) do |highest, current| cur = current.to_f.to_s.split(".").last.size cur > highest ? cur : highest end my_precision = @precision_limit if my_precision > @precision_limit elsif @precision == :none my_precision = 0 end my_separator = @separator my_separator = "" unless my_precision > 0 begin number = "" if @roundup == :none parts = number_with_precision(target, my_precision).split('.') number = parts[0].to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{@delimiter}") + my_separator + parts[1].to_s else number = roundup(target.to_f, @roundup).to_i.to_s end number rescue StandardError => e target end end
ruby
def format(target, idx, options) my_precision = @precision if @precision == :auto my_precision = options[:all_values].inject(0) do |highest, current| cur = current.to_f.to_s.split(".").last.size cur > highest ? cur : highest end my_precision = @precision_limit if my_precision > @precision_limit elsif @precision == :none my_precision = 0 end my_separator = @separator my_separator = "" unless my_precision > 0 begin number = "" if @roundup == :none parts = number_with_precision(target, my_precision).split('.') number = parts[0].to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{@delimiter}") + my_separator + parts[1].to_s else number = roundup(target.to_f, @roundup).to_i.to_s end number rescue StandardError => e target end end
[ "def", "format", "(", "target", ",", "idx", ",", "options", ")", "my_precision", "=", "@precision", "if", "@precision", "==", ":auto", "my_precision", "=", "options", "[", ":all_values", "]", ".", "inject", "(", "0", ")", "do", "|", "highest", ",", "current", "|", "cur", "=", "current", ".", "to_f", ".", "to_s", ".", "split", "(", "\".\"", ")", ".", "last", ".", "size", "cur", ">", "highest", "?", "cur", ":", "highest", "end", "my_precision", "=", "@precision_limit", "if", "my_precision", ">", "@precision_limit", "elsif", "@precision", "==", ":none", "my_precision", "=", "0", "end", "my_separator", "=", "@separator", "my_separator", "=", "\"\"", "unless", "my_precision", ">", "0", "begin", "number", "=", "\"\"", "if", "@roundup", "==", ":none", "parts", "=", "number_with_precision", "(", "target", ",", "my_precision", ")", ".", "split", "(", "'.'", ")", "number", "=", "parts", "[", "0", "]", ".", "to_s", ".", "gsub", "(", "/", "\\d", "\\d", "\\d", "\\d", "\\d", "/", ",", "\"\\\\1#{@delimiter}\"", ")", "+", "my_separator", "+", "parts", "[", "1", "]", ".", "to_s", "else", "number", "=", "roundup", "(", "target", ".", "to_f", ",", "@roundup", ")", ".", "to_i", ".", "to_s", "end", "number", "rescue", "StandardError", "=>", "e", "target", "end", "end" ]
Returns a new Number formatter. Options: precision:: precision to use for value. Can be set to an integer, :none or :auto. :auto will use whatever precision is necessary to portray all the numerical information, up to :precision_limit. Example: [100.1, 100.44, 200.323] will result in [100.100, 100.440, 200.323] separator:: decimal separator. Defaults to '.' delimiter:: delimiter character. Defaults to ',' precision_limit:: upper limit for auto precision. (Ignored if roundup is specified) roundup:: round up the number to the given interval Formats the value.
[ "Returns", "a", "new", "Number", "formatter", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/formatters.rb#L95-L125
3,078
brasten/scruffy
lib/scruffy/formatters.rb
Scruffy::Formatters.Currency.format
def format(target, idx, options) @separator = "" unless @precision > 0 begin parts = number_with_precision(target, @precision).split('.') if @special_negatives && (target.to_f < 0) number = "(" + @unit + parts[0].to_i.abs.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{@delimiter}") + @separator + parts[1].to_s + ")" else number = @unit + parts[0].to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{@delimiter}") + @separator + parts[1].to_s number.gsub!(@unit + '-', '-' + @unit) end if (target.to_f < 0) && @negative_color options[:marker_color_override] = @negative_color else options[:marker_color_override] = nil end number rescue target end end
ruby
def format(target, idx, options) @separator = "" unless @precision > 0 begin parts = number_with_precision(target, @precision).split('.') if @special_negatives && (target.to_f < 0) number = "(" + @unit + parts[0].to_i.abs.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{@delimiter}") + @separator + parts[1].to_s + ")" else number = @unit + parts[0].to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{@delimiter}") + @separator + parts[1].to_s number.gsub!(@unit + '-', '-' + @unit) end if (target.to_f < 0) && @negative_color options[:marker_color_override] = @negative_color else options[:marker_color_override] = nil end number rescue target end end
[ "def", "format", "(", "target", ",", "idx", ",", "options", ")", "@separator", "=", "\"\"", "unless", "@precision", ">", "0", "begin", "parts", "=", "number_with_precision", "(", "target", ",", "@precision", ")", ".", "split", "(", "'.'", ")", "if", "@special_negatives", "&&", "(", "target", ".", "to_f", "<", "0", ")", "number", "=", "\"(\"", "+", "@unit", "+", "parts", "[", "0", "]", ".", "to_i", ".", "abs", ".", "to_s", ".", "gsub", "(", "/", "\\d", "\\d", "\\d", "\\d", "\\d", "/", ",", "\"\\\\1#{@delimiter}\"", ")", "+", "@separator", "+", "parts", "[", "1", "]", ".", "to_s", "+", "\")\"", "else", "number", "=", "@unit", "+", "parts", "[", "0", "]", ".", "to_s", ".", "gsub", "(", "/", "\\d", "\\d", "\\d", "\\d", "\\d", "/", ",", "\"\\\\1#{@delimiter}\"", ")", "+", "@separator", "+", "parts", "[", "1", "]", ".", "to_s", "number", ".", "gsub!", "(", "@unit", "+", "'-'", ",", "'-'", "+", "@unit", ")", "end", "if", "(", "target", ".", "to_f", "<", "0", ")", "&&", "@negative_color", "options", "[", ":marker_color_override", "]", "=", "@negative_color", "else", "options", "[", ":marker_color_override", "]", "=", "nil", "end", "number", "rescue", "target", "end", "end" ]
Returns a new Currency class. Options: precision:: precision of value unit:: Defaults to '$' separator:: Defaults to '.' delimiter:: Defaults to ',' negative_color:: Color of value marker for negative values. Defaults to 'red' special_negatives:: If set to true, parenthesizes negative numbers. ie: -$150.50 becomes ($150.50). Defaults to false. Formats value marker.
[ "Returns", "a", "new", "Currency", "class", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/formatters.rb#L163-L182
3,079
brasten/scruffy
lib/scruffy/formatters.rb
Scruffy::Formatters.Percentage.format
def format(target) begin number = number_with_precision(target, @precision) parts = number.split('.') if parts.at(1).nil? parts[0] + "%" else parts[0] + @separator + parts[1].to_s + "%" end rescue target end end
ruby
def format(target) begin number = number_with_precision(target, @precision) parts = number.split('.') if parts.at(1).nil? parts[0] + "%" else parts[0] + @separator + parts[1].to_s + "%" end rescue target end end
[ "def", "format", "(", "target", ")", "begin", "number", "=", "number_with_precision", "(", "target", ",", "@precision", ")", "parts", "=", "number", ".", "split", "(", "'.'", ")", "if", "parts", ".", "at", "(", "1", ")", ".", "nil?", "parts", "[", "0", "]", "+", "\"%\"", "else", "parts", "[", "0", "]", "+", "@separator", "+", "parts", "[", "1", "]", ".", "to_s", "+", "\"%\"", "end", "rescue", "target", "end", "end" ]
Returns new Percentage formatter. Options: precision:: Defaults to 3. separator:: Defaults to '.' Formats percentages.
[ "Returns", "new", "Percentage", "formatter", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/formatters.rb#L201-L213
3,080
opentox/lazar
lib/physchem.rb
OpenTox.PhysChem.openbabel
def openbabel descriptor, compound obdescriptor = OpenBabel::OBDescriptor.find_type descriptor obmol = OpenBabel::OBMol.new obconversion = OpenBabel::OBConversion.new obconversion.set_in_format 'smi' obconversion.read_string obmol, compound.smiles {"#{library.capitalize}.#{descriptor}" => fix_value(obdescriptor.predict(obmol))} end
ruby
def openbabel descriptor, compound obdescriptor = OpenBabel::OBDescriptor.find_type descriptor obmol = OpenBabel::OBMol.new obconversion = OpenBabel::OBConversion.new obconversion.set_in_format 'smi' obconversion.read_string obmol, compound.smiles {"#{library.capitalize}.#{descriptor}" => fix_value(obdescriptor.predict(obmol))} end
[ "def", "openbabel", "descriptor", ",", "compound", "obdescriptor", "=", "OpenBabel", "::", "OBDescriptor", ".", "find_type", "descriptor", "obmol", "=", "OpenBabel", "::", "OBMol", ".", "new", "obconversion", "=", "OpenBabel", "::", "OBConversion", ".", "new", "obconversion", ".", "set_in_format", "'smi'", "obconversion", ".", "read_string", "obmol", ",", "compound", ".", "smiles", "{", "\"#{library.capitalize}.#{descriptor}\"", "=>", "fix_value", "(", "obdescriptor", ".", "predict", "(", "obmol", ")", ")", "}", "end" ]
Calculate OpenBabel descriptors @param [String] descriptor type @param [OpenTox::Compound] @return [Hash]
[ "Calculate", "OpenBabel", "descriptors" ]
1ee7de09c969e16fd11522d22179224e694b0161
https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/physchem.rb#L94-L101
3,081
mezis/tsuga
lib/tsuga/model/tile.rb
Tsuga::Model.Tile.neighbours
def neighbours offsets = (-1..1).to_a.product((-1..1).to_a) offsets.map do |lat, lng| begin neighbour(lat:lat, lng:lng) rescue ArgumentError nil # occurs on world boundaries end end.compact end
ruby
def neighbours offsets = (-1..1).to_a.product((-1..1).to_a) offsets.map do |lat, lng| begin neighbour(lat:lat, lng:lng) rescue ArgumentError nil # occurs on world boundaries end end.compact end
[ "def", "neighbours", "offsets", "=", "(", "-", "1", "..", "1", ")", ".", "to_a", ".", "product", "(", "(", "-", "1", "..", "1", ")", ".", "to_a", ")", "offsets", ".", "map", "do", "|", "lat", ",", "lng", "|", "begin", "neighbour", "(", "lat", ":", "lat", ",", "lng", ":", "lng", ")", "rescue", "ArgumentError", "nil", "# occurs on world boundaries", "end", "end", ".", "compact", "end" ]
return neighbouring tiles to the north, northeast, and east
[ "return", "neighbouring", "tiles", "to", "the", "north", "northeast", "and", "east" ]
418a1dac7af068fb388883c47f39eb52113af096
https://github.com/mezis/tsuga/blob/418a1dac7af068fb388883c47f39eb52113af096/lib/tsuga/model/tile.rb#L55-L64
3,082
ktonon/cog
lib/cog/seed.rb
Cog.Seed.stamp_class
def stamp_class(path, opt={}) Cog.activate_language opt[:language] do l = Cog.active_language raise Errors::ActiveLanguageDoesNotSupportSeeds.new :language => l if l.nil? || l.seed_extension.nil? @in_header = false @header_path = if l.seed_header "#{path}.#{l.seed_header}" end stamp "cog/#{l.key}/seed.#{l.seed_extension}", "#{path}.#{l.seed_extension}" if l.seed_header @in_header = true stamp "cog/#{l.key}/seed.#{l.seed_header}", @header_path end end end
ruby
def stamp_class(path, opt={}) Cog.activate_language opt[:language] do l = Cog.active_language raise Errors::ActiveLanguageDoesNotSupportSeeds.new :language => l if l.nil? || l.seed_extension.nil? @in_header = false @header_path = if l.seed_header "#{path}.#{l.seed_header}" end stamp "cog/#{l.key}/seed.#{l.seed_extension}", "#{path}.#{l.seed_extension}" if l.seed_header @in_header = true stamp "cog/#{l.key}/seed.#{l.seed_header}", @header_path end end end
[ "def", "stamp_class", "(", "path", ",", "opt", "=", "{", "}", ")", "Cog", ".", "activate_language", "opt", "[", ":language", "]", "do", "l", "=", "Cog", ".", "active_language", "raise", "Errors", "::", "ActiveLanguageDoesNotSupportSeeds", ".", "new", ":language", "=>", "l", "if", "l", ".", "nil?", "||", "l", ".", "seed_extension", ".", "nil?", "@in_header", "=", "false", "@header_path", "=", "if", "l", ".", "seed_header", "\"#{path}.#{l.seed_header}\"", "end", "stamp", "\"cog/#{l.key}/seed.#{l.seed_extension}\"", ",", "\"#{path}.#{l.seed_extension}\"", "if", "l", ".", "seed_header", "@in_header", "=", "true", "stamp", "\"cog/#{l.key}/seed.#{l.seed_header}\"", ",", "@header_path", "end", "end", "end" ]
Render the class in the currently active language @param path [String] file system path without the extension, relative to the project root. The extension will be determined based on the currently active language @option opt [String] :language key for the language to use. The language must define a seed extension
[ "Render", "the", "class", "in", "the", "currently", "active", "language" ]
156c81a0873135d7dc47c79c705c477893fff74a
https://github.com/ktonon/cog/blob/156c81a0873135d7dc47c79c705c477893fff74a/lib/cog/seed.rb#L41-L56
3,083
brasten/scruffy
lib/scruffy/layers/box.rb
Scruffy::Layers.Box.draw
def draw(svg, coords, options = {}) coords.each_with_index do |coord,idx| x, y, bar_height = (coord.first), coord.last, 1#(height - coord.last) valh = max_value + min_value * -1 #value_height maxh = max_value * height / valh #positive area height minh = min_value * height / valh #negative area height #puts "height = #{height} and max_value = #{max_value} and min_value = #{min_value} and y = #{y} and point = #{points[idx]}" #if points[idx] > 0 # bar_height = points[idx]*maxh/max_value #else # bar_height = points[idx]*minh/min_value #end #puts " y = #{y} and point = #{points[idx]}" #svg.g(:transform => "translate(-#{relative(0.5)}, -#{relative(0.5)})") { # svg.rect( :x => x, :y => y, :width => @bar_width + relative(1), :height => bar_height + relative(1), # :style => "fill: black; fill-opacity: 0.15; stroke: none;" ) # svg.rect( :x => x+relative(0.5), :y => y+relative(2), :width => @bar_width + relative(1), :height => bar_height - relative(0.5), # :style => "fill: black; fill-opacity: 0.15; stroke: none;" ) # #} svg.line(:x1=>x+@bar_width/2,:x2=>x+@bar_width/2,:y1=>y[0],:y2=>y[4], :style => "stroke:#{(outline.to_s || options[:theme].marker || 'white').to_s}; stroke-width:1") svg.line(:x1=>x+@bar_width/4,:x2=>x+@bar_width/4*3,:y1=>y[0],:y2=>y[0], :style => "stroke:#{(outline.to_s || options[:theme].marker || 'white').to_s}; stroke-width:1") svg.line(:x1=>x+@bar_width/4,:x2=>x+@bar_width/4*3,:y1=>y[4],:y2=>y[4], :style => "stroke:#{(outline.to_s || options[:theme].marker || 'white').to_s}; stroke-width:1") svg.rect( :x => x, :y => y[1], :width => @bar_width, :height => (y[1]-y[3])*-1, :fill => color.to_s, 'style' => "opacity: #{opacity}; stroke:#{(outline.to_s || options[:theme].marker || 'white').to_s}; stroke-width:1;" ) svg.line(:x1=>x,:x2=>x+@bar_width,:y1=>y[2],:y2=>y[2], :style => "stroke:#{(outline.to_s || options[:theme].marker || 'white').to_s}; stroke-width:1") #svg.rect( :x => x, :y => y, :width => @bar_width, :height => bar_height, # :fill => color.to_s, 'style' => "opacity: #{opacity}; stroke: none;" ) end end
ruby
def draw(svg, coords, options = {}) coords.each_with_index do |coord,idx| x, y, bar_height = (coord.first), coord.last, 1#(height - coord.last) valh = max_value + min_value * -1 #value_height maxh = max_value * height / valh #positive area height minh = min_value * height / valh #negative area height #puts "height = #{height} and max_value = #{max_value} and min_value = #{min_value} and y = #{y} and point = #{points[idx]}" #if points[idx] > 0 # bar_height = points[idx]*maxh/max_value #else # bar_height = points[idx]*minh/min_value #end #puts " y = #{y} and point = #{points[idx]}" #svg.g(:transform => "translate(-#{relative(0.5)}, -#{relative(0.5)})") { # svg.rect( :x => x, :y => y, :width => @bar_width + relative(1), :height => bar_height + relative(1), # :style => "fill: black; fill-opacity: 0.15; stroke: none;" ) # svg.rect( :x => x+relative(0.5), :y => y+relative(2), :width => @bar_width + relative(1), :height => bar_height - relative(0.5), # :style => "fill: black; fill-opacity: 0.15; stroke: none;" ) # #} svg.line(:x1=>x+@bar_width/2,:x2=>x+@bar_width/2,:y1=>y[0],:y2=>y[4], :style => "stroke:#{(outline.to_s || options[:theme].marker || 'white').to_s}; stroke-width:1") svg.line(:x1=>x+@bar_width/4,:x2=>x+@bar_width/4*3,:y1=>y[0],:y2=>y[0], :style => "stroke:#{(outline.to_s || options[:theme].marker || 'white').to_s}; stroke-width:1") svg.line(:x1=>x+@bar_width/4,:x2=>x+@bar_width/4*3,:y1=>y[4],:y2=>y[4], :style => "stroke:#{(outline.to_s || options[:theme].marker || 'white').to_s}; stroke-width:1") svg.rect( :x => x, :y => y[1], :width => @bar_width, :height => (y[1]-y[3])*-1, :fill => color.to_s, 'style' => "opacity: #{opacity}; stroke:#{(outline.to_s || options[:theme].marker || 'white').to_s}; stroke-width:1;" ) svg.line(:x1=>x,:x2=>x+@bar_width,:y1=>y[2],:y2=>y[2], :style => "stroke:#{(outline.to_s || options[:theme].marker || 'white').to_s}; stroke-width:1") #svg.rect( :x => x, :y => y, :width => @bar_width, :height => bar_height, # :fill => color.to_s, 'style' => "opacity: #{opacity}; stroke: none;" ) end end
[ "def", "draw", "(", "svg", ",", "coords", ",", "options", "=", "{", "}", ")", "coords", ".", "each_with_index", "do", "|", "coord", ",", "idx", "|", "x", ",", "y", ",", "bar_height", "=", "(", "coord", ".", "first", ")", ",", "coord", ".", "last", ",", "1", "#(height - coord.last)", "valh", "=", "max_value", "+", "min_value", "*", "-", "1", "#value_height", "maxh", "=", "max_value", "*", "height", "/", "valh", "#positive area height", "minh", "=", "min_value", "*", "height", "/", "valh", "#negative area height", "#puts \"height = #{height} and max_value = #{max_value} and min_value = #{min_value} and y = #{y} and point = #{points[idx]}\"", "#if points[idx] > 0", "# bar_height = points[idx]*maxh/max_value", "#else", "# bar_height = points[idx]*minh/min_value", "#end", "#puts \" y = #{y} and point = #{points[idx]}\" ", "#svg.g(:transform => \"translate(-#{relative(0.5)}, -#{relative(0.5)})\") {", "# svg.rect( :x => x, :y => y, :width => @bar_width + relative(1), :height => bar_height + relative(1), ", "# :style => \"fill: black; fill-opacity: 0.15; stroke: none;\" )", "# svg.rect( :x => x+relative(0.5), :y => y+relative(2), :width => @bar_width + relative(1), :height => bar_height - relative(0.5), ", "# :style => \"fill: black; fill-opacity: 0.15; stroke: none;\" )", "#", "#}", "svg", ".", "line", "(", ":x1", "=>", "x", "+", "@bar_width", "/", "2", ",", ":x2", "=>", "x", "+", "@bar_width", "/", "2", ",", ":y1", "=>", "y", "[", "0", "]", ",", ":y2", "=>", "y", "[", "4", "]", ",", ":style", "=>", "\"stroke:#{(outline.to_s || options[:theme].marker || 'white').to_s}; stroke-width:1\"", ")", "svg", ".", "line", "(", ":x1", "=>", "x", "+", "@bar_width", "/", "4", ",", ":x2", "=>", "x", "+", "@bar_width", "/", "4", "*", "3", ",", ":y1", "=>", "y", "[", "0", "]", ",", ":y2", "=>", "y", "[", "0", "]", ",", ":style", "=>", "\"stroke:#{(outline.to_s || options[:theme].marker || 'white').to_s}; stroke-width:1\"", ")", "svg", ".", "line", "(", ":x1", "=>", "x", "+", "@bar_width", "/", "4", ",", ":x2", "=>", "x", "+", "@bar_width", "/", "4", "*", "3", ",", ":y1", "=>", "y", "[", "4", "]", ",", ":y2", "=>", "y", "[", "4", "]", ",", ":style", "=>", "\"stroke:#{(outline.to_s || options[:theme].marker || 'white').to_s}; stroke-width:1\"", ")", "svg", ".", "rect", "(", ":x", "=>", "x", ",", ":y", "=>", "y", "[", "1", "]", ",", ":width", "=>", "@bar_width", ",", ":height", "=>", "(", "y", "[", "1", "]", "-", "y", "[", "3", "]", ")", "*", "-", "1", ",", ":fill", "=>", "color", ".", "to_s", ",", "'style'", "=>", "\"opacity: #{opacity}; stroke:#{(outline.to_s || options[:theme].marker || 'white').to_s}; stroke-width:1;\"", ")", "svg", ".", "line", "(", ":x1", "=>", "x", ",", ":x2", "=>", "x", "+", "@bar_width", ",", ":y1", "=>", "y", "[", "2", "]", ",", ":y2", "=>", "y", "[", "2", "]", ",", ":style", "=>", "\"stroke:#{(outline.to_s || options[:theme].marker || 'white').to_s}; stroke-width:1\"", ")", "#svg.rect( :x => x, :y => y, :width => @bar_width, :height => bar_height, ", "# :fill => color.to_s, 'style' => \"opacity: #{opacity}; stroke: none;\" )", "end", "end" ]
Draw box plot.
[ "Draw", "box", "plot", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/box.rb#L11-L44
3,084
ktonon/cog
lib/cog/embeds.rb
Cog.Embeds.copy_keeps
def copy_keeps(original, scratch) Cog.activate_language(:filename => original) do original = scratch unless File.exists? original keeps = gather_keeps original, scratch keeps.each_pair do |hook, c| result = update c, :type => 'keep' do |c| c.keep_body end raise Errors::UnrecognizedKeepHook.new :hook => hook, :filename => original if result.nil? end end end
ruby
def copy_keeps(original, scratch) Cog.activate_language(:filename => original) do original = scratch unless File.exists? original keeps = gather_keeps original, scratch keeps.each_pair do |hook, c| result = update c, :type => 'keep' do |c| c.keep_body end raise Errors::UnrecognizedKeepHook.new :hook => hook, :filename => original if result.nil? end end end
[ "def", "copy_keeps", "(", "original", ",", "scratch", ")", "Cog", ".", "activate_language", "(", ":filename", "=>", "original", ")", "do", "original", "=", "scratch", "unless", "File", ".", "exists?", "original", "keeps", "=", "gather_keeps", "original", ",", "scratch", "keeps", ".", "each_pair", "do", "|", "hook", ",", "c", "|", "result", "=", "update", "c", ",", ":type", "=>", "'keep'", "do", "|", "c", "|", "c", ".", "keep_body", "end", "raise", "Errors", "::", "UnrecognizedKeepHook", ".", "new", ":hook", "=>", "hook", ",", ":filename", "=>", "original", "if", "result", ".", "nil?", "end", "end", "end" ]
Copy keep bodies from the original file to the scratch file @param original [String] file in which to search for keep statements. If the original does not exist, then scratch will serve as the original (we do this so that the keeps will get expanded in any case) @param scratch [String] file to which keep bodies will be copied @return [nil]
[ "Copy", "keep", "bodies", "from", "the", "original", "file", "to", "the", "scratch", "file" ]
156c81a0873135d7dc47c79c705c477893fff74a
https://github.com/ktonon/cog/blob/156c81a0873135d7dc47c79c705c477893fff74a/lib/cog/embeds.rb#L39-L50
3,085
brasten/scruffy
lib/scruffy/layers/multi.rb
Scruffy::Layers.Multi.render
def render(svg, options = {}) #TODO ensure this works with new points #current_points = points layers.each_with_index do |layer,i| #real_points = layer.points #layer.points = current_points layer_options = options.dup layer_options[:num_bars] = layers.size layer_options[:position] = i layer_options[:color] = layer.preferred_color || layer.color || options[:theme].next_color layer.render(svg, layer_options) options.merge(layer_options) #layer.points = real_points #layer.points.each_with_index { |val, idx| current_points[idx] -= val } end end
ruby
def render(svg, options = {}) #TODO ensure this works with new points #current_points = points layers.each_with_index do |layer,i| #real_points = layer.points #layer.points = current_points layer_options = options.dup layer_options[:num_bars] = layers.size layer_options[:position] = i layer_options[:color] = layer.preferred_color || layer.color || options[:theme].next_color layer.render(svg, layer_options) options.merge(layer_options) #layer.points = real_points #layer.points.each_with_index { |val, idx| current_points[idx] -= val } end end
[ "def", "render", "(", "svg", ",", "options", "=", "{", "}", ")", "#TODO ensure this works with new points", "#current_points = points", "layers", ".", "each_with_index", "do", "|", "layer", ",", "i", "|", "#real_points = layer.points", "#layer.points = current_points", "layer_options", "=", "options", ".", "dup", "layer_options", "[", ":num_bars", "]", "=", "layers", ".", "size", "layer_options", "[", ":position", "]", "=", "i", "layer_options", "[", ":color", "]", "=", "layer", ".", "preferred_color", "||", "layer", ".", "color", "||", "options", "[", ":theme", "]", ".", "next_color", "layer", ".", "render", "(", "svg", ",", "layer_options", ")", "options", ".", "merge", "(", "layer_options", ")", "#layer.points = real_points", "#layer.points.each_with_index { |val, idx| current_points[idx] -= val }", "end", "end" ]
Returns new Multi graph. You can provide a block for easily adding layers during (just after) initialization. Example: Multi.new do |multi| multi << Scruffy::Layers::Line.new( ... ) multi.add(:multi_bar, 'My Bar', [...]) end The initialize method passes itself to the block, and since multi is a LayerContainer, layers can be added just as if they were being added to Graph. Overrides Base#render to fiddle with layers' points to achieve a multi effect.
[ "Returns", "new", "Multi", "graph", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/multi.rb#L33-L52
3,086
brasten/scruffy
lib/scruffy/layers/bar.rb
Scruffy::Layers.Bar.draw
def draw(svg, coords, options = {}) coords.each_with_index do |coord,idx| next if coord.nil? x, y, bar_height = (coord.first), coord.last, 1#(height - coord.last) valh = max_value + min_value * -1 #value_height maxh = max_value * height / valh #positive area height minh = min_value * height / valh #negative area height #puts "height = #{height} and max_value = #{max_value} and min_value = #{min_value} and y = #{y} and point = #{points[idx]}" if points[idx] > 0 bar_height = points[idx]*maxh/max_value else bar_height = points[idx]*minh/min_value end #puts " y = #{y} and point = #{points[idx]}" unless options[:border] == false svg.g(:transform => "translate(-#{relative(0.5)}, -#{relative(0.5)})") { svg.rect( :x => x, :y => y, :width => @bar_width + relative(1), :height => bar_height + relative(1), :style => "fill: black; fill-opacity: 0.15; stroke: none;" ) svg.rect( :x => x+relative(0.5), :y => y+relative(2), :width => @bar_width + relative(1), :height => bar_height - relative(0.5), :style => "fill: black; fill-opacity: 0.15; stroke: none;" ) } end current_colour = color.is_a?(Array) ? color[idx % color.size] : color svg.rect( :x => x, :y => y, :width => @bar_width, :height => bar_height, :fill => current_colour.to_s, 'style' => "opacity: #{opacity}; stroke: none;" ) end end
ruby
def draw(svg, coords, options = {}) coords.each_with_index do |coord,idx| next if coord.nil? x, y, bar_height = (coord.first), coord.last, 1#(height - coord.last) valh = max_value + min_value * -1 #value_height maxh = max_value * height / valh #positive area height minh = min_value * height / valh #negative area height #puts "height = #{height} and max_value = #{max_value} and min_value = #{min_value} and y = #{y} and point = #{points[idx]}" if points[idx] > 0 bar_height = points[idx]*maxh/max_value else bar_height = points[idx]*minh/min_value end #puts " y = #{y} and point = #{points[idx]}" unless options[:border] == false svg.g(:transform => "translate(-#{relative(0.5)}, -#{relative(0.5)})") { svg.rect( :x => x, :y => y, :width => @bar_width + relative(1), :height => bar_height + relative(1), :style => "fill: black; fill-opacity: 0.15; stroke: none;" ) svg.rect( :x => x+relative(0.5), :y => y+relative(2), :width => @bar_width + relative(1), :height => bar_height - relative(0.5), :style => "fill: black; fill-opacity: 0.15; stroke: none;" ) } end current_colour = color.is_a?(Array) ? color[idx % color.size] : color svg.rect( :x => x, :y => y, :width => @bar_width, :height => bar_height, :fill => current_colour.to_s, 'style' => "opacity: #{opacity}; stroke: none;" ) end end
[ "def", "draw", "(", "svg", ",", "coords", ",", "options", "=", "{", "}", ")", "coords", ".", "each_with_index", "do", "|", "coord", ",", "idx", "|", "next", "if", "coord", ".", "nil?", "x", ",", "y", ",", "bar_height", "=", "(", "coord", ".", "first", ")", ",", "coord", ".", "last", ",", "1", "#(height - coord.last)", "valh", "=", "max_value", "+", "min_value", "*", "-", "1", "#value_height", "maxh", "=", "max_value", "*", "height", "/", "valh", "#positive area height", "minh", "=", "min_value", "*", "height", "/", "valh", "#negative area height", "#puts \"height = #{height} and max_value = #{max_value} and min_value = #{min_value} and y = #{y} and point = #{points[idx]}\"", "if", "points", "[", "idx", "]", ">", "0", "bar_height", "=", "points", "[", "idx", "]", "*", "maxh", "/", "max_value", "else", "bar_height", "=", "points", "[", "idx", "]", "*", "minh", "/", "min_value", "end", "#puts \" y = #{y} and point = #{points[idx]}\" ", "unless", "options", "[", ":border", "]", "==", "false", "svg", ".", "g", "(", ":transform", "=>", "\"translate(-#{relative(0.5)}, -#{relative(0.5)})\"", ")", "{", "svg", ".", "rect", "(", ":x", "=>", "x", ",", ":y", "=>", "y", ",", ":width", "=>", "@bar_width", "+", "relative", "(", "1", ")", ",", ":height", "=>", "bar_height", "+", "relative", "(", "1", ")", ",", ":style", "=>", "\"fill: black; fill-opacity: 0.15; stroke: none;\"", ")", "svg", ".", "rect", "(", ":x", "=>", "x", "+", "relative", "(", "0.5", ")", ",", ":y", "=>", "y", "+", "relative", "(", "2", ")", ",", ":width", "=>", "@bar_width", "+", "relative", "(", "1", ")", ",", ":height", "=>", "bar_height", "-", "relative", "(", "0.5", ")", ",", ":style", "=>", "\"fill: black; fill-opacity: 0.15; stroke: none;\"", ")", "}", "end", "current_colour", "=", "color", ".", "is_a?", "(", "Array", ")", "?", "color", "[", "idx", "%", "color", ".", "size", "]", ":", "color", "svg", ".", "rect", "(", ":x", "=>", "x", ",", ":y", "=>", "y", ",", ":width", "=>", "@bar_width", ",", ":height", "=>", "bar_height", ",", ":fill", "=>", "current_colour", ".", "to_s", ",", "'style'", "=>", "\"opacity: #{opacity}; stroke: none;\"", ")", "end", "end" ]
Draw bar graph. Now handles positive and negative values gracefully.
[ "Draw", "bar", "graph", ".", "Now", "handles", "positive", "and", "negative", "values", "gracefully", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/bar.rb#L12-L42
3,087
ktonon/cog
lib/cog/generator.rb
Cog.Generator.stamp
def stamp(template_path, destination=nil, opt={}) # Ignore destination if its a hash, its meant to be opt opt, destination = destination, nil if destination.is_a? Hash # Render and filter r = find_and_render template_path, opt r = filter_through r, opt[:filter] return r if destination.nil? # Place it in a file write_scratch_file(destination, r, opt[:absolute_destination]) do |path, scratch| updated = File.exists? path Embeds.copy_keeps(path, scratch) if files_are_same?(path, scratch) || (opt[:once] && updated) FileUtils.rm scratch else FileUtils.mv scratch, path STDOUT.write "#{updated ? :Updated : :Created} #{path.relative_to_project_root}\n".color(updated ? :white : :green) unless opt[:quiet] end end nil end
ruby
def stamp(template_path, destination=nil, opt={}) # Ignore destination if its a hash, its meant to be opt opt, destination = destination, nil if destination.is_a? Hash # Render and filter r = find_and_render template_path, opt r = filter_through r, opt[:filter] return r if destination.nil? # Place it in a file write_scratch_file(destination, r, opt[:absolute_destination]) do |path, scratch| updated = File.exists? path Embeds.copy_keeps(path, scratch) if files_are_same?(path, scratch) || (opt[:once] && updated) FileUtils.rm scratch else FileUtils.mv scratch, path STDOUT.write "#{updated ? :Updated : :Created} #{path.relative_to_project_root}\n".color(updated ? :white : :green) unless opt[:quiet] end end nil end
[ "def", "stamp", "(", "template_path", ",", "destination", "=", "nil", ",", "opt", "=", "{", "}", ")", "# Ignore destination if its a hash, its meant to be opt", "opt", ",", "destination", "=", "destination", ",", "nil", "if", "destination", ".", "is_a?", "Hash", "# Render and filter", "r", "=", "find_and_render", "template_path", ",", "opt", "r", "=", "filter_through", "r", ",", "opt", "[", ":filter", "]", "return", "r", "if", "destination", ".", "nil?", "# Place it in a file", "write_scratch_file", "(", "destination", ",", "r", ",", "opt", "[", ":absolute_destination", "]", ")", "do", "|", "path", ",", "scratch", "|", "updated", "=", "File", ".", "exists?", "path", "Embeds", ".", "copy_keeps", "(", "path", ",", "scratch", ")", "if", "files_are_same?", "(", "path", ",", "scratch", ")", "||", "(", "opt", "[", ":once", "]", "&&", "updated", ")", "FileUtils", ".", "rm", "scratch", "else", "FileUtils", ".", "mv", "scratch", ",", "path", "STDOUT", ".", "write", "\"#{updated ? :Updated : :Created} #{path.relative_to_project_root}\\n\"", ".", "color", "(", "updated", "?", ":white", ":", ":green", ")", "unless", "opt", "[", ":quiet", "]", "end", "end", "nil", "end" ]
Stamp a template into a file or return it as a string @param template_path [String] path to template file relative to {Config#template_path} @param destination [String] path to which the generated file should be written, relative to the {Config::ProjectConfig#project_path} @option opt [Boolean] :absolute_template_path (false) is the +template_path+ absolute? @option opt [Boolean] :absolute_destination (false) is the +destination+ absolute? @option opt [Boolean] :once (false) if +true+, the file will not be updated if it already exists @option opt [Binding] :binding (nil) an optional binding to use while evaluating the template @option opt [String, Array<String>] :filter (nil) name(s) of {Filters} @option opt [Boolean] :quiet (false) suppress writing to STDOUT? @return [nil or String] if +destination+ is not provided, the stamped template is returned as a string
[ "Stamp", "a", "template", "into", "a", "file", "or", "return", "it", "as", "a", "string" ]
156c81a0873135d7dc47c79c705c477893fff74a
https://github.com/ktonon/cog/blob/156c81a0873135d7dc47c79c705c477893fff74a/lib/cog/generator.rb#L39-L60
3,088
ktonon/cog
lib/cog/generator.rb
Cog.Generator.embed
def embed(hook, &block) eaten = 0 # keep track of eaten statements so that the index can be adjusted Embeds.find(hook) do |c| c.eaten = eaten if Embeds.update c, &block eaten += 1 if c.once? STDOUT.write "Updated #{c.path.relative_to_project_root} - #{(c.index + 1).ordinalize} occurrence of embed '#{c.hook}'\n".color :white end end end
ruby
def embed(hook, &block) eaten = 0 # keep track of eaten statements so that the index can be adjusted Embeds.find(hook) do |c| c.eaten = eaten if Embeds.update c, &block eaten += 1 if c.once? STDOUT.write "Updated #{c.path.relative_to_project_root} - #{(c.index + 1).ordinalize} occurrence of embed '#{c.hook}'\n".color :white end end end
[ "def", "embed", "(", "hook", ",", "&", "block", ")", "eaten", "=", "0", "# keep track of eaten statements so that the index can be adjusted", "Embeds", ".", "find", "(", "hook", ")", "do", "|", "c", "|", "c", ".", "eaten", "=", "eaten", "if", "Embeds", ".", "update", "c", ",", "block", "eaten", "+=", "1", "if", "c", ".", "once?", "STDOUT", ".", "write", "\"Updated #{c.path.relative_to_project_root} - #{(c.index + 1).ordinalize} occurrence of embed '#{c.hook}'\\n\"", ".", "color", ":white", "end", "end", "end" ]
Provide a value for embeds with the given hook @param hook [String] hook name used in the embed statements @yieldparam context [EmbedContext] provides information about the environment in which the embed statement was found @yieldreturn The value which will be used to expand the embed (or replace the embedded content) @return [nil]
[ "Provide", "a", "value", "for", "embeds", "with", "the", "given", "hook" ]
156c81a0873135d7dc47c79c705c477893fff74a
https://github.com/ktonon/cog/blob/156c81a0873135d7dc47c79c705c477893fff74a/lib/cog/generator.rb#L67-L76
3,089
rossf7/elasticrawl
lib/elasticrawl/combine_job.rb
Elasticrawl.CombineJob.set_input_jobs
def set_input_jobs(input_jobs) segment_count = 0 input_paths = [] input_jobs.each do |job_name| input_job = Job.where(:job_name => job_name, :type => 'Elasticrawl::ParseJob').first_or_initialize step_count = input_job.job_steps.count if step_count > 0 segment_count += step_count input_paths << set_input_path(input_job) end end self.job_name = set_job_name self.job_desc = set_job_desc(segment_count) job_steps.push(create_job_step(input_paths.join(','))) end
ruby
def set_input_jobs(input_jobs) segment_count = 0 input_paths = [] input_jobs.each do |job_name| input_job = Job.where(:job_name => job_name, :type => 'Elasticrawl::ParseJob').first_or_initialize step_count = input_job.job_steps.count if step_count > 0 segment_count += step_count input_paths << set_input_path(input_job) end end self.job_name = set_job_name self.job_desc = set_job_desc(segment_count) job_steps.push(create_job_step(input_paths.join(','))) end
[ "def", "set_input_jobs", "(", "input_jobs", ")", "segment_count", "=", "0", "input_paths", "=", "[", "]", "input_jobs", ".", "each", "do", "|", "job_name", "|", "input_job", "=", "Job", ".", "where", "(", ":job_name", "=>", "job_name", ",", ":type", "=>", "'Elasticrawl::ParseJob'", ")", ".", "first_or_initialize", "step_count", "=", "input_job", ".", "job_steps", ".", "count", "if", "step_count", ">", "0", "segment_count", "+=", "step_count", "input_paths", "<<", "set_input_path", "(", "input_job", ")", "end", "end", "self", ".", "job_name", "=", "set_job_name", "self", ".", "job_desc", "=", "set_job_desc", "(", "segment_count", ")", "job_steps", ".", "push", "(", "create_job_step", "(", "input_paths", ".", "join", "(", "','", ")", ")", ")", "end" ]
Takes in an array of parse jobs that are to be combined. Creates a single job step whose input paths are the outputs of the parse jobs.
[ "Takes", "in", "an", "array", "of", "parse", "jobs", "that", "are", "to", "be", "combined", ".", "Creates", "a", "single", "job", "step", "whose", "input", "paths", "are", "the", "outputs", "of", "the", "parse", "jobs", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/combine_job.rb#L10-L28
3,090
rossf7/elasticrawl
lib/elasticrawl/combine_job.rb
Elasticrawl.CombineJob.run
def run emr_config = job_config['emr_config'] job_flow_id = run_job_flow(emr_config) if job_flow_id.present? self.job_flow_id = job_flow_id self.save self.result_message end end
ruby
def run emr_config = job_config['emr_config'] job_flow_id = run_job_flow(emr_config) if job_flow_id.present? self.job_flow_id = job_flow_id self.save self.result_message end end
[ "def", "run", "emr_config", "=", "job_config", "[", "'emr_config'", "]", "job_flow_id", "=", "run_job_flow", "(", "emr_config", ")", "if", "job_flow_id", ".", "present?", "self", ".", "job_flow_id", "=", "job_flow_id", "self", ".", "save", "self", ".", "result_message", "end", "end" ]
Runs the job by calling the Elastic MapReduce API.
[ "Runs", "the", "job", "by", "calling", "the", "Elastic", "MapReduce", "API", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/combine_job.rb#L31-L40
3,091
rossf7/elasticrawl
lib/elasticrawl/combine_job.rb
Elasticrawl.CombineJob.set_input_path
def set_input_path(input_job) job_name = input_job.job_name input_filter = job_config['input_filter'] s3_path = "/data/1-parse/#{job_name}/segments/*/#{input_filter}" build_s3_uri(s3_path) end
ruby
def set_input_path(input_job) job_name = input_job.job_name input_filter = job_config['input_filter'] s3_path = "/data/1-parse/#{job_name}/segments/*/#{input_filter}" build_s3_uri(s3_path) end
[ "def", "set_input_path", "(", "input_job", ")", "job_name", "=", "input_job", ".", "job_name", "input_filter", "=", "job_config", "[", "'input_filter'", "]", "s3_path", "=", "\"/data/1-parse/#{job_name}/segments/*/#{input_filter}\"", "build_s3_uri", "(", "s3_path", ")", "end" ]
Returns the S3 location for reading a parse job. A wildcard is used for the segment names. The input filter depends on the output file type of the parse job and what type of compression is used.
[ "Returns", "the", "S3", "location", "for", "reading", "a", "parse", "job", ".", "A", "wildcard", "is", "used", "for", "the", "segment", "names", ".", "The", "input", "filter", "depends", "on", "the", "output", "file", "type", "of", "the", "parse", "job", "and", "what", "type", "of", "compression", "is", "used", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/combine_job.rb#L60-L66
3,092
rossf7/elasticrawl
lib/elasticrawl/config.rb
Elasticrawl.Config.load_config
def load_config(config_file) if dir_exists? begin config_file = File.join(config_dir, "#{config_file}.yml") config = YAML::load(File.open(config_file)) rescue StandardError => e raise FileAccessError, e.message end else raise ConfigDirMissingError, 'Config dir missing. Run init command' end end
ruby
def load_config(config_file) if dir_exists? begin config_file = File.join(config_dir, "#{config_file}.yml") config = YAML::load(File.open(config_file)) rescue StandardError => e raise FileAccessError, e.message end else raise ConfigDirMissingError, 'Config dir missing. Run init command' end end
[ "def", "load_config", "(", "config_file", ")", "if", "dir_exists?", "begin", "config_file", "=", "File", ".", "join", "(", "config_dir", ",", "\"#{config_file}.yml\"", ")", "config", "=", "YAML", "::", "load", "(", "File", ".", "open", "(", "config_file", ")", ")", "rescue", "StandardError", "=>", "e", "raise", "FileAccessError", ",", "e", ".", "message", "end", "else", "raise", "ConfigDirMissingError", ",", "'Config dir missing. Run init command'", "end", "end" ]
Loads a YAML configuration file.
[ "Loads", "a", "YAML", "configuration", "file", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/config.rb#L57-L69
3,093
rossf7/elasticrawl
lib/elasticrawl/config.rb
Elasticrawl.Config.load_database
def load_database if dir_exists? config = { 'adapter' => 'sqlite3', 'database' => File.join(config_dir, DATABASE_FILE), 'pool' => 5, 'timeout' => 5000 } begin ActiveRecord::Base.establish_connection(config) ActiveRecord::Migrator.migrate(File.join(File.dirname(__FILE__), \ '../../db/migrate'), ENV['VERSION'] ? ENV['VERSION'].to_i : nil ) rescue StandardError => e raise DatabaseAccessError, e.message end else raise ConfigDirMissingError, 'Config dir missing. Run init command' end end
ruby
def load_database if dir_exists? config = { 'adapter' => 'sqlite3', 'database' => File.join(config_dir, DATABASE_FILE), 'pool' => 5, 'timeout' => 5000 } begin ActiveRecord::Base.establish_connection(config) ActiveRecord::Migrator.migrate(File.join(File.dirname(__FILE__), \ '../../db/migrate'), ENV['VERSION'] ? ENV['VERSION'].to_i : nil ) rescue StandardError => e raise DatabaseAccessError, e.message end else raise ConfigDirMissingError, 'Config dir missing. Run init command' end end
[ "def", "load_database", "if", "dir_exists?", "config", "=", "{", "'adapter'", "=>", "'sqlite3'", ",", "'database'", "=>", "File", ".", "join", "(", "config_dir", ",", "DATABASE_FILE", ")", ",", "'pool'", "=>", "5", ",", "'timeout'", "=>", "5000", "}", "begin", "ActiveRecord", "::", "Base", ".", "establish_connection", "(", "config", ")", "ActiveRecord", "::", "Migrator", ".", "migrate", "(", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "'../../db/migrate'", ")", ",", "ENV", "[", "'VERSION'", "]", "?", "ENV", "[", "'VERSION'", "]", ".", "to_i", ":", "nil", ")", "rescue", "StandardError", "=>", "e", "raise", "DatabaseAccessError", ",", "e", ".", "message", "end", "else", "raise", "ConfigDirMissingError", ",", "'Config dir missing. Run init command'", "end", "end" ]
Loads the sqlite database. If no database exists it will be created and the database migrations will be run.
[ "Loads", "the", "sqlite", "database", ".", "If", "no", "database", "exists", "it", "will", "be", "created", "and", "the", "database", "migrations", "will", "be", "run", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/config.rb#L73-L93
3,094
rossf7/elasticrawl
lib/elasticrawl/config.rb
Elasticrawl.Config.bucket_exists?
def bucket_exists?(bucket_name) begin s3 = AWS::S3.new s3.buckets[bucket_name].exists? rescue AWS::S3::Errors::SignatureDoesNotMatch => e raise AWSCredentialsInvalidError, 'AWS access credentials are invalid' rescue AWS::Errors::Base => s3e raise S3AccessError.new(s3e.http_response), s3e.message end end
ruby
def bucket_exists?(bucket_name) begin s3 = AWS::S3.new s3.buckets[bucket_name].exists? rescue AWS::S3::Errors::SignatureDoesNotMatch => e raise AWSCredentialsInvalidError, 'AWS access credentials are invalid' rescue AWS::Errors::Base => s3e raise S3AccessError.new(s3e.http_response), s3e.message end end
[ "def", "bucket_exists?", "(", "bucket_name", ")", "begin", "s3", "=", "AWS", "::", "S3", ".", "new", "s3", ".", "buckets", "[", "bucket_name", "]", ".", "exists?", "rescue", "AWS", "::", "S3", "::", "Errors", "::", "SignatureDoesNotMatch", "=>", "e", "raise", "AWSCredentialsInvalidError", ",", "'AWS access credentials are invalid'", "rescue", "AWS", "::", "Errors", "::", "Base", "=>", "s3e", "raise", "S3AccessError", ".", "new", "(", "s3e", ".", "http_response", ")", ",", "s3e", ".", "message", "end", "end" ]
Checks if a S3 bucket name is in use.
[ "Checks", "if", "a", "S3", "bucket", "name", "is", "in", "use", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/config.rb#L96-L106
3,095
rossf7/elasticrawl
lib/elasticrawl/config.rb
Elasticrawl.Config.create_bucket
def create_bucket(bucket_name) begin s3 = AWS::S3.new s3.buckets.create(bucket_name) rescue AWS::Errors::Base => s3e raise S3AccessError.new(s3e.http_response), s3e.message end end
ruby
def create_bucket(bucket_name) begin s3 = AWS::S3.new s3.buckets.create(bucket_name) rescue AWS::Errors::Base => s3e raise S3AccessError.new(s3e.http_response), s3e.message end end
[ "def", "create_bucket", "(", "bucket_name", ")", "begin", "s3", "=", "AWS", "::", "S3", ".", "new", "s3", ".", "buckets", ".", "create", "(", "bucket_name", ")", "rescue", "AWS", "::", "Errors", "::", "Base", "=>", "s3e", "raise", "S3AccessError", ".", "new", "(", "s3e", ".", "http_response", ")", ",", "s3e", ".", "message", "end", "end" ]
Creates a bucket using the S3 API.
[ "Creates", "a", "bucket", "using", "the", "S3", "API", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/config.rb#L156-L164
3,096
rossf7/elasticrawl
lib/elasticrawl/config.rb
Elasticrawl.Config.delete_bucket
def delete_bucket(bucket_name) begin s3 = AWS::S3.new bucket = s3.buckets[bucket_name] bucket.delete! rescue AWS::Errors::Base => s3e raise S3AccessError.new(s3e.http_response), s3e.message end end
ruby
def delete_bucket(bucket_name) begin s3 = AWS::S3.new bucket = s3.buckets[bucket_name] bucket.delete! rescue AWS::Errors::Base => s3e raise S3AccessError.new(s3e.http_response), s3e.message end end
[ "def", "delete_bucket", "(", "bucket_name", ")", "begin", "s3", "=", "AWS", "::", "S3", ".", "new", "bucket", "=", "s3", ".", "buckets", "[", "bucket_name", "]", "bucket", ".", "delete!", "rescue", "AWS", "::", "Errors", "::", "Base", "=>", "s3e", "raise", "S3AccessError", ".", "new", "(", "s3e", ".", "http_response", ")", ",", "s3e", ".", "message", "end", "end" ]
Deletes a bucket and its contents using the S3 API.
[ "Deletes", "a", "bucket", "and", "its", "contents", "using", "the", "S3", "API", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/config.rb#L167-L176
3,097
rossf7/elasticrawl
lib/elasticrawl/config.rb
Elasticrawl.Config.deploy_templates
def deploy_templates(bucket_name) begin Dir.mkdir(config_dir, 0755) if dir_exists? == false TEMPLATE_FILES.each do |template_file| FileUtils.cp(File.join(File.dirname(__FILE__), TEMPLATES_DIR, template_file), File.join(config_dir, template_file)) end save_config('jobs', { 'BUCKET_NAME' => bucket_name }) save_aws_config rescue StandardError => e raise FileAccessError, e.message end end
ruby
def deploy_templates(bucket_name) begin Dir.mkdir(config_dir, 0755) if dir_exists? == false TEMPLATE_FILES.each do |template_file| FileUtils.cp(File.join(File.dirname(__FILE__), TEMPLATES_DIR, template_file), File.join(config_dir, template_file)) end save_config('jobs', { 'BUCKET_NAME' => bucket_name }) save_aws_config rescue StandardError => e raise FileAccessError, e.message end end
[ "def", "deploy_templates", "(", "bucket_name", ")", "begin", "Dir", ".", "mkdir", "(", "config_dir", ",", "0755", ")", "if", "dir_exists?", "==", "false", "TEMPLATE_FILES", ".", "each", "do", "|", "template_file", "|", "FileUtils", ".", "cp", "(", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "TEMPLATES_DIR", ",", "template_file", ")", ",", "File", ".", "join", "(", "config_dir", ",", "template_file", ")", ")", "end", "save_config", "(", "'jobs'", ",", "{", "'BUCKET_NAME'", "=>", "bucket_name", "}", ")", "save_aws_config", "rescue", "StandardError", "=>", "e", "raise", "FileAccessError", ",", "e", ".", "message", "end", "end" ]
Creates config directory and copies config templates into it. Saves S3 bucket name to jobs.yml and AWS credentials to aws.yml.
[ "Creates", "config", "directory", "and", "copies", "config", "templates", "into", "it", ".", "Saves", "S3", "bucket", "name", "to", "jobs", ".", "yml", "and", "AWS", "credentials", "to", "aws", ".", "yml", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/config.rb#L180-L195
3,098
rossf7/elasticrawl
lib/elasticrawl/config.rb
Elasticrawl.Config.save_aws_config
def save_aws_config env_key = ENV['AWS_ACCESS_KEY_ID'] env_secret = ENV['AWS_SECRET_ACCESS_KEY'] creds = {} creds['ACCESS_KEY_ID'] = @access_key_id unless @access_key_id == env_key creds['SECRET_ACCESS_KEY'] = @secret_access_key \ unless @secret_access_key == env_secret save_config('aws', creds) end
ruby
def save_aws_config env_key = ENV['AWS_ACCESS_KEY_ID'] env_secret = ENV['AWS_SECRET_ACCESS_KEY'] creds = {} creds['ACCESS_KEY_ID'] = @access_key_id unless @access_key_id == env_key creds['SECRET_ACCESS_KEY'] = @secret_access_key \ unless @secret_access_key == env_secret save_config('aws', creds) end
[ "def", "save_aws_config", "env_key", "=", "ENV", "[", "'AWS_ACCESS_KEY_ID'", "]", "env_secret", "=", "ENV", "[", "'AWS_SECRET_ACCESS_KEY'", "]", "creds", "=", "{", "}", "creds", "[", "'ACCESS_KEY_ID'", "]", "=", "@access_key_id", "unless", "@access_key_id", "==", "env_key", "creds", "[", "'SECRET_ACCESS_KEY'", "]", "=", "@secret_access_key", "unless", "@secret_access_key", "==", "env_secret", "save_config", "(", "'aws'", ",", "creds", ")", "end" ]
Saves AWS access credentials to aws.yml unless they are configured as environment variables.
[ "Saves", "AWS", "access", "credentials", "to", "aws", ".", "yml", "unless", "they", "are", "configured", "as", "environment", "variables", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/config.rb#L199-L209
3,099
rossf7/elasticrawl
lib/elasticrawl/config.rb
Elasticrawl.Config.save_config
def save_config(template, params) config_file = File.join(config_dir, "#{template}.yml") config = File.read(config_file) params.map { |key, value| config = config.gsub(key, value) } File.open(config_file, 'w') { |file| file.write(config) } end
ruby
def save_config(template, params) config_file = File.join(config_dir, "#{template}.yml") config = File.read(config_file) params.map { |key, value| config = config.gsub(key, value) } File.open(config_file, 'w') { |file| file.write(config) } end
[ "def", "save_config", "(", "template", ",", "params", ")", "config_file", "=", "File", ".", "join", "(", "config_dir", ",", "\"#{template}.yml\"", ")", "config", "=", "File", ".", "read", "(", "config_file", ")", "params", ".", "map", "{", "|", "key", ",", "value", "|", "config", "=", "config", ".", "gsub", "(", "key", ",", "value", ")", "}", "File", ".", "open", "(", "config_file", ",", "'w'", ")", "{", "|", "file", "|", "file", ".", "write", "(", "config", ")", "}", "end" ]
Saves config values by overwriting placeholder values in template.
[ "Saves", "config", "values", "by", "overwriting", "placeholder", "values", "in", "template", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/config.rb#L212-L219