repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
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
train
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
train
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", "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
train
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
train
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
train
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
train
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
train
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
train
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", "|", "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
train
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", "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
train
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
train
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
train
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
train
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
train
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", "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
train
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", ")", "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
train
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", ")", "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
train
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", ")", "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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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", "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
train
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
train
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", "valh", "=", "max_value", "+", "min_value", "*", "-", "1", "maxh", "=", "max_value", "*", "height", "/", "valh", "minh", "=", "min_value", "*", "height", "/", "valh", "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\"", ")", "end", "end" ]
Draw box plot.
[ "Draw", "box", "plot", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/box.rb#L11-L44
train
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
train
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", "=", "{", "}", ")", "layers", ".", "each_with_index", "do", "|", "layer", ",", "i", "|", "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", ")", "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
train
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", "valh", "=", "max_value", "+", "min_value", "*", "-", "1", "maxh", "=", "max_value", "*", "height", "/", "valh", "minh", "=", "min_value", "*", "height", "/", "valh", "if", "points", "[", "idx", "]", ">", "0", "bar_height", "=", "points", "[", "idx", "]", "*", "maxh", "/", "max_value", "else", "bar_height", "=", "points", "[", "idx", "]", "*", "minh", "/", "min_value", "end", "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
train
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", "=", "{", "}", ")", "opt", ",", "destination", "=", "destination", ",", "nil", "if", "destination", ".", "is_a?", "Hash", "r", "=", "find_and_render", "template_path", ",", "opt", "r", "=", "filter_through", "r", ",", "opt", "[", ":filter", "]", "return", "r", "if", "destination", ".", "nil?", "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
train
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", "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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
rossf7/elasticrawl
lib/elasticrawl/config.rb
Elasticrawl.Config.delete_config_dir
def delete_config_dir begin FileUtils.rm_r(config_dir) if dir_exists? rescue StandardError => e raise FileAccessError, e.message end end
ruby
def delete_config_dir begin FileUtils.rm_r(config_dir) if dir_exists? rescue StandardError => e raise FileAccessError, e.message end end
[ "def", "delete_config_dir", "begin", "FileUtils", ".", "rm_r", "(", "config_dir", ")", "if", "dir_exists?", "rescue", "StandardError", "=>", "e", "raise", "FileAccessError", ",", "e", ".", "message", "end", "end" ]
Deletes the config directory including its contents.
[ "Deletes", "the", "config", "directory", "including", "its", "contents", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/config.rb#L222-L229
train
rossf7/elasticrawl
lib/elasticrawl/config.rb
Elasticrawl.Config.status_message
def status_message(bucket_name, state) message = ['', "Bucket s3://#{bucket_name} #{state}"] message << "Config dir #{config_dir} #{state}" state = 'complete' if state == 'created' message << "Config #{state}" message.join("\n") end
ruby
def status_message(bucket_name, state) message = ['', "Bucket s3://#{bucket_name} #{state}"] message << "Config dir #{config_dir} #{state}" state = 'complete' if state == 'created' message << "Config #{state}" message.join("\n") end
[ "def", "status_message", "(", "bucket_name", ",", "state", ")", "message", "=", "[", "''", ",", "\"Bucket s3://#{bucket_name} #{state}\"", "]", "message", "<<", "\"Config dir #{config_dir} #{state}\"", "state", "=", "'complete'", "if", "state", "==", "'created'", "message", "<<", "\"Config #{state}\"", "message", ".", "join", "(", "\"\\n\"", ")", "end" ]
Notifies user of results of init or destroy commands.
[ "Notifies", "user", "of", "results", "of", "init", "or", "destroy", "commands", "." ]
db70bb6819c86805869f389daf1920f3acc87cef
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/config.rb#L232-L240
train
ivpusic/migrate
lib/migrate/migrator.rb
Migrate.Migrator.exec_migration
def exec_migration(migration, is_up) migration_dir = self.migration_dir(migration) result = @lang.exec_migration(migration_dir, is_up) if @lang.ext != "sql" puts result end Log.info("Updating current version number...") version = migration["version"] is_up ? @db.log_up(version) : @db.log_down(version) end
ruby
def exec_migration(migration, is_up) migration_dir = self.migration_dir(migration) result = @lang.exec_migration(migration_dir, is_up) if @lang.ext != "sql" puts result end Log.info("Updating current version number...") version = migration["version"] is_up ? @db.log_up(version) : @db.log_down(version) end
[ "def", "exec_migration", "(", "migration", ",", "is_up", ")", "migration_dir", "=", "self", ".", "migration_dir", "(", "migration", ")", "result", "=", "@lang", ".", "exec_migration", "(", "migration_dir", ",", "is_up", ")", "if", "@lang", ".", "ext", "!=", "\"sql\"", "puts", "result", "end", "Log", ".", "info", "(", "\"Updating current version number...\"", ")", "version", "=", "migration", "[", "\"version\"", "]", "is_up", "?", "@db", ".", "log_up", "(", "version", ")", ":", "@db", ".", "log_down", "(", "version", ")", "end" ]
will execute single migration by running up or down script
[ "will", "execute", "single", "migration", "by", "running", "up", "or", "down", "script" ]
2673115509e42c436e09857451d4a1c335e1089d
https://github.com/ivpusic/migrate/blob/2673115509e42c436e09857451d4a1c335e1089d/lib/migrate/migrator.rb#L79-L89
train
ivpusic/migrate
lib/migrate/migrator.rb
Migrate.Migrator.exec_migrations
def exec_migrations(is_up=true) Log.info("Executing migrations...") migrations = yield @db.current_version if migrations.count == 0 Log.warn("Migrations not found") return end migrations.each do |migration| self.exec_migration(migration, is_up) end Log.success("Migrations executed. Current version: #{@db.current_version}") end
ruby
def exec_migrations(is_up=true) Log.info("Executing migrations...") migrations = yield @db.current_version if migrations.count == 0 Log.warn("Migrations not found") return end migrations.each do |migration| self.exec_migration(migration, is_up) end Log.success("Migrations executed. Current version: #{@db.current_version}") end
[ "def", "exec_migrations", "(", "is_up", "=", "true", ")", "Log", ".", "info", "(", "\"Executing migrations...\"", ")", "migrations", "=", "yield", "@db", ".", "current_version", "if", "migrations", ".", "count", "==", "0", "Log", ".", "warn", "(", "\"Migrations not found\"", ")", "return", "end", "migrations", ".", "each", "do", "|", "migration", "|", "self", ".", "exec_migration", "(", "migration", ",", "is_up", ")", "end", "Log", ".", "success", "(", "\"Migrations executed. Current version: #{@db.current_version}\"", ")", "end" ]
will execute range of migrations
[ "will", "execute", "range", "of", "migrations" ]
2673115509e42c436e09857451d4a1c335e1089d
https://github.com/ivpusic/migrate/blob/2673115509e42c436e09857451d4a1c335e1089d/lib/migrate/migrator.rb#L92-L105
train
rrrene/sparkr
lib/sparkr/cli.rb
Sparkr.CLI.run
def run(*args) if args.empty? || (args.size == 1 && %w(-h --help).include?(args.first)) puts help else sparkline = Sparkline.new(args.map(&:to_f)) puts sparkline.to_s end end
ruby
def run(*args) if args.empty? || (args.size == 1 && %w(-h --help).include?(args.first)) puts help else sparkline = Sparkline.new(args.map(&:to_f)) puts sparkline.to_s end end
[ "def", "run", "(", "*", "args", ")", "if", "args", ".", "empty?", "||", "(", "args", ".", "size", "==", "1", "&&", "%w(", "-h", "--help", ")", ".", "include?", "(", "args", ".", "first", ")", ")", "puts", "help", "else", "sparkline", "=", "Sparkline", ".", "new", "(", "args", ".", "map", "(", "&", ":to_f", ")", ")", "puts", "sparkline", ".", "to_s", "end", "end" ]
Runs sparkr with the given +args+ @return [void]
[ "Runs", "sparkr", "with", "the", "given", "+", "args", "+" ]
2329d965ae421dfbc4743dd728884f2da501a107
https://github.com/rrrene/sparkr/blob/2329d965ae421dfbc4743dd728884f2da501a107/lib/sparkr/cli.rb#L17-L24
train
opentox/lazar
lib/compound.rb
OpenTox.Compound.fingerprint
def fingerprint type=DEFAULT_FINGERPRINT unless fingerprints[type] return [] unless self.smiles #http://openbabel.org/docs/dev/FileFormats/MolPrint2D_format.html#molprint2d-format if type == "MP2D" fp = obconversion(smiles,"smi","mpd").strip.split("\t") name = fp.shift # remove Title fingerprints[type] = fp.uniq # no fingerprint counts #http://openbabel.org/docs/dev/FileFormats/Multilevel_Neighborhoods_of_Atoms_(MNA).html elsif type== "MNA" level = 2 # TODO: level as parameter, evaluate level 1, see paper fp = obconversion(smiles,"smi","mna","xL\"#{level}\"").split("\n") fp.shift # remove Title fingerprints[type] = fp else # standard fingerprints fp = OpenBabel::OBFingerprint.find_fingerprint(type) obmol = OpenBabel::OBMol.new obconversion = OpenBabel::OBConversion.new obconversion.set_in_format "smi" obconversion.read_string obmol, self.smiles result = OpenBabel::VectorUnsignedInt.new fp.get_fingerprint(obmol,result) # TODO: %ignore *::DescribeBits @ line 163 openbabel/scripts/openbabel-ruby.i #p OpenBabel::OBFingerprint.describe_bits(result) # convert result to a list of the bits that are set # from openbabel/scripts/python/pybel.py line 830 # see also http://openbabel.org/docs/dev/UseTheLibrary/Python_Pybel.html#fingerprints result = result.to_a bitsperint = OpenBabel::OBFingerprint.getbitsperint() bits_set = [] start = 1 result.each do |x| i = start while x > 0 do bits_set << i if (x % 2) == 1 x >>= 1 i += 1 end start += bitsperint end fingerprints[type] = bits_set end save end fingerprints[type] end
ruby
def fingerprint type=DEFAULT_FINGERPRINT unless fingerprints[type] return [] unless self.smiles #http://openbabel.org/docs/dev/FileFormats/MolPrint2D_format.html#molprint2d-format if type == "MP2D" fp = obconversion(smiles,"smi","mpd").strip.split("\t") name = fp.shift # remove Title fingerprints[type] = fp.uniq # no fingerprint counts #http://openbabel.org/docs/dev/FileFormats/Multilevel_Neighborhoods_of_Atoms_(MNA).html elsif type== "MNA" level = 2 # TODO: level as parameter, evaluate level 1, see paper fp = obconversion(smiles,"smi","mna","xL\"#{level}\"").split("\n") fp.shift # remove Title fingerprints[type] = fp else # standard fingerprints fp = OpenBabel::OBFingerprint.find_fingerprint(type) obmol = OpenBabel::OBMol.new obconversion = OpenBabel::OBConversion.new obconversion.set_in_format "smi" obconversion.read_string obmol, self.smiles result = OpenBabel::VectorUnsignedInt.new fp.get_fingerprint(obmol,result) # TODO: %ignore *::DescribeBits @ line 163 openbabel/scripts/openbabel-ruby.i #p OpenBabel::OBFingerprint.describe_bits(result) # convert result to a list of the bits that are set # from openbabel/scripts/python/pybel.py line 830 # see also http://openbabel.org/docs/dev/UseTheLibrary/Python_Pybel.html#fingerprints result = result.to_a bitsperint = OpenBabel::OBFingerprint.getbitsperint() bits_set = [] start = 1 result.each do |x| i = start while x > 0 do bits_set << i if (x % 2) == 1 x >>= 1 i += 1 end start += bitsperint end fingerprints[type] = bits_set end save end fingerprints[type] end
[ "def", "fingerprint", "type", "=", "DEFAULT_FINGERPRINT", "unless", "fingerprints", "[", "type", "]", "return", "[", "]", "unless", "self", ".", "smiles", "if", "type", "==", "\"MP2D\"", "fp", "=", "obconversion", "(", "smiles", ",", "\"smi\"", ",", "\"mpd\"", ")", ".", "strip", ".", "split", "(", "\"\\t\"", ")", "name", "=", "fp", ".", "shift", "fingerprints", "[", "type", "]", "=", "fp", ".", "uniq", "elsif", "type", "==", "\"MNA\"", "level", "=", "2", "fp", "=", "obconversion", "(", "smiles", ",", "\"smi\"", ",", "\"mna\"", ",", "\"xL\\\"#{level}\\\"\"", ")", ".", "split", "(", "\"\\n\"", ")", "fp", ".", "shift", "fingerprints", "[", "type", "]", "=", "fp", "else", "fp", "=", "OpenBabel", "::", "OBFingerprint", ".", "find_fingerprint", "(", "type", ")", "obmol", "=", "OpenBabel", "::", "OBMol", ".", "new", "obconversion", "=", "OpenBabel", "::", "OBConversion", ".", "new", "obconversion", ".", "set_in_format", "\"smi\"", "obconversion", ".", "read_string", "obmol", ",", "self", ".", "smiles", "result", "=", "OpenBabel", "::", "VectorUnsignedInt", ".", "new", "fp", ".", "get_fingerprint", "(", "obmol", ",", "result", ")", "result", "=", "result", ".", "to_a", "bitsperint", "=", "OpenBabel", "::", "OBFingerprint", ".", "getbitsperint", "(", ")", "bits_set", "=", "[", "]", "start", "=", "1", "result", ".", "each", "do", "|", "x", "|", "i", "=", "start", "while", "x", ">", "0", "do", "bits_set", "<<", "i", "if", "(", "x", "%", "2", ")", "==", "1", "x", ">>=", "1", "i", "+=", "1", "end", "start", "+=", "bitsperint", "end", "fingerprints", "[", "type", "]", "=", "bits_set", "end", "save", "end", "fingerprints", "[", "type", "]", "end" ]
Create chemical fingerprint @param [String] fingerprint type @return [Array<String>]
[ "Create", "chemical", "fingerprint" ]
1ee7de09c969e16fd11522d22179224e694b0161
https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/compound.rb#L35-L80
train
opentox/lazar
lib/compound.rb
OpenTox.Compound.smarts_match
def smarts_match smarts, count=false obconversion = OpenBabel::OBConversion.new obmol = OpenBabel::OBMol.new obconversion.set_in_format('smi') obconversion.read_string(obmol,self.smiles) smarts_pattern = OpenBabel::OBSmartsPattern.new smarts.collect do |sma| smarts_pattern.init(sma.smarts) if smarts_pattern.match(obmol) count ? value = smarts_pattern.get_map_list.to_a.size : value = 1 else value = 0 end value end end
ruby
def smarts_match smarts, count=false obconversion = OpenBabel::OBConversion.new obmol = OpenBabel::OBMol.new obconversion.set_in_format('smi') obconversion.read_string(obmol,self.smiles) smarts_pattern = OpenBabel::OBSmartsPattern.new smarts.collect do |sma| smarts_pattern.init(sma.smarts) if smarts_pattern.match(obmol) count ? value = smarts_pattern.get_map_list.to_a.size : value = 1 else value = 0 end value end end
[ "def", "smarts_match", "smarts", ",", "count", "=", "false", "obconversion", "=", "OpenBabel", "::", "OBConversion", ".", "new", "obmol", "=", "OpenBabel", "::", "OBMol", ".", "new", "obconversion", ".", "set_in_format", "(", "'smi'", ")", "obconversion", ".", "read_string", "(", "obmol", ",", "self", ".", "smiles", ")", "smarts_pattern", "=", "OpenBabel", "::", "OBSmartsPattern", ".", "new", "smarts", ".", "collect", "do", "|", "sma", "|", "smarts_pattern", ".", "init", "(", "sma", ".", "smarts", ")", "if", "smarts_pattern", ".", "match", "(", "obmol", ")", "count", "?", "value", "=", "smarts_pattern", ".", "get_map_list", ".", "to_a", ".", "size", ":", "value", "=", "1", "else", "value", "=", "0", "end", "value", "end", "end" ]
Match a SMARTS substructure @param [String] smarts @param [TrueClass,FalseClass] count matches or return true/false @return [TrueClass,FalseClass,Fixnum]
[ "Match", "a", "SMARTS", "substructure" ]
1ee7de09c969e16fd11522d22179224e694b0161
https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/compound.rb#L110-L125
train
opentox/lazar
lib/compound.rb
OpenTox.Compound.svg
def svg if self.svg_id.nil? svg = obconversion(smiles,"smi","svg") file = Mongo::Grid::File.new(svg, :filename => "#{id}.svg", :content_type => "image/svg") update(:svg_id => $gridfs.insert_one(file)) end $gridfs.find_one(_id: self.svg_id).data end
ruby
def svg if self.svg_id.nil? svg = obconversion(smiles,"smi","svg") file = Mongo::Grid::File.new(svg, :filename => "#{id}.svg", :content_type => "image/svg") update(:svg_id => $gridfs.insert_one(file)) end $gridfs.find_one(_id: self.svg_id).data end
[ "def", "svg", "if", "self", ".", "svg_id", ".", "nil?", "svg", "=", "obconversion", "(", "smiles", ",", "\"smi\"", ",", "\"svg\"", ")", "file", "=", "Mongo", "::", "Grid", "::", "File", ".", "new", "(", "svg", ",", ":filename", "=>", "\"#{id}.svg\"", ",", ":content_type", "=>", "\"image/svg\"", ")", "update", "(", ":svg_id", "=>", "$gridfs", ".", "insert_one", "(", "file", ")", ")", "end", "$gridfs", ".", "find_one", "(", "_id", ":", "self", ".", "svg_id", ")", ".", "data", "end" ]
Get SVG image @return [image/svg] Image data
[ "Get", "SVG", "image" ]
1ee7de09c969e16fd11522d22179224e694b0161
https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/compound.rb#L214-L221
train
opentox/lazar
lib/compound.rb
OpenTox.Compound.png
def png if self.png_id.nil? png = obconversion(smiles,"smi","_png2") file = Mongo::Grid::File.new(Base64.encode64(png), :filename => "#{id}.png", :content_type => "image/png") update(:png_id => $gridfs.insert_one(file)) end Base64.decode64($gridfs.find_one(_id: self.png_id).data) end
ruby
def png if self.png_id.nil? png = obconversion(smiles,"smi","_png2") file = Mongo::Grid::File.new(Base64.encode64(png), :filename => "#{id}.png", :content_type => "image/png") update(:png_id => $gridfs.insert_one(file)) end Base64.decode64($gridfs.find_one(_id: self.png_id).data) end
[ "def", "png", "if", "self", ".", "png_id", ".", "nil?", "png", "=", "obconversion", "(", "smiles", ",", "\"smi\"", ",", "\"_png2\"", ")", "file", "=", "Mongo", "::", "Grid", "::", "File", ".", "new", "(", "Base64", ".", "encode64", "(", "png", ")", ",", ":filename", "=>", "\"#{id}.png\"", ",", ":content_type", "=>", "\"image/png\"", ")", "update", "(", ":png_id", "=>", "$gridfs", ".", "insert_one", "(", "file", ")", ")", "end", "Base64", ".", "decode64", "(", "$gridfs", ".", "find_one", "(", "_id", ":", "self", ".", "png_id", ")", ".", "data", ")", "end" ]
Get png image @example image = compound.png @return [image/png] Image data
[ "Get", "png", "image" ]
1ee7de09c969e16fd11522d22179224e694b0161
https://github.com/opentox/lazar/blob/1ee7de09c969e16fd11522d22179224e694b0161/lib/compound.rb#L227-L234
train
brasten/scruffy
lib/scruffy/layers/average.rb
Scruffy::Layers.Average.generate_coordinates
def generate_coordinates(options = {}) key_layer = layers.find { |layer| layer.relevant_data? } options[:point_distance] = width / (key_layer.points.size - 1).to_f coords = [] #TODO this will likely break with the new hash model key_layer.points.each_with_index do |layer, idx| sum, objects = points.inject([0, 0]) do |arr, elem| if elem.relevant_data? arr[0] += elem.points[idx] arr[1] += 1 end arr end average = sum / objects.to_f x_coord = options[:point_distance] * idx relative_percent = ((average == min_value) ? 0 : ((average - min_value) / (max_value - min_value).to_f)) y_coord = (height - (height * relative_percent)) coords << [x_coord, y_coord].join(',') end return coords end
ruby
def generate_coordinates(options = {}) key_layer = layers.find { |layer| layer.relevant_data? } options[:point_distance] = width / (key_layer.points.size - 1).to_f coords = [] #TODO this will likely break with the new hash model key_layer.points.each_with_index do |layer, idx| sum, objects = points.inject([0, 0]) do |arr, elem| if elem.relevant_data? arr[0] += elem.points[idx] arr[1] += 1 end arr end average = sum / objects.to_f x_coord = options[:point_distance] * idx relative_percent = ((average == min_value) ? 0 : ((average - min_value) / (max_value - min_value).to_f)) y_coord = (height - (height * relative_percent)) coords << [x_coord, y_coord].join(',') end return coords end
[ "def", "generate_coordinates", "(", "options", "=", "{", "}", ")", "key_layer", "=", "layers", ".", "find", "{", "|", "layer", "|", "layer", ".", "relevant_data?", "}", "options", "[", ":point_distance", "]", "=", "width", "/", "(", "key_layer", ".", "points", ".", "size", "-", "1", ")", ".", "to_f", "coords", "=", "[", "]", "key_layer", ".", "points", ".", "each_with_index", "do", "|", "layer", ",", "idx", "|", "sum", ",", "objects", "=", "points", ".", "inject", "(", "[", "0", ",", "0", "]", ")", "do", "|", "arr", ",", "elem", "|", "if", "elem", ".", "relevant_data?", "arr", "[", "0", "]", "+=", "elem", ".", "points", "[", "idx", "]", "arr", "[", "1", "]", "+=", "1", "end", "arr", "end", "average", "=", "sum", "/", "objects", ".", "to_f", "x_coord", "=", "options", "[", ":point_distance", "]", "*", "idx", "relative_percent", "=", "(", "(", "average", "==", "min_value", ")", "?", "0", ":", "(", "(", "average", "-", "min_value", ")", "/", "(", "max_value", "-", "min_value", ")", ".", "to_f", ")", ")", "y_coord", "=", "(", "height", "-", "(", "height", "*", "relative_percent", ")", ")", "coords", "<<", "[", "x_coord", ",", "y_coord", "]", ".", "join", "(", "','", ")", "end", "return", "coords", "end" ]
Override default generate_coordinates method to iterate through the layers and generate coordinates based on the average data points.
[ "Override", "default", "generate_coordinates", "method", "to", "iterate", "through", "the", "layers", "and", "generate", "coordinates", "based", "on", "the", "average", "data", "points", "." ]
4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e
https://github.com/brasten/scruffy/blob/4aad4f9ab2b946ba0f6e6251dc7eb3b9747a4e9e/lib/scruffy/layers/average.rb#L36-L64
train
social-snippet/social-snippet
lib/social_snippet/repository/repository_manager.rb
SocialSnippet::Repository.RepositoryManager.resolve_snippet_path
def resolve_snippet_path(context, tag) if tag.has_repo? pkg = find_package_by_tag(tag) pkg.snippet_path tag.path else new_context = context.clone new_context.dirname + "/" + tag.filename end end
ruby
def resolve_snippet_path(context, tag) if tag.has_repo? pkg = find_package_by_tag(tag) pkg.snippet_path tag.path else new_context = context.clone new_context.dirname + "/" + tag.filename end end
[ "def", "resolve_snippet_path", "(", "context", ",", "tag", ")", "if", "tag", ".", "has_repo?", "pkg", "=", "find_package_by_tag", "(", "tag", ")", "pkg", ".", "snippet_path", "tag", ".", "path", "else", "new_context", "=", "context", ".", "clone", "new_context", ".", "dirname", "+", "\"/\"", "+", "tag", ".", "filename", "end", "end" ]
Resolve snippet path by context and tag @param context [::SocialSnippet::Context] The context of snippet @param tag [::SocialSnippet::Tag] The tag of snippet
[ "Resolve", "snippet", "path", "by", "context", "and", "tag" ]
46ae25b3e8ced2c8b5b4923ed9e1a019c9835367
https://github.com/social-snippet/social-snippet/blob/46ae25b3e8ced2c8b5b4923ed9e1a019c9835367/lib/social_snippet/repository/repository_manager.rb#L26-L34
train
social-snippet/social-snippet
lib/social_snippet/repository/repository_manager.rb
SocialSnippet::Repository.RepositoryManager.find_package_by_tag
def find_package_by_tag(tag) if tag.has_ref? find_package(tag.repo, tag.ref) else find_package(tag.repo) end end
ruby
def find_package_by_tag(tag) if tag.has_ref? find_package(tag.repo, tag.ref) else find_package(tag.repo) end end
[ "def", "find_package_by_tag", "(", "tag", ")", "if", "tag", ".", "has_ref?", "find_package", "(", "tag", ".", "repo", ",", "tag", ".", "ref", ")", "else", "find_package", "(", "tag", ".", "repo", ")", "end", "end" ]
Find repository by tag @param tag [::SocialSnippet::Tag] The tag of repository
[ "Find", "repository", "by", "tag" ]
46ae25b3e8ced2c8b5b4923ed9e1a019c9835367
https://github.com/social-snippet/social-snippet/blob/46ae25b3e8ced2c8b5b4923ed9e1a019c9835367/lib/social_snippet/repository/repository_manager.rb#L39-L45
train
social-snippet/social-snippet
lib/social_snippet/repository/repository_manager.rb
SocialSnippet::Repository.RepositoryManager.find_package
def find_package(name, ref = nil) repo = find_repository(name) ref ||= repo.latest_package_version || repo.current_ref raise "invalid references" unless repo.has_ref?(ref) Models::Package.find_by( :repo_name => name, :rev_hash => repo.rev_hash[ref], ) end
ruby
def find_package(name, ref = nil) repo = find_repository(name) ref ||= repo.latest_package_version || repo.current_ref raise "invalid references" unless repo.has_ref?(ref) Models::Package.find_by( :repo_name => name, :rev_hash => repo.rev_hash[ref], ) end
[ "def", "find_package", "(", "name", ",", "ref", "=", "nil", ")", "repo", "=", "find_repository", "(", "name", ")", "ref", "||=", "repo", ".", "latest_package_version", "||", "repo", ".", "current_ref", "raise", "\"invalid references\"", "unless", "repo", ".", "has_ref?", "(", "ref", ")", "Models", "::", "Package", ".", "find_by", "(", ":repo_name", "=>", "name", ",", ":rev_hash", "=>", "repo", ".", "rev_hash", "[", "ref", "]", ",", ")", "end" ]
Find repository by repo name @param name [String] The name of repository
[ "Find", "repository", "by", "repo", "name" ]
46ae25b3e8ced2c8b5b4923ed9e1a019c9835367
https://github.com/social-snippet/social-snippet/blob/46ae25b3e8ced2c8b5b4923ed9e1a019c9835367/lib/social_snippet/repository/repository_manager.rb#L50-L58
train
drish/hyperb
lib/hyperb/images/images.rb
Hyperb.Images.remove_image
def remove_image(params = {}) raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name') path = '/images/' + params[:name] query = {} query[:force] = true if params.key?(:force) res = JSON.parse(Hyperb::Request.new(self, path, query, 'delete').perform) downcase_symbolize(res) end
ruby
def remove_image(params = {}) raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name') path = '/images/' + params[:name] query = {} query[:force] = true if params.key?(:force) res = JSON.parse(Hyperb::Request.new(self, path, query, 'delete').perform) downcase_symbolize(res) end
[ "def", "remove_image", "(", "params", "=", "{", "}", ")", "raise", "ArgumentError", ",", "'Invalid arguments.'", "unless", "check_arguments", "(", "params", ",", "'name'", ")", "path", "=", "'/images/'", "+", "params", "[", ":name", "]", "query", "=", "{", "}", "query", "[", ":force", "]", "=", "true", "if", "params", ".", "key?", "(", ":force", ")", "res", "=", "JSON", ".", "parse", "(", "Hyperb", "::", "Request", ".", "new", "(", "self", ",", "path", ",", "query", ",", "'delete'", ")", ".", "perform", ")", "downcase_symbolize", "(", "res", ")", "end" ]
remove an image @see https://docs.hyper.sh/Reference/API/2016-04-04%20[Ver.%201.23]/Image/remove.html @raise [Hyperb::Error::Unauthorized] raised when credentials are not valid. @raise [Hyperb::Error::NotFound] raised when tag is not found. @raise [Hyperb::Error::Conflict] raised when the image will only be removed with force. @raise [Hyperb::Error::InternalServerError] server error. @return [Array] array of downcase symbolized json response. @param params [Hash] A customizable set of params. @option params [String] :name image name to be removed @option params [Boolean] :force force image to be removed
[ "remove", "an", "image" ]
637de68dc304d8d07470a771f499e33f227955f4
https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/images/images.rb#L80-L87
train
drish/hyperb
lib/hyperb/images/images.rb
Hyperb.Images.inspect_image
def inspect_image(params = {}) raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name') path = '/images/' + params[:name] + '/json' res = JSON.parse(Hyperb::Request.new(self, path, {}, 'get').perform) downcase_symbolize(res) end
ruby
def inspect_image(params = {}) raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name') path = '/images/' + params[:name] + '/json' res = JSON.parse(Hyperb::Request.new(self, path, {}, 'get').perform) downcase_symbolize(res) end
[ "def", "inspect_image", "(", "params", "=", "{", "}", ")", "raise", "ArgumentError", ",", "'Invalid arguments.'", "unless", "check_arguments", "(", "params", ",", "'name'", ")", "path", "=", "'/images/'", "+", "params", "[", ":name", "]", "+", "'/json'", "res", "=", "JSON", ".", "parse", "(", "Hyperb", "::", "Request", ".", "new", "(", "self", ",", "path", ",", "{", "}", ",", "'get'", ")", ".", "perform", ")", "downcase_symbolize", "(", "res", ")", "end" ]
inspect an image @see https://docs.hyper.sh/Reference/API/2016-04-04%20[Ver.%201.23]/Image/inspect.html @raise [Hyperb::Error::Unauthorized] raised when credentials are not valid. @raise [Hyperb::Error::NotFound] raised when tag is not found. @raise [Hyperb::Error::InternalServerError] server error on hyper side. @return [Hash] downcased symbolized `inspect` json response. @param params [Hash] A customizable set of params. @option params [String] :name image name to be removed
[ "inspect", "an", "image" ]
637de68dc304d8d07470a771f499e33f227955f4
https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/images/images.rb#L101-L106
train
mwunsch/redwood
lib/redwood/node.rb
Redwood.Node.add_child
def add_child(name) child = self.class.new(name, self) yield child if block_given? children << child child end
ruby
def add_child(name) child = self.class.new(name, self) yield child if block_given? children << child child end
[ "def", "add_child", "(", "name", ")", "child", "=", "self", ".", "class", ".", "new", "(", "name", ",", "self", ")", "yield", "child", "if", "block_given?", "children", "<<", "child", "child", "end" ]
Creates a child, adds it to children, and returns the child
[ "Creates", "a", "child", "adds", "it", "to", "children", "and", "returns", "the", "child" ]
6f3f980d8d84fd9a90aac30d92c3fb7ffcae1055
https://github.com/mwunsch/redwood/blob/6f3f980d8d84fd9a90aac30d92c3fb7ffcae1055/lib/redwood/node.rb#L16-L21
train
mwunsch/redwood
lib/redwood/node.rb
Redwood.Node.[]
def [](key) selected_child = children.select {|child| child.name == key } selected_child.size.eql?(1) ? selected_child.first : selected_child end
ruby
def [](key) selected_child = children.select {|child| child.name == key } selected_child.size.eql?(1) ? selected_child.first : selected_child end
[ "def", "[]", "(", "key", ")", "selected_child", "=", "children", ".", "select", "{", "|", "child", "|", "child", ".", "name", "==", "key", "}", "selected_child", ".", "size", ".", "eql?", "(", "1", ")", "?", "selected_child", ".", "first", ":", "selected_child", "end" ]
Lookup a child node by its name
[ "Lookup", "a", "child", "node", "by", "its", "name" ]
6f3f980d8d84fd9a90aac30d92c3fb7ffcae1055
https://github.com/mwunsch/redwood/blob/6f3f980d8d84fd9a90aac30d92c3fb7ffcae1055/lib/redwood/node.rb#L29-L32
train
fabiokr/manageable
app/controllers/manageable/application_controller.rb
Manageable.ApplicationController.respond_with_with_storage
def respond_with_with_storage(*args, &block) @responded_with = args.last.is_a?(Hash) ? args - [args.last] : args respond_with_without_storage(*args, &block) end
ruby
def respond_with_with_storage(*args, &block) @responded_with = args.last.is_a?(Hash) ? args - [args.last] : args respond_with_without_storage(*args, &block) end
[ "def", "respond_with_with_storage", "(", "*", "args", ",", "&", "block", ")", "@responded_with", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", "-", "[", "args", ".", "last", "]", ":", "args", "respond_with_without_storage", "(", "*", "args", ",", "&", "block", ")", "end" ]
Custom respond_with wich stores resources for later use
[ "Custom", "respond_with", "wich", "stores", "resources", "for", "later", "use" ]
9db47dea0e2e73e164923de23be20109fe1cf35f
https://github.com/fabiokr/manageable/blob/9db47dea0e2e73e164923de23be20109fe1cf35f/app/controllers/manageable/application_controller.rb#L50-L53
train
drish/hyperb
lib/hyperb/containers/host_config.rb
Hyperb.HostConfig.fmt
def fmt formated = {} attrs.each_key do |key| formated[camelize(key)] = attrs[key] end formated end
ruby
def fmt formated = {} attrs.each_key do |key| formated[camelize(key)] = attrs[key] end formated end
[ "def", "fmt", "formated", "=", "{", "}", "attrs", ".", "each_key", "do", "|", "key", "|", "formated", "[", "camelize", "(", "key", ")", "]", "=", "attrs", "[", "key", "]", "end", "formated", "end" ]
returns a hash containing formated host config data @returns [Hash]
[ "returns", "a", "hash", "containing", "formated", "host", "config", "data" ]
637de68dc304d8d07470a771f499e33f227955f4
https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/containers/host_config.rb#L23-L29
train
ekylibre/beardley
lib/beardley/report.rb
Beardley.Report.to_pdf
def to_pdf(*args) options = extract_options!(args) datasource = args[0] _JasperPrint = Rjb.import('net.sf.jasperreports.engine.JasperPrint') _JasperExportManager = Rjb.import('net.sf.jasperreports.engine.JasperExportManager') _JasperExportManager._invoke('exportReportToPdf', 'Lnet.sf.jasperreports.engine.JasperPrint;', prepare(datasource)) end
ruby
def to_pdf(*args) options = extract_options!(args) datasource = args[0] _JasperPrint = Rjb.import('net.sf.jasperreports.engine.JasperPrint') _JasperExportManager = Rjb.import('net.sf.jasperreports.engine.JasperExportManager') _JasperExportManager._invoke('exportReportToPdf', 'Lnet.sf.jasperreports.engine.JasperPrint;', prepare(datasource)) end
[ "def", "to_pdf", "(", "*", "args", ")", "options", "=", "extract_options!", "(", "args", ")", "datasource", "=", "args", "[", "0", "]", "_JasperPrint", "=", "Rjb", ".", "import", "(", "'net.sf.jasperreports.engine.JasperPrint'", ")", "_JasperExportManager", "=", "Rjb", ".", "import", "(", "'net.sf.jasperreports.engine.JasperExportManager'", ")", "_JasperExportManager", ".", "_invoke", "(", "'exportReportToPdf'", ",", "'Lnet.sf.jasperreports.engine.JasperPrint;'", ",", "prepare", "(", "datasource", ")", ")", "end" ]
Constructor for a report generator Export report to PDF with given datasource
[ "Constructor", "for", "a", "report", "generator", "Export", "report", "to", "PDF", "with", "given", "datasource" ]
7483991cb2a670a1d977a4868f204ad66c0be243
https://github.com/ekylibre/beardley/blob/7483991cb2a670a1d977a4868f204ad66c0be243/lib/beardley/report.rb#L56-L62
train
ekylibre/beardley
lib/beardley/report.rb
Beardley.Report.to_file
def to_file(format, *args) options = extract_options!(args) datasource = args[0] path = options[:path] || File.join(Dir.tmpdir, "beardley_#{Time.now.to_i.to_s(36)}_#{rand(100_000_000_000).to_s(36)}.#{format}") if format == :pdf _JasperPrint = Rjb.import('net.sf.jasperreports.engine.JasperPrint') _JasperExportManager = Rjb.import('net.sf.jasperreports.engine.JasperExportManager') _JasperExportManager._invoke('exportReportToPdfFile', 'Lnet.sf.jasperreports.engine.JasperPrint;Ljava.lang.String;', prepare(datasource), Rjb.import('java.lang.String').new(path.to_s)) elsif Beardley.exporters[format] exporter = Beardley.with_warnings { Rjb.import(Beardley.exporters[format]) }.new _JRExporterParameter = Rjb.import('net.sf.jasperreports.engine.JRExporterParameter') exporter.setParameter(_JRExporterParameter.JASPER_PRINT, prepare(datasource)) exporter.setParameter(_JRExporterParameter.OUTPUT_FILE_NAME, path.to_s) exporter.exportReport else raise "Invalid export format: #{format.inspect}" end path end
ruby
def to_file(format, *args) options = extract_options!(args) datasource = args[0] path = options[:path] || File.join(Dir.tmpdir, "beardley_#{Time.now.to_i.to_s(36)}_#{rand(100_000_000_000).to_s(36)}.#{format}") if format == :pdf _JasperPrint = Rjb.import('net.sf.jasperreports.engine.JasperPrint') _JasperExportManager = Rjb.import('net.sf.jasperreports.engine.JasperExportManager') _JasperExportManager._invoke('exportReportToPdfFile', 'Lnet.sf.jasperreports.engine.JasperPrint;Ljava.lang.String;', prepare(datasource), Rjb.import('java.lang.String').new(path.to_s)) elsif Beardley.exporters[format] exporter = Beardley.with_warnings { Rjb.import(Beardley.exporters[format]) }.new _JRExporterParameter = Rjb.import('net.sf.jasperreports.engine.JRExporterParameter') exporter.setParameter(_JRExporterParameter.JASPER_PRINT, prepare(datasource)) exporter.setParameter(_JRExporterParameter.OUTPUT_FILE_NAME, path.to_s) exporter.exportReport else raise "Invalid export format: #{format.inspect}" end path end
[ "def", "to_file", "(", "format", ",", "*", "args", ")", "options", "=", "extract_options!", "(", "args", ")", "datasource", "=", "args", "[", "0", "]", "path", "=", "options", "[", ":path", "]", "||", "File", ".", "join", "(", "Dir", ".", "tmpdir", ",", "\"beardley_#{Time.now.to_i.to_s(36)}_#{rand(100_000_000_000).to_s(36)}.#{format}\"", ")", "if", "format", "==", ":pdf", "_JasperPrint", "=", "Rjb", ".", "import", "(", "'net.sf.jasperreports.engine.JasperPrint'", ")", "_JasperExportManager", "=", "Rjb", ".", "import", "(", "'net.sf.jasperreports.engine.JasperExportManager'", ")", "_JasperExportManager", ".", "_invoke", "(", "'exportReportToPdfFile'", ",", "'Lnet.sf.jasperreports.engine.JasperPrint;Ljava.lang.String;'", ",", "prepare", "(", "datasource", ")", ",", "Rjb", ".", "import", "(", "'java.lang.String'", ")", ".", "new", "(", "path", ".", "to_s", ")", ")", "elsif", "Beardley", ".", "exporters", "[", "format", "]", "exporter", "=", "Beardley", ".", "with_warnings", "{", "Rjb", ".", "import", "(", "Beardley", ".", "exporters", "[", "format", "]", ")", "}", ".", "new", "_JRExporterParameter", "=", "Rjb", ".", "import", "(", "'net.sf.jasperreports.engine.JRExporterParameter'", ")", "exporter", ".", "setParameter", "(", "_JRExporterParameter", ".", "JASPER_PRINT", ",", "prepare", "(", "datasource", ")", ")", "exporter", ".", "setParameter", "(", "_JRExporterParameter", ".", "OUTPUT_FILE_NAME", ",", "path", ".", "to_s", ")", "exporter", ".", "exportReport", "else", "raise", "\"Invalid export format: #{format.inspect}\"", "end", "path", "end" ]
Generic method to export to some format like ODT and DOCX as file in the given place
[ "Generic", "method", "to", "export", "to", "some", "format", "like", "ODT", "and", "DOCX", "as", "file", "in", "the", "given", "place" ]
7483991cb2a670a1d977a4868f204ad66c0be243
https://github.com/ekylibre/beardley/blob/7483991cb2a670a1d977a4868f204ad66c0be243/lib/beardley/report.rb#L90-L108
train
ekylibre/beardley
lib/beardley/report.rb
Beardley.Report.to
def to(format, *args) options = extract_options!(args) datasource = args[0] file = Tempfile.new("to_#{format}") exporter = Beardley.with_warnings { Rjb.import(Beardley.exporters[format]) }.new _JRExporterParameter = Rjb.import('net.sf.jasperreports.engine.JRExporterParameter') exporter.setParameter(_JRExporterParameter.JASPER_PRINT, prepare(datasource)) exporter.setParameter(_JRExporterParameter.OUTPUT_FILE_NAME, file.path.to_s) exporter.exportReport file.rewind report = file.read file.close(true) report end
ruby
def to(format, *args) options = extract_options!(args) datasource = args[0] file = Tempfile.new("to_#{format}") exporter = Beardley.with_warnings { Rjb.import(Beardley.exporters[format]) }.new _JRExporterParameter = Rjb.import('net.sf.jasperreports.engine.JRExporterParameter') exporter.setParameter(_JRExporterParameter.JASPER_PRINT, prepare(datasource)) exporter.setParameter(_JRExporterParameter.OUTPUT_FILE_NAME, file.path.to_s) exporter.exportReport file.rewind report = file.read file.close(true) report end
[ "def", "to", "(", "format", ",", "*", "args", ")", "options", "=", "extract_options!", "(", "args", ")", "datasource", "=", "args", "[", "0", "]", "file", "=", "Tempfile", ".", "new", "(", "\"to_#{format}\"", ")", "exporter", "=", "Beardley", ".", "with_warnings", "{", "Rjb", ".", "import", "(", "Beardley", ".", "exporters", "[", "format", "]", ")", "}", ".", "new", "_JRExporterParameter", "=", "Rjb", ".", "import", "(", "'net.sf.jasperreports.engine.JRExporterParameter'", ")", "exporter", ".", "setParameter", "(", "_JRExporterParameter", ".", "JASPER_PRINT", ",", "prepare", "(", "datasource", ")", ")", "exporter", ".", "setParameter", "(", "_JRExporterParameter", ".", "OUTPUT_FILE_NAME", ",", "file", ".", "path", ".", "to_s", ")", "exporter", ".", "exportReport", "file", ".", "rewind", "report", "=", "file", ".", "read", "file", ".", "close", "(", "true", ")", "report", "end" ]
Generic method to export to some format like ODT and DOCX
[ "Generic", "method", "to", "export", "to", "some", "format", "like", "ODT", "and", "DOCX" ]
7483991cb2a670a1d977a4868f204ad66c0be243
https://github.com/ekylibre/beardley/blob/7483991cb2a670a1d977a4868f204ad66c0be243/lib/beardley/report.rb#L123-L136
train
ekylibre/beardley
lib/beardley/report.rb
Beardley.Report.prepare
def prepare(datasource = nil) # Compile it, if needed if @source_file && ((!@object_file.exist? && @source_file.exist?) || (@source_file.exist? && @source_file.mtime > @object_file.mtime)) _JasperCompileManager = Rjb.import('net.sf.jasperreports.engine.JasperCompileManager') _JasperCompileManager.compileReportToFile(@source_file.to_s, @object_file.to_s) end load_datasource(datasource) end
ruby
def prepare(datasource = nil) # Compile it, if needed if @source_file && ((!@object_file.exist? && @source_file.exist?) || (@source_file.exist? && @source_file.mtime > @object_file.mtime)) _JasperCompileManager = Rjb.import('net.sf.jasperreports.engine.JasperCompileManager') _JasperCompileManager.compileReportToFile(@source_file.to_s, @object_file.to_s) end load_datasource(datasource) end
[ "def", "prepare", "(", "datasource", "=", "nil", ")", "if", "@source_file", "&&", "(", "(", "!", "@object_file", ".", "exist?", "&&", "@source_file", ".", "exist?", ")", "||", "(", "@source_file", ".", "exist?", "&&", "@source_file", ".", "mtime", ">", "@object_file", ".", "mtime", ")", ")", "_JasperCompileManager", "=", "Rjb", ".", "import", "(", "'net.sf.jasperreports.engine.JasperCompileManager'", ")", "_JasperCompileManager", ".", "compileReportToFile", "(", "@source_file", ".", "to_s", ",", "@object_file", ".", "to_s", ")", "end", "load_datasource", "(", "datasource", ")", "end" ]
Create object file if not exist and load datasource
[ "Create", "object", "file", "if", "not", "exist", "and", "load", "datasource" ]
7483991cb2a670a1d977a4868f204ad66c0be243
https://github.com/ekylibre/beardley/blob/7483991cb2a670a1d977a4868f204ad66c0be243/lib/beardley/report.rb#L144-L151
train
ekylibre/beardley
lib/beardley/report.rb
Beardley.Report.prepare_params
def prepare_params _HashMap = Rjb.import('java.util.HashMap') _JavaString = Rjb.import('java.lang.String') # Converting default report params to java HashMap params = _HashMap.new Beardley.config[:report_params].each do |k, v| params.put(k, v) end # Convert the ruby parameters' hash to a java HashMap, but keeps it as # default when they already represent a JRB entity. # Pay attention that, for now, all other parameters are converted to string! @parameters.each do |key, value| params.put(_JavaString.new(key.to_s), parameter_value_of(value)) end params end
ruby
def prepare_params _HashMap = Rjb.import('java.util.HashMap') _JavaString = Rjb.import('java.lang.String') # Converting default report params to java HashMap params = _HashMap.new Beardley.config[:report_params].each do |k, v| params.put(k, v) end # Convert the ruby parameters' hash to a java HashMap, but keeps it as # default when they already represent a JRB entity. # Pay attention that, for now, all other parameters are converted to string! @parameters.each do |key, value| params.put(_JavaString.new(key.to_s), parameter_value_of(value)) end params end
[ "def", "prepare_params", "_HashMap", "=", "Rjb", ".", "import", "(", "'java.util.HashMap'", ")", "_JavaString", "=", "Rjb", ".", "import", "(", "'java.lang.String'", ")", "params", "=", "_HashMap", ".", "new", "Beardley", ".", "config", "[", ":report_params", "]", ".", "each", "do", "|", "k", ",", "v", "|", "params", ".", "put", "(", "k", ",", "v", ")", "end", "@parameters", ".", "each", "do", "|", "key", ",", "value", "|", "params", ".", "put", "(", "_JavaString", ".", "new", "(", "key", ".", "to_s", ")", ",", "parameter_value_of", "(", "value", ")", ")", "end", "params", "end" ]
Build the default parameters Hash for printing
[ "Build", "the", "default", "parameters", "Hash", "for", "printing" ]
7483991cb2a670a1d977a4868f204ad66c0be243
https://github.com/ekylibre/beardley/blob/7483991cb2a670a1d977a4868f204ad66c0be243/lib/beardley/report.rb#L154-L172
train
ekylibre/beardley
lib/beardley/report.rb
Beardley.Report.load_datasource
def load_datasource(datasource = nil) jasper_params = prepare_params # Parse and load XML as datasource if datasource _InputSource = Rjb.import('org.xml.sax.InputSource') _StringReader = Rjb.import('java.io.StringReader') _JRXmlUtils = Rjb.import('net.sf.jasperreports.engine.util.JRXmlUtils') _JRXPathQueryExecuterFactory = Beardley.with_warnings { Rjb.import('net.sf.jasperreports.engine.query.JRXPathQueryExecuterFactory') } input_source = _InputSource.new input_source.setCharacterStream(_StringReader.new(datasource.to_s)) data_document = Beardley.with_warnings do _JRXmlUtils._invoke('parse', 'Lorg.xml.sax.InputSource;', input_source) end jasper_params.put(_JRXPathQueryExecuterFactory.PARAMETER_XML_DATA_DOCUMENT, data_document) end # Build JasperPrint fill_report(jasper_params, datasource) end
ruby
def load_datasource(datasource = nil) jasper_params = prepare_params # Parse and load XML as datasource if datasource _InputSource = Rjb.import('org.xml.sax.InputSource') _StringReader = Rjb.import('java.io.StringReader') _JRXmlUtils = Rjb.import('net.sf.jasperreports.engine.util.JRXmlUtils') _JRXPathQueryExecuterFactory = Beardley.with_warnings { Rjb.import('net.sf.jasperreports.engine.query.JRXPathQueryExecuterFactory') } input_source = _InputSource.new input_source.setCharacterStream(_StringReader.new(datasource.to_s)) data_document = Beardley.with_warnings do _JRXmlUtils._invoke('parse', 'Lorg.xml.sax.InputSource;', input_source) end jasper_params.put(_JRXPathQueryExecuterFactory.PARAMETER_XML_DATA_DOCUMENT, data_document) end # Build JasperPrint fill_report(jasper_params, datasource) end
[ "def", "load_datasource", "(", "datasource", "=", "nil", ")", "jasper_params", "=", "prepare_params", "if", "datasource", "_InputSource", "=", "Rjb", ".", "import", "(", "'org.xml.sax.InputSource'", ")", "_StringReader", "=", "Rjb", ".", "import", "(", "'java.io.StringReader'", ")", "_JRXmlUtils", "=", "Rjb", ".", "import", "(", "'net.sf.jasperreports.engine.util.JRXmlUtils'", ")", "_JRXPathQueryExecuterFactory", "=", "Beardley", ".", "with_warnings", "{", "Rjb", ".", "import", "(", "'net.sf.jasperreports.engine.query.JRXPathQueryExecuterFactory'", ")", "}", "input_source", "=", "_InputSource", ".", "new", "input_source", ".", "setCharacterStream", "(", "_StringReader", ".", "new", "(", "datasource", ".", "to_s", ")", ")", "data_document", "=", "Beardley", ".", "with_warnings", "do", "_JRXmlUtils", ".", "_invoke", "(", "'parse'", ",", "'Lorg.xml.sax.InputSource;'", ",", "input_source", ")", "end", "jasper_params", ".", "put", "(", "_JRXPathQueryExecuterFactory", ".", "PARAMETER_XML_DATA_DOCUMENT", ",", "data_document", ")", "end", "fill_report", "(", "jasper_params", ",", "datasource", ")", "end" ]
Load parseable XML datasource with java component
[ "Load", "parseable", "XML", "datasource", "with", "java", "component" ]
7483991cb2a670a1d977a4868f204ad66c0be243
https://github.com/ekylibre/beardley/blob/7483991cb2a670a1d977a4868f204ad66c0be243/lib/beardley/report.rb#L175-L194
train
ekylibre/beardley
lib/beardley/report.rb
Beardley.Report.fill_report
def fill_report(params, datasource = nil) _JasperFillManager = Rjb.import('net.sf.jasperreports.engine.JasperFillManager') if datasource return _JasperFillManager.fillReport(@object_file.to_s, params) else _JREmptyDataSource = Rjb.import('net.sf.jasperreports.engine.JREmptyDataSource') return _JasperFillManager.fillReport(@object_file.to_s, params, _JREmptyDataSource.new) end end
ruby
def fill_report(params, datasource = nil) _JasperFillManager = Rjb.import('net.sf.jasperreports.engine.JasperFillManager') if datasource return _JasperFillManager.fillReport(@object_file.to_s, params) else _JREmptyDataSource = Rjb.import('net.sf.jasperreports.engine.JREmptyDataSource') return _JasperFillManager.fillReport(@object_file.to_s, params, _JREmptyDataSource.new) end end
[ "def", "fill_report", "(", "params", ",", "datasource", "=", "nil", ")", "_JasperFillManager", "=", "Rjb", ".", "import", "(", "'net.sf.jasperreports.engine.JasperFillManager'", ")", "if", "datasource", "return", "_JasperFillManager", ".", "fillReport", "(", "@object_file", ".", "to_s", ",", "params", ")", "else", "_JREmptyDataSource", "=", "Rjb", ".", "import", "(", "'net.sf.jasperreports.engine.JREmptyDataSource'", ")", "return", "_JasperFillManager", ".", "fillReport", "(", "@object_file", ".", "to_s", ",", "params", ",", "_JREmptyDataSource", ".", "new", ")", "end", "end" ]
Fill the report with valid method depending on datasource
[ "Fill", "the", "report", "with", "valid", "method", "depending", "on", "datasource" ]
7483991cb2a670a1d977a4868f204ad66c0be243
https://github.com/ekylibre/beardley/blob/7483991cb2a670a1d977a4868f204ad66c0be243/lib/beardley/report.rb#L197-L205
train
localmed/outbox
lib/outbox/message_fields.rb
Outbox.MessageFields.fields
def fields(new_fields = nil) if new_fields.nil? fields = {} self.class.fields.each do |field| fields[field] = public_send(field) end fields else self.fields = new_fields end end
ruby
def fields(new_fields = nil) if new_fields.nil? fields = {} self.class.fields.each do |field| fields[field] = public_send(field) end fields else self.fields = new_fields end end
[ "def", "fields", "(", "new_fields", "=", "nil", ")", "if", "new_fields", ".", "nil?", "fields", "=", "{", "}", "self", ".", "class", ".", "fields", ".", "each", "do", "|", "field", "|", "fields", "[", "field", "]", "=", "public_send", "(", "field", ")", "end", "fields", "else", "self", ".", "fields", "=", "new_fields", "end", "end" ]
Returns a hash of the defined fields. class SomeMessageType < Outbox::Messages::Base fields :to, :from end message = SomeMessageType.new to: 'Bob' message.from 'John' message.fields #=> { to: 'Bob', from: 'John' } Also allows you to set fields if you pass in a hash. message.fields to: 'Bob', from: 'Sally' message.fields #=> { to: 'Bob', from: 'Sally' }
[ "Returns", "a", "hash", "of", "the", "defined", "fields", "." ]
4c7bd2129df7d2bbb49e464699afed9eb8396a5f
https://github.com/localmed/outbox/blob/4c7bd2129df7d2bbb49e464699afed9eb8396a5f/lib/outbox/message_fields.rb#L175-L185
train
localmed/outbox
lib/outbox/message_fields.rb
Outbox.MessageFields.fields=
def fields=(new_fields) new_fields.each do |field, value| public_send(field, value) if respond_to?(field) end end
ruby
def fields=(new_fields) new_fields.each do |field, value| public_send(field, value) if respond_to?(field) end end
[ "def", "fields", "=", "(", "new_fields", ")", "new_fields", ".", "each", "do", "|", "field", ",", "value", "|", "public_send", "(", "field", ",", "value", ")", "if", "respond_to?", "(", "field", ")", "end", "end" ]
Assigns the values of the given hash. message.to = 'Bob' message.fields = { from: 'Sally' } message.fields #=> { to: 'Bob', from: 'Sally' }
[ "Assigns", "the", "values", "of", "the", "given", "hash", "." ]
4c7bd2129df7d2bbb49e464699afed9eb8396a5f
https://github.com/localmed/outbox/blob/4c7bd2129df7d2bbb49e464699afed9eb8396a5f/lib/outbox/message_fields.rb#L192-L196
train
localmed/outbox
lib/outbox/message_fields.rb
Outbox.MessageFields.validate_fields
def validate_fields self.class.required_fields.each do |field| value = public_send(field) if value.nil? || value.respond_to?(:empty?) && value.empty? raise Outbox::MissingRequiredFieldError, "Missing required field: #{field}" end end end
ruby
def validate_fields self.class.required_fields.each do |field| value = public_send(field) if value.nil? || value.respond_to?(:empty?) && value.empty? raise Outbox::MissingRequiredFieldError, "Missing required field: #{field}" end end end
[ "def", "validate_fields", "self", ".", "class", ".", "required_fields", ".", "each", "do", "|", "field", "|", "value", "=", "public_send", "(", "field", ")", "if", "value", ".", "nil?", "||", "value", ".", "respond_to?", "(", ":empty?", ")", "&&", "value", ".", "empty?", "raise", "Outbox", "::", "MissingRequiredFieldError", ",", "\"Missing required field: #{field}\"", "end", "end", "end" ]
Checks the current values of the fields and raises errors for any validation issues.
[ "Checks", "the", "current", "values", "of", "the", "fields", "and", "raises", "errors", "for", "any", "validation", "issues", "." ]
4c7bd2129df7d2bbb49e464699afed9eb8396a5f
https://github.com/localmed/outbox/blob/4c7bd2129df7d2bbb49e464699afed9eb8396a5f/lib/outbox/message_fields.rb#L200-L207
train
cknadler/git-feats
lib/git-feats/serializer.rb
GitFeats.Serializer.serialize
def serialize(path, data) # Make a path to the data file if one doesn't already exist mkpath_to path File.open(path, "w") do |f| f.puts data.to_json end end
ruby
def serialize(path, data) # Make a path to the data file if one doesn't already exist mkpath_to path File.open(path, "w") do |f| f.puts data.to_json end end
[ "def", "serialize", "(", "path", ",", "data", ")", "mkpath_to", "path", "File", ".", "open", "(", "path", ",", "\"w\"", ")", "do", "|", "f", "|", "f", ".", "puts", "data", ".", "to_json", "end", "end" ]
serialize a ruby object to a file in json path - file path data - data to be serialized Returns nothing
[ "serialize", "a", "ruby", "object", "to", "a", "file", "in", "json" ]
a2425c2c5998b0c5f817d8a80efc8c2bd053786e
https://github.com/cknadler/git-feats/blob/a2425c2c5998b0c5f817d8a80efc8c2bd053786e/lib/git-feats/serializer.rb#L15-L22
train
cknadler/git-feats
lib/git-feats/serializer.rb
GitFeats.Serializer.unserialize
def unserialize(path) if File.exists?(path) && !File.zero?(path) begin return JSON.parse(IO.binread(path)) rescue JSON::ParserError => e puts e end end end
ruby
def unserialize(path) if File.exists?(path) && !File.zero?(path) begin return JSON.parse(IO.binread(path)) rescue JSON::ParserError => e puts e end end end
[ "def", "unserialize", "(", "path", ")", "if", "File", ".", "exists?", "(", "path", ")", "&&", "!", "File", ".", "zero?", "(", "path", ")", "begin", "return", "JSON", ".", "parse", "(", "IO", ".", "binread", "(", "path", ")", ")", "rescue", "JSON", "::", "ParserError", "=>", "e", "puts", "e", "end", "end", "end" ]
unserialize a json file to a ruby object path - file path Returns a ruby object or nil
[ "unserialize", "a", "json", "file", "to", "a", "ruby", "object" ]
a2425c2c5998b0c5f817d8a80efc8c2bd053786e
https://github.com/cknadler/git-feats/blob/a2425c2c5998b0c5f817d8a80efc8c2bd053786e/lib/git-feats/serializer.rb#L29-L37
train
norman/phonology
lib/phonology/orthography.rb
Phonology.OrthographyTranslator.translate
def translate(string) @string = string @max = array.length SoundSequence.new(array.each_index.map do |index| @index = index instance_eval(&@rules) end.flatten.compact) ensure @max = 0 @string = nil @array = nil @index = nil @last_sound = nil end
ruby
def translate(string) @string = string @max = array.length SoundSequence.new(array.each_index.map do |index| @index = index instance_eval(&@rules) end.flatten.compact) ensure @max = 0 @string = nil @array = nil @index = nil @last_sound = nil end
[ "def", "translate", "(", "string", ")", "@string", "=", "string", "@max", "=", "array", ".", "length", "SoundSequence", ".", "new", "(", "array", ".", "each_index", ".", "map", "do", "|", "index", "|", "@index", "=", "index", "instance_eval", "(", "&", "@rules", ")", "end", ".", "flatten", ".", "compact", ")", "ensure", "@max", "=", "0", "@string", "=", "nil", "@array", "=", "nil", "@index", "=", "nil", "@last_sound", "=", "nil", "end" ]
Translate orthorgraphy to IPA
[ "Translate", "orthorgraphy", "to", "IPA" ]
910207237aecbcd8e1a464a9148d9b3fd4d1f3e4
https://github.com/norman/phonology/blob/910207237aecbcd8e1a464a9148d9b3fd4d1f3e4/lib/phonology/orthography.rb#L95-L108
train
tomasc/semantic_date_time_tags
lib/semantic_date_time_tags/view_helpers.rb
SemanticDateTimeTags.ViewHelpers.semantic_date_time_tag
def semantic_date_time_tag(date_time, options = {}) SemanticDateTimeTags::Tag::DateTime.new(date_time, options).to_html end
ruby
def semantic_date_time_tag(date_time, options = {}) SemanticDateTimeTags::Tag::DateTime.new(date_time, options).to_html end
[ "def", "semantic_date_time_tag", "(", "date_time", ",", "options", "=", "{", "}", ")", "SemanticDateTimeTags", "::", "Tag", "::", "DateTime", ".", "new", "(", "date_time", ",", "options", ")", ".", "to_html", "end" ]
accepts only datetime
[ "accepts", "only", "datetime" ]
5748521591720bb6c3b87659b016d01775fd08eb
https://github.com/tomasc/semantic_date_time_tags/blob/5748521591720bb6c3b87659b016d01775fd08eb/lib/semantic_date_time_tags/view_helpers.rb#L24-L26
train
tomasc/semantic_date_time_tags
lib/semantic_date_time_tags/view_helpers.rb
SemanticDateTimeTags.ViewHelpers.semantic_time_tag
def semantic_time_tag(time, options = {}) SemanticDateTimeTags::Tag::Time.new(time, options).to_html end
ruby
def semantic_time_tag(time, options = {}) SemanticDateTimeTags::Tag::Time.new(time, options).to_html end
[ "def", "semantic_time_tag", "(", "time", ",", "options", "=", "{", "}", ")", "SemanticDateTimeTags", "::", "Tag", "::", "Time", ".", "new", "(", "time", ",", "options", ")", ".", "to_html", "end" ]
accepts datetime and time
[ "accepts", "datetime", "and", "time" ]
5748521591720bb6c3b87659b016d01775fd08eb
https://github.com/tomasc/semantic_date_time_tags/blob/5748521591720bb6c3b87659b016d01775fd08eb/lib/semantic_date_time_tags/view_helpers.rb#L34-L36
train
wr0ngway/lumber
lib/lumber/inheritance_registry.rb
Lumber.InheritanceRegistry.register_inheritance_handler
def register_inheritance_handler synchronize do return if defined?(Object.inherited_with_lumber_registry) Object.class_eval do class << self def inherited_with_lumber_registry(subclass) inherited_without_lumber_registry(subclass) # Add a logger to 'subclass' if it is directly in the registry # No need to check full inheritance chain LoggerSupport handles it # Also prevent rails from subsequently overriding our logger when rails # is loaded after registering logger inheritance if Lumber::InheritanceRegistry[subclass.name] subclass.send(:include, Lumber.logger_concern) end end alias_method_chain :inherited, :lumber_registry end end end end
ruby
def register_inheritance_handler synchronize do return if defined?(Object.inherited_with_lumber_registry) Object.class_eval do class << self def inherited_with_lumber_registry(subclass) inherited_without_lumber_registry(subclass) # Add a logger to 'subclass' if it is directly in the registry # No need to check full inheritance chain LoggerSupport handles it # Also prevent rails from subsequently overriding our logger when rails # is loaded after registering logger inheritance if Lumber::InheritanceRegistry[subclass.name] subclass.send(:include, Lumber.logger_concern) end end alias_method_chain :inherited, :lumber_registry end end end end
[ "def", "register_inheritance_handler", "synchronize", "do", "return", "if", "defined?", "(", "Object", ".", "inherited_with_lumber_registry", ")", "Object", ".", "class_eval", "do", "class", "<<", "self", "def", "inherited_with_lumber_registry", "(", "subclass", ")", "inherited_without_lumber_registry", "(", "subclass", ")", "if", "Lumber", "::", "InheritanceRegistry", "[", "subclass", ".", "name", "]", "subclass", ".", "send", "(", ":include", ",", "Lumber", ".", "logger_concern", ")", "end", "end", "alias_method_chain", ":inherited", ",", ":lumber_registry", "end", "end", "end", "end" ]
Adds a inheritance handler to Object so we can add loggers for registered classes
[ "Adds", "a", "inheritance", "handler", "to", "Object", "so", "we", "can", "add", "loggers", "for", "registered", "classes" ]
6a483ea44f496d4e98f5698590be59941b58fe9b
https://github.com/wr0ngway/lumber/blob/6a483ea44f496d4e98f5698590be59941b58fe9b/lib/lumber/inheritance_registry.rb#L52-L80
train
bbtfr/index_for
lib/index_for/helper.rb
IndexFor.Helper.index_for
def index_for objects, html_options = {}, &block html_options = html_options.dup objects = fetch_objects objects, html_options tag = html_options[:table_tag] || IndexFor.table_tag klass = html_options[:klass] || objects.try(:klass) || objects.first.class html_options[:id] ||= index_for_id(klass) html_options[:class] = index_for_class(klass, html_options) head = index_for_head(klass.new, html_options, &block) body = index_for_body(objects, html_options, &block) content = head + body content_tag(tag, content, html_options) end
ruby
def index_for objects, html_options = {}, &block html_options = html_options.dup objects = fetch_objects objects, html_options tag = html_options[:table_tag] || IndexFor.table_tag klass = html_options[:klass] || objects.try(:klass) || objects.first.class html_options[:id] ||= index_for_id(klass) html_options[:class] = index_for_class(klass, html_options) head = index_for_head(klass.new, html_options, &block) body = index_for_body(objects, html_options, &block) content = head + body content_tag(tag, content, html_options) end
[ "def", "index_for", "objects", ",", "html_options", "=", "{", "}", ",", "&", "block", "html_options", "=", "html_options", ".", "dup", "objects", "=", "fetch_objects", "objects", ",", "html_options", "tag", "=", "html_options", "[", ":table_tag", "]", "||", "IndexFor", ".", "table_tag", "klass", "=", "html_options", "[", ":klass", "]", "||", "objects", ".", "try", "(", ":klass", ")", "||", "objects", ".", "first", ".", "class", "html_options", "[", ":id", "]", "||=", "index_for_id", "(", "klass", ")", "html_options", "[", ":class", "]", "=", "index_for_class", "(", "klass", ",", "html_options", ")", "head", "=", "index_for_head", "(", "klass", ".", "new", ",", "html_options", ",", "&", "block", ")", "body", "=", "index_for_body", "(", "objects", ",", "html_options", ",", "&", "block", ")", "content", "=", "head", "+", "body", "content_tag", "(", "tag", ",", "content", ",", "html_options", ")", "end" ]
Creates a table around the objects and yields a builder. Example: index_for @users do |t| t.attribute :name t.attribute :email end
[ "Creates", "a", "table", "around", "the", "objects", "and", "yields", "a", "builder", "." ]
cc615ce56e661b0592cc3bd7a9af3ac28b51b44f
https://github.com/bbtfr/index_for/blob/cc615ce56e661b0592cc3bd7a9af3ac28b51b44f/lib/index_for/helper.rb#L14-L30
train
bbtfr/index_for
lib/index_for/helper.rb
IndexFor.Helper.index_for_actions
def index_for_actions object, *action_names, &block html_options = action_names.extract_options! action_names = [:show, :edit, :destroy] if action_names == [:all] builder = html_options[:action_builder] || IndexFor::ActionBuilder builder = builder.new(object, html_options, self) content = capture(builder) do |a| action_names.map do |action_name| a.action_link action_name end.join.html_safe end content += capture(builder, &block) if block content end
ruby
def index_for_actions object, *action_names, &block html_options = action_names.extract_options! action_names = [:show, :edit, :destroy] if action_names == [:all] builder = html_options[:action_builder] || IndexFor::ActionBuilder builder = builder.new(object, html_options, self) content = capture(builder) do |a| action_names.map do |action_name| a.action_link action_name end.join.html_safe end content += capture(builder, &block) if block content end
[ "def", "index_for_actions", "object", ",", "*", "action_names", ",", "&", "block", "html_options", "=", "action_names", ".", "extract_options!", "action_names", "=", "[", ":show", ",", ":edit", ",", ":destroy", "]", "if", "action_names", "==", "[", ":all", "]", "builder", "=", "html_options", "[", ":action_builder", "]", "||", "IndexFor", "::", "ActionBuilder", "builder", "=", "builder", ".", "new", "(", "object", ",", "html_options", ",", "self", ")", "content", "=", "capture", "(", "builder", ")", "do", "|", "a", "|", "action_names", ".", "map", "do", "|", "action_name", "|", "a", ".", "action_link", "action_name", "end", ".", "join", ".", "html_safe", "end", "content", "+=", "capture", "(", "builder", ",", "&", "block", ")", "if", "block", "content", "end" ]
Create action links and yields a builder. Example: index_for_actions @user do |a| a.action_link :show a.action_link :edit end index_for_actions @user, :show, :edit
[ "Create", "action", "links", "and", "yields", "a", "builder", "." ]
cc615ce56e661b0592cc3bd7a9af3ac28b51b44f
https://github.com/bbtfr/index_for/blob/cc615ce56e661b0592cc3bd7a9af3ac28b51b44f/lib/index_for/helper.rb#L60-L76
train
bbtfr/index_for
lib/index_for/helper.rb
IndexFor.Helper.show_for
def show_for object, html_options = {}, &block html_options = html_options.dup tag = html_options[:list_tag] || IndexFor.list_tag html_options[:id] ||= show_for_id(object) html_options[:class] = show_for_class(object, html_options) builder = html_options[:builder] || IndexFor::ListColumnBuilder content = capture(builder.new(object, html_options, self), &block) content_tag(tag, content, html_options) end
ruby
def show_for object, html_options = {}, &block html_options = html_options.dup tag = html_options[:list_tag] || IndexFor.list_tag html_options[:id] ||= show_for_id(object) html_options[:class] = show_for_class(object, html_options) builder = html_options[:builder] || IndexFor::ListColumnBuilder content = capture(builder.new(object, html_options, self), &block) content_tag(tag, content, html_options) end
[ "def", "show_for", "object", ",", "html_options", "=", "{", "}", ",", "&", "block", "html_options", "=", "html_options", ".", "dup", "tag", "=", "html_options", "[", ":list_tag", "]", "||", "IndexFor", ".", "list_tag", "html_options", "[", ":id", "]", "||=", "show_for_id", "(", "object", ")", "html_options", "[", ":class", "]", "=", "show_for_class", "(", "object", ",", "html_options", ")", "builder", "=", "html_options", "[", ":builder", "]", "||", "IndexFor", "::", "ListColumnBuilder", "content", "=", "capture", "(", "builder", ".", "new", "(", "object", ",", "html_options", ",", "self", ")", ",", "&", "block", ")", "content_tag", "(", "tag", ",", "content", ",", "html_options", ")", "end" ]
Creates a desc list around the object and yields a builder. Example: show_for @user do |l| l.attribute :name l.attribute :email end
[ "Creates", "a", "desc", "list", "around", "the", "object", "and", "yields", "a", "builder", "." ]
cc615ce56e661b0592cc3bd7a9af3ac28b51b44f
https://github.com/bbtfr/index_for/blob/cc615ce56e661b0592cc3bd7a9af3ac28b51b44f/lib/index_for/helper.rb#L87-L99
train
BrightcoveOS/Ruby-MAPI-Wrapper
lib/brightcove-api.rb
Brightcove.API.post
def post(api_method, parameters = {}) parameters.merge!({"token" => @token}) body = {} body.merge!({:method => api_method}) body.merge!({:params => parameters}) self.class.post(@write_api_url, {:body => {:json => JSON.generate(body)}}) end
ruby
def post(api_method, parameters = {}) parameters.merge!({"token" => @token}) body = {} body.merge!({:method => api_method}) body.merge!({:params => parameters}) self.class.post(@write_api_url, {:body => {:json => JSON.generate(body)}}) end
[ "def", "post", "(", "api_method", ",", "parameters", "=", "{", "}", ")", "parameters", ".", "merge!", "(", "{", "\"token\"", "=>", "@token", "}", ")", "body", "=", "{", "}", "body", ".", "merge!", "(", "{", ":method", "=>", "api_method", "}", ")", "body", ".", "merge!", "(", "{", ":params", "=>", "parameters", "}", ")", "self", ".", "class", ".", "post", "(", "@write_api_url", ",", "{", ":body", "=>", "{", ":json", "=>", "JSON", ".", "generate", "(", "body", ")", "}", "}", ")", "end" ]
Make an HTTP POST call to the Brightcove API for a particular API method. @param api_method [String] Brightcove API method. @param parameters [Hash] Optional hash containing parameter names and values.
[ "Make", "an", "HTTP", "POST", "call", "to", "the", "Brightcove", "API", "for", "a", "particular", "API", "method", "." ]
babde5c12ef08b8908d460f04aa156c1905205b8
https://github.com/BrightcoveOS/Ruby-MAPI-Wrapper/blob/babde5c12ef08b8908d460f04aa156c1905205b8/lib/brightcove-api.rb#L84-L92
train
tecfoundary/hicube
app/controllers/hicube/contents_controller.rb
Hicube.ContentsController.load_resource
def load_resource @page = Hicube::Page.unscoped.find(params[:page_id]) @content = @page.content.find_or_create_by(name: params[:id]) end
ruby
def load_resource @page = Hicube::Page.unscoped.find(params[:page_id]) @content = @page.content.find_or_create_by(name: params[:id]) end
[ "def", "load_resource", "@page", "=", "Hicube", "::", "Page", ".", "unscoped", ".", "find", "(", "params", "[", ":page_id", "]", ")", "@content", "=", "@page", ".", "content", ".", "find_or_create_by", "(", "name", ":", "params", "[", ":id", "]", ")", "end" ]
Nested attributes are currently not handled in basecontroller
[ "Nested", "attributes", "are", "currently", "not", "handled", "in", "basecontroller" ]
57e0e6bd2d6400dd6c7027deaeffbd95a175bbfe
https://github.com/tecfoundary/hicube/blob/57e0e6bd2d6400dd6c7027deaeffbd95a175bbfe/app/controllers/hicube/contents_controller.rb#L43-L46
train
czarneckid/hipchat-api
lib/hipchat-api.rb
HipChat.API.rooms_create
def rooms_create(name, owner_user_id, privacy = 'public', topic = '', guest_access = 0) self.class.post(hipchat_api_url_for('rooms/create'), :body => {:auth_token => @token, :name => name, :owner_user_id => owner_user_id, :topic => topic, :privacy => privacy, :guest_access => guest_access}) end
ruby
def rooms_create(name, owner_user_id, privacy = 'public', topic = '', guest_access = 0) self.class.post(hipchat_api_url_for('rooms/create'), :body => {:auth_token => @token, :name => name, :owner_user_id => owner_user_id, :topic => topic, :privacy => privacy, :guest_access => guest_access}) end
[ "def", "rooms_create", "(", "name", ",", "owner_user_id", ",", "privacy", "=", "'public'", ",", "topic", "=", "''", ",", "guest_access", "=", "0", ")", "self", ".", "class", ".", "post", "(", "hipchat_api_url_for", "(", "'rooms/create'", ")", ",", ":body", "=>", "{", ":auth_token", "=>", "@token", ",", ":name", "=>", "name", ",", ":owner_user_id", "=>", "owner_user_id", ",", ":topic", "=>", "topic", ",", ":privacy", "=>", "privacy", ",", ":guest_access", "=>", "guest_access", "}", ")", "end" ]
Creates a new room. @param name [String] Name of the room. @param owner_user_id [int] User ID of the room's owner. @param privacy [String, 'public'] Privacy setting for room. @param topic [String, ''] Room topic. @param guest_access [int, 0] Whether or not to enable guest access for this room. 0 = false, 1 = true. (default: 0). @see https://www.hipchat.com/docs/api/method/rooms/create
[ "Creates", "a", "new", "room", "." ]
195b921e7c615433977927d3ad6f5a9cdb9b308f
https://github.com/czarneckid/hipchat-api/blob/195b921e7c615433977927d3ad6f5a9cdb9b308f/lib/hipchat-api.rb#L69-L72
train
czarneckid/hipchat-api
lib/hipchat-api.rb
HipChat.API.rooms_message
def rooms_message(room_id, from, message, notify = 0, color = 'yellow', message_format = 'html') self.class.post(hipchat_api_url_for('rooms/message'), :body => {:auth_token => @token, :room_id => room_id, :from => from, :message => message, :notify => notify, :color => color, :message_format => message_format}) end
ruby
def rooms_message(room_id, from, message, notify = 0, color = 'yellow', message_format = 'html') self.class.post(hipchat_api_url_for('rooms/message'), :body => {:auth_token => @token, :room_id => room_id, :from => from, :message => message, :notify => notify, :color => color, :message_format => message_format}) end
[ "def", "rooms_message", "(", "room_id", ",", "from", ",", "message", ",", "notify", "=", "0", ",", "color", "=", "'yellow'", ",", "message_format", "=", "'html'", ")", "self", ".", "class", ".", "post", "(", "hipchat_api_url_for", "(", "'rooms/message'", ")", ",", ":body", "=>", "{", ":auth_token", "=>", "@token", ",", ":room_id", "=>", "room_id", ",", ":from", "=>", "from", ",", ":message", "=>", "message", ",", ":notify", "=>", "notify", ",", ":color", "=>", "color", ",", ":message_format", "=>", "message_format", "}", ")", "end" ]
Send a message to a room. @param room_id [int] ID of the room. @param from [String] Name the message will appear be sent from. Must be less than 15 characters long. May contain letters, numbers, -, _, and spaces. @param message [String] The message body. Must be valid XHTML. HTML entities must be escaped (e.g.: &amp; instead of &). May contain basic tags: a, b, i, strong, em, br, img, pre, code. 5000 characters max. @param notify [int] Boolean flag of whether or not this message should trigger a notification for people in the room (based on their individual notification preferences). 0 = false, 1 = true. (default: 0) @param color [String] Background color for message. One of "yellow", "red", "green", "purple", or "random". (default: yellow) @param message_format [String] Determines how the message is treated by HipChat's server and rendered inside HipChat applications. One of "html" or "text". (default: html) @see https://www.hipchat.com/docs/api/method/rooms/message
[ "Send", "a", "message", "to", "a", "room", "." ]
195b921e7c615433977927d3ad6f5a9cdb9b308f
https://github.com/czarneckid/hipchat-api/blob/195b921e7c615433977927d3ad6f5a9cdb9b308f/lib/hipchat-api.rb#L111-L114
train
czarneckid/hipchat-api
lib/hipchat-api.rb
HipChat.API.users_create
def users_create(email, name, title, is_group_admin = 0, password = nil, timezone = 'UTC') self.class.post(hipchat_api_url_for('users/create'), :body => {:auth_token => @token, :email => email, :name => name, :title => title, :is_group_admin => is_group_admin, :password => password, :timezone => timezone}.reject{|key, value| value.nil?}) end
ruby
def users_create(email, name, title, is_group_admin = 0, password = nil, timezone = 'UTC') self.class.post(hipchat_api_url_for('users/create'), :body => {:auth_token => @token, :email => email, :name => name, :title => title, :is_group_admin => is_group_admin, :password => password, :timezone => timezone}.reject{|key, value| value.nil?}) end
[ "def", "users_create", "(", "email", ",", "name", ",", "title", ",", "is_group_admin", "=", "0", ",", "password", "=", "nil", ",", "timezone", "=", "'UTC'", ")", "self", ".", "class", ".", "post", "(", "hipchat_api_url_for", "(", "'users/create'", ")", ",", ":body", "=>", "{", ":auth_token", "=>", "@token", ",", ":email", "=>", "email", ",", ":name", "=>", "name", ",", ":title", "=>", "title", ",", ":is_group_admin", "=>", "is_group_admin", ",", ":password", "=>", "password", ",", ":timezone", "=>", "timezone", "}", ".", "reject", "{", "|", "key", ",", "value", "|", "value", ".", "nil?", "}", ")", "end" ]
Create a new user in your group. @param email [String] User's email. @param name [String] User's full name. @param title [String] User's title. @param is_group_admin [int] Whether or not this user is an admin. 0 = false, 1 = true. (default: 0) @param password [String, nil] User's password. If not provided, a randomly generated password will be returned. @param timezone [String, 'UTC'] User's timezone. Must be a PHP supported timezone. (default: UTC) @see https://www.hipchat.com/docs/api/method/users/create
[ "Create", "a", "new", "user", "in", "your", "group", "." ]
195b921e7c615433977927d3ad6f5a9cdb9b308f
https://github.com/czarneckid/hipchat-api/blob/195b921e7c615433977927d3ad6f5a9cdb9b308f/lib/hipchat-api.rb#L146-L149
train
luikore/markascend
lib/markascend/popular_company_macros.rb
Markascend.Macro.parse_video
def parse_video # standard unless /\A\s*(?<width>\d+)x(?<height>\d+)\s+(?<url>.+)\z/ =~ content env.warn 'can not parse \video content, should be "#{WIDTH}x#{HEIGHT} #{URL}"' return end case url when /youtu\.?be/ # NOTE merging them into one regexp fails (because longest match?) unless id = url[/(?<=watch\?v=)\w+/] || url[/(?<=embed\/)\w+/] || url[/(?<=youtu\.be\/)\w+/] env.warn 'can not parse youtube id' return end %Q|<iframe width="#{width}" height="#{height}" src="https://www.youtube-nocookie.com/embed/#{id}?rel=0" frameborder="0" allowfullscreen></iframe>| when /vimeo/ unless id = url[/(?<=vimeo\.com\/)\w+/] env.warn 'can not parse vimeo id, should use link like this "http://vimeo.com/#{DIGITS}"' return end %Q|<iframe width="#{width}" height="#{height}" src="https://player.vimeo.com/video/#{id}" frameborder="0" allowFullScreen></iframe>| when /sm/ unless id = url[/\bsm\d+/] env.warn 'can not find "sm#{DIGITS}" from link' return end %Q|<script src="https://ext.nicovideo.jp/thumb_watch/#{id}?w=#{width}&h=#{height}"></script>"| else env.warn 'failed to parse video link, currently only youtube, vimeo and niconico are supported' return end end
ruby
def parse_video # standard unless /\A\s*(?<width>\d+)x(?<height>\d+)\s+(?<url>.+)\z/ =~ content env.warn 'can not parse \video content, should be "#{WIDTH}x#{HEIGHT} #{URL}"' return end case url when /youtu\.?be/ # NOTE merging them into one regexp fails (because longest match?) unless id = url[/(?<=watch\?v=)\w+/] || url[/(?<=embed\/)\w+/] || url[/(?<=youtu\.be\/)\w+/] env.warn 'can not parse youtube id' return end %Q|<iframe width="#{width}" height="#{height}" src="https://www.youtube-nocookie.com/embed/#{id}?rel=0" frameborder="0" allowfullscreen></iframe>| when /vimeo/ unless id = url[/(?<=vimeo\.com\/)\w+/] env.warn 'can not parse vimeo id, should use link like this "http://vimeo.com/#{DIGITS}"' return end %Q|<iframe width="#{width}" height="#{height}" src="https://player.vimeo.com/video/#{id}" frameborder="0" allowFullScreen></iframe>| when /sm/ unless id = url[/\bsm\d+/] env.warn 'can not find "sm#{DIGITS}" from link' return end %Q|<script src="https://ext.nicovideo.jp/thumb_watch/#{id}?w=#{width}&h=#{height}"></script>"| else env.warn 'failed to parse video link, currently only youtube, vimeo and niconico are supported' return end end
[ "def", "parse_video", "unless", "/", "\\A", "\\s", "\\d", "\\d", "\\s", "\\z", "/", "=~", "content", "env", ".", "warn", "'can not parse \\video content, should be \"#{WIDTH}x#{HEIGHT} #{URL}\"'", "return", "end", "case", "url", "when", "/", "\\.", "/", "unless", "id", "=", "url", "[", "/", "\\?", "\\w", "/", "]", "||", "url", "[", "/", "\\/", "\\w", "/", "]", "||", "url", "[", "/", "\\.", "\\/", "\\w", "/", "]", "env", ".", "warn", "'can not parse youtube id'", "return", "end", "%Q|<iframe width=\"#{width}\" height=\"#{height}\" src=\"https://www.youtube-nocookie.com/embed/#{id}?rel=0\" frameborder=\"0\" allowfullscreen></iframe>|", "when", "/", "/", "unless", "id", "=", "url", "[", "/", "\\.", "\\/", "\\w", "/", "]", "env", ".", "warn", "'can not parse vimeo id, should use link like this \"http://vimeo.com/#{DIGITS}\"'", "return", "end", "%Q|<iframe width=\"#{width}\" height=\"#{height}\" src=\"https://player.vimeo.com/video/#{id}\" frameborder=\"0\" allowFullScreen></iframe>|", "when", "/", "/", "unless", "id", "=", "url", "[", "/", "\\b", "\\d", "/", "]", "env", ".", "warn", "'can not find \"sm#{DIGITS}\" from link'", "return", "end", "%Q|<script src=\"https://ext.nicovideo.jp/thumb_watch/#{id}?w=#{width}&h=#{height}\"></script>\"|", "else", "env", ".", "warn", "'failed to parse video link, currently only youtube, vimeo and niconico are supported'", "return", "end", "end" ]
embed video, calculates embed iframe by urls from various simple formats, but not accept iframe code
[ "embed", "video", "calculates", "embed", "iframe", "by", "urls", "from", "various", "simple", "formats", "but", "not", "accept", "iframe", "code" ]
58a7d9c18bf764dba537f7b4bf52ac550bbccb50
https://github.com/luikore/markascend/blob/58a7d9c18bf764dba537f7b4bf52ac550bbccb50/lib/markascend/popular_company_macros.rb#L54-L85
train
flajann2/k-tree
lib/k-tree/k-tree.rb
KTree.KTree.create_tree
def create_tree(vupper, vlower, &block) @root = Node.new(vupper, vlower, @depth) @root.create_children &block end
ruby
def create_tree(vupper, vlower, &block) @root = Node.new(vupper, vlower, @depth) @root.create_children &block end
[ "def", "create_tree", "(", "vupper", ",", "vlower", ",", "&", "block", ")", "@root", "=", "Node", ".", "new", "(", "vupper", ",", "vlower", ",", "@depth", ")", "@root", ".", "create_children", "&", "block", "end" ]
The block is passed node itself as parent and the vector midpoints of its children to be. The block sets is own refob, and returns either true, in which case all the children are created, or it returns false, in which case none of the children will be created, in effect, marking itself as a leaf node.
[ "The", "block", "is", "passed", "node", "itself", "as", "parent", "and", "the", "vector", "midpoints", "of", "its", "children", "to", "be", "." ]
16a96dcfd38705160cc21ed892d44bb23ba59ebb
https://github.com/flajann2/k-tree/blob/16a96dcfd38705160cc21ed892d44bb23ba59ebb/lib/k-tree/k-tree.rb#L84-L87
train
rberger/asi_bod
lib/asi_bod/asi.rb
AsiBod.Asi.array_data_to_hash
def array_data_to_hash(array_data) array_data.each_with_object({}) do |node, memo| memo[node['Address'].to_i] = clean_node(node) end end
ruby
def array_data_to_hash(array_data) array_data.each_with_object({}) do |node, memo| memo[node['Address'].to_i] = clean_node(node) end end
[ "def", "array_data_to_hash", "(", "array_data", ")", "array_data", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "node", ",", "memo", "|", "memo", "[", "node", "[", "'Address'", "]", ".", "to_i", "]", "=", "clean_node", "(", "node", ")", "end", "end" ]
Asi.new reads in the source file for the ASIObjectDictionary and creates an internal Hash @param params [Hash] Convert the array of hashes to a hash with the address as primary key
[ "Asi", ".", "new", "reads", "in", "the", "source", "file", "for", "the", "ASIObjectDictionary", "and", "creates", "an", "internal", "Hash" ]
7aa6c86f996bf856f83d84bb6f0a22dbe257f925
https://github.com/rberger/asi_bod/blob/7aa6c86f996bf856f83d84bb6f0a22dbe257f925/lib/asi_bod/asi.rb#L29-L33
train
wr0ngway/lumber
lib/lumber/level_util.rb
Lumber.LevelUtil.start_monitor
def start_monitor(interval=10) t = MonitorThread.new do loop do break if Thread.current.should_exit begin activate_levels rescue => e $stderr.puts "Failure activating log levels: #{e}" end sleep interval end end at_exit { t.should_exit = true } t end
ruby
def start_monitor(interval=10) t = MonitorThread.new do loop do break if Thread.current.should_exit begin activate_levels rescue => e $stderr.puts "Failure activating log levels: #{e}" end sleep interval end end at_exit { t.should_exit = true } t end
[ "def", "start_monitor", "(", "interval", "=", "10", ")", "t", "=", "MonitorThread", ".", "new", "do", "loop", "do", "break", "if", "Thread", ".", "current", ".", "should_exit", "begin", "activate_levels", "rescue", "=>", "e", "$stderr", ".", "puts", "\"Failure activating log levels: #{e}\"", "end", "sleep", "interval", "end", "end", "at_exit", "{", "t", ".", "should_exit", "=", "true", "}", "t", "end" ]
Convenience method for starting a thread to watch for changes in log levels and apply them. You don't need to use this if you are manually calling activate levels at all your entry points. @param [Integer] How long to sleep between checks @return [Thread] The monitor thread
[ "Convenience", "method", "for", "starting", "a", "thread", "to", "watch", "for", "changes", "in", "log", "levels", "and", "apply", "them", ".", "You", "don", "t", "need", "to", "use", "this", "if", "you", "are", "manually", "calling", "activate", "levels", "at", "all", "your", "entry", "points", "." ]
6a483ea44f496d4e98f5698590be59941b58fe9b
https://github.com/wr0ngway/lumber/blob/6a483ea44f496d4e98f5698590be59941b58fe9b/lib/lumber/level_util.rb#L82-L99
train