id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
2,000
dicom/rtp-connect
lib/rtp-connect/record.rb
RTP.Record.delete_children
def delete_children(attribute) self.send(attribute).each { |c| c.parent = nil } self.send(attribute).clear end
ruby
def delete_children(attribute) self.send(attribute).each { |c| c.parent = nil } self.send(attribute).clear end
[ "def", "delete_children", "(", "attribute", ")", "self", ".", "send", "(", "attribute", ")", ".", "each", "{", "|", "c", "|", "c", ".", "parent", "=", "nil", "}", "self", ".", "send", "(", "attribute", ")", ".", "clear", "end" ]
Removes all child references of the given type from this instance. @param [Symbol] attribute the name of the child attribute to be cleared
[ "Removes", "all", "child", "references", "of", "the", "given", "type", "from", "this", "instance", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/record.rb#L153-L156
2,001
dicom/rtp-connect
lib/rtp-connect/record.rb
RTP.Record.set_attributes
def set_attributes(values) import_indices([values.length - 1, @max_elements - 1].min).each_with_index do |indices, i| param = nil if indices param = values.values_at(*indices) param = param[0] if param.length == 1 end self.send("#{@attributes[i]}=", param) end @crc = values[-1] end
ruby
def set_attributes(values) import_indices([values.length - 1, @max_elements - 1].min).each_with_index do |indices, i| param = nil if indices param = values.values_at(*indices) param = param[0] if param.length == 1 end self.send("#{@attributes[i]}=", param) end @crc = values[-1] end
[ "def", "set_attributes", "(", "values", ")", "import_indices", "(", "[", "values", ".", "length", "-", "1", ",", "@max_elements", "-", "1", "]", ".", "min", ")", ".", "each_with_index", "do", "|", "indices", ",", "i", "|", "param", "=", "nil", "if", "indices", "param", "=", "values", ".", "values_at", "(", "indices", ")", "param", "=", "param", "[", "0", "]", "if", "param", ".", "length", "==", "1", "end", "self", ".", "send", "(", "\"#{@attributes[i]}=\"", ",", "param", ")", "end", "@crc", "=", "values", "[", "-", "1", "]", "end" ]
Sets the attributes of the record instance. @param [Array<String>] values the record attributes (as parsed from a record string)
[ "Sets", "the", "attributes", "of", "the", "record", "instance", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/record.rb#L162-L172
2,002
dicom/rtp-connect
lib/rtp-connect/record.rb
RTP.Record.discard_unsupported_attributes
def discard_unsupported_attributes(values, options={}) case self when SiteSetup options[:version].to_f >= 2.6 ? values : values[0..-4] when Field options[:version].to_f >= 2.64 ? values : values[0..-4] when ExtendedField options[:version].to_f >= 2.4 ? values : values[0..-5] when ControlPoint options[:version].to_f >= 2.64 ? values : values[0..31] + values[35..-1] else values end end
ruby
def discard_unsupported_attributes(values, options={}) case self when SiteSetup options[:version].to_f >= 2.6 ? values : values[0..-4] when Field options[:version].to_f >= 2.64 ? values : values[0..-4] when ExtendedField options[:version].to_f >= 2.4 ? values : values[0..-5] when ControlPoint options[:version].to_f >= 2.64 ? values : values[0..31] + values[35..-1] else values end end
[ "def", "discard_unsupported_attributes", "(", "values", ",", "options", "=", "{", "}", ")", "case", "self", "when", "SiteSetup", "options", "[", ":version", "]", ".", "to_f", ">=", "2.6", "?", "values", ":", "values", "[", "0", "..", "-", "4", "]", "when", "Field", "options", "[", ":version", "]", ".", "to_f", ">=", "2.64", "?", "values", ":", "values", "[", "0", "..", "-", "4", "]", "when", "ExtendedField", "options", "[", ":version", "]", ".", "to_f", ">=", "2.4", "?", "values", ":", "values", "[", "0", "..", "-", "5", "]", "when", "ControlPoint", "options", "[", ":version", "]", ".", "to_f", ">=", "2.64", "?", "values", ":", "values", "[", "0", "..", "31", "]", "+", "values", "[", "35", "..", "-", "1", "]", "else", "values", "end", "end" ]
Removes any attributes that are newer than the given compatibility target version. E.g. if a compatibility version of Mosaiq 2.4 is specified, attributes that were introduced in Mosaiq 2.5 or later is removed before the RTP string is created. @param [Array<String>] values the complete set of values of this record @param [Hash] options an optional hash parameter @option options [Float] :version the Mosaiq compatibility version number (e.g. 2.4) used for the output @return [Array<String>] an array of attributes where some of the recent attributes may have been removed
[ "Removes", "any", "attributes", "that", "are", "newer", "than", "the", "given", "compatibility", "target", "version", ".", "E", ".", "g", ".", "if", "a", "compatibility", "version", "of", "Mosaiq", "2", ".", "4", "is", "specified", "attributes", "that", "were", "introduced", "in", "Mosaiq", "2", ".", "5", "or", "later", "is", "removed", "before", "the", "RTP", "string", "is", "created", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/record.rb#L192-L205
2,003
seanedwards/cfer
lib/cfer/config.rb
Cfer.Config.include_config
def include_config(*files) include_base = File.dirname(@config_file) if @config_file files.each do |file| path = File.join(include_base, file) if include_base include_file(path || file) end end
ruby
def include_config(*files) include_base = File.dirname(@config_file) if @config_file files.each do |file| path = File.join(include_base, file) if include_base include_file(path || file) end end
[ "def", "include_config", "(", "*", "files", ")", "include_base", "=", "File", ".", "dirname", "(", "@config_file", ")", "if", "@config_file", "files", ".", "each", "do", "|", "file", "|", "path", "=", "File", ".", "join", "(", "include_base", ",", "file", ")", "if", "include_base", "include_file", "(", "path", "||", "file", ")", "end", "end" ]
Includes config code from one or more files, and evals it in the context of this stack. Filenames are relative to the file containing the invocation of this method.
[ "Includes", "config", "code", "from", "one", "or", "more", "files", "and", "evals", "it", "in", "the", "context", "of", "this", "stack", ".", "Filenames", "are", "relative", "to", "the", "file", "containing", "the", "invocation", "of", "this", "method", "." ]
802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086
https://github.com/seanedwards/cfer/blob/802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086/lib/cfer/config.rb#L34-L40
2,004
dicom/rtp-connect
lib/rtp-connect/plan.rb
RTP.Plan.write
def write(file, options={}) f = open_file(file) f.write(to_s(options)) f.close end
ruby
def write(file, options={}) f = open_file(file) f.write(to_s(options)) f.close end
[ "def", "write", "(", "file", ",", "options", "=", "{", "}", ")", "f", "=", "open_file", "(", "file", ")", "f", ".", "write", "(", "to_s", "(", "options", ")", ")", "f", ".", "close", "end" ]
Writes the Plan object, along with its hiearchy of child objects, to a properly formatted RTPConnect ascii file. @param [String] file a path/file string @param [Hash] options an optional hash parameter @option options [Float] :version the Mosaiq compatibility version number (e.g. 2.4) used for the output
[ "Writes", "the", "Plan", "object", "along", "with", "its", "hiearchy", "of", "child", "objects", "to", "a", "properly", "formatted", "RTPConnect", "ascii", "file", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan.rb#L317-L321
2,005
seanedwards/cfer
lib/cfer/cfn/client.rb
Cfer::Cfn.Client.tail
def tail(options = {}) q = [] event_id_highwater = nil counter = 0 number = options[:number] || 0 for_each_event name do |fetched_event| q.unshift fetched_event if counter < number counter = counter + 1 end while q.size > 0 event = q.shift yield event event_id_highwater = event.event_id end sleep_time = 1 running = true if options[:follow] while running sleep_time = [sleep_time * (options[:backoff] || 1), options[:backoff_max_wait] || 15].min begin stack_status = describe_stacks(stack_name: name).stacks.first.stack_status running = running && (/.+_(COMPLETE|FAILED)$/.match(stack_status) == nil) yielding = true for_each_event name do |fetched_event| if event_id_highwater == fetched_event.event_id yielding = false end if yielding q.unshift fetched_event end end rescue Aws::CloudFormation::Errors::Throttling Cfer::LOGGER.debug "AWS SDK is being throttled..." # Keep going though. rescue Aws::CloudFormation::Errors::ValidationError running = false end while q.size > 0 event = q.shift yield event event_id_highwater = event.event_id sleep_time = 1 end sleep sleep_time if running unless options[:no_sleep] end end end
ruby
def tail(options = {}) q = [] event_id_highwater = nil counter = 0 number = options[:number] || 0 for_each_event name do |fetched_event| q.unshift fetched_event if counter < number counter = counter + 1 end while q.size > 0 event = q.shift yield event event_id_highwater = event.event_id end sleep_time = 1 running = true if options[:follow] while running sleep_time = [sleep_time * (options[:backoff] || 1), options[:backoff_max_wait] || 15].min begin stack_status = describe_stacks(stack_name: name).stacks.first.stack_status running = running && (/.+_(COMPLETE|FAILED)$/.match(stack_status) == nil) yielding = true for_each_event name do |fetched_event| if event_id_highwater == fetched_event.event_id yielding = false end if yielding q.unshift fetched_event end end rescue Aws::CloudFormation::Errors::Throttling Cfer::LOGGER.debug "AWS SDK is being throttled..." # Keep going though. rescue Aws::CloudFormation::Errors::ValidationError running = false end while q.size > 0 event = q.shift yield event event_id_highwater = event.event_id sleep_time = 1 end sleep sleep_time if running unless options[:no_sleep] end end end
[ "def", "tail", "(", "options", "=", "{", "}", ")", "q", "=", "[", "]", "event_id_highwater", "=", "nil", "counter", "=", "0", "number", "=", "options", "[", ":number", "]", "||", "0", "for_each_event", "name", "do", "|", "fetched_event", "|", "q", ".", "unshift", "fetched_event", "if", "counter", "<", "number", "counter", "=", "counter", "+", "1", "end", "while", "q", ".", "size", ">", "0", "event", "=", "q", ".", "shift", "yield", "event", "event_id_highwater", "=", "event", ".", "event_id", "end", "sleep_time", "=", "1", "running", "=", "true", "if", "options", "[", ":follow", "]", "while", "running", "sleep_time", "=", "[", "sleep_time", "*", "(", "options", "[", ":backoff", "]", "||", "1", ")", ",", "options", "[", ":backoff_max_wait", "]", "||", "15", "]", ".", "min", "begin", "stack_status", "=", "describe_stacks", "(", "stack_name", ":", "name", ")", ".", "stacks", ".", "first", ".", "stack_status", "running", "=", "running", "&&", "(", "/", "/", ".", "match", "(", "stack_status", ")", "==", "nil", ")", "yielding", "=", "true", "for_each_event", "name", "do", "|", "fetched_event", "|", "if", "event_id_highwater", "==", "fetched_event", ".", "event_id", "yielding", "=", "false", "end", "if", "yielding", "q", ".", "unshift", "fetched_event", "end", "end", "rescue", "Aws", "::", "CloudFormation", "::", "Errors", "::", "Throttling", "Cfer", "::", "LOGGER", ".", "debug", "\"AWS SDK is being throttled...\"", "# Keep going though.", "rescue", "Aws", "::", "CloudFormation", "::", "Errors", "::", "ValidationError", "running", "=", "false", "end", "while", "q", ".", "size", ">", "0", "event", "=", "q", ".", "shift", "yield", "event", "event_id_highwater", "=", "event", ".", "event_id", "sleep_time", "=", "1", "end", "sleep", "sleep_time", "if", "running", "unless", "options", "[", ":no_sleep", "]", "end", "end", "end" ]
Yields to the given block for each CloudFormation event that qualifies, given the specified options. @param options [Hash] The options hash @option options [Fixnum] :number The maximum number of already-existing CloudFormation events to yield. @option options [Boolean] :follow Set to true to wait until the stack enters a `COMPLETE` or `FAILED` state, yielding events as they occur. @option options [Boolean] :no_sleep Don't pause between polling. This is used for tests, and shouldn't be when polling the AWS API. @option options [Fixnum] :backoff The exponential backoff factor (default 1.5) @option options [Fixnum] :backoff_max_wait The maximum amount of time that exponential backoff will wait before polling agian (default 15s)
[ "Yields", "to", "the", "given", "block", "for", "each", "CloudFormation", "event", "that", "qualifies", "given", "the", "specified", "options", "." ]
802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086
https://github.com/seanedwards/cfer/blob/802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086/lib/cfer/cfn/client.rb#L154-L207
2,006
seanedwards/cfer
lib/cfer/block.rb
Cfer.Block.build_from_block
def build_from_block(*args, &block) pre_block Docile.dsl_eval(self, *args, &block) if block post_block self end
ruby
def build_from_block(*args, &block) pre_block Docile.dsl_eval(self, *args, &block) if block post_block self end
[ "def", "build_from_block", "(", "*", "args", ",", "&", "block", ")", "pre_block", "Docile", ".", "dsl_eval", "(", "self", ",", "args", ",", "block", ")", "if", "block", "post_block", "self", "end" ]
Evaluates a DSL directly from a Ruby block, calling pre- and post- hooks. @param args [Array<Object>] Extra arguments to be passed into the block.
[ "Evaluates", "a", "DSL", "directly", "from", "a", "Ruby", "block", "calling", "pre", "-", "and", "post", "-", "hooks", "." ]
802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086
https://github.com/seanedwards/cfer/blob/802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086/lib/cfer/block.rb#L10-L15
2,007
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.add_angle
def add_angle(item, angle_tag, direction_tag, angle, direction, current_angle) if !self.send(current_angle) || angle != self.send(current_angle) self.send("#{current_angle}=", angle) DICOM::Element.new(angle_tag, angle, :parent => item) DICOM::Element.new(direction_tag, (direction.empty? ? 'NONE' : direction), :parent => item) end end
ruby
def add_angle(item, angle_tag, direction_tag, angle, direction, current_angle) if !self.send(current_angle) || angle != self.send(current_angle) self.send("#{current_angle}=", angle) DICOM::Element.new(angle_tag, angle, :parent => item) DICOM::Element.new(direction_tag, (direction.empty? ? 'NONE' : direction), :parent => item) end end
[ "def", "add_angle", "(", "item", ",", "angle_tag", ",", "direction_tag", ",", "angle", ",", "direction", ",", "current_angle", ")", "if", "!", "self", ".", "send", "(", "current_angle", ")", "||", "angle", "!=", "self", ".", "send", "(", "current_angle", ")", "self", ".", "send", "(", "\"#{current_angle}=\"", ",", "angle", ")", "DICOM", "::", "Element", ".", "new", "(", "angle_tag", ",", "angle", ",", ":parent", "=>", "item", ")", "DICOM", "::", "Element", ".", "new", "(", "direction_tag", ",", "(", "direction", ".", "empty?", "?", "'NONE'", ":", "direction", ")", ",", ":parent", "=>", "item", ")", "end", "end" ]
Adds an angular type value to a Control Point Item, by creating the necessary DICOM elements. Note that the element is only added if there is no 'current' attribute defined, or the given value is different form the current attribute. @param [DICOM::Item] item the DICOM control point item in which to create the elements @param [String] angle_tag the DICOM tag of the angle element @param [String] direction_tag the DICOM tag of the direction element @param [String, NilClass] angle the collimator angle attribute @param [String, NilClass] direction the collimator rotation direction attribute @param [Symbol] current_angle the instance variable that keeps track of the current value of this attribute
[ "Adds", "an", "angular", "type", "value", "to", "a", "Control", "Point", "Item", "by", "creating", "the", "necessary", "DICOM", "elements", ".", "Note", "that", "the", "element", "is", "only", "added", "if", "there", "is", "no", "current", "attribute", "defined", "or", "the", "given", "value", "is", "different", "form", "the", "current", "attribute", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L383-L389
2,008
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.add_couch_position
def add_couch_position(item, tag, value, current) if !self.send(current) || value != self.send(current) self.send("#{current}=", value) DICOM::Element.new(tag, (value.empty? ? '' : value.to_f * 10), :parent => item) end end
ruby
def add_couch_position(item, tag, value, current) if !self.send(current) || value != self.send(current) self.send("#{current}=", value) DICOM::Element.new(tag, (value.empty? ? '' : value.to_f * 10), :parent => item) end end
[ "def", "add_couch_position", "(", "item", ",", "tag", ",", "value", ",", "current", ")", "if", "!", "self", ".", "send", "(", "current", ")", "||", "value", "!=", "self", ".", "send", "(", "current", ")", "self", ".", "send", "(", "\"#{current}=\"", ",", "value", ")", "DICOM", "::", "Element", ".", "new", "(", "tag", ",", "(", "value", ".", "empty?", "?", "''", ":", "value", ".", "to_f", "*", "10", ")", ",", ":parent", "=>", "item", ")", "end", "end" ]
Adds a Table Top Position element to a Control Point Item. Note that the element is only added if there is no 'current' attribute defined, or the given value is different form the current attribute. @param [DICOM::Item] item the DICOM control point item in which to create the element @param [String] tag the DICOM tag of the couch position element @param [String, NilClass] value the couch position @param [Symbol] current the instance variable that keeps track of the current value of this attribute
[ "Adds", "a", "Table", "Top", "Position", "element", "to", "a", "Control", "Point", "Item", ".", "Note", "that", "the", "element", "is", "only", "added", "if", "there", "is", "no", "current", "attribute", "defined", "or", "the", "given", "value", "is", "different", "form", "the", "current", "attribute", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L400-L405
2,009
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.add_doserate
def add_doserate(value, item) if !@current_doserate || value != @current_doserate @current_doserate = value DICOM::Element.new('300A,0115', value, :parent => item) end end
ruby
def add_doserate(value, item) if !@current_doserate || value != @current_doserate @current_doserate = value DICOM::Element.new('300A,0115', value, :parent => item) end end
[ "def", "add_doserate", "(", "value", ",", "item", ")", "if", "!", "@current_doserate", "||", "value", "!=", "@current_doserate", "@current_doserate", "=", "value", "DICOM", "::", "Element", ".", "new", "(", "'300A,0115'", ",", "value", ",", ":parent", "=>", "item", ")", "end", "end" ]
Adds a Dose Rate Set element to a Control Point Item. Note that the element is only added if there is no 'current' attribute defined, or the given value is different form the current attribute. @param [String, NilClass] value the doserate attribute @param [DICOM::Item] item the DICOM control point item in which to create an element
[ "Adds", "a", "Dose", "Rate", "Set", "element", "to", "a", "Control", "Point", "Item", ".", "Note", "that", "the", "element", "is", "only", "added", "if", "there", "is", "no", "current", "attribute", "defined", "or", "the", "given", "value", "is", "different", "form", "the", "current", "attribute", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L414-L419
2,010
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.create_control_point
def create_control_point(cp, sequence, options={}) cp_item = DICOM::Item.new(:parent => sequence) # Some CP attributes will always be written (CP index, BLD positions & Cumulative meterset weight). # The other attributes are only written if they are different from the previous control point. # Control Point Index: DICOM::Element.new('300A,0112', "#{cp.index}", :parent => cp_item) # Beam Limiting Device Position Sequence: create_beam_limiting_device_positions(cp_item, cp, options) # Source to Surface Distance: add_ssd(cp.ssd, cp_item) # Cumulative Meterset Weight: DICOM::Element.new('300A,0134', cp.monitor_units.to_f, :parent => cp_item) # Referenced Dose Reference Sequence: create_referenced_dose_reference(cp_item) if options[:dose_ref] # Attributes that are only added if they carry an updated value: # Nominal Beam Energy: add_energy(cp.energy, cp_item) # Dose Rate Set: add_doserate(cp.doserate, cp_item) # Gantry Angle & Rotation Direction: add_angle(cp_item, '300A,011E', '300A,011F', cp.gantry_angle, cp.gantry_dir, :current_gantry) # Beam Limiting Device Angle & Rotation Direction: add_angle(cp_item, '300A,0120', '300A,0121', cp.collimator_angle, cp.collimator_dir, :current_collimator) # Patient Support Angle & Rotation Direction: add_angle(cp_item, '300A,0122', '300A,0123', cp.couch_pedestal, cp.couch_ped_dir, :current_couch_pedestal) # Table Top Eccentric Angle & Rotation Direction: add_angle(cp_item, '300A,0125', '300A,0126', cp.couch_angle, cp.couch_dir, :current_couch_angle) # Table Top Vertical Position: add_couch_position(cp_item, '300A,0128', cp.couch_vertical, :current_couch_vertical) # Table Top Longitudinal Position: add_couch_position(cp_item, '300A,0129', cp.couch_longitudinal, :current_couch_longitudinal) # Table Top Lateral Position: add_couch_position(cp_item, '300A,012A', cp.couch_lateral, :current_couch_lateral) # Isocenter Position (x\y\z): add_isosenter(cp.parent.parent.site_setup, cp_item) cp_item end
ruby
def create_control_point(cp, sequence, options={}) cp_item = DICOM::Item.new(:parent => sequence) # Some CP attributes will always be written (CP index, BLD positions & Cumulative meterset weight). # The other attributes are only written if they are different from the previous control point. # Control Point Index: DICOM::Element.new('300A,0112', "#{cp.index}", :parent => cp_item) # Beam Limiting Device Position Sequence: create_beam_limiting_device_positions(cp_item, cp, options) # Source to Surface Distance: add_ssd(cp.ssd, cp_item) # Cumulative Meterset Weight: DICOM::Element.new('300A,0134', cp.monitor_units.to_f, :parent => cp_item) # Referenced Dose Reference Sequence: create_referenced_dose_reference(cp_item) if options[:dose_ref] # Attributes that are only added if they carry an updated value: # Nominal Beam Energy: add_energy(cp.energy, cp_item) # Dose Rate Set: add_doserate(cp.doserate, cp_item) # Gantry Angle & Rotation Direction: add_angle(cp_item, '300A,011E', '300A,011F', cp.gantry_angle, cp.gantry_dir, :current_gantry) # Beam Limiting Device Angle & Rotation Direction: add_angle(cp_item, '300A,0120', '300A,0121', cp.collimator_angle, cp.collimator_dir, :current_collimator) # Patient Support Angle & Rotation Direction: add_angle(cp_item, '300A,0122', '300A,0123', cp.couch_pedestal, cp.couch_ped_dir, :current_couch_pedestal) # Table Top Eccentric Angle & Rotation Direction: add_angle(cp_item, '300A,0125', '300A,0126', cp.couch_angle, cp.couch_dir, :current_couch_angle) # Table Top Vertical Position: add_couch_position(cp_item, '300A,0128', cp.couch_vertical, :current_couch_vertical) # Table Top Longitudinal Position: add_couch_position(cp_item, '300A,0129', cp.couch_longitudinal, :current_couch_longitudinal) # Table Top Lateral Position: add_couch_position(cp_item, '300A,012A', cp.couch_lateral, :current_couch_lateral) # Isocenter Position (x\y\z): add_isosenter(cp.parent.parent.site_setup, cp_item) cp_item end
[ "def", "create_control_point", "(", "cp", ",", "sequence", ",", "options", "=", "{", "}", ")", "cp_item", "=", "DICOM", "::", "Item", ".", "new", "(", ":parent", "=>", "sequence", ")", "# Some CP attributes will always be written (CP index, BLD positions & Cumulative meterset weight).", "# The other attributes are only written if they are different from the previous control point.", "# Control Point Index:", "DICOM", "::", "Element", ".", "new", "(", "'300A,0112'", ",", "\"#{cp.index}\"", ",", ":parent", "=>", "cp_item", ")", "# Beam Limiting Device Position Sequence:", "create_beam_limiting_device_positions", "(", "cp_item", ",", "cp", ",", "options", ")", "# Source to Surface Distance:", "add_ssd", "(", "cp", ".", "ssd", ",", "cp_item", ")", "# Cumulative Meterset Weight:", "DICOM", "::", "Element", ".", "new", "(", "'300A,0134'", ",", "cp", ".", "monitor_units", ".", "to_f", ",", ":parent", "=>", "cp_item", ")", "# Referenced Dose Reference Sequence:", "create_referenced_dose_reference", "(", "cp_item", ")", "if", "options", "[", ":dose_ref", "]", "# Attributes that are only added if they carry an updated value:", "# Nominal Beam Energy:", "add_energy", "(", "cp", ".", "energy", ",", "cp_item", ")", "# Dose Rate Set:", "add_doserate", "(", "cp", ".", "doserate", ",", "cp_item", ")", "# Gantry Angle & Rotation Direction:", "add_angle", "(", "cp_item", ",", "'300A,011E'", ",", "'300A,011F'", ",", "cp", ".", "gantry_angle", ",", "cp", ".", "gantry_dir", ",", ":current_gantry", ")", "# Beam Limiting Device Angle & Rotation Direction:", "add_angle", "(", "cp_item", ",", "'300A,0120'", ",", "'300A,0121'", ",", "cp", ".", "collimator_angle", ",", "cp", ".", "collimator_dir", ",", ":current_collimator", ")", "# Patient Support Angle & Rotation Direction:", "add_angle", "(", "cp_item", ",", "'300A,0122'", ",", "'300A,0123'", ",", "cp", ".", "couch_pedestal", ",", "cp", ".", "couch_ped_dir", ",", ":current_couch_pedestal", ")", "# Table Top Eccentric Angle & Rotation Direction:", "add_angle", "(", "cp_item", ",", "'300A,0125'", ",", "'300A,0126'", ",", "cp", ".", "couch_angle", ",", "cp", ".", "couch_dir", ",", ":current_couch_angle", ")", "# Table Top Vertical Position:", "add_couch_position", "(", "cp_item", ",", "'300A,0128'", ",", "cp", ".", "couch_vertical", ",", ":current_couch_vertical", ")", "# Table Top Longitudinal Position:", "add_couch_position", "(", "cp_item", ",", "'300A,0129'", ",", "cp", ".", "couch_longitudinal", ",", ":current_couch_longitudinal", ")", "# Table Top Lateral Position:", "add_couch_position", "(", "cp_item", ",", "'300A,012A'", ",", "cp", ".", "couch_lateral", ",", ":current_couch_lateral", ")", "# Isocenter Position (x\\y\\z):", "add_isosenter", "(", "cp", ".", "parent", ".", "parent", ".", "site_setup", ",", "cp_item", ")", "cp_item", "end" ]
Creates a control point item in the given control point sequence, based on an RTP control point record. @param [ControlPoint] cp the RTP ControlPoint record to convert @param [DICOM::Sequence] sequence the DICOM parent sequence of the item to be created @param [Hash] options the options to use for creating the control point @option options [Boolean] :dose_ref if set, a Referenced Dose Reference sequence will be included in the generated control point item @return [DICOM::Item] the constructed control point DICOM item
[ "Creates", "a", "control", "point", "item", "in", "the", "given", "control", "point", "sequence", "based", "on", "an", "RTP", "control", "point", "record", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L481-L517
2,011
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.create_beam_limiting_devices
def create_beam_limiting_devices(beam_item, field) bl_seq = DICOM::Sequence.new('300A,00B6', :parent => beam_item) # The ASYMX item ('backup jaws') doesn't exist on all models: if ['SYM', 'ASY'].include?(field.field_x_mode.upcase) bl_item_x = DICOM::Item.new(:parent => bl_seq) DICOM::Element.new('300A,00B8', "ASYMX", :parent => bl_item_x) DICOM::Element.new('300A,00BC', "1", :parent => bl_item_x) end # The ASYMY item is always created: bl_item_y = DICOM::Item.new(:parent => bl_seq) # RT Beam Limiting Device Type: DICOM::Element.new('300A,00B8', "ASYMY", :parent => bl_item_y) # Number of Leaf/Jaw Pairs: DICOM::Element.new('300A,00BC', "1", :parent => bl_item_y) # MLCX item is only created if leaves are defined: # (NB: The RTP file doesn't specify leaf position boundaries, so we # have to set these based on a set of known MLC types, their number # of leaves, and their leaf boundary positions.) if field.control_points.length > 0 bl_item_mlcx = DICOM::Item.new(:parent => bl_seq) DICOM::Element.new('300A,00B8', "MLCX", :parent => bl_item_mlcx) num_leaves = field.control_points.first.mlc_leaves.to_i DICOM::Element.new('300A,00BC', num_leaves.to_s, :parent => bl_item_mlcx) DICOM::Element.new('300A,00BE', "#{RTP.leaf_boundaries(num_leaves).join("\\")}", :parent => bl_item_mlcx) end bl_seq end
ruby
def create_beam_limiting_devices(beam_item, field) bl_seq = DICOM::Sequence.new('300A,00B6', :parent => beam_item) # The ASYMX item ('backup jaws') doesn't exist on all models: if ['SYM', 'ASY'].include?(field.field_x_mode.upcase) bl_item_x = DICOM::Item.new(:parent => bl_seq) DICOM::Element.new('300A,00B8', "ASYMX", :parent => bl_item_x) DICOM::Element.new('300A,00BC', "1", :parent => bl_item_x) end # The ASYMY item is always created: bl_item_y = DICOM::Item.new(:parent => bl_seq) # RT Beam Limiting Device Type: DICOM::Element.new('300A,00B8', "ASYMY", :parent => bl_item_y) # Number of Leaf/Jaw Pairs: DICOM::Element.new('300A,00BC', "1", :parent => bl_item_y) # MLCX item is only created if leaves are defined: # (NB: The RTP file doesn't specify leaf position boundaries, so we # have to set these based on a set of known MLC types, their number # of leaves, and their leaf boundary positions.) if field.control_points.length > 0 bl_item_mlcx = DICOM::Item.new(:parent => bl_seq) DICOM::Element.new('300A,00B8', "MLCX", :parent => bl_item_mlcx) num_leaves = field.control_points.first.mlc_leaves.to_i DICOM::Element.new('300A,00BC', num_leaves.to_s, :parent => bl_item_mlcx) DICOM::Element.new('300A,00BE', "#{RTP.leaf_boundaries(num_leaves).join("\\")}", :parent => bl_item_mlcx) end bl_seq end
[ "def", "create_beam_limiting_devices", "(", "beam_item", ",", "field", ")", "bl_seq", "=", "DICOM", "::", "Sequence", ".", "new", "(", "'300A,00B6'", ",", ":parent", "=>", "beam_item", ")", "# The ASYMX item ('backup jaws') doesn't exist on all models:", "if", "[", "'SYM'", ",", "'ASY'", "]", ".", "include?", "(", "field", ".", "field_x_mode", ".", "upcase", ")", "bl_item_x", "=", "DICOM", "::", "Item", ".", "new", "(", ":parent", "=>", "bl_seq", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,00B8'", ",", "\"ASYMX\"", ",", ":parent", "=>", "bl_item_x", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,00BC'", ",", "\"1\"", ",", ":parent", "=>", "bl_item_x", ")", "end", "# The ASYMY item is always created:", "bl_item_y", "=", "DICOM", "::", "Item", ".", "new", "(", ":parent", "=>", "bl_seq", ")", "# RT Beam Limiting Device Type:", "DICOM", "::", "Element", ".", "new", "(", "'300A,00B8'", ",", "\"ASYMY\"", ",", ":parent", "=>", "bl_item_y", ")", "# Number of Leaf/Jaw Pairs:", "DICOM", "::", "Element", ".", "new", "(", "'300A,00BC'", ",", "\"1\"", ",", ":parent", "=>", "bl_item_y", ")", "# MLCX item is only created if leaves are defined:", "# (NB: The RTP file doesn't specify leaf position boundaries, so we", "# have to set these based on a set of known MLC types, their number", "# of leaves, and their leaf boundary positions.)", "if", "field", ".", "control_points", ".", "length", ">", "0", "bl_item_mlcx", "=", "DICOM", "::", "Item", ".", "new", "(", ":parent", "=>", "bl_seq", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,00B8'", ",", "\"MLCX\"", ",", ":parent", "=>", "bl_item_mlcx", ")", "num_leaves", "=", "field", ".", "control_points", ".", "first", ".", "mlc_leaves", ".", "to_i", "DICOM", "::", "Element", ".", "new", "(", "'300A,00BC'", ",", "num_leaves", ".", "to_s", ",", ":parent", "=>", "bl_item_mlcx", ")", "DICOM", "::", "Element", ".", "new", "(", "'300A,00BE'", ",", "\"#{RTP.leaf_boundaries(num_leaves).join(\"\\\\\")}\"", ",", ":parent", "=>", "bl_item_mlcx", ")", "end", "bl_seq", "end" ]
Creates a beam limiting device sequence in the given DICOM object. @param [DICOM::Item] beam_item the DICOM beam item in which to insert the sequence @param [Field] field the RTP field to fetch device parameters from @return [DICOM::Sequence] the constructed beam limiting device sequence
[ "Creates", "a", "beam", "limiting", "device", "sequence", "in", "the", "given", "DICOM", "object", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L525-L551
2,012
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.create_asym_item
def create_asym_item(cp, dcm_parent, axis, options={}) val1 = cp.send("dcm_collimator_#{axis.to_s}1", options[:scale]) val2 = cp.send("dcm_collimator_#{axis.to_s}2", options[:scale]) item = DICOM::Item.new(:parent => dcm_parent) # RT Beam Limiting Device Type: DICOM::Element.new('300A,00B8', "ASYM#{axis.to_s.upcase}", :parent => item) # Leaf/Jaw Positions: DICOM::Element.new('300A,011C', "#{val1}\\#{val2}", :parent => item) item end
ruby
def create_asym_item(cp, dcm_parent, axis, options={}) val1 = cp.send("dcm_collimator_#{axis.to_s}1", options[:scale]) val2 = cp.send("dcm_collimator_#{axis.to_s}2", options[:scale]) item = DICOM::Item.new(:parent => dcm_parent) # RT Beam Limiting Device Type: DICOM::Element.new('300A,00B8', "ASYM#{axis.to_s.upcase}", :parent => item) # Leaf/Jaw Positions: DICOM::Element.new('300A,011C', "#{val1}\\#{val2}", :parent => item) item end
[ "def", "create_asym_item", "(", "cp", ",", "dcm_parent", ",", "axis", ",", "options", "=", "{", "}", ")", "val1", "=", "cp", ".", "send", "(", "\"dcm_collimator_#{axis.to_s}1\"", ",", "options", "[", ":scale", "]", ")", "val2", "=", "cp", ".", "send", "(", "\"dcm_collimator_#{axis.to_s}2\"", ",", "options", "[", ":scale", "]", ")", "item", "=", "DICOM", "::", "Item", ".", "new", "(", ":parent", "=>", "dcm_parent", ")", "# RT Beam Limiting Device Type:", "DICOM", "::", "Element", ".", "new", "(", "'300A,00B8'", ",", "\"ASYM#{axis.to_s.upcase}\"", ",", ":parent", "=>", "item", ")", "# Leaf/Jaw Positions:", "DICOM", "::", "Element", ".", "new", "(", "'300A,011C'", ",", "\"#{val1}\\\\#{val2}\"", ",", ":parent", "=>", "item", ")", "item", "end" ]
Creates an ASYMX or ASYMY item. @param [ControlPoint] cp the RTP control point to fetch device parameters from @param [DICOM::Sequence] dcm_parent the DICOM sequence in which to insert the item @param [Symbol] axis the axis for the item (:x or :y) @return [DICOM::Item] the constructed ASYMX or ASYMY item
[ "Creates", "an", "ASYMX", "or", "ASYMY", "item", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L583-L592
2,013
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.create_dose_reference
def create_dose_reference(dcm, description) dr_seq = DICOM::Sequence.new('300A,0010', :parent => dcm) dr_item = DICOM::Item.new(:parent => dr_seq) # Dose Reference Number: DICOM::Element.new('300A,0012', '1', :parent => dr_item) # Dose Reference Structure Type: DICOM::Element.new('300A,0014', 'SITE', :parent => dr_item) # Dose Reference Description: DICOM::Element.new('300A,0016', description, :parent => dr_item) # Dose Reference Type: DICOM::Element.new('300A,0020', 'TARGET', :parent => dr_item) dr_seq end
ruby
def create_dose_reference(dcm, description) dr_seq = DICOM::Sequence.new('300A,0010', :parent => dcm) dr_item = DICOM::Item.new(:parent => dr_seq) # Dose Reference Number: DICOM::Element.new('300A,0012', '1', :parent => dr_item) # Dose Reference Structure Type: DICOM::Element.new('300A,0014', 'SITE', :parent => dr_item) # Dose Reference Description: DICOM::Element.new('300A,0016', description, :parent => dr_item) # Dose Reference Type: DICOM::Element.new('300A,0020', 'TARGET', :parent => dr_item) dr_seq end
[ "def", "create_dose_reference", "(", "dcm", ",", "description", ")", "dr_seq", "=", "DICOM", "::", "Sequence", ".", "new", "(", "'300A,0010'", ",", ":parent", "=>", "dcm", ")", "dr_item", "=", "DICOM", "::", "Item", ".", "new", "(", ":parent", "=>", "dr_seq", ")", "# Dose Reference Number:", "DICOM", "::", "Element", ".", "new", "(", "'300A,0012'", ",", "'1'", ",", ":parent", "=>", "dr_item", ")", "# Dose Reference Structure Type:", "DICOM", "::", "Element", ".", "new", "(", "'300A,0014'", ",", "'SITE'", ",", ":parent", "=>", "dr_item", ")", "# Dose Reference Description:", "DICOM", "::", "Element", ".", "new", "(", "'300A,0016'", ",", "description", ",", ":parent", "=>", "dr_item", ")", "# Dose Reference Type:", "DICOM", "::", "Element", ".", "new", "(", "'300A,0020'", ",", "'TARGET'", ",", ":parent", "=>", "dr_item", ")", "dr_seq", "end" ]
Creates a dose reference sequence in the given DICOM object. @param [DICOM::DObject] dcm the DICOM object in which to insert the sequence @param [String] description the value to use for Dose Reference Description @return [DICOM::Sequence] the constructed dose reference sequence
[ "Creates", "a", "dose", "reference", "sequence", "in", "the", "given", "DICOM", "object", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L619-L631
2,014
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.create_referenced_dose_reference
def create_referenced_dose_reference(cp_item) # Referenced Dose Reference Sequence: rd_seq = DICOM::Sequence.new('300C,0050', :parent => cp_item) rd_item = DICOM::Item.new(:parent => rd_seq) # Cumulative Dose Reference Coeffecient: DICOM::Element.new('300A,010C', '', :parent => rd_item) # Referenced Dose Reference Number: DICOM::Element.new('300C,0051', '1', :parent => rd_item) rd_seq end
ruby
def create_referenced_dose_reference(cp_item) # Referenced Dose Reference Sequence: rd_seq = DICOM::Sequence.new('300C,0050', :parent => cp_item) rd_item = DICOM::Item.new(:parent => rd_seq) # Cumulative Dose Reference Coeffecient: DICOM::Element.new('300A,010C', '', :parent => rd_item) # Referenced Dose Reference Number: DICOM::Element.new('300C,0051', '1', :parent => rd_item) rd_seq end
[ "def", "create_referenced_dose_reference", "(", "cp_item", ")", "# Referenced Dose Reference Sequence:", "rd_seq", "=", "DICOM", "::", "Sequence", ".", "new", "(", "'300C,0050'", ",", ":parent", "=>", "cp_item", ")", "rd_item", "=", "DICOM", "::", "Item", ".", "new", "(", ":parent", "=>", "rd_seq", ")", "# Cumulative Dose Reference Coeffecient:", "DICOM", "::", "Element", ".", "new", "(", "'300A,010C'", ",", "''", ",", ":parent", "=>", "rd_item", ")", "# Referenced Dose Reference Number:", "DICOM", "::", "Element", ".", "new", "(", "'300C,0051'", ",", "'1'", ",", ":parent", "=>", "rd_item", ")", "rd_seq", "end" ]
Creates a referenced dose reference sequence in the given DICOM object. @param [DICOM::Item] cp_item the DICOM item in which to insert the sequence @return [DICOM::Sequence] the constructed referenced dose reference sequence
[ "Creates", "a", "referenced", "dose", "reference", "sequence", "in", "the", "given", "DICOM", "object", "." ]
e23791970218a7087a0d798aa430acf36f79d758
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L638-L647
2,015
nicotaing/yaml_record
lib/yaml_record/base.rb
YamlRecord.Base.save
def save run_callbacks(:before_save) run_callbacks(:before_create) unless self.is_created existing_items = self.class.all if self.new_record? existing_items << self else # update existing record updated_item = existing_items.find { |item| item.id == self.id } return false unless updated_item updated_item.attributes = self.attributes end raw_data = existing_items ? existing_items.map { |item| item.persisted_attributes } : [] self.class.write_contents(raw_data) if self.valid? run_callbacks(:after_create) unless self.is_created run_callbacks(:after_save) true rescue IOError false end
ruby
def save run_callbacks(:before_save) run_callbacks(:before_create) unless self.is_created existing_items = self.class.all if self.new_record? existing_items << self else # update existing record updated_item = existing_items.find { |item| item.id == self.id } return false unless updated_item updated_item.attributes = self.attributes end raw_data = existing_items ? existing_items.map { |item| item.persisted_attributes } : [] self.class.write_contents(raw_data) if self.valid? run_callbacks(:after_create) unless self.is_created run_callbacks(:after_save) true rescue IOError false end
[ "def", "save", "run_callbacks", "(", ":before_save", ")", "run_callbacks", "(", ":before_create", ")", "unless", "self", ".", "is_created", "existing_items", "=", "self", ".", "class", ".", "all", "if", "self", ".", "new_record?", "existing_items", "<<", "self", "else", "# update existing record", "updated_item", "=", "existing_items", ".", "find", "{", "|", "item", "|", "item", ".", "id", "==", "self", ".", "id", "}", "return", "false", "unless", "updated_item", "updated_item", ".", "attributes", "=", "self", ".", "attributes", "end", "raw_data", "=", "existing_items", "?", "existing_items", ".", "map", "{", "|", "item", "|", "item", ".", "persisted_attributes", "}", ":", "[", "]", "self", ".", "class", ".", "write_contents", "(", "raw_data", ")", "if", "self", ".", "valid?", "run_callbacks", "(", ":after_create", ")", "unless", "self", ".", "is_created", "run_callbacks", "(", ":after_save", ")", "true", "rescue", "IOError", "false", "end" ]
Saved YamlRecord instance to file Executes save and create callbacks Returns true if record saved; false otherwise === Example: @post.save => true
[ "Saved", "YamlRecord", "instance", "to", "file", "Executes", "save", "and", "create", "callbacks", "Returns", "true", "if", "record", "saved", ";", "false", "otherwise" ]
653a7f6b6c53f67bc91082a455914489fd3498fa
https://github.com/nicotaing/yaml_record/blob/653a7f6b6c53f67bc91082a455914489fd3498fa/lib/yaml_record/base.rb#L57-L78
2,016
nicotaing/yaml_record
lib/yaml_record/base.rb
YamlRecord.Base.destroy
def destroy run_callbacks(:before_destroy) new_data = self.class.all.reject { |item| item.persisted_attributes == self.persisted_attributes }.map { |item| item.persisted_attributes } self.class.write_contents(new_data) self.is_destroyed = true run_callbacks(:after_destroy) true rescue IOError false end
ruby
def destroy run_callbacks(:before_destroy) new_data = self.class.all.reject { |item| item.persisted_attributes == self.persisted_attributes }.map { |item| item.persisted_attributes } self.class.write_contents(new_data) self.is_destroyed = true run_callbacks(:after_destroy) true rescue IOError false end
[ "def", "destroy", "run_callbacks", "(", ":before_destroy", ")", "new_data", "=", "self", ".", "class", ".", "all", ".", "reject", "{", "|", "item", "|", "item", ".", "persisted_attributes", "==", "self", ".", "persisted_attributes", "}", ".", "map", "{", "|", "item", "|", "item", ".", "persisted_attributes", "}", "self", ".", "class", ".", "write_contents", "(", "new_data", ")", "self", ".", "is_destroyed", "=", "true", "run_callbacks", "(", ":after_destroy", ")", "true", "rescue", "IOError", "false", "end" ]
Remove a persisted YamlRecord object Returns true if destroyed; false otherwise === Example: @post = Post.create(:foo => "bar", :miso => "great") Post.all.size => 1 @post.destroy => true Post.all.size => 0
[ "Remove", "a", "persisted", "YamlRecord", "object", "Returns", "true", "if", "destroyed", ";", "false", "otherwise" ]
653a7f6b6c53f67bc91082a455914489fd3498fa
https://github.com/nicotaing/yaml_record/blob/653a7f6b6c53f67bc91082a455914489fd3498fa/lib/yaml_record/base.rb#L154-L163
2,017
seanedwards/cfer
lib/cfer/core/resource.rb
Cfer::Core.Resource.tag
def tag(k, v, **options) self[:Properties][:Tags] ||= [] self[:Properties][:Tags].delete_if { |kv| kv["Key"] == k } self[:Properties][:Tags].unshift({"Key" => k, "Value" => v}.merge(options)) end
ruby
def tag(k, v, **options) self[:Properties][:Tags] ||= [] self[:Properties][:Tags].delete_if { |kv| kv["Key"] == k } self[:Properties][:Tags].unshift({"Key" => k, "Value" => v}.merge(options)) end
[ "def", "tag", "(", "k", ",", "v", ",", "**", "options", ")", "self", "[", ":Properties", "]", "[", ":Tags", "]", "||=", "[", "]", "self", "[", ":Properties", "]", "[", ":Tags", "]", ".", "delete_if", "{", "|", "kv", "|", "kv", "[", "\"Key\"", "]", "==", "k", "}", "self", "[", ":Properties", "]", "[", ":Tags", "]", ".", "unshift", "(", "{", "\"Key\"", "=>", "k", ",", "\"Value\"", "=>", "v", "}", ".", "merge", "(", "options", ")", ")", "end" ]
Sets a tag on this resource. The resource must support the CloudFormation `Tags` property. @param k [String] The name of the tag to set @param v [String] The value for this tag @param options [Hash] An arbitrary set of additional properties to be added to this tag, for example `PropagateOnLaunch` on `AWS::AutoScaling::AutoScalingGroup`
[ "Sets", "a", "tag", "on", "this", "resource", ".", "The", "resource", "must", "support", "the", "CloudFormation", "Tags", "property", "." ]
802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086
https://github.com/seanedwards/cfer/blob/802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086/lib/cfer/core/resource.rb#L42-L46
2,018
seanedwards/cfer
lib/cfer/core/stack.rb
Cfer::Core.Stack.parameter
def parameter(name, options = {}) param = {} options.each do |key, v| next if v === nil k = key.to_s.camelize.to_sym param[k] = case k when :AllowedPattern if v.class == Regexp v.source end when :Default @parameters[name] ||= v end param[k] ||= v end param[:Type] ||= 'String' self[:Parameters][name] = param end
ruby
def parameter(name, options = {}) param = {} options.each do |key, v| next if v === nil k = key.to_s.camelize.to_sym param[k] = case k when :AllowedPattern if v.class == Regexp v.source end when :Default @parameters[name] ||= v end param[k] ||= v end param[:Type] ||= 'String' self[:Parameters][name] = param end
[ "def", "parameter", "(", "name", ",", "options", "=", "{", "}", ")", "param", "=", "{", "}", "options", ".", "each", "do", "|", "key", ",", "v", "|", "next", "if", "v", "===", "nil", "k", "=", "key", ".", "to_s", ".", "camelize", ".", "to_sym", "param", "[", "k", "]", "=", "case", "k", "when", ":AllowedPattern", "if", "v", ".", "class", "==", "Regexp", "v", ".", "source", "end", "when", ":Default", "@parameters", "[", "name", "]", "||=", "v", "end", "param", "[", "k", "]", "||=", "v", "end", "param", "[", ":Type", "]", "||=", "'String'", "self", "[", ":Parameters", "]", "[", "name", "]", "=", "param", "end" ]
Declares a CloudFormation parameter @param name [String] The parameter name @param options [Hash] @option options [String] :type The type for the CloudFormation parameter @option options [String] :default A value of the appropriate type for the template to use if no value is specified when a stack is created. If you define constraints for the parameter, you must specify a value that adheres to those constraints. @option options [String] :no_echo Whether to mask the parameter value whenever anyone makes a call that describes the stack. If you set the value to `true`, the parameter value is masked with asterisks (*****). @option options [String] :allowed_values An array containing the list of values allowed for the parameter. @option options [String] :allowed_pattern A regular expression that represents the patterns you want to allow for String types. @option options [Number] :max_length An integer value that determines the largest number of characters you want to allow for String types. @option options [Number] :min_length An integer value that determines the smallest number of characters you want to allow for String types. @option options [Number] :max_value A numeric value that determines the largest numeric value you want to allow for Number types. @option options [Number] :min_value A numeric value that determines the smallest numeric value you want to allow for Number types. @option options [String] :description A string of up to 4000 characters that describes the parameter. @option options [String] :constraint_description A string that explains the constraint when the constraint is violated. For example, without a constraint description, a parameter that has an allowed pattern of `[A-Za-z0-9]+` displays the following error message when the user specifies an invalid value: ```Malformed input-Parameter MyParameter must match pattern [A-Za-z0-9]+``` By adding a constraint description, such as must only contain upper- and lowercase letters, and numbers, you can display a customized error message: ```Malformed input-Parameter MyParameter must only contain upper and lower case letters and numbers```
[ "Declares", "a", "CloudFormation", "parameter" ]
802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086
https://github.com/seanedwards/cfer/blob/802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086/lib/cfer/core/stack.rb#L104-L123
2,019
seanedwards/cfer
lib/cfer/core/stack.rb
Cfer::Core.Stack.resource
def resource(name, type, options = {}, &block) Preconditions.check_argument(/[[:alnum:]]+/ =~ name, "Resource name must be alphanumeric") clazz = Cfer::Core::Resource.resource_class(type) rc = clazz.new(name, type, self, options, &block) self[:Resources][name] = rc rc.handle end
ruby
def resource(name, type, options = {}, &block) Preconditions.check_argument(/[[:alnum:]]+/ =~ name, "Resource name must be alphanumeric") clazz = Cfer::Core::Resource.resource_class(type) rc = clazz.new(name, type, self, options, &block) self[:Resources][name] = rc rc.handle end
[ "def", "resource", "(", "name", ",", "type", ",", "options", "=", "{", "}", ",", "&", "block", ")", "Preconditions", ".", "check_argument", "(", "/", "/", "=~", "name", ",", "\"Resource name must be alphanumeric\"", ")", "clazz", "=", "Cfer", "::", "Core", "::", "Resource", ".", "resource_class", "(", "type", ")", "rc", "=", "clazz", ".", "new", "(", "name", ",", "type", ",", "self", ",", "options", ",", "block", ")", "self", "[", ":Resources", "]", "[", "name", "]", "=", "rc", "rc", ".", "handle", "end" ]
Creates a CloudFormation resource @param name [String] The name of the resource (must be alphanumeric) @param type [String] The type of CloudFormation resource to create. @param options [Hash] Additional attributes to add to the resource block (such as the `UpdatePolicy` for an `AWS::AutoScaling::AutoScalingGroup`)
[ "Creates", "a", "CloudFormation", "resource" ]
802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086
https://github.com/seanedwards/cfer/blob/802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086/lib/cfer/core/stack.rb#L141-L149
2,020
seanedwards/cfer
lib/cfer/core/stack.rb
Cfer::Core.Stack.include_template
def include_template(*files) include_base = options[:include_base] || File.dirname(caller.first.split(/:\d/,2).first) files.each do |file| path = File.join(include_base, file) include_file(path) end end
ruby
def include_template(*files) include_base = options[:include_base] || File.dirname(caller.first.split(/:\d/,2).first) files.each do |file| path = File.join(include_base, file) include_file(path) end end
[ "def", "include_template", "(", "*", "files", ")", "include_base", "=", "options", "[", ":include_base", "]", "||", "File", ".", "dirname", "(", "caller", ".", "first", ".", "split", "(", "/", "\\d", "/", ",", "2", ")", ".", "first", ")", "files", ".", "each", "do", "|", "file", "|", "path", "=", "File", ".", "join", "(", "include_base", ",", "file", ")", "include_file", "(", "path", ")", "end", "end" ]
Includes template code from one or more files, and evals it in the context of this stack. Filenames are relative to the file containing the invocation of this method.
[ "Includes", "template", "code", "from", "one", "or", "more", "files", "and", "evals", "it", "in", "the", "context", "of", "this", "stack", ".", "Filenames", "are", "relative", "to", "the", "file", "containing", "the", "invocation", "of", "this", "method", "." ]
802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086
https://github.com/seanedwards/cfer/blob/802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086/lib/cfer/core/stack.rb#L177-L183
2,021
seanedwards/cfer
lib/cfer/core/stack.rb
Cfer::Core.Stack.lookup_outputs
def lookup_outputs(stack) client = @options[:client] || raise(Cfer::Util::CferError, "Can not fetch stack outputs without a client") client.fetch_outputs(stack) end
ruby
def lookup_outputs(stack) client = @options[:client] || raise(Cfer::Util::CferError, "Can not fetch stack outputs without a client") client.fetch_outputs(stack) end
[ "def", "lookup_outputs", "(", "stack", ")", "client", "=", "@options", "[", ":client", "]", "||", "raise", "(", "Cfer", "::", "Util", "::", "CferError", ",", "\"Can not fetch stack outputs without a client\"", ")", "client", ".", "fetch_outputs", "(", "stack", ")", "end" ]
Looks up a hash of all outputs from another CloudFormation stack in the same region. @param stack [String] The name of the stack to fetch outputs from
[ "Looks", "up", "a", "hash", "of", "all", "outputs", "from", "another", "CloudFormation", "stack", "in", "the", "same", "region", "." ]
802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086
https://github.com/seanedwards/cfer/blob/802c9ce10f7c4ddc4e6dc6b927f459f4b47b5086/lib/cfer/core/stack.rb#L194-L197
2,022
envato/rack_fake_s3
lib/rack_fake_s3/sorted_object_list.rb
RackFakeS3.SortedObjectList.list
def list(options) marker = options[:marker] prefix = options[:prefix] max_keys = options[:max_keys] || 1000 delimiter = options[:delimiter] ms = S3MatchSet.new marker_found = true pseudo = nil if marker marker_found = false if !@object_map[marker] pseudo = S3Object.new pseudo.name = marker @sorted_set << pseudo end end count = 0 @sorted_set.each do |s3_object| if marker_found && (!prefix or s3_object.name.index(prefix) == 0) count += 1 if count <= max_keys ms.matches << s3_object else is_truncated = true break end end if marker and marker == s3_object.name marker_found = true end end if pseudo @sorted_set.delete(pseudo) end return ms end
ruby
def list(options) marker = options[:marker] prefix = options[:prefix] max_keys = options[:max_keys] || 1000 delimiter = options[:delimiter] ms = S3MatchSet.new marker_found = true pseudo = nil if marker marker_found = false if !@object_map[marker] pseudo = S3Object.new pseudo.name = marker @sorted_set << pseudo end end count = 0 @sorted_set.each do |s3_object| if marker_found && (!prefix or s3_object.name.index(prefix) == 0) count += 1 if count <= max_keys ms.matches << s3_object else is_truncated = true break end end if marker and marker == s3_object.name marker_found = true end end if pseudo @sorted_set.delete(pseudo) end return ms end
[ "def", "list", "(", "options", ")", "marker", "=", "options", "[", ":marker", "]", "prefix", "=", "options", "[", ":prefix", "]", "max_keys", "=", "options", "[", ":max_keys", "]", "||", "1000", "delimiter", "=", "options", "[", ":delimiter", "]", "ms", "=", "S3MatchSet", ".", "new", "marker_found", "=", "true", "pseudo", "=", "nil", "if", "marker", "marker_found", "=", "false", "if", "!", "@object_map", "[", "marker", "]", "pseudo", "=", "S3Object", ".", "new", "pseudo", ".", "name", "=", "marker", "@sorted_set", "<<", "pseudo", "end", "end", "count", "=", "0", "@sorted_set", ".", "each", "do", "|", "s3_object", "|", "if", "marker_found", "&&", "(", "!", "prefix", "or", "s3_object", ".", "name", ".", "index", "(", "prefix", ")", "==", "0", ")", "count", "+=", "1", "if", "count", "<=", "max_keys", "ms", ".", "matches", "<<", "s3_object", "else", "is_truncated", "=", "true", "break", "end", "end", "if", "marker", "and", "marker", "==", "s3_object", ".", "name", "marker_found", "=", "true", "end", "end", "if", "pseudo", "@sorted_set", ".", "delete", "(", "pseudo", ")", "end", "return", "ms", "end" ]
Return back a set of matches based on the passed in options options: :marker : a string to start the lexographical search (it is not included in the result) :max_keys : a maximum number of results :prefix : a string to filter the results by :delimiter : not supported yet
[ "Return", "back", "a", "set", "of", "matches", "based", "on", "the", "passed", "in", "options" ]
d230c40579496acd8eccd62363c43b7329f6f27d
https://github.com/envato/rack_fake_s3/blob/d230c40579496acd8eccd62363c43b7329f6f27d/lib/rack_fake_s3/sorted_object_list.rb#L57-L98
2,023
locomote/gusteau
lib/gusteau/config.rb
Gusteau.Config.build_node
def build_node(node_name, env_hash, node_hash) node_config = { 'server' => node_hash.slice('host', 'port', 'user', 'password', 'platform', 'vagrant'), 'attributes' => (node_hash['attributes'] || {}).deep_merge(env_hash['attributes'] || {}), 'run_list' => node_hash['run_list'] || env_hash['run_list'], 'before' => env_hash['before'] || @config['before'], 'after' => env_hash['after'] || @config['after'] } node_config['server'].delete 'attributes' Gusteau::Node.new(node_name, node_config) end
ruby
def build_node(node_name, env_hash, node_hash) node_config = { 'server' => node_hash.slice('host', 'port', 'user', 'password', 'platform', 'vagrant'), 'attributes' => (node_hash['attributes'] || {}).deep_merge(env_hash['attributes'] || {}), 'run_list' => node_hash['run_list'] || env_hash['run_list'], 'before' => env_hash['before'] || @config['before'], 'after' => env_hash['after'] || @config['after'] } node_config['server'].delete 'attributes' Gusteau::Node.new(node_name, node_config) end
[ "def", "build_node", "(", "node_name", ",", "env_hash", ",", "node_hash", ")", "node_config", "=", "{", "'server'", "=>", "node_hash", ".", "slice", "(", "'host'", ",", "'port'", ",", "'user'", ",", "'password'", ",", "'platform'", ",", "'vagrant'", ")", ",", "'attributes'", "=>", "(", "node_hash", "[", "'attributes'", "]", "||", "{", "}", ")", ".", "deep_merge", "(", "env_hash", "[", "'attributes'", "]", "||", "{", "}", ")", ",", "'run_list'", "=>", "node_hash", "[", "'run_list'", "]", "||", "env_hash", "[", "'run_list'", "]", ",", "'before'", "=>", "env_hash", "[", "'before'", "]", "||", "@config", "[", "'before'", "]", ",", "'after'", "=>", "env_hash", "[", "'after'", "]", "||", "@config", "[", "'after'", "]", "}", "node_config", "[", "'server'", "]", ".", "delete", "'attributes'", "Gusteau", "::", "Node", ".", "new", "(", "node_name", ",", "node_config", ")", "end" ]
Node attributes get deep-merged with the environment ones Node run_list overrides the environment one Environment before hooks override global ones
[ "Node", "attributes", "get", "deep", "-", "merged", "with", "the", "environment", "ones", "Node", "run_list", "overrides", "the", "environment", "one", "Environment", "before", "hooks", "override", "global", "ones" ]
1c4d7ba0dcb9879c84c2d5b8499385399c1c6d77
https://github.com/locomote/gusteau/blob/1c4d7ba0dcb9879c84c2d5b8499385399c1c6d77/lib/gusteau/config.rb#L62-L72
2,024
envato/rack_fake_s3
lib/rack_fake_s3/server.rb
RackFakeS3.Servlet.normalize_request
def normalize_request(rack_req) host = rack_req.host s_req = Request.new s_req.path = path_for_rack_request(rack_req) s_req.is_path_style = true s_req.rack_request = rack_req if !@root_hostnames.include?(host) s_req.bucket = host.split(".")[0] s_req.is_path_style = false end s_req.http_verb = rack_req.request_method case rack_req.request_method when 'PUT' normalize_put(rack_req,s_req) when 'GET','HEAD' normalize_get(rack_req,s_req) when 'DELETE' normalize_delete(rack_req,s_req) when 'POST' normalize_post(rack_req,s_req) when 'OPTIONS' nomalize_options(rack_req,s_req) else return false end if s_req.type.nil? return false end return s_req end
ruby
def normalize_request(rack_req) host = rack_req.host s_req = Request.new s_req.path = path_for_rack_request(rack_req) s_req.is_path_style = true s_req.rack_request = rack_req if !@root_hostnames.include?(host) s_req.bucket = host.split(".")[0] s_req.is_path_style = false end s_req.http_verb = rack_req.request_method case rack_req.request_method when 'PUT' normalize_put(rack_req,s_req) when 'GET','HEAD' normalize_get(rack_req,s_req) when 'DELETE' normalize_delete(rack_req,s_req) when 'POST' normalize_post(rack_req,s_req) when 'OPTIONS' nomalize_options(rack_req,s_req) else return false end if s_req.type.nil? return false end return s_req end
[ "def", "normalize_request", "(", "rack_req", ")", "host", "=", "rack_req", ".", "host", "s_req", "=", "Request", ".", "new", "s_req", ".", "path", "=", "path_for_rack_request", "(", "rack_req", ")", "s_req", ".", "is_path_style", "=", "true", "s_req", ".", "rack_request", "=", "rack_req", "if", "!", "@root_hostnames", ".", "include?", "(", "host", ")", "s_req", ".", "bucket", "=", "host", ".", "split", "(", "\".\"", ")", "[", "0", "]", "s_req", ".", "is_path_style", "=", "false", "end", "s_req", ".", "http_verb", "=", "rack_req", ".", "request_method", "case", "rack_req", ".", "request_method", "when", "'PUT'", "normalize_put", "(", "rack_req", ",", "s_req", ")", "when", "'GET'", ",", "'HEAD'", "normalize_get", "(", "rack_req", ",", "s_req", ")", "when", "'DELETE'", "normalize_delete", "(", "rack_req", ",", "s_req", ")", "when", "'POST'", "normalize_post", "(", "rack_req", ",", "s_req", ")", "when", "'OPTIONS'", "nomalize_options", "(", "rack_req", ",", "s_req", ")", "else", "return", "false", "end", "if", "s_req", ".", "type", ".", "nil?", "return", "false", "end", "return", "s_req", "end" ]
This method takes a rack request and generates a normalized RackFakeS3 request
[ "This", "method", "takes", "a", "rack", "request", "and", "generates", "a", "normalized", "RackFakeS3", "request" ]
d230c40579496acd8eccd62363c43b7329f6f27d
https://github.com/envato/rack_fake_s3/blob/d230c40579496acd8eccd62363c43b7329f6f27d/lib/rack_fake_s3/server.rb#L356-L391
2,025
koraktor/metior
lib/metior/report.rb
Metior.Report.generate
def generate(target_dir, with_assets = true) target_dir = File.expand_path target_dir copy_assets target_dir if with_assets render.each do |view_name, output| file_name = File.join target_dir, view_name.to_s.downcase + '.html' begin output_file = File.open file_name, 'wb' output_file.write output ensure output_file.close end end end
ruby
def generate(target_dir, with_assets = true) target_dir = File.expand_path target_dir copy_assets target_dir if with_assets render.each do |view_name, output| file_name = File.join target_dir, view_name.to_s.downcase + '.html' begin output_file = File.open file_name, 'wb' output_file.write output ensure output_file.close end end end
[ "def", "generate", "(", "target_dir", ",", "with_assets", "=", "true", ")", "target_dir", "=", "File", ".", "expand_path", "target_dir", "copy_assets", "target_dir", "if", "with_assets", "render", ".", "each", "do", "|", "view_name", ",", "output", "|", "file_name", "=", "File", ".", "join", "target_dir", ",", "view_name", ".", "to_s", ".", "downcase", "+", "'.html'", "begin", "output_file", "=", "File", ".", "open", "file_name", ",", "'wb'", "output_file", ".", "write", "output", "ensure", "output_file", ".", "close", "end", "end", "end" ]
Creates a new report for the given repository and commit range @param [Repository] repository The repository to analyze @param [String, Range] range The commit range to analyze Generates this report's output into the given target directory This will generate individual HTML files for the main views of the report. @param [String] target_dir The target directory of the report @param [Boolean] with_assets If `false` the report's assets will not be copied to the target directory
[ "Creates", "a", "new", "report", "for", "the", "given", "repository", "and", "commit", "range" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/report.rb#L163-L176
2,026
koraktor/metior
lib/metior/report.rb
Metior.Report.copy_assets
def copy_assets(target_dir) FileUtils.mkdir_p target_dir self.class.assets.map do |asset| asset_path = self.class.find asset asset_dir = File.join target_dir, File.dirname(asset) FileUtils.mkdir_p asset_dir unless File.exists? asset_dir FileUtils.cp_r asset_path, asset_dir end end
ruby
def copy_assets(target_dir) FileUtils.mkdir_p target_dir self.class.assets.map do |asset| asset_path = self.class.find asset asset_dir = File.join target_dir, File.dirname(asset) FileUtils.mkdir_p asset_dir unless File.exists? asset_dir FileUtils.cp_r asset_path, asset_dir end end
[ "def", "copy_assets", "(", "target_dir", ")", "FileUtils", ".", "mkdir_p", "target_dir", "self", ".", "class", ".", "assets", ".", "map", "do", "|", "asset", "|", "asset_path", "=", "self", ".", "class", ".", "find", "asset", "asset_dir", "=", "File", ".", "join", "target_dir", ",", "File", ".", "dirname", "(", "asset", ")", "FileUtils", ".", "mkdir_p", "asset_dir", "unless", "File", ".", "exists?", "asset_dir", "FileUtils", ".", "cp_r", "asset_path", ",", "asset_dir", "end", "end" ]
Copies the assets coming with this report to the given target directory This will copy the files and directories that have been specified for the report from the report's path (or the report's ancestors) into the target directory. @param [String] target_dir The target directory of the report @see .assets
[ "Copies", "the", "assets", "coming", "with", "this", "report", "to", "the", "given", "target", "directory" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/report.rb#L221-L230
2,027
koraktor/metior
lib/metior/repository.rb
Metior.Repository.actor
def actor(actor) id = self.class::Actor.id_for(actor) @actors[id] ||= self.class::Actor.new(self, actor) end
ruby
def actor(actor) id = self.class::Actor.id_for(actor) @actors[id] ||= self.class::Actor.new(self, actor) end
[ "def", "actor", "(", "actor", ")", "id", "=", "self", ".", "class", "::", "Actor", ".", "id_for", "(", "actor", ")", "@actors", "[", "id", "]", "||=", "self", ".", "class", "::", "Actor", ".", "new", "(", "self", ",", "actor", ")", "end" ]
Creates a new repository instance with the given file system path @param [String] path The file system path of the repository Returns a single VCS specific actor object from the raw data of the actor provided by the VCS implementation The actor object is either created from the given raw data or retrieved from the cache using the VCS specific unique identifier of the actor. @param [Object] actor The raw data of the actor provided by the VCS @return [Actor] A object representing the actor @see Actor.id_for
[ "Creates", "a", "new", "repository", "instance", "with", "the", "given", "file", "system", "path" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/repository.rb#L44-L47
2,028
koraktor/metior
lib/metior/repository.rb
Metior.Repository.commits
def commits(range = current_branch) range = parse_range range commits = cached_commits range if commits.empty? base_commit, raw_commits = load_commits(range) commits = build_commits raw_commits unless base_commit.nil? base_commit = self.class::Commit.new(self, base_commit) base_commit.add_child commits.last.id @commits[base_commit.id] = base_commit end else if range.first == '' unless commits.last.parents.empty? raw_commits = load_commits(''..commits.last.id).last commits += build_commits raw_commits[0..-2] end else if commits.first.id != range.last raw_commits = load_commits(commits.first.id..range.last).last commits = build_commits(raw_commits) + commits end unless commits.last.parents.include? range.first raw_commits = load_commits(range.first..commits.last.id).last commits += build_commits raw_commits end end end CommitCollection.new commits, range end
ruby
def commits(range = current_branch) range = parse_range range commits = cached_commits range if commits.empty? base_commit, raw_commits = load_commits(range) commits = build_commits raw_commits unless base_commit.nil? base_commit = self.class::Commit.new(self, base_commit) base_commit.add_child commits.last.id @commits[base_commit.id] = base_commit end else if range.first == '' unless commits.last.parents.empty? raw_commits = load_commits(''..commits.last.id).last commits += build_commits raw_commits[0..-2] end else if commits.first.id != range.last raw_commits = load_commits(commits.first.id..range.last).last commits = build_commits(raw_commits) + commits end unless commits.last.parents.include? range.first raw_commits = load_commits(range.first..commits.last.id).last commits += build_commits raw_commits end end end CommitCollection.new commits, range end
[ "def", "commits", "(", "range", "=", "current_branch", ")", "range", "=", "parse_range", "range", "commits", "=", "cached_commits", "range", "if", "commits", ".", "empty?", "base_commit", ",", "raw_commits", "=", "load_commits", "(", "range", ")", "commits", "=", "build_commits", "raw_commits", "unless", "base_commit", ".", "nil?", "base_commit", "=", "self", ".", "class", "::", "Commit", ".", "new", "(", "self", ",", "base_commit", ")", "base_commit", ".", "add_child", "commits", ".", "last", ".", "id", "@commits", "[", "base_commit", ".", "id", "]", "=", "base_commit", "end", "else", "if", "range", ".", "first", "==", "''", "unless", "commits", ".", "last", ".", "parents", ".", "empty?", "raw_commits", "=", "load_commits", "(", "''", "..", "commits", ".", "last", ".", "id", ")", ".", "last", "commits", "+=", "build_commits", "raw_commits", "[", "0", "..", "-", "2", "]", "end", "else", "if", "commits", ".", "first", ".", "id", "!=", "range", ".", "last", "raw_commits", "=", "load_commits", "(", "commits", ".", "first", ".", "id", "..", "range", ".", "last", ")", ".", "last", "commits", "=", "build_commits", "(", "raw_commits", ")", "+", "commits", "end", "unless", "commits", ".", "last", ".", "parents", ".", "include?", "range", ".", "first", "raw_commits", "=", "load_commits", "(", "range", ".", "first", "..", "commits", ".", "last", ".", "id", ")", ".", "last", "commits", "+=", "build_commits", "raw_commits", "end", "end", "end", "CommitCollection", ".", "new", "commits", ",", "range", "end" ]
Loads all commits including their committers and authors from the given commit range @param [String, Range] range The range of commits for which the commits should be retrieved. This may be given as a string (`'master..development'`), a range (`'master'..'development'`) or as a single ref (`'master'`). A single ref name means all commits reachable from that ref. @return [CommitCollection] All commits from the given commit range
[ "Loads", "all", "commits", "including", "their", "committers", "and", "authors", "from", "the", "given", "commit", "range" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/repository.rb#L83-L114
2,029
koraktor/metior
lib/metior/repository.rb
Metior.Repository.file_stats
def file_stats(range = current_branch) support! :file_stats stats = {} commits(range).each_value do |commit| commit.added_files.each do |file| stats[file] = { :modifications => 0 } unless stats.key? file stats[file][:added_date] = commit.authored_date stats[file][:modifications] += 1 end commit.modified_files.each do |file| stats[file] = { :modifications => 0 } unless stats.key? file stats[file][:last_modified_date] = commit.authored_date stats[file][:modifications] += 1 end commit.deleted_files.each do |file| stats[file] = { :modifications => 0 } unless stats.key? file stats[file][:deleted_date] = commit.authored_date end end stats end
ruby
def file_stats(range = current_branch) support! :file_stats stats = {} commits(range).each_value do |commit| commit.added_files.each do |file| stats[file] = { :modifications => 0 } unless stats.key? file stats[file][:added_date] = commit.authored_date stats[file][:modifications] += 1 end commit.modified_files.each do |file| stats[file] = { :modifications => 0 } unless stats.key? file stats[file][:last_modified_date] = commit.authored_date stats[file][:modifications] += 1 end commit.deleted_files.each do |file| stats[file] = { :modifications => 0 } unless stats.key? file stats[file][:deleted_date] = commit.authored_date end end stats end
[ "def", "file_stats", "(", "range", "=", "current_branch", ")", "support!", ":file_stats", "stats", "=", "{", "}", "commits", "(", "range", ")", ".", "each_value", "do", "|", "commit", "|", "commit", ".", "added_files", ".", "each", "do", "|", "file", "|", "stats", "[", "file", "]", "=", "{", ":modifications", "=>", "0", "}", "unless", "stats", ".", "key?", "file", "stats", "[", "file", "]", "[", ":added_date", "]", "=", "commit", ".", "authored_date", "stats", "[", "file", "]", "[", ":modifications", "]", "+=", "1", "end", "commit", ".", "modified_files", ".", "each", "do", "|", "file", "|", "stats", "[", "file", "]", "=", "{", ":modifications", "=>", "0", "}", "unless", "stats", ".", "key?", "file", "stats", "[", "file", "]", "[", ":last_modified_date", "]", "=", "commit", ".", "authored_date", "stats", "[", "file", "]", "[", ":modifications", "]", "+=", "1", "end", "commit", ".", "deleted_files", ".", "each", "do", "|", "file", "|", "stats", "[", "file", "]", "=", "{", ":modifications", "=>", "0", "}", "unless", "stats", ".", "key?", "file", "stats", "[", "file", "]", "[", ":deleted_date", "]", "=", "commit", ".", "authored_date", "end", "end", "stats", "end" ]
This evaluates basic statistics about the files in a given commit range. @example repo.file_stats => { 'a_file.rb' => { :added_date => Tue Mar 29 16:13:47 +0200 2011, :deleted_date => Sun Jun 05 12:56:18 +0200 2011, :last_modified_date => Thu Apr 21 20:08:00 +0200 2011, :modifications => 9 } } @param [String, Range] range The range of commits for which the file stats should be retrieved. This may be given as a string (`'master..development'`), a range (`'master'..'development'`) or as a single ref (`'master'`). A single ref name means all commits reachable from that ref. @return [Hash<String, Hash<Symbol, Object>>] Each file is returned as a key in this hash. The value of this key is another hash containing the stats for this file. Depending on the state of the file this includes `:added_date`, `:last_modified_date`, `:last_modified_date` and `'master..development'`. @see Commit#added_files @see Commit#deleted_files @see Commit#modified_files
[ "This", "evaluates", "basic", "statistics", "about", "the", "files", "in", "a", "given", "commit", "range", "." ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/repository.rb#L179-L201
2,030
koraktor/metior
lib/metior/repository.rb
Metior.Repository.build_commits
def build_commits(raw_commits) child_commit_id = nil raw_commits.map do |commit| commit = self.class::Commit.new(self, commit) commit.add_child child_commit_id unless child_commit_id.nil? child_commit_id = commit.id @commits[commit.id] = commit commit end end
ruby
def build_commits(raw_commits) child_commit_id = nil raw_commits.map do |commit| commit = self.class::Commit.new(self, commit) commit.add_child child_commit_id unless child_commit_id.nil? child_commit_id = commit.id @commits[commit.id] = commit commit end end
[ "def", "build_commits", "(", "raw_commits", ")", "child_commit_id", "=", "nil", "raw_commits", ".", "map", "do", "|", "commit", "|", "commit", "=", "self", ".", "class", "::", "Commit", ".", "new", "(", "self", ",", "commit", ")", "commit", ".", "add_child", "child_commit_id", "unless", "child_commit_id", ".", "nil?", "child_commit_id", "=", "commit", ".", "id", "@commits", "[", "commit", ".", "id", "]", "=", "commit", "commit", "end", "end" ]
Builds VCS specific commit objects for each given commit's raw data that is provided by the VCS implementation The raw data will be transformed into commit objects that will also be saved into the commit cache. Authors and committers of the given commits will be created and stored into the cache or loaded from the cache if they already exist. Additionally this method will establish an association between the commits and their children. @param [Array<Object>] raw_commits The commits' raw data provided by the VCS implementation @return [Array<Commit>] The commit objects representing the given commits @see Commit @see Commit#add_child
[ "Builds", "VCS", "specific", "commit", "objects", "for", "each", "given", "commit", "s", "raw", "data", "that", "is", "provided", "by", "the", "VCS", "implementation" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/repository.rb#L344-L353
2,031
koraktor/metior
lib/metior/repository.rb
Metior.Repository.cached_commits
def cached_commits(range) commits = [] direction = nil if @commits.key? range.last current_commits = [@commits[range.last]] direction = :parents elsif @commits.key? range.first current_commits = [@commits[range.first]] direction = :children end unless direction.nil? while !current_commits.empty? do new_commits = [] current_commits.each do |commit| new_commits += commit.send direction commits << commit if commit.id != range.first if direction == :parents && new_commits.include?(range.first) new_commits = [] break end end unless new_commits.include? range.first current_commits = new_commits.uniq.map do |commit| commit = @commits[commit] commits.include?(commit) ? nil : commit end.compact end end end commits.sort_by { |c| c.committed_date }.reverse end
ruby
def cached_commits(range) commits = [] direction = nil if @commits.key? range.last current_commits = [@commits[range.last]] direction = :parents elsif @commits.key? range.first current_commits = [@commits[range.first]] direction = :children end unless direction.nil? while !current_commits.empty? do new_commits = [] current_commits.each do |commit| new_commits += commit.send direction commits << commit if commit.id != range.first if direction == :parents && new_commits.include?(range.first) new_commits = [] break end end unless new_commits.include? range.first current_commits = new_commits.uniq.map do |commit| commit = @commits[commit] commits.include?(commit) ? nil : commit end.compact end end end commits.sort_by { |c| c.committed_date }.reverse end
[ "def", "cached_commits", "(", "range", ")", "commits", "=", "[", "]", "direction", "=", "nil", "if", "@commits", ".", "key?", "range", ".", "last", "current_commits", "=", "[", "@commits", "[", "range", ".", "last", "]", "]", "direction", "=", ":parents", "elsif", "@commits", ".", "key?", "range", ".", "first", "current_commits", "=", "[", "@commits", "[", "range", ".", "first", "]", "]", "direction", "=", ":children", "end", "unless", "direction", ".", "nil?", "while", "!", "current_commits", ".", "empty?", "do", "new_commits", "=", "[", "]", "current_commits", ".", "each", "do", "|", "commit", "|", "new_commits", "+=", "commit", ".", "send", "direction", "commits", "<<", "commit", "if", "commit", ".", "id", "!=", "range", ".", "first", "if", "direction", "==", ":parents", "&&", "new_commits", ".", "include?", "(", "range", ".", "first", ")", "new_commits", "=", "[", "]", "break", "end", "end", "unless", "new_commits", ".", "include?", "range", ".", "first", "current_commits", "=", "new_commits", ".", "uniq", ".", "map", "do", "|", "commit", "|", "commit", "=", "@commits", "[", "commit", "]", "commits", ".", "include?", "(", "commit", ")", "?", "nil", ":", "commit", "end", ".", "compact", "end", "end", "end", "commits", ".", "sort_by", "{", "|", "c", "|", "c", ".", "committed_date", "}", ".", "reverse", "end" ]
Tries to retrieve as many commits as possible in the given commit range from the commit cache This method calls itself recursively to walk the given commit range either from the start to the end or vice versa depending on which commit could be found in the cache. @param [Range] range The range of commits which should be retrieved from the cache. This may be given a range of commit IDs (`'master'..'development'`). @return [Array<Commit>] A list of commit objects that could be retrieved from the cache @see Commit#children
[ "Tries", "to", "retrieve", "as", "many", "commits", "as", "possible", "in", "the", "given", "commit", "range", "from", "the", "commit", "cache" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/repository.rb#L368-L401
2,032
koraktor/metior
lib/metior/repository.rb
Metior.Repository.parse_range
def parse_range(range) unless range.is_a? Range range = range.to_s.split '..' range = ((range.size == 1) ? '' : range.first)..range.last end range = id_for_ref(range.first)..range.last if range.first != '' range.first..id_for_ref(range.last) end
ruby
def parse_range(range) unless range.is_a? Range range = range.to_s.split '..' range = ((range.size == 1) ? '' : range.first)..range.last end range = id_for_ref(range.first)..range.last if range.first != '' range.first..id_for_ref(range.last) end
[ "def", "parse_range", "(", "range", ")", "unless", "range", ".", "is_a?", "Range", "range", "=", "range", ".", "to_s", ".", "split", "'..'", "range", "=", "(", "(", "range", ".", "size", "==", "1", ")", "?", "''", ":", "range", ".", "first", ")", "..", "range", ".", "last", "end", "range", "=", "id_for_ref", "(", "range", ".", "first", ")", "..", "range", ".", "last", "if", "range", ".", "first", "!=", "''", "range", ".", "first", "..", "id_for_ref", "(", "range", ".", "last", ")", "end" ]
Parses a string or range of commit IDs or ref names into the coresponding range of unique commit IDs @param [String, Range] range The string that should be parsed for a range or an existing range @return [Range] The range of commit IDs parsed from the given parameter @see #id_for_ref
[ "Parses", "a", "string", "or", "range", "of", "commit", "IDs", "or", "ref", "names", "into", "the", "coresponding", "range", "of", "unique", "commit", "IDs" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/repository.rb#L457-L465
2,033
koraktor/metior
lib/metior/adapter.rb
Metior::Adapter.ClassMethods.register_for
def register_for(vcs) vcs = Metior.find_vcs vcs vcs.register_adapter id, self class_variable_set :@@vcs, vcs end
ruby
def register_for(vcs) vcs = Metior.find_vcs vcs vcs.register_adapter id, self class_variable_set :@@vcs, vcs end
[ "def", "register_for", "(", "vcs", ")", "vcs", "=", "Metior", ".", "find_vcs", "vcs", "vcs", ".", "register_adapter", "id", ",", "self", "class_variable_set", ":@@vcs", ",", "vcs", "end" ]
Registers this adapter with a VCS @param [Symbol] vcs_name The name of the VCS to register this adapter with
[ "Registers", "this", "adapter", "with", "a", "VCS" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter.rb#L56-L60
2,034
jrochkind/bento_search
app/models/bento_search/openurl_creator.rb
BentoSearch.OpenurlCreator.ensure_no_tags
def ensure_no_tags(str) return str unless str.html_safe? str = str.to_str # get it out of HTMLSafeBuffer, which messes things up str = strip_tags(str) str = HTMLEntities.new.decode(str) return str end
ruby
def ensure_no_tags(str) return str unless str.html_safe? str = str.to_str # get it out of HTMLSafeBuffer, which messes things up str = strip_tags(str) str = HTMLEntities.new.decode(str) return str end
[ "def", "ensure_no_tags", "(", "str", ")", "return", "str", "unless", "str", ".", "html_safe?", "str", "=", "str", ".", "to_str", "# get it out of HTMLSafeBuffer, which messes things up", "str", "=", "strip_tags", "(", "str", ")", "str", "=", "HTMLEntities", ".", "new", ".", "decode", "(", "str", ")", "return", "str", "end" ]
If the input is not marked html_safe?, just return it. Otherwise strip html tags from it AND replace HTML char entities
[ "If", "the", "input", "is", "not", "marked", "html_safe?", "just", "return", "it", ".", "Otherwise", "strip", "html", "tags", "from", "it", "AND", "replace", "HTML", "char", "entities" ]
f567ead386d4a2e283c03b787e7c0d620567c9de
https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/models/bento_search/openurl_creator.rb#L156-L165
2,035
pcorliss/ruby_route_53
lib/route53/dns_record.rb
Route53.DNSRecord.update
def update(name,type,ttl,values,comment=nil, zone_apex = nil) prev = self.clone @name = name unless name.nil? @type = type unless type.nil? @ttl = ttl unless ttl.nil? @values = values unless values.nil? @zone_apex = zone_apex unless zone_apex.nil? @zone.perform_actions([ {:action => "DELETE", :record => prev}, {:action => "CREATE", :record => self}, ],comment) end
ruby
def update(name,type,ttl,values,comment=nil, zone_apex = nil) prev = self.clone @name = name unless name.nil? @type = type unless type.nil? @ttl = ttl unless ttl.nil? @values = values unless values.nil? @zone_apex = zone_apex unless zone_apex.nil? @zone.perform_actions([ {:action => "DELETE", :record => prev}, {:action => "CREATE", :record => self}, ],comment) end
[ "def", "update", "(", "name", ",", "type", ",", "ttl", ",", "values", ",", "comment", "=", "nil", ",", "zone_apex", "=", "nil", ")", "prev", "=", "self", ".", "clone", "@name", "=", "name", "unless", "name", ".", "nil?", "@type", "=", "type", "unless", "type", ".", "nil?", "@ttl", "=", "ttl", "unless", "ttl", ".", "nil?", "@values", "=", "values", "unless", "values", ".", "nil?", "@zone_apex", "=", "zone_apex", "unless", "zone_apex", ".", "nil?", "@zone", ".", "perform_actions", "(", "[", "{", ":action", "=>", "\"DELETE\"", ",", ":record", "=>", "prev", "}", ",", "{", ":action", "=>", "\"CREATE\"", ",", ":record", "=>", "self", "}", ",", "]", ",", "comment", ")", "end" ]
Need to modify to a param hash
[ "Need", "to", "modify", "to", "a", "param", "hash" ]
f96fab52931f069ba4b5fddb291aa53c7412aa52
https://github.com/pcorliss/ruby_route_53/blob/f96fab52931f069ba4b5fddb291aa53c7412aa52/lib/route53/dns_record.rb#L66-L77
2,036
pcorliss/ruby_route_53
lib/route53/dns_record.rb
Route53.DNSRecord.update_dirty
def update_dirty(name,type,ttl,values,zone_apex = nil) prev = self.clone @name = name unless name.nil? @type = type unless type.nil? @ttl = ttl unless ttl.nil? @values = values unless values.nil? @zone_apex = zone_apex unless zone_apex.nil? return [{:action => "DELETE", :record => prev}, {:action => "CREATE", :record => self}] end
ruby
def update_dirty(name,type,ttl,values,zone_apex = nil) prev = self.clone @name = name unless name.nil? @type = type unless type.nil? @ttl = ttl unless ttl.nil? @values = values unless values.nil? @zone_apex = zone_apex unless zone_apex.nil? return [{:action => "DELETE", :record => prev}, {:action => "CREATE", :record => self}] end
[ "def", "update_dirty", "(", "name", ",", "type", ",", "ttl", ",", "values", ",", "zone_apex", "=", "nil", ")", "prev", "=", "self", ".", "clone", "@name", "=", "name", "unless", "name", ".", "nil?", "@type", "=", "type", "unless", "type", ".", "nil?", "@ttl", "=", "ttl", "unless", "ttl", ".", "nil?", "@values", "=", "values", "unless", "values", ".", "nil?", "@zone_apex", "=", "zone_apex", "unless", "zone_apex", ".", "nil?", "return", "[", "{", ":action", "=>", "\"DELETE\"", ",", ":record", "=>", "prev", "}", ",", "{", ":action", "=>", "\"CREATE\"", ",", ":record", "=>", "self", "}", "]", "end" ]
Returns the raw array so the developer can update large batches manually Need to modify to a param hash
[ "Returns", "the", "raw", "array", "so", "the", "developer", "can", "update", "large", "batches", "manually", "Need", "to", "modify", "to", "a", "param", "hash" ]
f96fab52931f069ba4b5fddb291aa53c7412aa52
https://github.com/pcorliss/ruby_route_53/blob/f96fab52931f069ba4b5fddb291aa53c7412aa52/lib/route53/dns_record.rb#L81-L90
2,037
koraktor/metior
lib/metior/collections/actor_collection.rb
Metior.ActorCollection.most_significant
def most_significant(count = 3) support! :line_stats authors = ActorCollection.new sort_by { |author| -author.modifications }.each do |author| authors << author break if authors.size == count end authors end
ruby
def most_significant(count = 3) support! :line_stats authors = ActorCollection.new sort_by { |author| -author.modifications }.each do |author| authors << author break if authors.size == count end authors end
[ "def", "most_significant", "(", "count", "=", "3", ")", "support!", ":line_stats", "authors", "=", "ActorCollection", ".", "new", "sort_by", "{", "|", "author", "|", "-", "author", ".", "modifications", "}", ".", "each", "do", "|", "author", "|", "authors", "<<", "author", "break", "if", "authors", ".", "size", "==", "count", "end", "authors", "end" ]
Returns up to the given number of actors in this collection with the biggest impact on the repository, i.e. changing the most code @param [Numeric] count The number of actors to return @return [ActorCollection] The given number of actors ordered by impact @see Actor#modifications
[ "Returns", "up", "to", "the", "given", "number", "of", "actors", "in", "this", "collection", "with", "the", "biggest", "impact", "on", "the", "repository", "i", ".", "e", ".", "changing", "the", "most", "code" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/actor_collection.rb#L47-L56
2,038
koraktor/metior
lib/metior/collections/actor_collection.rb
Metior.ActorCollection.top
def top(count = 3) authors = ActorCollection.new sort_by { |author| -author.authored_commits.size }.each do |author| authors << author break if authors.size == count end authors end
ruby
def top(count = 3) authors = ActorCollection.new sort_by { |author| -author.authored_commits.size }.each do |author| authors << author break if authors.size == count end authors end
[ "def", "top", "(", "count", "=", "3", ")", "authors", "=", "ActorCollection", ".", "new", "sort_by", "{", "|", "author", "|", "-", "author", ".", "authored_commits", ".", "size", "}", ".", "each", "do", "|", "author", "|", "authors", "<<", "author", "break", "if", "authors", ".", "size", "==", "count", "end", "authors", "end" ]
Returns up to the given number of actors in this collection with the most commits @param [Numeric] count The number of actors to return @return [ActorCollection] The given number of actors ordered by commit count @see Actor#commits
[ "Returns", "up", "to", "the", "given", "number", "of", "actors", "in", "this", "collection", "with", "the", "most", "commits" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/actor_collection.rb#L65-L72
2,039
koraktor/metior
lib/metior/collections/actor_collection.rb
Metior.ActorCollection.load_commits
def load_commits(commit_type, actor_id = nil) commits = CommitCollection.new if actor_id.nil? each { |actor| commits.merge! actor.send(commit_type) } elsif key? actor_id commits = self[actor_id].send commit_type end commits end
ruby
def load_commits(commit_type, actor_id = nil) commits = CommitCollection.new if actor_id.nil? each { |actor| commits.merge! actor.send(commit_type) } elsif key? actor_id commits = self[actor_id].send commit_type end commits end
[ "def", "load_commits", "(", "commit_type", ",", "actor_id", "=", "nil", ")", "commits", "=", "CommitCollection", ".", "new", "if", "actor_id", ".", "nil?", "each", "{", "|", "actor", "|", "commits", ".", "merge!", "actor", ".", "send", "(", "commit_type", ")", "}", "elsif", "key?", "actor_id", "commits", "=", "self", "[", "actor_id", "]", ".", "send", "commit_type", "end", "commits", "end" ]
Loads the commits authored or committed by all actors in this collection or a specific actor @param [:authored_commits, :committed_commits] commit_type The type of commits to load @param [Object] actor_id The ID of the actor, if only the commits of a specific actor should be returned @return [CommitCollection] All commits authored or committed by the actors in this collection or by a specific actor
[ "Loads", "the", "commits", "authored", "or", "committed", "by", "all", "actors", "in", "this", "collection", "or", "a", "specific", "actor" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/actor_collection.rb#L85-L93
2,040
koraktor/metior
lib/metior/adapter/octokit/repository.rb
Metior::Adapter::Octokit.Repository.load_commits
def load_commits(range) base_commit = nil commits = [] last_commit = nil loop do new_commits = ::Octokit.commits(@path, nil, :last_sha => last_commit, :per_page => 100, :top => range.last) break if new_commits.empty? base_commit_index = new_commits.find_index do |commit| commit.sha == range.first end unless range.first == '' unless base_commit_index.nil? if base_commit_index > 0 commits += new_commits[0..base_commit_index-1] end base_commit = new_commits[base_commit_index] break end commits += new_commits last_commit = new_commits.last.sha end [base_commit, commits] end
ruby
def load_commits(range) base_commit = nil commits = [] last_commit = nil loop do new_commits = ::Octokit.commits(@path, nil, :last_sha => last_commit, :per_page => 100, :top => range.last) break if new_commits.empty? base_commit_index = new_commits.find_index do |commit| commit.sha == range.first end unless range.first == '' unless base_commit_index.nil? if base_commit_index > 0 commits += new_commits[0..base_commit_index-1] end base_commit = new_commits[base_commit_index] break end commits += new_commits last_commit = new_commits.last.sha end [base_commit, commits] end
[ "def", "load_commits", "(", "range", ")", "base_commit", "=", "nil", "commits", "=", "[", "]", "last_commit", "=", "nil", "loop", "do", "new_commits", "=", "::", "Octokit", ".", "commits", "(", "@path", ",", "nil", ",", ":last_sha", "=>", "last_commit", ",", ":per_page", "=>", "100", ",", ":top", "=>", "range", ".", "last", ")", "break", "if", "new_commits", ".", "empty?", "base_commit_index", "=", "new_commits", ".", "find_index", "do", "|", "commit", "|", "commit", ".", "sha", "==", "range", ".", "first", "end", "unless", "range", ".", "first", "==", "''", "unless", "base_commit_index", ".", "nil?", "if", "base_commit_index", ">", "0", "commits", "+=", "new_commits", "[", "0", "..", "base_commit_index", "-", "1", "]", "end", "base_commit", "=", "new_commits", "[", "base_commit_index", "]", "break", "end", "commits", "+=", "new_commits", "last_commit", "=", "new_commits", ".", "last", ".", "sha", "end", "[", "base_commit", ",", "commits", "]", "end" ]
This method uses Octokit to load all commits from the given commit range @note GitHub API is currently limited to 60 calls a minute, so you won't be able to query branches with more than 2100 commits (35 commits per call). @param [String, Range] range The range of commits for which the commits should be loaded. This may be given as a string (`'master..development'`), a range (`'master'..'development'`) or as a single ref (`'master'`). A single ref name means all commits reachable from that ref. @return [Hashie::Mash, nil] The base commit of the requested range or `nil` if the the range starts at the beginning of the history @return [Array<Hashie::Mash>] All commits in the given commit range @see Octokit::Commits#commits
[ "This", "method", "uses", "Octokit", "to", "load", "all", "commits", "from", "the", "given", "commit", "range" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter/octokit/repository.rb#L85-L108
2,041
danieldreier/autosign
lib/autosign/validator.rb
Autosign.Validator.validate
def validate(challenge_password, certname, raw_csr) @log.debug "running validate" fail unless challenge_password.is_a?(String) fail unless certname.is_a?(String) case perform_validation(challenge_password, certname, raw_csr) when true @log.debug "validated successfully" @log.info "Validated '#{certname}' using '#{name}' validator" return true when false @log.debug "validation failed" @log.debug "Unable to validate '#{certname}' using '#{name}' validator" return false else @log.error "perform_validation returned a non-boolean result" raise "perform_validation returned a non-boolean result" end end
ruby
def validate(challenge_password, certname, raw_csr) @log.debug "running validate" fail unless challenge_password.is_a?(String) fail unless certname.is_a?(String) case perform_validation(challenge_password, certname, raw_csr) when true @log.debug "validated successfully" @log.info "Validated '#{certname}' using '#{name}' validator" return true when false @log.debug "validation failed" @log.debug "Unable to validate '#{certname}' using '#{name}' validator" return false else @log.error "perform_validation returned a non-boolean result" raise "perform_validation returned a non-boolean result" end end
[ "def", "validate", "(", "challenge_password", ",", "certname", ",", "raw_csr", ")", "@log", ".", "debug", "\"running validate\"", "fail", "unless", "challenge_password", ".", "is_a?", "(", "String", ")", "fail", "unless", "certname", ".", "is_a?", "(", "String", ")", "case", "perform_validation", "(", "challenge_password", ",", "certname", ",", "raw_csr", ")", "when", "true", "@log", ".", "debug", "\"validated successfully\"", "@log", ".", "info", "\"Validated '#{certname}' using '#{name}' validator\"", "return", "true", "when", "false", "@log", ".", "debug", "\"validation failed\"", "@log", ".", "debug", "\"Unable to validate '#{certname}' using '#{name}' validator\"", "return", "false", "else", "@log", ".", "error", "\"perform_validation returned a non-boolean result\"", "raise", "\"perform_validation returned a non-boolean result\"", "end", "end" ]
wrapper method that wraps input validation and logging around the perform_validation method. Do not override or use this class in child classes. This is the class that gets called on validator objects.
[ "wrapper", "method", "that", "wraps", "input", "validation", "and", "logging", "around", "the", "perform_validation", "method", ".", "Do", "not", "override", "or", "use", "this", "class", "in", "child", "classes", ".", "This", "is", "the", "class", "that", "gets", "called", "on", "validator", "objects", "." ]
d457eeec5b2084ff63ee4555f7de97cf87be1aca
https://github.com/danieldreier/autosign/blob/d457eeec5b2084ff63ee4555f7de97cf87be1aca/lib/autosign/validator.rb#L68-L86
2,042
danieldreier/autosign
lib/autosign/validator.rb
Autosign.Validator.settings
def settings @log.debug "merging settings" setting_sources = [get_override_settings, load_config, default_settings] merged_settings = setting_sources.inject({}) { |merged, hash| merged.deep_merge(hash) } @log.debug "using merged settings: " + merged_settings.to_s @log.debug "validating merged settings" if validate_settings(merged_settings) @log.debug "successfully validated merged settings" return merged_settings else @log.warn "validation of merged settings failed" @log.warn "unable to validate settings in #{self.name} validator" raise "settings validation error" end end
ruby
def settings @log.debug "merging settings" setting_sources = [get_override_settings, load_config, default_settings] merged_settings = setting_sources.inject({}) { |merged, hash| merged.deep_merge(hash) } @log.debug "using merged settings: " + merged_settings.to_s @log.debug "validating merged settings" if validate_settings(merged_settings) @log.debug "successfully validated merged settings" return merged_settings else @log.warn "validation of merged settings failed" @log.warn "unable to validate settings in #{self.name} validator" raise "settings validation error" end end
[ "def", "settings", "@log", ".", "debug", "\"merging settings\"", "setting_sources", "=", "[", "get_override_settings", ",", "load_config", ",", "default_settings", "]", "merged_settings", "=", "setting_sources", ".", "inject", "(", "{", "}", ")", "{", "|", "merged", ",", "hash", "|", "merged", ".", "deep_merge", "(", "hash", ")", "}", "@log", ".", "debug", "\"using merged settings: \"", "+", "merged_settings", ".", "to_s", "@log", ".", "debug", "\"validating merged settings\"", "if", "validate_settings", "(", "merged_settings", ")", "@log", ".", "debug", "\"successfully validated merged settings\"", "return", "merged_settings", "else", "@log", ".", "warn", "\"validation of merged settings failed\"", "@log", ".", "warn", "\"unable to validate settings in #{self.name} validator\"", "raise", "\"settings validation error\"", "end", "end" ]
provide a merged settings hash of default settings for a validator, config file settings for the validator, and override settings defined in the validator. Do not override this in child classes. If you need to set custom config settings, override the get_override_settings method. The section of the config file this reads from is the same as the name method returns. @return [Hash] of config settings
[ "provide", "a", "merged", "settings", "hash", "of", "default", "settings", "for", "a", "validator", "config", "file", "settings", "for", "the", "validator", "and", "override", "settings", "defined", "in", "the", "validator", "." ]
d457eeec5b2084ff63ee4555f7de97cf87be1aca
https://github.com/danieldreier/autosign/blob/d457eeec5b2084ff63ee4555f7de97cf87be1aca/lib/autosign/validator.rb#L153-L167
2,043
danieldreier/autosign
lib/autosign/validator.rb
Autosign.Validator.load_config
def load_config @log.debug "loading validator-specific configuration" config = Autosign::Config.new if config.settings.to_hash[self.name].nil? @log.warn "Unable to load validator-specific configuration" @log.warn "Cannot load configuration section named '#{self.name}'" return {} else @log.debug "Set validator-specific settings from config file: " + config.settings.to_hash[self.name].to_s return config.settings.to_hash[self.name] end end
ruby
def load_config @log.debug "loading validator-specific configuration" config = Autosign::Config.new if config.settings.to_hash[self.name].nil? @log.warn "Unable to load validator-specific configuration" @log.warn "Cannot load configuration section named '#{self.name}'" return {} else @log.debug "Set validator-specific settings from config file: " + config.settings.to_hash[self.name].to_s return config.settings.to_hash[self.name] end end
[ "def", "load_config", "@log", ".", "debug", "\"loading validator-specific configuration\"", "config", "=", "Autosign", "::", "Config", ".", "new", "if", "config", ".", "settings", ".", "to_hash", "[", "self", ".", "name", "]", ".", "nil?", "@log", ".", "warn", "\"Unable to load validator-specific configuration\"", "@log", ".", "warn", "\"Cannot load configuration section named '#{self.name}'\"", "return", "{", "}", "else", "@log", ".", "debug", "\"Set validator-specific settings from config file: \"", "+", "config", ".", "settings", ".", "to_hash", "[", "self", ".", "name", "]", ".", "to_s", "return", "config", ".", "settings", ".", "to_hash", "[", "self", ".", "name", "]", "end", "end" ]
load any required configuration from the config file. Do not override this in child classes. @return [Hash] configuration settings from the validator's section of the config file
[ "load", "any", "required", "configuration", "from", "the", "config", "file", ".", "Do", "not", "override", "this", "in", "child", "classes", "." ]
d457eeec5b2084ff63ee4555f7de97cf87be1aca
https://github.com/danieldreier/autosign/blob/d457eeec5b2084ff63ee4555f7de97cf87be1aca/lib/autosign/validator.rb#L193-L205
2,044
jrochkind/bento_search
app/models/bento_search/search_engine.rb
BentoSearch.SearchEngine.fill_in_search_metadata_for
def fill_in_search_metadata_for(results, normalized_arguments = {}) results.search_args = normalized_arguments results.start = normalized_arguments[:start] || 0 results.per_page = normalized_arguments[:per_page] results.engine_id = configuration.id results.display_configuration = configuration.for_display # We copy some configuraton info over to each Item, as a convenience # to display logic that may have decide what to do given only an item, # and may want to parameterize based on configuration. results.each do |item| item.engine_id = configuration.id item.decorator = configuration.lookup!("for_display.decorator") item.display_configuration = configuration.for_display end results end
ruby
def fill_in_search_metadata_for(results, normalized_arguments = {}) results.search_args = normalized_arguments results.start = normalized_arguments[:start] || 0 results.per_page = normalized_arguments[:per_page] results.engine_id = configuration.id results.display_configuration = configuration.for_display # We copy some configuraton info over to each Item, as a convenience # to display logic that may have decide what to do given only an item, # and may want to parameterize based on configuration. results.each do |item| item.engine_id = configuration.id item.decorator = configuration.lookup!("for_display.decorator") item.display_configuration = configuration.for_display end results end
[ "def", "fill_in_search_metadata_for", "(", "results", ",", "normalized_arguments", "=", "{", "}", ")", "results", ".", "search_args", "=", "normalized_arguments", "results", ".", "start", "=", "normalized_arguments", "[", ":start", "]", "||", "0", "results", ".", "per_page", "=", "normalized_arguments", "[", ":per_page", "]", "results", ".", "engine_id", "=", "configuration", ".", "id", "results", ".", "display_configuration", "=", "configuration", ".", "for_display", "# We copy some configuraton info over to each Item, as a convenience", "# to display logic that may have decide what to do given only an item,", "# and may want to parameterize based on configuration.", "results", ".", "each", "do", "|", "item", "|", "item", ".", "engine_id", "=", "configuration", ".", "id", "item", ".", "decorator", "=", "configuration", ".", "lookup!", "(", "\"for_display.decorator\"", ")", "item", ".", "display_configuration", "=", "configuration", ".", "for_display", "end", "results", "end" ]
SOME of the elements of Results to be returned that SearchEngine implementation fills in automatically post-search. Extracted into a method for DRY in error handling to try to fill these in even in errors. Also can be used as public method for de-serialized or mock results.
[ "SOME", "of", "the", "elements", "of", "Results", "to", "be", "returned", "that", "SearchEngine", "implementation", "fills", "in", "automatically", "post", "-", "search", ".", "Extracted", "into", "a", "method", "for", "DRY", "in", "error", "handling", "to", "try", "to", "fill", "these", "in", "even", "in", "errors", ".", "Also", "can", "be", "used", "as", "public", "method", "for", "de", "-", "serialized", "or", "mock", "results", "." ]
f567ead386d4a2e283c03b787e7c0d620567c9de
https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/models/bento_search/search_engine.rb#L300-L318
2,045
healthfinch/allscripts-unity-client
lib/allscripts_unity_client/json_unity_request.rb
AllscriptsUnityClient.JSONUnityRequest.to_hash
def to_hash action = @parameters[:action] userid = @parameters[:userid] appname = @parameters[:appname] || @appname patientid = @parameters[:patientid] token = @parameters[:token] || @security_token parameter1 = process_date(@parameters[:parameter1]) || '' parameter2 = process_date(@parameters[:parameter2]) || '' parameter3 = process_date(@parameters[:parameter3]) || '' parameter4 = process_date(@parameters[:parameter4]) || '' parameter5 = process_date(@parameters[:parameter5]) || '' parameter6 = process_date(@parameters[:parameter6]) || '' data = Utilities::encode_data(@parameters[:data]) || '' { 'Action' => action, 'AppUserID' => userid, 'Appname' => appname, 'PatientID' => patientid, 'Token' => token, 'Parameter1' => parameter1, 'Parameter2' => parameter2, 'Parameter3' => parameter3, 'Parameter4' => parameter4, 'Parameter5' => parameter5, 'Parameter6' => parameter6, 'Data' => data } end
ruby
def to_hash action = @parameters[:action] userid = @parameters[:userid] appname = @parameters[:appname] || @appname patientid = @parameters[:patientid] token = @parameters[:token] || @security_token parameter1 = process_date(@parameters[:parameter1]) || '' parameter2 = process_date(@parameters[:parameter2]) || '' parameter3 = process_date(@parameters[:parameter3]) || '' parameter4 = process_date(@parameters[:parameter4]) || '' parameter5 = process_date(@parameters[:parameter5]) || '' parameter6 = process_date(@parameters[:parameter6]) || '' data = Utilities::encode_data(@parameters[:data]) || '' { 'Action' => action, 'AppUserID' => userid, 'Appname' => appname, 'PatientID' => patientid, 'Token' => token, 'Parameter1' => parameter1, 'Parameter2' => parameter2, 'Parameter3' => parameter3, 'Parameter4' => parameter4, 'Parameter5' => parameter5, 'Parameter6' => parameter6, 'Data' => data } end
[ "def", "to_hash", "action", "=", "@parameters", "[", ":action", "]", "userid", "=", "@parameters", "[", ":userid", "]", "appname", "=", "@parameters", "[", ":appname", "]", "||", "@appname", "patientid", "=", "@parameters", "[", ":patientid", "]", "token", "=", "@parameters", "[", ":token", "]", "||", "@security_token", "parameter1", "=", "process_date", "(", "@parameters", "[", ":parameter1", "]", ")", "||", "''", "parameter2", "=", "process_date", "(", "@parameters", "[", ":parameter2", "]", ")", "||", "''", "parameter3", "=", "process_date", "(", "@parameters", "[", ":parameter3", "]", ")", "||", "''", "parameter4", "=", "process_date", "(", "@parameters", "[", ":parameter4", "]", ")", "||", "''", "parameter5", "=", "process_date", "(", "@parameters", "[", ":parameter5", "]", ")", "||", "''", "parameter6", "=", "process_date", "(", "@parameters", "[", ":parameter6", "]", ")", "||", "''", "data", "=", "Utilities", "::", "encode_data", "(", "@parameters", "[", ":data", "]", ")", "||", "''", "{", "'Action'", "=>", "action", ",", "'AppUserID'", "=>", "userid", ",", "'Appname'", "=>", "appname", ",", "'PatientID'", "=>", "patientid", ",", "'Token'", "=>", "token", ",", "'Parameter1'", "=>", "parameter1", ",", "'Parameter2'", "=>", "parameter2", ",", "'Parameter3'", "=>", "parameter3", ",", "'Parameter4'", "=>", "parameter4", ",", "'Parameter5'", "=>", "parameter5", ",", "'Parameter6'", "=>", "parameter6", ",", "'Data'", "=>", "data", "}", "end" ]
Convert the parameters to a Hash for Faraday with all possible dates converted to the Organization's localtime.
[ "Convert", "the", "parameters", "to", "a", "Hash", "for", "Faraday", "with", "all", "possible", "dates", "converted", "to", "the", "Organization", "s", "localtime", "." ]
fd9b7148cb6fe806a3f9dba70c138ba8c5e75985
https://github.com/healthfinch/allscripts-unity-client/blob/fd9b7148cb6fe806a3f9dba70c138ba8c5e75985/lib/allscripts_unity_client/json_unity_request.rb#L8-L36
2,046
healthfinch/allscripts-unity-client
lib/allscripts_unity_client/client.rb
AllscriptsUnityClient.Client.get_encounter_list
def get_encounter_list( userid, patientid, encounter_type = nil, when_param = nil, nostradamus = 0, show_past_flag = true, billing_provider_user_name = nil, show_all = false) magic_parameters = { action: 'GetEncounterList', userid: userid, patientid: patientid, parameter1: encounter_type, parameter2: when_param, parameter3: nostradamus, parameter4: unity_boolean_parameter(show_past_flag), parameter5: billing_provider_user_name, # According to the developer guide this parameter is no longer # used. parameter6: show_all ? 'all' : nil } response = magic(magic_parameters) unless response.is_a?(Array) response = [ response ] end # Remove nil encounters response.delete_if do |value| value[:id] == '0' && value[:patientid] == '0' end end
ruby
def get_encounter_list( userid, patientid, encounter_type = nil, when_param = nil, nostradamus = 0, show_past_flag = true, billing_provider_user_name = nil, show_all = false) magic_parameters = { action: 'GetEncounterList', userid: userid, patientid: patientid, parameter1: encounter_type, parameter2: when_param, parameter3: nostradamus, parameter4: unity_boolean_parameter(show_past_flag), parameter5: billing_provider_user_name, # According to the developer guide this parameter is no longer # used. parameter6: show_all ? 'all' : nil } response = magic(magic_parameters) unless response.is_a?(Array) response = [ response ] end # Remove nil encounters response.delete_if do |value| value[:id] == '0' && value[:patientid] == '0' end end
[ "def", "get_encounter_list", "(", "userid", ",", "patientid", ",", "encounter_type", "=", "nil", ",", "when_param", "=", "nil", ",", "nostradamus", "=", "0", ",", "show_past_flag", "=", "true", ",", "billing_provider_user_name", "=", "nil", ",", "show_all", "=", "false", ")", "magic_parameters", "=", "{", "action", ":", "'GetEncounterList'", ",", "userid", ":", "userid", ",", "patientid", ":", "patientid", ",", "parameter1", ":", "encounter_type", ",", "parameter2", ":", "when_param", ",", "parameter3", ":", "nostradamus", ",", "parameter4", ":", "unity_boolean_parameter", "(", "show_past_flag", ")", ",", "parameter5", ":", "billing_provider_user_name", ",", "# According to the developer guide this parameter is no longer", "# used.", "parameter6", ":", "show_all", "?", "'all'", ":", "nil", "}", "response", "=", "magic", "(", "magic_parameters", ")", "unless", "response", ".", "is_a?", "(", "Array", ")", "response", "=", "[", "response", "]", "end", "# Remove nil encounters", "response", ".", "delete_if", "do", "|", "value", "|", "value", "[", ":id", "]", "==", "'0'", "&&", "value", "[", ":patientid", "]", "==", "'0'", "end", "end" ]
GetEncounterList helper method. @param [Object] userid @param [Object] patientid @param [String, nil] encounter_type encounter type to filter on. A value of `nil` filters nothing. Defaults to `nil`. @param [Object] when_param @param [Fixnum, nil] nostradamus how many days to look into the future. Defaults to `0`. @param [Object] show_past_flag whether to show previous encounters. All truthy values aside from the string `"N"` are considered to be true (or `"Y"`) all other values are considered to be false (or `"N"`). Defaults to `true`. @param [Object] billing_provider_user_name filter by user name. Defaults to `nil`. @param [Object] show_all @return [Array<Hash>] the filtered encounter list.
[ "GetEncounterList", "helper", "method", "." ]
fd9b7148cb6fe806a3f9dba70c138ba8c5e75985
https://github.com/healthfinch/allscripts-unity-client/blob/fd9b7148cb6fe806a3f9dba70c138ba8c5e75985/lib/allscripts_unity_client/client.rb#L233-L266
2,047
healthfinch/allscripts-unity-client
lib/allscripts_unity_client/client.rb
AllscriptsUnityClient.Client.get_task_list
def get_task_list(userid = nil, since = nil, delegated = nil, task_types = nil, task_statuses = nil) magic_parameters = { action: 'GetTaskList', userid: userid, parameter1: since, parameter2: task_types, parameter3: task_statuses, parameter4: delegated } response = magic(magic_parameters) unless response.is_a?(Array) response = [ response ] end response end
ruby
def get_task_list(userid = nil, since = nil, delegated = nil, task_types = nil, task_statuses = nil) magic_parameters = { action: 'GetTaskList', userid: userid, parameter1: since, parameter2: task_types, parameter3: task_statuses, parameter4: delegated } response = magic(magic_parameters) unless response.is_a?(Array) response = [ response ] end response end
[ "def", "get_task_list", "(", "userid", "=", "nil", ",", "since", "=", "nil", ",", "delegated", "=", "nil", ",", "task_types", "=", "nil", ",", "task_statuses", "=", "nil", ")", "magic_parameters", "=", "{", "action", ":", "'GetTaskList'", ",", "userid", ":", "userid", ",", "parameter1", ":", "since", ",", "parameter2", ":", "task_types", ",", "parameter3", ":", "task_statuses", ",", "parameter4", ":", "delegated", "}", "response", "=", "magic", "(", "magic_parameters", ")", "unless", "response", ".", "is_a?", "(", "Array", ")", "response", "=", "[", "response", "]", "end", "response", "end" ]
delegated is an undocumented parameter
[ "delegated", "is", "an", "undocumented", "parameter" ]
fd9b7148cb6fe806a3f9dba70c138ba8c5e75985
https://github.com/healthfinch/allscripts-unity-client/blob/fd9b7148cb6fe806a3f9dba70c138ba8c5e75985/lib/allscripts_unity_client/client.rb#L536-L552
2,048
pcorliss/ruby_route_53
lib/route53/zone.rb
Route53.Zone.perform_actions
def perform_actions(change_list,comment=nil) xml_str = gen_change_xml(change_list,comment) @conn.request(@conn.base_url + @host_url+"/rrset","POST",xml_str) end
ruby
def perform_actions(change_list,comment=nil) xml_str = gen_change_xml(change_list,comment) @conn.request(@conn.base_url + @host_url+"/rrset","POST",xml_str) end
[ "def", "perform_actions", "(", "change_list", ",", "comment", "=", "nil", ")", "xml_str", "=", "gen_change_xml", "(", "change_list", ",", "comment", ")", "@conn", ".", "request", "(", "@conn", ".", "base_url", "+", "@host_url", "+", "\"/rrset\"", ",", "\"POST\"", ",", "xml_str", ")", "end" ]
For modifying multiple or single records within a single transaction
[ "For", "modifying", "multiple", "or", "single", "records", "within", "a", "single", "transaction" ]
f96fab52931f069ba4b5fddb291aa53c7412aa52
https://github.com/pcorliss/ruby_route_53/blob/f96fab52931f069ba4b5fddb291aa53c7412aa52/lib/route53/zone.rb#L124-L127
2,049
pcorliss/ruby_route_53
lib/route53/cli.rb
Route53.CLI.process_options
def process_options @options.verbose = false if @options.quiet @options.file = (user_home+"/.route53") if @options.file.nil? #setup file if @options.setup setup end load_config @config['access_key'] = @options.access unless @options.access.nil? @config['secret_key'] = @options.secret unless @options.secret.nil? required_options("",["--access-key"]) if @config['access_key'].nil? || @config['access_key'] == "" required_options("",["--secret_key"]) if @config['secret_key'].nil? || @config['secret_key'] == "" end
ruby
def process_options @options.verbose = false if @options.quiet @options.file = (user_home+"/.route53") if @options.file.nil? #setup file if @options.setup setup end load_config @config['access_key'] = @options.access unless @options.access.nil? @config['secret_key'] = @options.secret unless @options.secret.nil? required_options("",["--access-key"]) if @config['access_key'].nil? || @config['access_key'] == "" required_options("",["--secret_key"]) if @config['secret_key'].nil? || @config['secret_key'] == "" end
[ "def", "process_options", "@options", ".", "verbose", "=", "false", "if", "@options", ".", "quiet", "@options", ".", "file", "=", "(", "user_home", "+", "\"/.route53\"", ")", "if", "@options", ".", "file", ".", "nil?", "#setup file", "if", "@options", ".", "setup", "setup", "end", "load_config", "@config", "[", "'access_key'", "]", "=", "@options", ".", "access", "unless", "@options", ".", "access", ".", "nil?", "@config", "[", "'secret_key'", "]", "=", "@options", ".", "secret", "unless", "@options", ".", "secret", ".", "nil?", "required_options", "(", "\"\"", ",", "[", "\"--access-key\"", "]", ")", "if", "@config", "[", "'access_key'", "]", ".", "nil?", "||", "@config", "[", "'access_key'", "]", "==", "\"\"", "required_options", "(", "\"\"", ",", "[", "\"--secret_key\"", "]", ")", "if", "@config", "[", "'secret_key'", "]", ".", "nil?", "||", "@config", "[", "'secret_key'", "]", "==", "\"\"", "end" ]
Performs post-parse processing on options
[ "Performs", "post", "-", "parse", "processing", "on", "options" ]
f96fab52931f069ba4b5fddb291aa53c7412aa52
https://github.com/pcorliss/ruby_route_53/blob/f96fab52931f069ba4b5fddb291aa53c7412aa52/lib/route53/cli.rb#L92-L107
2,050
pcorliss/ruby_route_53
lib/route53/cli.rb
Route53.CLI.process_arguments
def process_arguments if @options.new_zone new_zone elsif @options.delete_zone delete_zone elsif @options.create_record create_record elsif @options.remove_record remove_record elsif @options.change_record change_record else list end end
ruby
def process_arguments if @options.new_zone new_zone elsif @options.delete_zone delete_zone elsif @options.create_record create_record elsif @options.remove_record remove_record elsif @options.change_record change_record else list end end
[ "def", "process_arguments", "if", "@options", ".", "new_zone", "new_zone", "elsif", "@options", ".", "delete_zone", "delete_zone", "elsif", "@options", ".", "create_record", "create_record", "elsif", "@options", ".", "remove_record", "remove_record", "elsif", "@options", ".", "change_record", "change_record", "else", "list", "end", "end" ]
Setup the arguments
[ "Setup", "the", "arguments" ]
f96fab52931f069ba4b5fddb291aa53c7412aa52
https://github.com/pcorliss/ruby_route_53/blob/f96fab52931f069ba4b5fddb291aa53c7412aa52/lib/route53/cli.rb#L128-L142
2,051
mongoid/mongoid-cached-json
lib/mongoid-cached-json/cached_json.rb
Mongoid.CachedJson.as_json_partial
def as_json_partial(options = {}) options ||= {} if options[:properties] && !all_json_properties.member?(options[:properties]) fail ArgumentError.new("Unknown properties option: #{options[:properties]}") end # partial, unmaterialized JSON keys, partial_json = self.class.materialize_json({ properties: :short, is_top_level_json: true, version: Mongoid::CachedJson.config.default_version }.merge(options), object: self) [keys, partial_json] end
ruby
def as_json_partial(options = {}) options ||= {} if options[:properties] && !all_json_properties.member?(options[:properties]) fail ArgumentError.new("Unknown properties option: #{options[:properties]}") end # partial, unmaterialized JSON keys, partial_json = self.class.materialize_json({ properties: :short, is_top_level_json: true, version: Mongoid::CachedJson.config.default_version }.merge(options), object: self) [keys, partial_json] end
[ "def", "as_json_partial", "(", "options", "=", "{", "}", ")", "options", "||=", "{", "}", "if", "options", "[", ":properties", "]", "&&", "!", "all_json_properties", ".", "member?", "(", "options", "[", ":properties", "]", ")", "fail", "ArgumentError", ".", "new", "(", "\"Unknown properties option: #{options[:properties]}\"", ")", "end", "# partial, unmaterialized JSON", "keys", ",", "partial_json", "=", "self", ".", "class", ".", "materialize_json", "(", "{", "properties", ":", ":short", ",", "is_top_level_json", ":", "true", ",", "version", ":", "Mongoid", "::", "CachedJson", ".", "config", ".", "default_version", "}", ".", "merge", "(", "options", ")", ",", "object", ":", "self", ")", "[", "keys", ",", "partial_json", "]", "end" ]
Return a partial JSON without resolved references and all the keys.
[ "Return", "a", "partial", "JSON", "without", "resolved", "references", "and", "all", "the", "keys", "." ]
d430e313d4259b13c4d75ed1782caad1609b5250
https://github.com/mongoid/mongoid-cached-json/blob/d430e313d4259b13c4d75ed1782caad1609b5250/lib/mongoid-cached-json/cached_json.rb#L200-L210
2,052
mongoid/mongoid-cached-json
lib/mongoid-cached-json/cached_json.rb
Mongoid.CachedJson.as_json_cached
def as_json_cached(options = {}) keys, json = as_json_partial(options) Mongoid::CachedJson.materialize_json_references_with_read_multi(keys, json) end
ruby
def as_json_cached(options = {}) keys, json = as_json_partial(options) Mongoid::CachedJson.materialize_json_references_with_read_multi(keys, json) end
[ "def", "as_json_cached", "(", "options", "=", "{", "}", ")", "keys", ",", "json", "=", "as_json_partial", "(", "options", ")", "Mongoid", "::", "CachedJson", ".", "materialize_json_references_with_read_multi", "(", "keys", ",", "json", ")", "end" ]
Fetch the partial JSON and materialize all JSON references.
[ "Fetch", "the", "partial", "JSON", "and", "materialize", "all", "JSON", "references", "." ]
d430e313d4259b13c4d75ed1782caad1609b5250
https://github.com/mongoid/mongoid-cached-json/blob/d430e313d4259b13c4d75ed1782caad1609b5250/lib/mongoid-cached-json/cached_json.rb#L213-L216
2,053
mongoid/mongoid-cached-json
lib/mongoid-cached-json/cached_json.rb
Mongoid.CachedJson.expire_cached_json
def expire_cached_json all_json_properties.each do |properties| [true, false].each do |is_top_level_json| all_json_versions.each do |version| Mongoid::CachedJson.config.cache.delete(self.class.cached_json_key({ properties: properties, is_top_level_json: is_top_level_json, version: version }, self.class, id)) end end end end
ruby
def expire_cached_json all_json_properties.each do |properties| [true, false].each do |is_top_level_json| all_json_versions.each do |version| Mongoid::CachedJson.config.cache.delete(self.class.cached_json_key({ properties: properties, is_top_level_json: is_top_level_json, version: version }, self.class, id)) end end end end
[ "def", "expire_cached_json", "all_json_properties", ".", "each", "do", "|", "properties", "|", "[", "true", ",", "false", "]", ".", "each", "do", "|", "is_top_level_json", "|", "all_json_versions", ".", "each", "do", "|", "version", "|", "Mongoid", "::", "CachedJson", ".", "config", ".", "cache", ".", "delete", "(", "self", ".", "class", ".", "cached_json_key", "(", "{", "properties", ":", "properties", ",", "is_top_level_json", ":", "is_top_level_json", ",", "version", ":", "version", "}", ",", "self", ".", "class", ",", "id", ")", ")", "end", "end", "end", "end" ]
Expire all JSON entries for this class.
[ "Expire", "all", "JSON", "entries", "for", "this", "class", "." ]
d430e313d4259b13c4d75ed1782caad1609b5250
https://github.com/mongoid/mongoid-cached-json/blob/d430e313d4259b13c4d75ed1782caad1609b5250/lib/mongoid-cached-json/cached_json.rb#L224-L236
2,054
danieldreier/autosign
lib/autosign/journal.rb
Autosign.Journal.setup
def setup @log.debug "using journalfile: " + self.settings['journalfile'] journalfile = self.settings['journalfile'] store = YAML::Store.new(journalfile, true) store.ultra_safe = true return store end
ruby
def setup @log.debug "using journalfile: " + self.settings['journalfile'] journalfile = self.settings['journalfile'] store = YAML::Store.new(journalfile, true) store.ultra_safe = true return store end
[ "def", "setup", "@log", ".", "debug", "\"using journalfile: \"", "+", "self", ".", "settings", "[", "'journalfile'", "]", "journalfile", "=", "self", ".", "settings", "[", "'journalfile'", "]", "store", "=", "YAML", "::", "Store", ".", "new", "(", "journalfile", ",", "true", ")", "store", ".", "ultra_safe", "=", "true", "return", "store", "end" ]
Create a new journal file, or load an existing one if it already exists. @return [YAML::Store] instance of YAML::Store using the configured journal file.
[ "Create", "a", "new", "journal", "file", "or", "load", "an", "existing", "one", "if", "it", "already", "exists", "." ]
d457eeec5b2084ff63ee4555f7de97cf87be1aca
https://github.com/danieldreier/autosign/blob/d457eeec5b2084ff63ee4555f7de97cf87be1aca/lib/autosign/journal.rb#L65-L71
2,055
danieldreier/autosign
lib/autosign/journal.rb
Autosign.Journal.validate_uuid
def validate_uuid(uuid) unless uuid.is_a?(String) @log.error "UUID is not a string" return false end unless !!/^\S{8}-\S{4}-4\S{3}-[89abAB]\S{3}-\S{12}$/.match(uuid.to_s) @log.error "UUID is not a valid V4 UUID" return false end return true end
ruby
def validate_uuid(uuid) unless uuid.is_a?(String) @log.error "UUID is not a string" return false end unless !!/^\S{8}-\S{4}-4\S{3}-[89abAB]\S{3}-\S{12}$/.match(uuid.to_s) @log.error "UUID is not a valid V4 UUID" return false end return true end
[ "def", "validate_uuid", "(", "uuid", ")", "unless", "uuid", ".", "is_a?", "(", "String", ")", "@log", ".", "error", "\"UUID is not a string\"", "return", "false", "end", "unless", "!", "!", "/", "\\S", "\\S", "\\S", "\\S", "\\S", "/", ".", "match", "(", "uuid", ".", "to_s", ")", "@log", ".", "error", "\"UUID is not a valid V4 UUID\"", "return", "false", "end", "return", "true", "end" ]
Verify that a string is a V4 UUID @param uuid [String] RFC4122 v4 UUID @return [Boolean] true if the uuid string is a valid UUID, false if not a valid UUID
[ "Verify", "that", "a", "string", "is", "a", "V4", "UUID" ]
d457eeec5b2084ff63ee4555f7de97cf87be1aca
https://github.com/danieldreier/autosign/blob/d457eeec5b2084ff63ee4555f7de97cf87be1aca/lib/autosign/journal.rb#L77-L88
2,056
koraktor/metior
lib/metior/collections/commit_collection.rb
Metior.CommitCollection.<<
def <<(commit) return self if key? commit.id if @additions.nil? && empty? && commit.line_stats? @additions = commit.additions @deletions = commit.deletions elsif [email protected]? @additions += commit.additions @deletions += commit.deletions end super end
ruby
def <<(commit) return self if key? commit.id if @additions.nil? && empty? && commit.line_stats? @additions = commit.additions @deletions = commit.deletions elsif [email protected]? @additions += commit.additions @deletions += commit.deletions end super end
[ "def", "<<", "(", "commit", ")", "return", "self", "if", "key?", "commit", ".", "id", "if", "@additions", ".", "nil?", "&&", "empty?", "&&", "commit", ".", "line_stats?", "@additions", "=", "commit", ".", "additions", "@deletions", "=", "commit", ".", "deletions", "elsif", "!", "@additions", ".", "nil?", "@additions", "+=", "commit", ".", "additions", "@deletions", "+=", "commit", ".", "deletions", "end", "super", "end" ]
Creates a new collection with the given commits @param [Array<Commit>] commits The commits that should be initially inserted into the collection Adds a commit to this collection @param [Commit] commit The commit to add to this collection @return [CommitCollection] The collection itself
[ "Creates", "a", "new", "collection", "with", "the", "given", "commits" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L47-L59
2,057
koraktor/metior
lib/metior/collections/commit_collection.rb
Metior.CommitCollection.activity
def activity activity = {} return activity if empty? commit_count = values.size active_days = {} each do |commit| date = commit.committed_date.utc day = Time.utc(date.year, date.month, date.day).send :to_date if active_days.key? day active_days[day] += 1 else active_days[day] = 1 end end most_active_day = active_days.sort_by { |day, count| count }.last.first activity[:first_commit_date] = last.committed_date activity[:last_commit_date] = first.committed_date age_in_days = (Time.now - activity[:first_commit_date]) / 86400.0 activity[:active_days] = active_days activity[:most_active_day] = most_active_day activity[:commits_per_day] = commit_count / age_in_days activity[:commits_per_active_day] = commit_count.to_f / active_days.size activity end
ruby
def activity activity = {} return activity if empty? commit_count = values.size active_days = {} each do |commit| date = commit.committed_date.utc day = Time.utc(date.year, date.month, date.day).send :to_date if active_days.key? day active_days[day] += 1 else active_days[day] = 1 end end most_active_day = active_days.sort_by { |day, count| count }.last.first activity[:first_commit_date] = last.committed_date activity[:last_commit_date] = first.committed_date age_in_days = (Time.now - activity[:first_commit_date]) / 86400.0 activity[:active_days] = active_days activity[:most_active_day] = most_active_day activity[:commits_per_day] = commit_count / age_in_days activity[:commits_per_active_day] = commit_count.to_f / active_days.size activity end
[ "def", "activity", "activity", "=", "{", "}", "return", "activity", "if", "empty?", "commit_count", "=", "values", ".", "size", "active_days", "=", "{", "}", "each", "do", "|", "commit", "|", "date", "=", "commit", ".", "committed_date", ".", "utc", "day", "=", "Time", ".", "utc", "(", "date", ".", "year", ",", "date", ".", "month", ",", "date", ".", "day", ")", ".", "send", ":to_date", "if", "active_days", ".", "key?", "day", "active_days", "[", "day", "]", "+=", "1", "else", "active_days", "[", "day", "]", "=", "1", "end", "end", "most_active_day", "=", "active_days", ".", "sort_by", "{", "|", "day", ",", "count", "|", "count", "}", ".", "last", ".", "first", "activity", "[", ":first_commit_date", "]", "=", "last", ".", "committed_date", "activity", "[", ":last_commit_date", "]", "=", "first", ".", "committed_date", "age_in_days", "=", "(", "Time", ".", "now", "-", "activity", "[", ":first_commit_date", "]", ")", "/", "86400.0", "activity", "[", ":active_days", "]", "=", "active_days", "activity", "[", ":most_active_day", "]", "=", "most_active_day", "activity", "[", ":commits_per_day", "]", "=", "commit_count", "/", "age_in_days", "activity", "[", ":commits_per_active_day", "]", "=", "commit_count", ".", "to_f", "/", "active_days", ".", "size", "activity", "end" ]
Calculate some predefined activity statistics for the commits in this collection @return [Hash<Symbol, Object>] The calculated statistics for the commits in this collection @see Commit#committed_date
[ "Calculate", "some", "predefined", "activity", "statistics", "for", "the", "commits", "in", "this", "collection" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L67-L97
2,058
koraktor/metior
lib/metior/collections/commit_collection.rb
Metior.CommitCollection.authors
def authors(commit_id = nil) authors = ActorCollection.new if commit_id.nil? each { |commit| authors << commit.author } elsif key? commit_id authors << self[commit_id].author end authors end
ruby
def authors(commit_id = nil) authors = ActorCollection.new if commit_id.nil? each { |commit| authors << commit.author } elsif key? commit_id authors << self[commit_id].author end authors end
[ "def", "authors", "(", "commit_id", "=", "nil", ")", "authors", "=", "ActorCollection", ".", "new", "if", "commit_id", ".", "nil?", "each", "{", "|", "commit", "|", "authors", "<<", "commit", ".", "author", "}", "elsif", "key?", "commit_id", "authors", "<<", "self", "[", "commit_id", "]", ".", "author", "end", "authors", "end" ]
Returns the authors of all or a specific commit in this collection @param [Object] commit_id The ID of the commit, if only the author of a specific commit should be returned @return [ActorCollection] All authors of the commits in this collection or the author of a specific commit @see Commit#author
[ "Returns", "the", "authors", "of", "all", "or", "a", "specific", "commit", "in", "this", "collection" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L139-L147
2,059
koraktor/metior
lib/metior/collections/commit_collection.rb
Metior.CommitCollection.before
def before(date) date = Time.parse date if date.is_a? String commits = CommitCollection.new each do |commit| commits << commit if commit.committed_date < date end commits end
ruby
def before(date) date = Time.parse date if date.is_a? String commits = CommitCollection.new each do |commit| commits << commit if commit.committed_date < date end commits end
[ "def", "before", "(", "date", ")", "date", "=", "Time", ".", "parse", "date", "if", "date", ".", "is_a?", "String", "commits", "=", "CommitCollection", ".", "new", "each", "do", "|", "commit", "|", "commits", "<<", "commit", "if", "commit", ".", "committed_date", "<", "date", "end", "commits", "end" ]
Returns the commits in this collection that have been committed before the given time @param [Time, Date, DateTime, String] date The time to use as the upper limit to filter the commits @return [CommitCollection] The commits that have been committed after the given date @see Commit#committed_date @see Time.parse
[ "Returns", "the", "commits", "in", "this", "collection", "that", "have", "been", "committed", "before", "the", "given", "time" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L158-L165
2,060
koraktor/metior
lib/metior/collections/commit_collection.rb
Metior.CommitCollection.by
def by(*author_ids) author_ids = author_ids.flatten.map do |author_id| author_id.is_a?(Actor) ? author_id.id : author_id end commits = CommitCollection.new each do |commit| commits << commit if author_ids.include? commit.author.id end commits end
ruby
def by(*author_ids) author_ids = author_ids.flatten.map do |author_id| author_id.is_a?(Actor) ? author_id.id : author_id end commits = CommitCollection.new each do |commit| commits << commit if author_ids.include? commit.author.id end commits end
[ "def", "by", "(", "*", "author_ids", ")", "author_ids", "=", "author_ids", ".", "flatten", ".", "map", "do", "|", "author_id", "|", "author_id", ".", "is_a?", "(", "Actor", ")", "?", "author_id", ".", "id", ":", "author_id", "end", "commits", "=", "CommitCollection", ".", "new", "each", "do", "|", "commit", "|", "commits", "<<", "commit", "if", "author_ids", ".", "include?", "commit", ".", "author", ".", "id", "end", "commits", "end" ]
Returns the list of commits that have been authored by the given authors @param [Array<Actor, Object>] author_ids One or more actual `Actor` instances or IDs of the authors that the commits should be filtered by @return [CommitCollection] The commits that have been authored by the given authors @see Commit#author
[ "Returns", "the", "list", "of", "commits", "that", "have", "been", "authored", "by", "the", "given", "authors" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L176-L185
2,061
koraktor/metior
lib/metior/collections/commit_collection.rb
Metior.CommitCollection.changing
def changing(*files) support! :file_stats commits = CommitCollection.new each do |commit| commit_files = commit.added_files + commit.deleted_files + commit.modified_files commits << commit unless (commit_files & files).empty? end commits end
ruby
def changing(*files) support! :file_stats commits = CommitCollection.new each do |commit| commit_files = commit.added_files + commit.deleted_files + commit.modified_files commits << commit unless (commit_files & files).empty? end commits end
[ "def", "changing", "(", "*", "files", ")", "support!", ":file_stats", "commits", "=", "CommitCollection", ".", "new", "each", "do", "|", "commit", "|", "commit_files", "=", "commit", ".", "added_files", "+", "commit", ".", "deleted_files", "+", "commit", ".", "modified_files", "commits", "<<", "commit", "unless", "(", "commit_files", "&", "files", ")", ".", "empty?", "end", "commits", "end" ]
Returns the commits in this collection that change any of the given files @param [Array<String>] files The path of the files to filter commits by @return [CommitCollection] The commits that contain changes to the given files @see Commit#added_files @see Commit#deleted_files @see Commit#modified_files
[ "Returns", "the", "commits", "in", "this", "collection", "that", "change", "any", "of", "the", "given", "files" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L195-L204
2,062
koraktor/metior
lib/metior/collections/commit_collection.rb
Metior.CommitCollection.committers
def committers(commit_id = nil) committers = ActorCollection.new if commit_id.nil? each { |commit| committers << commit.committer } elsif key? commit_id committers << self[commit_id].committer end committers end
ruby
def committers(commit_id = nil) committers = ActorCollection.new if commit_id.nil? each { |commit| committers << commit.committer } elsif key? commit_id committers << self[commit_id].committer end committers end
[ "def", "committers", "(", "commit_id", "=", "nil", ")", "committers", "=", "ActorCollection", ".", "new", "if", "commit_id", ".", "nil?", "each", "{", "|", "commit", "|", "committers", "<<", "commit", ".", "committer", "}", "elsif", "key?", "commit_id", "committers", "<<", "self", "[", "commit_id", "]", ".", "committer", "end", "committers", "end" ]
Returns the committers of all or a specific commit in this collection @param [Object] commit_id The ID of the commit, if only the committer of a specific commit should be returned @return [ActorCollection] All committers of the commits in this collection or the committer of a specific commit @see Commit#committer
[ "Returns", "the", "committers", "of", "all", "or", "a", "specific", "commit", "in", "this", "collection" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L214-L222
2,063
koraktor/metior
lib/metior/collections/commit_collection.rb
Metior.CommitCollection.line_history
def line_history support! :line_stats history = { :additions => [], :deletions => [] } values.reverse.each do |commit| history[:additions] << commit.additions history[:deletions] << -commit.deletions end history end
ruby
def line_history support! :line_stats history = { :additions => [], :deletions => [] } values.reverse.each do |commit| history[:additions] << commit.additions history[:deletions] << -commit.deletions end history end
[ "def", "line_history", "support!", ":line_stats", "history", "=", "{", ":additions", "=>", "[", "]", ",", ":deletions", "=>", "[", "]", "}", "values", ".", "reverse", ".", "each", "do", "|", "commit", "|", "history", "[", ":additions", "]", "<<", "commit", ".", "additions", "history", "[", ":deletions", "]", "<<", "-", "commit", ".", "deletions", "end", "history", "end" ]
This evaluates the changed lines in each commit of this collection For easier use, the values are stored in separate arrays where each number represents the number of changed (i.e. added or deleted) lines in one commit. @example commits.line_history => { :additions => [10, 5, 0], :deletions => [0, -2, -1] } @return [Hash<Symbol, Array>] Added lines are returned in an `Array` assigned to key `:additions`, deleted lines are assigned to `:deletions` @see Commit#additions @see Commit#deletions
[ "This", "evaluates", "the", "changed", "lines", "in", "each", "commit", "of", "this", "collection" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L252-L262
2,064
koraktor/metior
lib/metior/collections/commit_collection.rb
Metior.CommitCollection.most_significant
def most_significant(count = 10) support! :line_stats commits = CommitCollection.new sort_by { |commit| -commit.modifications }.each do |commit| commits << commit break if commits.size == count end commits end
ruby
def most_significant(count = 10) support! :line_stats commits = CommitCollection.new sort_by { |commit| -commit.modifications }.each do |commit| commits << commit break if commits.size == count end commits end
[ "def", "most_significant", "(", "count", "=", "10", ")", "support!", ":line_stats", "commits", "=", "CommitCollection", ".", "new", "sort_by", "{", "|", "commit", "|", "-", "commit", ".", "modifications", "}", ".", "each", "do", "|", "commit", "|", "commits", "<<", "commit", "break", "if", "commits", ".", "size", "==", "count", "end", "commits", "end" ]
Returns the given number of commits with most line changes on the repository @param [Numeric] count The number of commits to return @return [CommitCollection] The given number of commits ordered by impact @see Commit#modifications
[ "Returns", "the", "given", "number", "of", "commits", "with", "most", "line", "changes", "on", "the", "repository" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L279-L288
2,065
koraktor/metior
lib/metior/collections/commit_collection.rb
Metior.CommitCollection.with_impact
def with_impact(line_count) support! :line_stats commits = CommitCollection.new each do |commit| commits << commit if commit.modifications >= line_count end commits end
ruby
def with_impact(line_count) support! :line_stats commits = CommitCollection.new each do |commit| commits << commit if commit.modifications >= line_count end commits end
[ "def", "with_impact", "(", "line_count", ")", "support!", ":line_stats", "commits", "=", "CommitCollection", ".", "new", "each", "do", "|", "commit", "|", "commits", "<<", "commit", "if", "commit", ".", "modifications", ">=", "line_count", "end", "commits", "end" ]
Returns the commits in this collection that change at least the given number of lines @param [Numeric] line_count The number of lines that should be changed at least by the commits @return [CommitCollection] The commits that change at least the given number of lines @see Commit#modifications
[ "Returns", "the", "commits", "in", "this", "collection", "that", "change", "at", "least", "the", "given", "number", "of", "lines" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L299-L307
2,066
koraktor/metior
lib/metior/collections/commit_collection.rb
Metior.CommitCollection.load_line_stats
def load_line_stats @additions = 0 @deletions = 0 return if empty? line_stats = nil if @range.nil? ids = values.reject { |c| c.line_stats? }.map { |c| c.id } line_stats = first.repo.load_line_stats ids unless ids.empty? else line_stats = first.repo.load_line_stats @range end unless line_stats.nil? line_stats.each do |id, stats| commit = self[id] commit.line_stats = stats end end each do |commit| @additions += commit.additions @deletions += commit.deletions end end
ruby
def load_line_stats @additions = 0 @deletions = 0 return if empty? line_stats = nil if @range.nil? ids = values.reject { |c| c.line_stats? }.map { |c| c.id } line_stats = first.repo.load_line_stats ids unless ids.empty? else line_stats = first.repo.load_line_stats @range end unless line_stats.nil? line_stats.each do |id, stats| commit = self[id] commit.line_stats = stats end end each do |commit| @additions += commit.additions @deletions += commit.deletions end end
[ "def", "load_line_stats", "@additions", "=", "0", "@deletions", "=", "0", "return", "if", "empty?", "line_stats", "=", "nil", "if", "@range", ".", "nil?", "ids", "=", "values", ".", "reject", "{", "|", "c", "|", "c", ".", "line_stats?", "}", ".", "map", "{", "|", "c", "|", "c", ".", "id", "}", "line_stats", "=", "first", ".", "repo", ".", "load_line_stats", "ids", "unless", "ids", ".", "empty?", "else", "line_stats", "=", "first", ".", "repo", ".", "load_line_stats", "@range", "end", "unless", "line_stats", ".", "nil?", "line_stats", ".", "each", "do", "|", "id", ",", "stats", "|", "commit", "=", "self", "[", "id", "]", "commit", ".", "line_stats", "=", "stats", "end", "end", "each", "do", "|", "commit", "|", "@additions", "+=", "commit", ".", "additions", "@deletions", "+=", "commit", ".", "deletions", "end", "end" ]
Loads the line stats for the commits in this collection For collections holding a specific range of commits, this always gets the line stats for all commits. For other, lets say fragmented, collections this loads the line stats for all commits that are missing their stats. @see Commit#additions @see Commit#deletions @see Commit#line_stats? @see Repository#line_stats
[ "Loads", "the", "line", "stats", "for", "the", "commits", "in", "this", "collection" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/collections/commit_collection.rb#L321-L345
2,067
koraktor/metior
lib/metior/report/view.rb
Metior::Report.View.render
def render(*args) begin features = self.class.send :class_variable_get, :@@required_features super if features.all? { |feature| repository.supports? feature } rescue Metior::UnsupportedError end end
ruby
def render(*args) begin features = self.class.send :class_variable_get, :@@required_features super if features.all? { |feature| repository.supports? feature } rescue Metior::UnsupportedError end end
[ "def", "render", "(", "*", "args", ")", "begin", "features", "=", "self", ".", "class", ".", "send", ":class_variable_get", ",", ":@@required_features", "super", "if", "features", ".", "all?", "{", "|", "feature", "|", "repository", ".", "supports?", "feature", "}", "rescue", "Metior", "::", "UnsupportedError", "end", "end" ]
This checks if all required VCS features of this view are available for this report's repository @param [Object, ...] args The arguments expected by {Mustache#render} @see .requires @see http://rubydoc.info/gems/mustache/Mustache#render-instance_method Mustache#render
[ "This", "checks", "if", "all", "required", "VCS", "features", "of", "this", "view", "are", "available", "for", "this", "report", "s", "repository" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/report/view.rb#L105-L111
2,068
jrochkind/bento_search
app/controllers/bento_search/search_controller.rb
BentoSearch.SearchController.search
def search engine = BentoSearch.get_engine(params[:engine_id]) # put it in an iVar mainly for testing purposes. @engine = engine unless engine.configuration.allow_routable_results == true raise AccessDenied.new("engine needs to be registered with :allow_routable_results => true") end @results = engine.search safe_search_args(engine, params) # template name of a partial with 'yield' to use to wrap the results @partial_wrapper = @results.display_configuration.lookup!("ajax.wrapper_template") # partial HTML results render "bento_search/search/search", :layout => false end
ruby
def search engine = BentoSearch.get_engine(params[:engine_id]) # put it in an iVar mainly for testing purposes. @engine = engine unless engine.configuration.allow_routable_results == true raise AccessDenied.new("engine needs to be registered with :allow_routable_results => true") end @results = engine.search safe_search_args(engine, params) # template name of a partial with 'yield' to use to wrap the results @partial_wrapper = @results.display_configuration.lookup!("ajax.wrapper_template") # partial HTML results render "bento_search/search/search", :layout => false end
[ "def", "search", "engine", "=", "BentoSearch", ".", "get_engine", "(", "params", "[", ":engine_id", "]", ")", "# put it in an iVar mainly for testing purposes.", "@engine", "=", "engine", "unless", "engine", ".", "configuration", ".", "allow_routable_results", "==", "true", "raise", "AccessDenied", ".", "new", "(", "\"engine needs to be registered with :allow_routable_results => true\"", ")", "end", "@results", "=", "engine", ".", "search", "safe_search_args", "(", "engine", ",", "params", ")", "# template name of a partial with 'yield' to use to wrap the results", "@partial_wrapper", "=", "@results", ".", "display_configuration", ".", "lookup!", "(", "\"ajax.wrapper_template\"", ")", "# partial HTML results", "render", "\"bento_search/search/search\"", ",", ":layout", "=>", "false", "end" ]
returns partial HTML results, suitable for AJAX to insert into DOM. arguments for engine.search are taken from URI request params, whitelisted
[ "returns", "partial", "HTML", "results", "suitable", "for", "AJAX", "to", "insert", "into", "DOM", ".", "arguments", "for", "engine", ".", "search", "are", "taken", "from", "URI", "request", "params", "whitelisted" ]
f567ead386d4a2e283c03b787e7c0d620567c9de
https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/controllers/bento_search/search_controller.rb#L44-L61
2,069
koraktor/metior
lib/metior/adapter/grit/repository.rb
Metior::Adapter::Grit.Repository.current_branch
def current_branch branch = @grit_repo.head return branch.name unless branch.nil? commit = @grit_repo.commit('HEAD') commit.id unless commit.nil? end
ruby
def current_branch branch = @grit_repo.head return branch.name unless branch.nil? commit = @grit_repo.commit('HEAD') commit.id unless commit.nil? end
[ "def", "current_branch", "branch", "=", "@grit_repo", ".", "head", "return", "branch", ".", "name", "unless", "branch", ".", "nil?", "commit", "=", "@grit_repo", ".", "commit", "(", "'HEAD'", ")", "commit", ".", "id", "unless", "commit", ".", "nil?", "end" ]
Creates a new Git repository based on the given path This creates a new `Grit::Repo` instance to interface with the repository. @param [String] path The file system path of the repository Returns the current branch of the repository This is the target ref of Git's HEAD, i.e. the currently checked out branch. For a detached HEAD this may also be the commit ID of the checked out commit. @see Grit::Repo#head
[ "Creates", "a", "new", "Git", "repository", "based", "on", "the", "given", "path" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter/grit/repository.rb#L36-L41
2,070
koraktor/metior
lib/metior/adapter/grit/repository.rb
Metior::Adapter::Grit.Repository.load_line_stats
def load_line_stats(ids) if ids.is_a? Range if ids.first == '' range = ids.last else range = '%s..%s' % [ids.first, ids.last] end options = { :numstat => true, :timeout => false } output = @grit_repo.git.native :log, options, range commit_stats = ::Grit::CommitStats.list_from_string @grit_repo, output else commit_stats = [] ids.each_slice(500) do |id_slice| options = { :numstat => true, :timeout => false } output = @grit_repo.git.native :log, options, *id_slice commit_stats += ::Grit::CommitStats.list_from_string @grit_repo, output end end Hash[commit_stats.map do |stats| [stats.first, [stats.last.additions, stats.last.deletions]] end] end
ruby
def load_line_stats(ids) if ids.is_a? Range if ids.first == '' range = ids.last else range = '%s..%s' % [ids.first, ids.last] end options = { :numstat => true, :timeout => false } output = @grit_repo.git.native :log, options, range commit_stats = ::Grit::CommitStats.list_from_string @grit_repo, output else commit_stats = [] ids.each_slice(500) do |id_slice| options = { :numstat => true, :timeout => false } output = @grit_repo.git.native :log, options, *id_slice commit_stats += ::Grit::CommitStats.list_from_string @grit_repo, output end end Hash[commit_stats.map do |stats| [stats.first, [stats.last.additions, stats.last.deletions]] end] end
[ "def", "load_line_stats", "(", "ids", ")", "if", "ids", ".", "is_a?", "Range", "if", "ids", ".", "first", "==", "''", "range", "=", "ids", ".", "last", "else", "range", "=", "'%s..%s'", "%", "[", "ids", ".", "first", ",", "ids", ".", "last", "]", "end", "options", "=", "{", ":numstat", "=>", "true", ",", ":timeout", "=>", "false", "}", "output", "=", "@grit_repo", ".", "git", ".", "native", ":log", ",", "options", ",", "range", "commit_stats", "=", "::", "Grit", "::", "CommitStats", ".", "list_from_string", "@grit_repo", ",", "output", "else", "commit_stats", "=", "[", "]", "ids", ".", "each_slice", "(", "500", ")", "do", "|", "id_slice", "|", "options", "=", "{", ":numstat", "=>", "true", ",", ":timeout", "=>", "false", "}", "output", "=", "@grit_repo", ".", "git", ".", "native", ":log", ",", "options", ",", "id_slice", "commit_stats", "+=", "::", "Grit", "::", "CommitStats", ".", "list_from_string", "@grit_repo", ",", "output", "end", "end", "Hash", "[", "commit_stats", ".", "map", "do", "|", "stats", "|", "[", "stats", ".", "first", ",", "[", "stats", ".", "last", ".", "additions", ",", "stats", ".", "last", ".", "deletions", "]", "]", "end", "]", "end" ]
Loads the line stats for the commits given by a set of commit IDs @param [Array<String>] ids The IDs of the commits to load line stats for @return [Hash<String, Array<Fixnum>] An array of two number (line additions and deletions) for each of the given commit IDs
[ "Loads", "the", "line", "stats", "for", "the", "commits", "given", "by", "a", "set", "of", "commit", "IDs" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter/grit/repository.rb#L65-L88
2,071
koraktor/metior
lib/metior/adapter/grit/repository.rb
Metior::Adapter::Grit.Repository.load_branches
def load_branches Hash[@grit_repo.branches.map { |b| [b.name, b.commit.id] }] end
ruby
def load_branches Hash[@grit_repo.branches.map { |b| [b.name, b.commit.id] }] end
[ "def", "load_branches", "Hash", "[", "@grit_repo", ".", "branches", ".", "map", "{", "|", "b", "|", "[", "b", ".", "name", ",", "b", ".", "commit", ".", "id", "]", "}", "]", "end" ]
Loads all branches and the corresponding commit IDs of this repository @return [Hash<String, String>] The names of all branches and the corresponding commit IDs @see Grit::Repo#branches
[ "Loads", "all", "branches", "and", "the", "corresponding", "commit", "IDs", "of", "this", "repository" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter/grit/repository.rb#L106-L108
2,072
koraktor/metior
lib/metior/adapter/grit/repository.rb
Metior::Adapter::Grit.Repository.load_commits
def load_commits(range) if range.first == '' base_commit = nil range = range.last else base_commit = @grit_repo.commit(range.first) range = '%s..%s' % [range.first, range.last] end options = { :pretty => 'raw', :timeout => false } output = @grit_repo.git.native :rev_list, options, range commits = ::Grit::Commit.list_from_string @grit_repo, output [base_commit, commits] end
ruby
def load_commits(range) if range.first == '' base_commit = nil range = range.last else base_commit = @grit_repo.commit(range.first) range = '%s..%s' % [range.first, range.last] end options = { :pretty => 'raw', :timeout => false } output = @grit_repo.git.native :rev_list, options, range commits = ::Grit::Commit.list_from_string @grit_repo, output [base_commit, commits] end
[ "def", "load_commits", "(", "range", ")", "if", "range", ".", "first", "==", "''", "base_commit", "=", "nil", "range", "=", "range", ".", "last", "else", "base_commit", "=", "@grit_repo", ".", "commit", "(", "range", ".", "first", ")", "range", "=", "'%s..%s'", "%", "[", "range", ".", "first", ",", "range", ".", "last", "]", "end", "options", "=", "{", ":pretty", "=>", "'raw'", ",", ":timeout", "=>", "false", "}", "output", "=", "@grit_repo", ".", "git", ".", "native", ":rev_list", ",", "options", ",", "range", "commits", "=", "::", "Grit", "::", "Commit", ".", "list_from_string", "@grit_repo", ",", "output", "[", "base_commit", ",", "commits", "]", "end" ]
This method uses Grit to load all commits from the given commit range Because of some Grit internal limitations, the commits have to be loaded in batches of up to 300 commits. @note Grit will choke on huge repositories, like Homebrew or the Linux kernel. You will have to raise the timeout limit using `Grit.git_timeout=`. @param [String, Range] range The range of commits for which the commits should be loaded. This may be given as a string (`'master..development'`), a range (`'master'..'development'`) or as a single ref (`'master'`). A single ref name means all commits reachable from that ref. @return [Grit::Commit, nil] The base commit of the requested range or `nil` if the the range starts at the beginning of the history @return [Array<Grit::Commit>] All commits in the given commit range @see Grit::Repo#commits
[ "This", "method", "uses", "Grit", "to", "load", "all", "commits", "from", "the", "given", "commit", "range" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter/grit/repository.rb#L127-L141
2,073
koraktor/metior
lib/metior/adapter/grit/repository.rb
Metior::Adapter::Grit.Repository.load_name_and_description
def load_name_and_description description = @grit_repo.description if description.start_with? 'Unnamed repository' @name = '' @description = '' else description = description.lines.to_a @name = description.shift.strip @description = description.join("\n").strip end end
ruby
def load_name_and_description description = @grit_repo.description if description.start_with? 'Unnamed repository' @name = '' @description = '' else description = description.lines.to_a @name = description.shift.strip @description = description.join("\n").strip end end
[ "def", "load_name_and_description", "description", "=", "@grit_repo", ".", "description", "if", "description", ".", "start_with?", "'Unnamed repository'", "@name", "=", "''", "@description", "=", "''", "else", "description", "=", "description", ".", "lines", ".", "to_a", "@name", "=", "description", ".", "shift", ".", "strip", "@description", "=", "description", ".", "join", "(", "\"\\n\"", ")", ".", "strip", "end", "end" ]
Loads both the name and description of the project contained in the repository from the description file in `GIT_DIR`. The first line of that file is used as the project's name, the remaining text is used as a description of the project. @see #description @see #name @see Grit::Repo#name
[ "Loads", "both", "the", "name", "and", "description", "of", "the", "project", "contained", "in", "the", "repository", "from", "the", "description", "file", "in", "GIT_DIR", ".", "The", "first", "line", "of", "that", "file", "is", "used", "as", "the", "project", "s", "name", "the", "remaining", "text", "is", "used", "as", "a", "description", "of", "the", "project", "." ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter/grit/repository.rb#L151-L161
2,074
koraktor/metior
lib/metior/adapter/grit/repository.rb
Metior::Adapter::Grit.Repository.load_tags
def load_tags Hash[@grit_repo.tags.map { |b| [b.name, b.commit.id] }] end
ruby
def load_tags Hash[@grit_repo.tags.map { |b| [b.name, b.commit.id] }] end
[ "def", "load_tags", "Hash", "[", "@grit_repo", ".", "tags", ".", "map", "{", "|", "b", "|", "[", "b", ".", "name", ",", "b", ".", "commit", ".", "id", "]", "}", "]", "end" ]
Loads all tags and the corresponding commit IDs of this repository @return [Hash<String, String>] The names of all tags and the corresponding commit IDs @see Grit::Repo#tags
[ "Loads", "all", "tags", "and", "the", "corresponding", "commit", "IDs", "of", "this", "repository" ]
02da0f330774c91e1a7325a5a7edbe696f389f95
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/adapter/grit/repository.rb#L170-L172
2,075
rwz/nestive
lib/nestive/layout_helper.rb
Nestive.LayoutHelper.area
def area(name, content=nil, &block) content = capture(&block) if block_given? append name, content render_area name end
ruby
def area(name, content=nil, &block) content = capture(&block) if block_given? append name, content render_area name end
[ "def", "area", "(", "name", ",", "content", "=", "nil", ",", "&", "block", ")", "content", "=", "capture", "(", "block", ")", "if", "block_given?", "append", "name", ",", "content", "render_area", "name", "end" ]
Defines an area of content in your layout that can be modified or replaced by child layouts that extend it. You can optionally add content to an area using either a String, or a block. Areas are declared in a parent layout and modified by a child layout, but since Nestive allows for multiple levels of inheritance, a child layout can also declare an area for it's children to modify. @example Define an area without adding content to it: <%= area :sidebar %> @example Define an area and add a String of content to it: <%= area :sidebar, "Some content." %> @example Define an area and add content to it with a block: <%= area :sidebar do %> Some content. <% end %> @example Define an area in a child layout: <%= extends :global do %> <%= area :sidebar do %> Some content. <% end %> <% end %> @param [Symbol] name A unique name to identify this area of content. @param [String] content An optional String of content to add to the area as you declare it.
[ "Defines", "an", "area", "of", "content", "in", "your", "layout", "that", "can", "be", "modified", "or", "replaced", "by", "child", "layouts", "that", "extend", "it", ".", "You", "can", "optionally", "add", "content", "to", "an", "area", "using", "either", "a", "String", "or", "a", "block", "." ]
3f9cc1282c0059c4a3d8665507c14c2a6f0a986a
https://github.com/rwz/nestive/blob/3f9cc1282c0059c4a3d8665507c14c2a6f0a986a/lib/nestive/layout_helper.rb#L127-L131
2,076
rwz/nestive
lib/nestive/layout_helper.rb
Nestive.LayoutHelper.render_area
def render_area(name) [].tap do |output| @_area_for.fetch(name, []).reverse_each do |method_name, content| output.public_send method_name, content end end.join.html_safe end
ruby
def render_area(name) [].tap do |output| @_area_for.fetch(name, []).reverse_each do |method_name, content| output.public_send method_name, content end end.join.html_safe end
[ "def", "render_area", "(", "name", ")", "[", "]", ".", "tap", "do", "|", "output", "|", "@_area_for", ".", "fetch", "(", "name", ",", "[", "]", ")", ".", "reverse_each", "do", "|", "method_name", ",", "content", "|", "output", ".", "public_send", "method_name", ",", "content", "end", "end", ".", "join", ".", "html_safe", "end" ]
Take the instructions we've gathered for the area and replay them one after the other on an empty array. These instructions will push, unshift or replace items into our output array, which we then join and mark as html_safe. These instructions are reversed and replayed when we render the block (rather than as they happen) due to the way they are gathered by the layout extension process (in reverse).
[ "Take", "the", "instructions", "we", "ve", "gathered", "for", "the", "area", "and", "replay", "them", "one", "after", "the", "other", "on", "an", "empty", "array", ".", "These", "instructions", "will", "push", "unshift", "or", "replace", "items", "into", "our", "output", "array", "which", "we", "then", "join", "and", "mark", "as", "html_safe", "." ]
3f9cc1282c0059c4a3d8665507c14c2a6f0a986a
https://github.com/rwz/nestive/blob/3f9cc1282c0059c4a3d8665507c14c2a6f0a986a/lib/nestive/layout_helper.rb#L236-L242
2,077
jrochkind/bento_search
app/search_engines/bento_search/google_books_engine.rb
BentoSearch.GoogleBooksEngine.hash_to_item
def hash_to_item(item_response) v_info = item_response["volumeInfo"] || {} item = ResultItem.new item.unique_id = item_response["id"] item.title = format_title(v_info) item.publisher = v_info["publisher"] # previewLink gives you your search results highlighted, preferable # if it exists. item.link = v_info["previewLink"] || v_info["canonicalVolumeLink"] item.abstract = sanitize v_info["description"] item.year = get_year v_info["publishedDate"] # sometimes we have yyyy-mm, but we need a date to make a ruby Date, # we'll just say the 1st. item.publication_date = case v_info["publishedDate"] when /(\d\d\d\d)-(\d\d)/ then Date.parse "#{$1}-#{$2}-01" when /(\d\d\d\d)-(\d\d)-(\d\d)/ then Date.parse v_info["published_date"] else nil end item.format = if v_info["printType"] == "MAGAZINE" :serial else "Book" end item.language_code = v_info["language"] (v_info["authors"] || []).each do |author_name| item.authors << Author.new(:display => author_name) end # Find ISBN's, prefer ISBN-13 item.isbn = (v_info["industryIdentifiers"] || []).find {|node| node["type"] == "ISBN_13"}.try {|node| node["identifier"]} unless item.isbn # Look for ISBN-10 okay item.isbn = (v_info["industryIdentifiers"] || []).find {|node| node["type"] == "ISBN_10"}.try {|node| node["identifier"]} end # only VERY occasionally does a GBS hit have an OCLC number, but let's look # just in case. item.oclcnum = (v_info["industryIdentifiers"] || []). find {|node| node["type"] == "OTHER" && node["identifier"].starts_with?("OCLC:") }. try do |node| node =~ /OCLC:(.*)/ ? $1 : nil end # save viewability status in custom_data. PARTIAL, ALL_PAGES, NO_PAGES or UNKNOWN. # https://developers.google.com/books/docs/v1/reference/volumes#resource item.custom_data[:viewability] = item_response["accessInfo"].try {|h| h["viewability"]} item.link_is_fulltext = (item.custom_data[:viewability] == "ALL_PAGES") if item.custom_data[:viewability] return item end
ruby
def hash_to_item(item_response) v_info = item_response["volumeInfo"] || {} item = ResultItem.new item.unique_id = item_response["id"] item.title = format_title(v_info) item.publisher = v_info["publisher"] # previewLink gives you your search results highlighted, preferable # if it exists. item.link = v_info["previewLink"] || v_info["canonicalVolumeLink"] item.abstract = sanitize v_info["description"] item.year = get_year v_info["publishedDate"] # sometimes we have yyyy-mm, but we need a date to make a ruby Date, # we'll just say the 1st. item.publication_date = case v_info["publishedDate"] when /(\d\d\d\d)-(\d\d)/ then Date.parse "#{$1}-#{$2}-01" when /(\d\d\d\d)-(\d\d)-(\d\d)/ then Date.parse v_info["published_date"] else nil end item.format = if v_info["printType"] == "MAGAZINE" :serial else "Book" end item.language_code = v_info["language"] (v_info["authors"] || []).each do |author_name| item.authors << Author.new(:display => author_name) end # Find ISBN's, prefer ISBN-13 item.isbn = (v_info["industryIdentifiers"] || []).find {|node| node["type"] == "ISBN_13"}.try {|node| node["identifier"]} unless item.isbn # Look for ISBN-10 okay item.isbn = (v_info["industryIdentifiers"] || []).find {|node| node["type"] == "ISBN_10"}.try {|node| node["identifier"]} end # only VERY occasionally does a GBS hit have an OCLC number, but let's look # just in case. item.oclcnum = (v_info["industryIdentifiers"] || []). find {|node| node["type"] == "OTHER" && node["identifier"].starts_with?("OCLC:") }. try do |node| node =~ /OCLC:(.*)/ ? $1 : nil end # save viewability status in custom_data. PARTIAL, ALL_PAGES, NO_PAGES or UNKNOWN. # https://developers.google.com/books/docs/v1/reference/volumes#resource item.custom_data[:viewability] = item_response["accessInfo"].try {|h| h["viewability"]} item.link_is_fulltext = (item.custom_data[:viewability] == "ALL_PAGES") if item.custom_data[:viewability] return item end
[ "def", "hash_to_item", "(", "item_response", ")", "v_info", "=", "item_response", "[", "\"volumeInfo\"", "]", "||", "{", "}", "item", "=", "ResultItem", ".", "new", "item", ".", "unique_id", "=", "item_response", "[", "\"id\"", "]", "item", ".", "title", "=", "format_title", "(", "v_info", ")", "item", ".", "publisher", "=", "v_info", "[", "\"publisher\"", "]", "# previewLink gives you your search results highlighted, preferable", "# if it exists.", "item", ".", "link", "=", "v_info", "[", "\"previewLink\"", "]", "||", "v_info", "[", "\"canonicalVolumeLink\"", "]", "item", ".", "abstract", "=", "sanitize", "v_info", "[", "\"description\"", "]", "item", ".", "year", "=", "get_year", "v_info", "[", "\"publishedDate\"", "]", "# sometimes we have yyyy-mm, but we need a date to make a ruby Date,", "# we'll just say the 1st.", "item", ".", "publication_date", "=", "case", "v_info", "[", "\"publishedDate\"", "]", "when", "/", "\\d", "\\d", "\\d", "\\d", "\\d", "\\d", "/", "then", "Date", ".", "parse", "\"#{$1}-#{$2}-01\"", "when", "/", "\\d", "\\d", "\\d", "\\d", "\\d", "\\d", "\\d", "\\d", "/", "then", "Date", ".", "parse", "v_info", "[", "\"published_date\"", "]", "else", "nil", "end", "item", ".", "format", "=", "if", "v_info", "[", "\"printType\"", "]", "==", "\"MAGAZINE\"", ":serial", "else", "\"Book\"", "end", "item", ".", "language_code", "=", "v_info", "[", "\"language\"", "]", "(", "v_info", "[", "\"authors\"", "]", "||", "[", "]", ")", ".", "each", "do", "|", "author_name", "|", "item", ".", "authors", "<<", "Author", ".", "new", "(", ":display", "=>", "author_name", ")", "end", "# Find ISBN's, prefer ISBN-13", "item", ".", "isbn", "=", "(", "v_info", "[", "\"industryIdentifiers\"", "]", "||", "[", "]", ")", ".", "find", "{", "|", "node", "|", "node", "[", "\"type\"", "]", "==", "\"ISBN_13\"", "}", ".", "try", "{", "|", "node", "|", "node", "[", "\"identifier\"", "]", "}", "unless", "item", ".", "isbn", "# Look for ISBN-10 okay", "item", ".", "isbn", "=", "(", "v_info", "[", "\"industryIdentifiers\"", "]", "||", "[", "]", ")", ".", "find", "{", "|", "node", "|", "node", "[", "\"type\"", "]", "==", "\"ISBN_10\"", "}", ".", "try", "{", "|", "node", "|", "node", "[", "\"identifier\"", "]", "}", "end", "# only VERY occasionally does a GBS hit have an OCLC number, but let's look", "# just in case.", "item", ".", "oclcnum", "=", "(", "v_info", "[", "\"industryIdentifiers\"", "]", "||", "[", "]", ")", ".", "find", "{", "|", "node", "|", "node", "[", "\"type\"", "]", "==", "\"OTHER\"", "&&", "node", "[", "\"identifier\"", "]", ".", "starts_with?", "(", "\"OCLC:\"", ")", "}", ".", "try", "do", "|", "node", "|", "node", "=~", "/", "/", "?", "$1", ":", "nil", "end", "# save viewability status in custom_data. PARTIAL, ALL_PAGES, NO_PAGES or UNKNOWN.", "# https://developers.google.com/books/docs/v1/reference/volumes#resource", "item", ".", "custom_data", "[", ":viewability", "]", "=", "item_response", "[", "\"accessInfo\"", "]", ".", "try", "{", "|", "h", "|", "h", "[", "\"viewability\"", "]", "}", "item", ".", "link_is_fulltext", "=", "(", "item", ".", "custom_data", "[", ":viewability", "]", "==", "\"ALL_PAGES\"", ")", "if", "item", ".", "custom_data", "[", ":viewability", "]", "return", "item", "end" ]
take a hash from Google json response, representing a single item, return a ResultItem obj. Used internally.
[ "take", "a", "hash", "from", "Google", "json", "response", "representing", "a", "single", "item", "return", "a", "ResultItem", "obj", ".", "Used", "internally", "." ]
f567ead386d4a2e283c03b787e7c0d620567c9de
https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/search_engines/bento_search/google_books_engine.rb#L119-L178
2,078
jrochkind/bento_search
app/search_engines/bento_search/google_books_engine.rb
BentoSearch.GoogleBooksEngine.args_to_search_url
def args_to_search_url(arguments) query = if arguments[:query].kind_of? Hash #multi-field arguments[:query].collect {|field, query_value| fielded_query(query_value, field)}.join(" ") elsif arguments[:search_field] fielded_query(arguments[:query], arguments[:search_field]) else arguments[:query] end query_url = base_url + "volumes?q=#{CGI.escape query}" if configuration.api_key query_url += "&key=#{configuration.api_key}" end if arguments[:per_page] query_url += "&maxResults=#{arguments[:per_page]}" end if arguments[:start] query_url += "&startIndex=#{arguments[:start]}" end if arguments[:sort] && (defn = sort_definitions[arguments[:sort]]) && (value = defn[:implementation]) query_url += "&orderBy=#{CGI.escape(value)}" end return query_url end
ruby
def args_to_search_url(arguments) query = if arguments[:query].kind_of? Hash #multi-field arguments[:query].collect {|field, query_value| fielded_query(query_value, field)}.join(" ") elsif arguments[:search_field] fielded_query(arguments[:query], arguments[:search_field]) else arguments[:query] end query_url = base_url + "volumes?q=#{CGI.escape query}" if configuration.api_key query_url += "&key=#{configuration.api_key}" end if arguments[:per_page] query_url += "&maxResults=#{arguments[:per_page]}" end if arguments[:start] query_url += "&startIndex=#{arguments[:start]}" end if arguments[:sort] && (defn = sort_definitions[arguments[:sort]]) && (value = defn[:implementation]) query_url += "&orderBy=#{CGI.escape(value)}" end return query_url end
[ "def", "args_to_search_url", "(", "arguments", ")", "query", "=", "if", "arguments", "[", ":query", "]", ".", "kind_of?", "Hash", "#multi-field", "arguments", "[", ":query", "]", ".", "collect", "{", "|", "field", ",", "query_value", "|", "fielded_query", "(", "query_value", ",", "field", ")", "}", ".", "join", "(", "\" \"", ")", "elsif", "arguments", "[", ":search_field", "]", "fielded_query", "(", "arguments", "[", ":query", "]", ",", "arguments", "[", ":search_field", "]", ")", "else", "arguments", "[", ":query", "]", "end", "query_url", "=", "base_url", "+", "\"volumes?q=#{CGI.escape query}\"", "if", "configuration", ".", "api_key", "query_url", "+=", "\"&key=#{configuration.api_key}\"", "end", "if", "arguments", "[", ":per_page", "]", "query_url", "+=", "\"&maxResults=#{arguments[:per_page]}\"", "end", "if", "arguments", "[", ":start", "]", "query_url", "+=", "\"&startIndex=#{arguments[:start]}\"", "end", "if", "arguments", "[", ":sort", "]", "&&", "(", "defn", "=", "sort_definitions", "[", "arguments", "[", ":sort", "]", "]", ")", "&&", "(", "value", "=", "defn", "[", ":implementation", "]", ")", "query_url", "+=", "\"&orderBy=#{CGI.escape(value)}\"", "end", "return", "query_url", "end" ]
Our own implementation code takes a normalized #search arguments hash from SearchEngine turns it into a URL for Google API. Factored out to make testing possible.
[ "Our", "own", "implementation", "code" ]
f567ead386d4a2e283c03b787e7c0d620567c9de
https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/search_engines/bento_search/google_books_engine.rb#L223-L253
2,079
jrochkind/bento_search
app/item_decorators/bento_search/standard_decorator.rb
BentoSearch.StandardDecorator.render_authors_list
def render_authors_list parts = [] first_three = self.authors.slice(0,3) first_three.each_with_index do |author, index| parts << _h.content_tag("span", :class => "author") do self.author_display(author) end if (index + 1) < first_three.length parts << "; " end end if self.authors.length > 3 parts << I18n.t("bento_search.authors_et_al") end return _h.safe_join(parts, "") end
ruby
def render_authors_list parts = [] first_three = self.authors.slice(0,3) first_three.each_with_index do |author, index| parts << _h.content_tag("span", :class => "author") do self.author_display(author) end if (index + 1) < first_three.length parts << "; " end end if self.authors.length > 3 parts << I18n.t("bento_search.authors_et_al") end return _h.safe_join(parts, "") end
[ "def", "render_authors_list", "parts", "=", "[", "]", "first_three", "=", "self", ".", "authors", ".", "slice", "(", "0", ",", "3", ")", "first_three", ".", "each_with_index", "do", "|", "author", ",", "index", "|", "parts", "<<", "_h", ".", "content_tag", "(", "\"span\"", ",", ":class", "=>", "\"author\"", ")", "do", "self", ".", "author_display", "(", "author", ")", "end", "if", "(", "index", "+", "1", ")", "<", "first_three", ".", "length", "parts", "<<", "\"; \"", "end", "end", "if", "self", ".", "authors", ".", "length", ">", "3", "parts", "<<", "I18n", ".", "t", "(", "\"bento_search.authors_et_al\"", ")", "end", "return", "_h", ".", "safe_join", "(", "parts", ",", "\"\"", ")", "end" ]
display multiple authors, with HTML markup, returns html_safe string. experimentally trying this as a decorator helper method rather than a view partial, not sure which is best. Will limit to first three authors, with elipsis if there are more. Over-ride if you want to format authors names differently, or show more or less than first 3, etc.
[ "display", "multiple", "authors", "with", "HTML", "markup", "returns", "html_safe", "string", ".", "experimentally", "trying", "this", "as", "a", "decorator", "helper", "method", "rather", "than", "a", "view", "partial", "not", "sure", "which", "is", "best", "." ]
f567ead386d4a2e283c03b787e7c0d620567c9de
https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/item_decorators/bento_search/standard_decorator.rb#L38-L57
2,080
jrochkind/bento_search
app/item_decorators/bento_search/standard_decorator.rb
BentoSearch.StandardDecorator.render_citation_details
def render_citation_details # \u00A0 is unicode non-breaking space to keep labels and values from # getting separated. result_elements = [] result_elements.push("#{I18n.t('bento_search.volume')}\u00A0#{volume}") if volume.present? result_elements.push("#{I18n.t('bento_search.issue')}\u00A0#{issue}") if issue.present? if (! start_page.blank?) && (! end_page.blank?) result_elements.push html_escape "#{I18n.t('bento_search.pages')}\u00A0#{start_page}-#{end_page}" elsif ! start_page.blank? result_elements.push html_escape "#{I18n.t('bento_search.page')}\u00A0#{start_page}" end return nil if result_elements.empty? return result_elements.join(", ").html_safe end
ruby
def render_citation_details # \u00A0 is unicode non-breaking space to keep labels and values from # getting separated. result_elements = [] result_elements.push("#{I18n.t('bento_search.volume')}\u00A0#{volume}") if volume.present? result_elements.push("#{I18n.t('bento_search.issue')}\u00A0#{issue}") if issue.present? if (! start_page.blank?) && (! end_page.blank?) result_elements.push html_escape "#{I18n.t('bento_search.pages')}\u00A0#{start_page}-#{end_page}" elsif ! start_page.blank? result_elements.push html_escape "#{I18n.t('bento_search.page')}\u00A0#{start_page}" end return nil if result_elements.empty? return result_elements.join(", ").html_safe end
[ "def", "render_citation_details", "# \\u00A0 is unicode non-breaking space to keep labels and values from", "# getting separated.", "result_elements", "=", "[", "]", "result_elements", ".", "push", "(", "\"#{I18n.t('bento_search.volume')}\\u00A0#{volume}\"", ")", "if", "volume", ".", "present?", "result_elements", ".", "push", "(", "\"#{I18n.t('bento_search.issue')}\\u00A0#{issue}\"", ")", "if", "issue", ".", "present?", "if", "(", "!", "start_page", ".", "blank?", ")", "&&", "(", "!", "end_page", ".", "blank?", ")", "result_elements", ".", "push", "html_escape", "\"#{I18n.t('bento_search.pages')}\\u00A0#{start_page}-#{end_page}\"", "elsif", "!", "start_page", ".", "blank?", "result_elements", ".", "push", "html_escape", "\"#{I18n.t('bento_search.page')}\\u00A0#{start_page}\"", "end", "return", "nil", "if", "result_elements", ".", "empty?", "return", "result_elements", ".", "join", "(", "\", \"", ")", ".", "html_safe", "end" ]
volume, issue, and page numbers. With prefixed labels from I18n. That's it.
[ "volume", "issue", "and", "page", "numbers", ".", "With", "prefixed", "labels", "from", "I18n", ".", "That", "s", "it", "." ]
f567ead386d4a2e283c03b787e7c0d620567c9de
https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/item_decorators/bento_search/standard_decorator.rb#L104-L122
2,081
jrochkind/bento_search
app/item_decorators/bento_search/standard_decorator.rb
BentoSearch.StandardDecorator.render_summary
def render_summary summary = nil max_chars = (self.display_configuration.try {|h| h["summary_max_chars"]}) || 280 if self.snippets.length > 0 && !(self.display_configuration.try {|h| h["prefer_abstract_as_summary"]} && self.abstract) summary = self.snippets.first self.snippets.slice(1, self.snippets.length).each do |snippet| summary += ' '.html_safe + snippet if (summary.length + snippet.length) <= max_chars end else summary = _h.bento_truncate( self.abstract, :length => max_chars ) end summary end
ruby
def render_summary summary = nil max_chars = (self.display_configuration.try {|h| h["summary_max_chars"]}) || 280 if self.snippets.length > 0 && !(self.display_configuration.try {|h| h["prefer_abstract_as_summary"]} && self.abstract) summary = self.snippets.first self.snippets.slice(1, self.snippets.length).each do |snippet| summary += ' '.html_safe + snippet if (summary.length + snippet.length) <= max_chars end else summary = _h.bento_truncate( self.abstract, :length => max_chars ) end summary end
[ "def", "render_summary", "summary", "=", "nil", "max_chars", "=", "(", "self", ".", "display_configuration", ".", "try", "{", "|", "h", "|", "h", "[", "\"summary_max_chars\"", "]", "}", ")", "||", "280", "if", "self", ".", "snippets", ".", "length", ">", "0", "&&", "!", "(", "self", ".", "display_configuration", ".", "try", "{", "|", "h", "|", "h", "[", "\"prefer_abstract_as_summary\"", "]", "}", "&&", "self", ".", "abstract", ")", "summary", "=", "self", ".", "snippets", ".", "first", "self", ".", "snippets", ".", "slice", "(", "1", ",", "self", ".", "snippets", ".", "length", ")", ".", "each", "do", "|", "snippet", "|", "summary", "+=", "' '", ".", "html_safe", "+", "snippet", "if", "(", "summary", ".", "length", "+", "snippet", ".", "length", ")", "<=", "max_chars", "end", "else", "summary", "=", "_h", ".", "bento_truncate", "(", "self", ".", "abstract", ",", ":length", "=>", "max_chars", ")", "end", "summary", "end" ]
A summary. If config.for_dispaly.prefer_snippets_as_summary is set to true then prefers that, otherwise abstract. Truncates for display.
[ "A", "summary", ".", "If", "config", ".", "for_dispaly", ".", "prefer_snippets_as_summary", "is", "set", "to", "true", "then", "prefers", "that", "otherwise", "abstract", "." ]
f567ead386d4a2e283c03b787e7c0d620567c9de
https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/item_decorators/bento_search/standard_decorator.rb#L128-L144
2,082
danieldreier/autosign
lib/autosign/config.rb
Autosign.Config.configfile
def configfile @log.debug "Finding config file" @config_file_paths.each { |file| @log.debug "Checking if file '#{file}' exists" if File.file?(file) @log.debug "Reading config file from: " + file config_file = File.read(file) parsed_config_file = YAML.load(config_file) #parsed_config_file = IniParse.parse(config_file).to_hash @log.debug "configuration read from config file: " + parsed_config_file.to_s return parsed_config_file if parsed_config_file.is_a?(Hash) else @log.debug "Configuration file '#{file}' not found" end } return {} end
ruby
def configfile @log.debug "Finding config file" @config_file_paths.each { |file| @log.debug "Checking if file '#{file}' exists" if File.file?(file) @log.debug "Reading config file from: " + file config_file = File.read(file) parsed_config_file = YAML.load(config_file) #parsed_config_file = IniParse.parse(config_file).to_hash @log.debug "configuration read from config file: " + parsed_config_file.to_s return parsed_config_file if parsed_config_file.is_a?(Hash) else @log.debug "Configuration file '#{file}' not found" end } return {} end
[ "def", "configfile", "@log", ".", "debug", "\"Finding config file\"", "@config_file_paths", ".", "each", "{", "|", "file", "|", "@log", ".", "debug", "\"Checking if file '#{file}' exists\"", "if", "File", ".", "file?", "(", "file", ")", "@log", ".", "debug", "\"Reading config file from: \"", "+", "file", "config_file", "=", "File", ".", "read", "(", "file", ")", "parsed_config_file", "=", "YAML", ".", "load", "(", "config_file", ")", "#parsed_config_file = IniParse.parse(config_file).to_hash", "@log", ".", "debug", "\"configuration read from config file: \"", "+", "parsed_config_file", ".", "to_s", "return", "parsed_config_file", "if", "parsed_config_file", ".", "is_a?", "(", "Hash", ")", "else", "@log", ".", "debug", "\"Configuration file '#{file}' not found\"", "end", "}", "return", "{", "}", "end" ]
Locate the configuration file, parse it from INI-format, and return the results as a hash. Returns an empty hash if no config file is found. @return [Hash] configuration settings loaded from INI file
[ "Locate", "the", "configuration", "file", "parse", "it", "from", "INI", "-", "format", "and", "return", "the", "results", "as", "a", "hash", ".", "Returns", "an", "empty", "hash", "if", "no", "config", "file", "is", "found", "." ]
d457eeec5b2084ff63ee4555f7de97cf87be1aca
https://github.com/danieldreier/autosign/blob/d457eeec5b2084ff63ee4555f7de97cf87be1aca/lib/autosign/config.rb#L93-L109
2,083
danieldreier/autosign
lib/autosign/config.rb
Autosign.Config.validate_config_file
def validate_config_file(configfile = location) @log.debug "validating config file" unless File.file?(configfile) @log.error "configuration file not found at: #{configfile}" raise Autosign::Exceptions::NotFound end # check if file is world-readable if File.world_readable?(configfile) or File.world_writable?(configfile) @log.error "configuration file #{configfile} is world-readable or world-writable, which is a security risk" raise Autosign::Exceptions::Permissions end configfile end
ruby
def validate_config_file(configfile = location) @log.debug "validating config file" unless File.file?(configfile) @log.error "configuration file not found at: #{configfile}" raise Autosign::Exceptions::NotFound end # check if file is world-readable if File.world_readable?(configfile) or File.world_writable?(configfile) @log.error "configuration file #{configfile} is world-readable or world-writable, which is a security risk" raise Autosign::Exceptions::Permissions end configfile end
[ "def", "validate_config_file", "(", "configfile", "=", "location", ")", "@log", ".", "debug", "\"validating config file\"", "unless", "File", ".", "file?", "(", "configfile", ")", "@log", ".", "error", "\"configuration file not found at: #{configfile}\"", "raise", "Autosign", "::", "Exceptions", "::", "NotFound", "end", "# check if file is world-readable", "if", "File", ".", "world_readable?", "(", "configfile", ")", "or", "File", ".", "world_writable?", "(", "configfile", ")", "@log", ".", "error", "\"configuration file #{configfile} is world-readable or world-writable, which is a security risk\"", "raise", "Autosign", "::", "Exceptions", "::", "Permissions", "end", "configfile", "end" ]
Validate configuration file Raises an exception if the config file cannot be validated @param configfile [String] the absolute path of the config file to validate @return [String] the absolute path of the config file
[ "Validate", "configuration", "file", "Raises", "an", "exception", "if", "the", "config", "file", "cannot", "be", "validated" ]
d457eeec5b2084ff63ee4555f7de97cf87be1aca
https://github.com/danieldreier/autosign/blob/d457eeec5b2084ff63ee4555f7de97cf87be1aca/lib/autosign/config.rb#L116-L130
2,084
jrochkind/bento_search
app/models/bento_search/ris_creator.rb
BentoSearch.RISCreator.format_author_name
def format_author_name(author) if author.last.present? && author.first.present? str = "#{author.last}, #{author.first}" if author.middle.present? middle = author.middle middle += "." if middle.length == 1 str += " #{middle}" end return str elsif author.display.present? return author.display elsif author.last.present? return author.last? else return nil end end
ruby
def format_author_name(author) if author.last.present? && author.first.present? str = "#{author.last}, #{author.first}" if author.middle.present? middle = author.middle middle += "." if middle.length == 1 str += " #{middle}" end return str elsif author.display.present? return author.display elsif author.last.present? return author.last? else return nil end end
[ "def", "format_author_name", "(", "author", ")", "if", "author", ".", "last", ".", "present?", "&&", "author", ".", "first", ".", "present?", "str", "=", "\"#{author.last}, #{author.first}\"", "if", "author", ".", "middle", ".", "present?", "middle", "=", "author", ".", "middle", "middle", "+=", "\".\"", "if", "middle", ".", "length", "==", "1", "str", "+=", "\" #{middle}\"", "end", "return", "str", "elsif", "author", ".", "display", ".", "present?", "return", "author", ".", "display", "elsif", "author", ".", "last", ".", "present?", "return", "author", ".", "last?", "else", "return", "nil", "end", "end" ]
RIS wants `Last, First M.`, we'll do what we can.
[ "RIS", "wants", "Last", "First", "M", ".", "we", "ll", "do", "what", "we", "can", "." ]
f567ead386d4a2e283c03b787e7c0d620567c9de
https://github.com/jrochkind/bento_search/blob/f567ead386d4a2e283c03b787e7c0d620567c9de/app/models/bento_search/ris_creator.rb#L147-L163
2,085
sendwithus/sendwithus_ruby
lib/send_with_us/api.rb
SendWithUs.Api.send_email
def send_email(email_id, to, options = {}) if email_id.nil? raise SendWithUs::ApiNilEmailId, 'email_id cannot be nil' end payload = { email_id: email_id, recipient: to } if options[:data] && options[:data].any? payload[:email_data] = options[:data] end if options[:from] && options[:from].any? payload[:sender] = options[:from] end if options[:cc] && options[:cc].any? payload[:cc] = options[:cc] end if options[:bcc] && options[:bcc].any? payload[:bcc] = options[:bcc] end if options[:esp_account] payload[:esp_account] = options[:esp_account] end if options[:version_name] payload[:version_name] = options[:version_name] end if options[:headers] && options[:headers].any? payload[:headers] = options[:headers] end if options[:tags] && options[:tags].any? payload[:tags] = options[:tags] end if options[:locale] payload[:locale] = options[:locale] end if options[:files] && options[:files].any? payload[:files] = options[:files].map do |file_data| SendWithUs::File.new(file_data).to_h end end SendWithUs::ApiRequest.new(@configuration).post(:send, payload.to_json) end
ruby
def send_email(email_id, to, options = {}) if email_id.nil? raise SendWithUs::ApiNilEmailId, 'email_id cannot be nil' end payload = { email_id: email_id, recipient: to } if options[:data] && options[:data].any? payload[:email_data] = options[:data] end if options[:from] && options[:from].any? payload[:sender] = options[:from] end if options[:cc] && options[:cc].any? payload[:cc] = options[:cc] end if options[:bcc] && options[:bcc].any? payload[:bcc] = options[:bcc] end if options[:esp_account] payload[:esp_account] = options[:esp_account] end if options[:version_name] payload[:version_name] = options[:version_name] end if options[:headers] && options[:headers].any? payload[:headers] = options[:headers] end if options[:tags] && options[:tags].any? payload[:tags] = options[:tags] end if options[:locale] payload[:locale] = options[:locale] end if options[:files] && options[:files].any? payload[:files] = options[:files].map do |file_data| SendWithUs::File.new(file_data).to_h end end SendWithUs::ApiRequest.new(@configuration).post(:send, payload.to_json) end
[ "def", "send_email", "(", "email_id", ",", "to", ",", "options", "=", "{", "}", ")", "if", "email_id", ".", "nil?", "raise", "SendWithUs", "::", "ApiNilEmailId", ",", "'email_id cannot be nil'", "end", "payload", "=", "{", "email_id", ":", "email_id", ",", "recipient", ":", "to", "}", "if", "options", "[", ":data", "]", "&&", "options", "[", ":data", "]", ".", "any?", "payload", "[", ":email_data", "]", "=", "options", "[", ":data", "]", "end", "if", "options", "[", ":from", "]", "&&", "options", "[", ":from", "]", ".", "any?", "payload", "[", ":sender", "]", "=", "options", "[", ":from", "]", "end", "if", "options", "[", ":cc", "]", "&&", "options", "[", ":cc", "]", ".", "any?", "payload", "[", ":cc", "]", "=", "options", "[", ":cc", "]", "end", "if", "options", "[", ":bcc", "]", "&&", "options", "[", ":bcc", "]", ".", "any?", "payload", "[", ":bcc", "]", "=", "options", "[", ":bcc", "]", "end", "if", "options", "[", ":esp_account", "]", "payload", "[", ":esp_account", "]", "=", "options", "[", ":esp_account", "]", "end", "if", "options", "[", ":version_name", "]", "payload", "[", ":version_name", "]", "=", "options", "[", ":version_name", "]", "end", "if", "options", "[", ":headers", "]", "&&", "options", "[", ":headers", "]", ".", "any?", "payload", "[", ":headers", "]", "=", "options", "[", ":headers", "]", "end", "if", "options", "[", ":tags", "]", "&&", "options", "[", ":tags", "]", ".", "any?", "payload", "[", ":tags", "]", "=", "options", "[", ":tags", "]", "end", "if", "options", "[", ":locale", "]", "payload", "[", ":locale", "]", "=", "options", "[", ":locale", "]", "end", "if", "options", "[", ":files", "]", "&&", "options", "[", ":files", "]", ".", "any?", "payload", "[", ":files", "]", "=", "options", "[", ":files", "]", ".", "map", "do", "|", "file_data", "|", "SendWithUs", "::", "File", ".", "new", "(", "file_data", ")", ".", "to_h", "end", "end", "SendWithUs", "::", "ApiRequest", ".", "new", "(", "@configuration", ")", ".", "post", "(", ":send", ",", "payload", ".", "to_json", ")", "end" ]
Sends the specified email with any optional arguments * *Args* : - +email_id+ -> ID of the email to send - +to+ -> Hash of recipient details * *Options* : - +:data+ -> Hash of email data - +:from+ -> Hash of sender details - +:cc+ -> Array of CC recipients - +:bcc+ -> Array of BCC recipients - +:files+ -> Array of attachments - +:esp_account+ -> The ESP account to use - +:version_name+ -> The specific email version to use - +:headers+ -> Hash of headers - +:tags+ -> Array of tags - +:locale+ -> Localization string * *Notes* : - "send" is already a ruby-defined method on all classes
[ "Sends", "the", "specified", "email", "with", "any", "optional", "arguments" ]
e1d54e00e20da17cd032fb8e5b602ef99c7f984a
https://github.com/sendwithus/sendwithus_ruby/blob/e1d54e00e20da17cd032fb8e5b602ef99c7f984a/lib/send_with_us/api.rb#L83-L128
2,086
zorab47/active_admin-duplicatable
lib/active_admin/duplicatable.rb
ActiveAdmin.Duplicatable.enable_resource_duplication_via_form
def enable_resource_duplication_via_form action_item(*compatible_action_item_parameters) do if controller.action_methods.include?('new') && authorized?(ActiveAdmin::Auth::CREATE, active_admin_config.resource_class) link_to(I18n.t(:duplicate_model, default: "Duplicate %{model}", scope: [:active_admin], model: active_admin_config.resource_label), action: :new, _source_id: resource.id) end end controller do before_action only: :new do if !params[:_source_id].blank? source = resource_class.find(params[:_source_id]) @resource ||= source.amoeba_dup if source end end end end
ruby
def enable_resource_duplication_via_form action_item(*compatible_action_item_parameters) do if controller.action_methods.include?('new') && authorized?(ActiveAdmin::Auth::CREATE, active_admin_config.resource_class) link_to(I18n.t(:duplicate_model, default: "Duplicate %{model}", scope: [:active_admin], model: active_admin_config.resource_label), action: :new, _source_id: resource.id) end end controller do before_action only: :new do if !params[:_source_id].blank? source = resource_class.find(params[:_source_id]) @resource ||= source.amoeba_dup if source end end end end
[ "def", "enable_resource_duplication_via_form", "action_item", "(", "compatible_action_item_parameters", ")", "do", "if", "controller", ".", "action_methods", ".", "include?", "(", "'new'", ")", "&&", "authorized?", "(", "ActiveAdmin", "::", "Auth", "::", "CREATE", ",", "active_admin_config", ".", "resource_class", ")", "link_to", "(", "I18n", ".", "t", "(", ":duplicate_model", ",", "default", ":", "\"Duplicate %{model}\"", ",", "scope", ":", "[", ":active_admin", "]", ",", "model", ":", "active_admin_config", ".", "resource_label", ")", ",", "action", ":", ":new", ",", "_source_id", ":", "resource", ".", "id", ")", "end", "end", "controller", "do", "before_action", "only", ":", ":new", "do", "if", "!", "params", "[", ":_source_id", "]", ".", "blank?", "source", "=", "resource_class", ".", "find", "(", "params", "[", ":_source_id", "]", ")", "@resource", "||=", "source", ".", "amoeba_dup", "if", "source", "end", "end", "end", "end" ]
Enables resource duplication via new form. - Adds a duplicate action button. - Preloads a duplicated resource on `:new` to pre-fill the form fields. No return.
[ "Enables", "resource", "duplication", "via", "new", "form", "." ]
135c1712befcfe3a8af4bdc5c5e1f0f8a2652500
https://github.com/zorab47/active_admin-duplicatable/blob/135c1712befcfe3a8af4bdc5c5e1f0f8a2652500/lib/active_admin/duplicatable.rb#L41-L56
2,087
zorab47/active_admin-duplicatable
lib/active_admin/duplicatable.rb
ActiveAdmin.Duplicatable.enable_resource_duplication_via_save
def enable_resource_duplication_via_save action_item(*compatible_action_item_parameters) do if controller.action_methods.include?('new') && authorized?(ActiveAdmin::Auth::CREATE, active_admin_config.resource_class) link_to(I18n.t(:duplicate_model, default: "Duplicate %{model}", scope: [:active_admin], model: active_admin_config.resource_label), action: :duplicate) end end member_action :duplicate do resource = resource_class.find(params[:id]) authorize! ActiveAdmin::Auth::CREATE, resource duplicate = resource.amoeba_dup if duplicate.save redirect_to({ action: :edit, id: duplicate.id }, flash: { notice: "#{active_admin_config.resource_label} was successfully duplicated." }) else redirect_to({ action: :show }, flash: { error: "#{active_admin_config.resource_label} could not be duplicated." }) end end end
ruby
def enable_resource_duplication_via_save action_item(*compatible_action_item_parameters) do if controller.action_methods.include?('new') && authorized?(ActiveAdmin::Auth::CREATE, active_admin_config.resource_class) link_to(I18n.t(:duplicate_model, default: "Duplicate %{model}", scope: [:active_admin], model: active_admin_config.resource_label), action: :duplicate) end end member_action :duplicate do resource = resource_class.find(params[:id]) authorize! ActiveAdmin::Auth::CREATE, resource duplicate = resource.amoeba_dup if duplicate.save redirect_to({ action: :edit, id: duplicate.id }, flash: { notice: "#{active_admin_config.resource_label} was successfully duplicated." }) else redirect_to({ action: :show }, flash: { error: "#{active_admin_config.resource_label} could not be duplicated." }) end end end
[ "def", "enable_resource_duplication_via_save", "action_item", "(", "compatible_action_item_parameters", ")", "do", "if", "controller", ".", "action_methods", ".", "include?", "(", "'new'", ")", "&&", "authorized?", "(", "ActiveAdmin", "::", "Auth", "::", "CREATE", ",", "active_admin_config", ".", "resource_class", ")", "link_to", "(", "I18n", ".", "t", "(", ":duplicate_model", ",", "default", ":", "\"Duplicate %{model}\"", ",", "scope", ":", "[", ":active_admin", "]", ",", "model", ":", "active_admin_config", ".", "resource_label", ")", ",", "action", ":", ":duplicate", ")", "end", "end", "member_action", ":duplicate", "do", "resource", "=", "resource_class", ".", "find", "(", "params", "[", ":id", "]", ")", "authorize!", "ActiveAdmin", "::", "Auth", "::", "CREATE", ",", "resource", "duplicate", "=", "resource", ".", "amoeba_dup", "if", "duplicate", ".", "save", "redirect_to", "(", "{", "action", ":", ":edit", ",", "id", ":", "duplicate", ".", "id", "}", ",", "flash", ":", "{", "notice", ":", "\"#{active_admin_config.resource_label} was successfully duplicated.\"", "}", ")", "else", "redirect_to", "(", "{", "action", ":", ":show", "}", ",", "flash", ":", "{", "error", ":", "\"#{active_admin_config.resource_label} could not be duplicated.\"", "}", ")", "end", "end", "end" ]
Enables resource duplication via save. - Adds a duplicate action button. - Duplicates a resource, persists it, and redirects the user to edit the newly duplicated resource. No return.
[ "Enables", "resource", "duplication", "via", "save", "." ]
135c1712befcfe3a8af4bdc5c5e1f0f8a2652500
https://github.com/zorab47/active_admin-duplicatable/blob/135c1712befcfe3a8af4bdc5c5e1f0f8a2652500/lib/active_admin/duplicatable.rb#L65-L84
2,088
zorab47/active_admin-duplicatable
lib/active_admin/duplicatable.rb
ActiveAdmin.Duplicatable.enable_resource_duplication_via_custom_method
def enable_resource_duplication_via_custom_method(method) action_item(*compatible_action_item_parameters) do if controller.action_methods.include?('new') && authorized?(ActiveAdmin::Auth::CREATE, active_admin_config.resource_class) link_to(I18n.t(:duplicate_model, default: "Duplicate %{model}", scope: [:active_admin], model: active_admin_config.resource_label), action: :duplicate) end end member_action :duplicate do resource = resource_class.find(params[:id]) authorize! ActiveAdmin::Auth::CREATE, resource begin duplicate = resource.send method redirect_to({ action: :edit, id: duplicate.id }, flash: { notice: "#{active_admin_config.resource_label} was successfully duplicated." }) rescue => e Rails.logger.warn(e) redirect_to({ action: :show }, flash: { error: "#{active_admin_config.resource_label} could not be duplicated." }) end end end
ruby
def enable_resource_duplication_via_custom_method(method) action_item(*compatible_action_item_parameters) do if controller.action_methods.include?('new') && authorized?(ActiveAdmin::Auth::CREATE, active_admin_config.resource_class) link_to(I18n.t(:duplicate_model, default: "Duplicate %{model}", scope: [:active_admin], model: active_admin_config.resource_label), action: :duplicate) end end member_action :duplicate do resource = resource_class.find(params[:id]) authorize! ActiveAdmin::Auth::CREATE, resource begin duplicate = resource.send method redirect_to({ action: :edit, id: duplicate.id }, flash: { notice: "#{active_admin_config.resource_label} was successfully duplicated." }) rescue => e Rails.logger.warn(e) redirect_to({ action: :show }, flash: { error: "#{active_admin_config.resource_label} could not be duplicated." }) end end end
[ "def", "enable_resource_duplication_via_custom_method", "(", "method", ")", "action_item", "(", "compatible_action_item_parameters", ")", "do", "if", "controller", ".", "action_methods", ".", "include?", "(", "'new'", ")", "&&", "authorized?", "(", "ActiveAdmin", "::", "Auth", "::", "CREATE", ",", "active_admin_config", ".", "resource_class", ")", "link_to", "(", "I18n", ".", "t", "(", ":duplicate_model", ",", "default", ":", "\"Duplicate %{model}\"", ",", "scope", ":", "[", ":active_admin", "]", ",", "model", ":", "active_admin_config", ".", "resource_label", ")", ",", "action", ":", ":duplicate", ")", "end", "end", "member_action", ":duplicate", "do", "resource", "=", "resource_class", ".", "find", "(", "params", "[", ":id", "]", ")", "authorize!", "ActiveAdmin", "::", "Auth", "::", "CREATE", ",", "resource", "begin", "duplicate", "=", "resource", ".", "send", "method", "redirect_to", "(", "{", "action", ":", ":edit", ",", "id", ":", "duplicate", ".", "id", "}", ",", "flash", ":", "{", "notice", ":", "\"#{active_admin_config.resource_label} was successfully duplicated.\"", "}", ")", "rescue", "=>", "e", "Rails", ".", "logger", ".", "warn", "(", "e", ")", "redirect_to", "(", "{", "action", ":", ":show", "}", ",", "flash", ":", "{", "error", ":", "\"#{active_admin_config.resource_label} could not be duplicated.\"", "}", ")", "end", "end", "end" ]
Enables resource duplication via a custom method - Adds a duplicate action button. - Calls a custom duplication method on the model. The method should handle any copying of data and persistence of the new record. - Redirects the user to edit the newly duplicated resource. No return.
[ "Enables", "resource", "duplication", "via", "a", "custom", "method" ]
135c1712befcfe3a8af4bdc5c5e1f0f8a2652500
https://github.com/zorab47/active_admin-duplicatable/blob/135c1712befcfe3a8af4bdc5c5e1f0f8a2652500/lib/active_admin/duplicatable.rb#L94-L114
2,089
dilcom/gnuplotrb
lib/gnuplotrb/mixins/error_handling.rb
GnuplotRB.ErrorHandling.check_errors
def check_errors(raw: false) return if @err_array.empty? command = '' rest = '' @semaphore.synchronize do command = @err_array.first rest = @err_array[1..-1].join('; ') @err_array.clear end message = if raw "#{command};#{rest}}" else "Error in previous command (\"#{command}\"): \"#{rest}\"" end fail GnuplotError, message end
ruby
def check_errors(raw: false) return if @err_array.empty? command = '' rest = '' @semaphore.synchronize do command = @err_array.first rest = @err_array[1..-1].join('; ') @err_array.clear end message = if raw "#{command};#{rest}}" else "Error in previous command (\"#{command}\"): \"#{rest}\"" end fail GnuplotError, message end
[ "def", "check_errors", "(", "raw", ":", "false", ")", "return", "if", "@err_array", ".", "empty?", "command", "=", "''", "rest", "=", "''", "@semaphore", ".", "synchronize", "do", "command", "=", "@err_array", ".", "first", "rest", "=", "@err_array", "[", "1", "..", "-", "1", "]", ".", "join", "(", "'; '", ")", "@err_array", ".", "clear", "end", "message", "=", "if", "raw", "\"#{command};#{rest}}\"", "else", "\"Error in previous command (\\\"#{command}\\\"): \\\"#{rest}\\\"\"", "end", "fail", "GnuplotError", ",", "message", "end" ]
Check if there were errors in previous commands. Throws GnuplotError in case of any errors.
[ "Check", "if", "there", "were", "errors", "in", "previous", "commands", ".", "Throws", "GnuplotError", "in", "case", "of", "any", "errors", "." ]
0a3146386ae28fcbe2c09cb6e266fe40ebb659f4
https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/mixins/error_handling.rb#L14-L29
2,090
dilcom/gnuplotrb
lib/gnuplotrb/mixins/error_handling.rb
GnuplotRB.ErrorHandling.handle_stderr
def handle_stderr(stream) @err_array = [] # synchronize access to @err_array @semaphore = Mutex.new Thread.new do until (line = stream.gets).nil? line.strip! @semaphore.synchronize { @err_array << line if line.size > 3 } end end end
ruby
def handle_stderr(stream) @err_array = [] # synchronize access to @err_array @semaphore = Mutex.new Thread.new do until (line = stream.gets).nil? line.strip! @semaphore.synchronize { @err_array << line if line.size > 3 } end end end
[ "def", "handle_stderr", "(", "stream", ")", "@err_array", "=", "[", "]", "# synchronize access to @err_array", "@semaphore", "=", "Mutex", ".", "new", "Thread", ".", "new", "do", "until", "(", "line", "=", "stream", ".", "gets", ")", ".", "nil?", "line", ".", "strip!", "@semaphore", ".", "synchronize", "{", "@err_array", "<<", "line", "if", "line", ".", "size", ">", "3", "}", "end", "end", "end" ]
Start new thread that will read stderr given as stream and add errors into @err_array.
[ "Start", "new", "thread", "that", "will", "read", "stderr", "given", "as", "stream", "and", "add", "errors", "into" ]
0a3146386ae28fcbe2c09cb6e266fe40ebb659f4
https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/mixins/error_handling.rb#L36-L46
2,091
dilcom/gnuplotrb
lib/gnuplotrb/mixins/option_handling.rb
GnuplotRB.OptionHandling.option
def option(key, *value) if value.empty? value = options[key] value = value[0] if value && value.size == 1 value else options(key => value) end end
ruby
def option(key, *value) if value.empty? value = options[key] value = value[0] if value && value.size == 1 value else options(key => value) end end
[ "def", "option", "(", "key", ",", "*", "value", ")", "if", "value", ".", "empty?", "value", "=", "options", "[", "key", "]", "value", "=", "value", "[", "0", "]", "if", "value", "&&", "value", ".", "size", "==", "1", "value", "else", "options", "(", "key", "=>", "value", ")", "end", "end" ]
Return current option value if no value given. Create new object with given option set if value given.
[ "Return", "current", "option", "value", "if", "no", "value", "given", ".", "Create", "new", "object", "with", "given", "option", "set", "if", "value", "given", "." ]
0a3146386ae28fcbe2c09cb6e266fe40ebb659f4
https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/mixins/option_handling.rb#L174-L182
2,092
mezis/blurrily
lib/blurrily/client.rb
Blurrily.Client.put
def put(needle, ref, weight = 0) check_valid_needle(needle) check_valid_ref(ref) raise(ArgumentError, "WEIGHT value must be in #{WEIGHT_RANGE}") unless WEIGHT_RANGE.include?(weight) cmd = ["PUT", @db_name, needle, ref, weight] send_cmd_and_get_results(cmd) return end
ruby
def put(needle, ref, weight = 0) check_valid_needle(needle) check_valid_ref(ref) raise(ArgumentError, "WEIGHT value must be in #{WEIGHT_RANGE}") unless WEIGHT_RANGE.include?(weight) cmd = ["PUT", @db_name, needle, ref, weight] send_cmd_and_get_results(cmd) return end
[ "def", "put", "(", "needle", ",", "ref", ",", "weight", "=", "0", ")", "check_valid_needle", "(", "needle", ")", "check_valid_ref", "(", "ref", ")", "raise", "(", "ArgumentError", ",", "\"WEIGHT value must be in #{WEIGHT_RANGE}\"", ")", "unless", "WEIGHT_RANGE", ".", "include?", "(", "weight", ")", "cmd", "=", "[", "\"PUT\"", ",", "@db_name", ",", "needle", ",", "ref", ",", "weight", "]", "send_cmd_and_get_results", "(", "cmd", ")", "return", "end" ]
Index a given record. @param db_name The name of the data store being targeted. Required @param needle The string you wish to index. Must not contain tabs. Required @param ref The indentifying value of the record being indexed. Must be numeric. Required @param weight Weight of this particular reference. Default 0. Don't change unless you know what you're doing. Optional. Examples ``` @client.put('location_en', 'London', 123, 0) # => OK ``` @returns something to let you know that all is well.
[ "Index", "a", "given", "record", "." ]
496deee64a7e1c04b1241968dab46250e7b36569
https://github.com/mezis/blurrily/blob/496deee64a7e1c04b1241968dab46250e7b36569/lib/blurrily/client.rb#L76-L84
2,093
sparkleformation/sfn-parameters
lib/sfn-parameters/utils.rb
SfnParameters.Utils.lock_content
def lock_content(content) content = content.to_smash content.merge!(:sfn_lock_enabled => true) safe = SfnParameters::Safe.build( config.fetch(:sfn_parameters, :safe, Smash.new) ) safe.lock(dump_json(content)) end
ruby
def lock_content(content) content = content.to_smash content.merge!(:sfn_lock_enabled => true) safe = SfnParameters::Safe.build( config.fetch(:sfn_parameters, :safe, Smash.new) ) safe.lock(dump_json(content)) end
[ "def", "lock_content", "(", "content", ")", "content", "=", "content", ".", "to_smash", "content", ".", "merge!", "(", ":sfn_lock_enabled", "=>", "true", ")", "safe", "=", "SfnParameters", "::", "Safe", ".", "build", "(", "config", ".", "fetch", "(", ":sfn_parameters", ",", ":safe", ",", "Smash", ".", "new", ")", ")", "safe", ".", "lock", "(", "dump_json", "(", "content", ")", ")", "end" ]
Lock the given content @param content [Hash] content to lock @return [Hash] locked content
[ "Lock", "the", "given", "content" ]
9699a61327f1ef0603d967d0b597824290aa9001
https://github.com/sparkleformation/sfn-parameters/blob/9699a61327f1ef0603d967d0b597824290aa9001/lib/sfn-parameters/utils.rb#L11-L18
2,094
sparkleformation/sfn-parameters
lib/sfn-parameters/utils.rb
SfnParameters.Utils.unlock_content
def unlock_content(content) content = content.to_smash if content[:sfn_parameters_lock] safe = SfnParameters::Safe.build( config.fetch(:sfn_parameters, :safe, Smash.new) ) load_json(safe.unlock(content)).to_smash.merge(:sfn_lock_enabled => true) else content end end
ruby
def unlock_content(content) content = content.to_smash if content[:sfn_parameters_lock] safe = SfnParameters::Safe.build( config.fetch(:sfn_parameters, :safe, Smash.new) ) load_json(safe.unlock(content)).to_smash.merge(:sfn_lock_enabled => true) else content end end
[ "def", "unlock_content", "(", "content", ")", "content", "=", "content", ".", "to_smash", "if", "content", "[", ":sfn_parameters_lock", "]", "safe", "=", "SfnParameters", "::", "Safe", ".", "build", "(", "config", ".", "fetch", "(", ":sfn_parameters", ",", ":safe", ",", "Smash", ".", "new", ")", ")", "load_json", "(", "safe", ".", "unlock", "(", "content", ")", ")", ".", "to_smash", ".", "merge", "(", ":sfn_lock_enabled", "=>", "true", ")", "else", "content", "end", "end" ]
Unlock given content @param content [Hash] content to unlock @return [Hash] unlocked content
[ "Unlock", "given", "content" ]
9699a61327f1ef0603d967d0b597824290aa9001
https://github.com/sparkleformation/sfn-parameters/blob/9699a61327f1ef0603d967d0b597824290aa9001/lib/sfn-parameters/utils.rb#L24-L34
2,095
mediaburst/clockwork-ruby
lib/clockwork/api.rb
Clockwork.API.balance
def balance xml = Clockwork::XML::Balance.build( self ) response = Clockwork::HTTP.post( Clockwork::API::BALANCE_URL, xml, @use_ssl ) balance = Clockwork::XML::Balance.parse( response ) end
ruby
def balance xml = Clockwork::XML::Balance.build( self ) response = Clockwork::HTTP.post( Clockwork::API::BALANCE_URL, xml, @use_ssl ) balance = Clockwork::XML::Balance.parse( response ) end
[ "def", "balance", "xml", "=", "Clockwork", "::", "XML", "::", "Balance", ".", "build", "(", "self", ")", "response", "=", "Clockwork", "::", "HTTP", ".", "post", "(", "Clockwork", "::", "API", "::", "BALANCE_URL", ",", "xml", ",", "@use_ssl", ")", "balance", "=", "Clockwork", "::", "XML", "::", "Balance", ".", "parse", "(", "response", ")", "end" ]
Check the remaining credit for this account. @raise Clockwork::Error::Authentication - if API login details are incorrect @return [integer] Number of messages remaining
[ "Check", "the", "remaining", "credit", "for", "this", "account", "." ]
1c2a00ea56f68e9e8144601862b82e65ce77df85
https://github.com/mediaburst/clockwork-ruby/blob/1c2a00ea56f68e9e8144601862b82e65ce77df85/lib/clockwork/api.rb#L131-L135
2,096
dilcom/gnuplotrb
lib/gnuplotrb/multiplot.rb
GnuplotRB.Multiplot.mix_options
def mix_options(options) all_options = @options.merge(options) specific_options, plot_options = all_options.partition { |key, _value| specific_option?(key) } yield(plot_options, default_options.merge(specific_options)) end
ruby
def mix_options(options) all_options = @options.merge(options) specific_options, plot_options = all_options.partition { |key, _value| specific_option?(key) } yield(plot_options, default_options.merge(specific_options)) end
[ "def", "mix_options", "(", "options", ")", "all_options", "=", "@options", ".", "merge", "(", "options", ")", "specific_options", ",", "plot_options", "=", "all_options", ".", "partition", "{", "|", "key", ",", "_value", "|", "specific_option?", "(", "key", ")", "}", "yield", "(", "plot_options", ",", "default_options", ".", "merge", "(", "specific_options", ")", ")", "end" ]
Takes all options and splits them into specific and others. Requires a block where this two classes should be mixed.
[ "Takes", "all", "options", "and", "splits", "them", "into", "specific", "and", "others", ".", "Requires", "a", "block", "where", "this", "two", "classes", "should", "be", "mixed", "." ]
0a3146386ae28fcbe2c09cb6e266fe40ebb659f4
https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/multiplot.rb#L255-L259
2,097
flamontagne/rrschedule
lib/rrschedule.rb
RRSchedule.Schedule.generate
def generate(params={}) raise "You need to specify at least 1 team" if @teams.nil? || @teams.empty? raise "You need to specify at least 1 rule" if @rules.nil? || @rules.empty? arrange_flights init_stats @gamedays = []; @rounds = [] @flights.each_with_index do |teams,flight_id| current_cycle = current_round = 0 teams = teams.sort_by{rand} if @shuffle #loop to generate the whole round-robin(s) for the current flight begin t = teams.clone games = [] #process one round while !t.empty? do team_a = t.shift team_b = t.reverse!.shift t.reverse! x = (current_cycle % 2) == 0 ? [team_a,team_b] : [team_b,team_a] matchup = {:team_a => x[0], :team_b => x[1]} games << matchup end #done processing round current_round += 1 #Team rotation (the first team is fixed) teams = teams.insert(1,teams.delete_at(teams.size-1)) #add the round in memory @rounds ||= [] @rounds[flight_id] ||= [] @rounds[flight_id] << Round.new( :round => current_round, :cycle => current_cycle + 1, :round_with_cycle => current_cycle * (teams.size-1) + current_round, :flight => flight_id, :games => games.collect { |g| Game.new( :team_a => g[:team_a], :team_b => g[:team_b] ) } ) #done adding round #have we completed a full round-robin for the current flight? if current_round == teams.size-1 current_cycle += 1 current_round = 0 if current_cycle < self.cycles end end until current_round == teams.size-1 && current_cycle==self.cycles end dispatch_games(@rounds) self end
ruby
def generate(params={}) raise "You need to specify at least 1 team" if @teams.nil? || @teams.empty? raise "You need to specify at least 1 rule" if @rules.nil? || @rules.empty? arrange_flights init_stats @gamedays = []; @rounds = [] @flights.each_with_index do |teams,flight_id| current_cycle = current_round = 0 teams = teams.sort_by{rand} if @shuffle #loop to generate the whole round-robin(s) for the current flight begin t = teams.clone games = [] #process one round while !t.empty? do team_a = t.shift team_b = t.reverse!.shift t.reverse! x = (current_cycle % 2) == 0 ? [team_a,team_b] : [team_b,team_a] matchup = {:team_a => x[0], :team_b => x[1]} games << matchup end #done processing round current_round += 1 #Team rotation (the first team is fixed) teams = teams.insert(1,teams.delete_at(teams.size-1)) #add the round in memory @rounds ||= [] @rounds[flight_id] ||= [] @rounds[flight_id] << Round.new( :round => current_round, :cycle => current_cycle + 1, :round_with_cycle => current_cycle * (teams.size-1) + current_round, :flight => flight_id, :games => games.collect { |g| Game.new( :team_a => g[:team_a], :team_b => g[:team_b] ) } ) #done adding round #have we completed a full round-robin for the current flight? if current_round == teams.size-1 current_cycle += 1 current_round = 0 if current_cycle < self.cycles end end until current_round == teams.size-1 && current_cycle==self.cycles end dispatch_games(@rounds) self end
[ "def", "generate", "(", "params", "=", "{", "}", ")", "raise", "\"You need to specify at least 1 team\"", "if", "@teams", ".", "nil?", "||", "@teams", ".", "empty?", "raise", "\"You need to specify at least 1 rule\"", "if", "@rules", ".", "nil?", "||", "@rules", ".", "empty?", "arrange_flights", "init_stats", "@gamedays", "=", "[", "]", ";", "@rounds", "=", "[", "]", "@flights", ".", "each_with_index", "do", "|", "teams", ",", "flight_id", "|", "current_cycle", "=", "current_round", "=", "0", "teams", "=", "teams", ".", "sort_by", "{", "rand", "}", "if", "@shuffle", "#loop to generate the whole round-robin(s) for the current flight", "begin", "t", "=", "teams", ".", "clone", "games", "=", "[", "]", "#process one round", "while", "!", "t", ".", "empty?", "do", "team_a", "=", "t", ".", "shift", "team_b", "=", "t", ".", "reverse!", ".", "shift", "t", ".", "reverse!", "x", "=", "(", "current_cycle", "%", "2", ")", "==", "0", "?", "[", "team_a", ",", "team_b", "]", ":", "[", "team_b", ",", "team_a", "]", "matchup", "=", "{", ":team_a", "=>", "x", "[", "0", "]", ",", ":team_b", "=>", "x", "[", "1", "]", "}", "games", "<<", "matchup", "end", "#done processing round", "current_round", "+=", "1", "#Team rotation (the first team is fixed)", "teams", "=", "teams", ".", "insert", "(", "1", ",", "teams", ".", "delete_at", "(", "teams", ".", "size", "-", "1", ")", ")", "#add the round in memory", "@rounds", "||=", "[", "]", "@rounds", "[", "flight_id", "]", "||=", "[", "]", "@rounds", "[", "flight_id", "]", "<<", "Round", ".", "new", "(", ":round", "=>", "current_round", ",", ":cycle", "=>", "current_cycle", "+", "1", ",", ":round_with_cycle", "=>", "current_cycle", "*", "(", "teams", ".", "size", "-", "1", ")", "+", "current_round", ",", ":flight", "=>", "flight_id", ",", ":games", "=>", "games", ".", "collect", "{", "|", "g", "|", "Game", ".", "new", "(", ":team_a", "=>", "g", "[", ":team_a", "]", ",", ":team_b", "=>", "g", "[", ":team_b", "]", ")", "}", ")", "#done adding round", "#have we completed a full round-robin for the current flight?", "if", "current_round", "==", "teams", ".", "size", "-", "1", "current_cycle", "+=", "1", "current_round", "=", "0", "if", "current_cycle", "<", "self", ".", "cycles", "end", "end", "until", "current_round", "==", "teams", ".", "size", "-", "1", "&&", "current_cycle", "==", "self", ".", "cycles", "end", "dispatch_games", "(", "@rounds", ")", "self", "end" ]
This will generate the schedule based on the various parameters
[ "This", "will", "generate", "the", "schedule", "based", "on", "the", "various", "parameters" ]
7b334205e38901786a7569a6e96e49c24f9b425e
https://github.com/flamontagne/rrschedule/blob/7b334205e38901786a7569a6e96e49c24f9b425e/lib/rrschedule.rb#L24-L89
2,098
flamontagne/rrschedule
lib/rrschedule.rb
RRSchedule.Schedule.to_s
def to_s res = "" res << "#{self.gamedays.size.to_s} gamedays\n" self.gamedays.each do |gd| res << gd.date.strftime("%Y-%m-%d") + "\n" res << "==========\n" gd.games.sort{|g1,g2| g1.gt == g2.gt ? g1.ps <=> g2.ps : g1.gt <=> g2.gt}.each do |g| res << "#{g.ta.to_s} VS #{g.tb.to_s} on playing surface #{g.ps} at #{g.gt.strftime("%I:%M %p")}\n" end res << "\n" end res end
ruby
def to_s res = "" res << "#{self.gamedays.size.to_s} gamedays\n" self.gamedays.each do |gd| res << gd.date.strftime("%Y-%m-%d") + "\n" res << "==========\n" gd.games.sort{|g1,g2| g1.gt == g2.gt ? g1.ps <=> g2.ps : g1.gt <=> g2.gt}.each do |g| res << "#{g.ta.to_s} VS #{g.tb.to_s} on playing surface #{g.ps} at #{g.gt.strftime("%I:%M %p")}\n" end res << "\n" end res end
[ "def", "to_s", "res", "=", "\"\"", "res", "<<", "\"#{self.gamedays.size.to_s} gamedays\\n\"", "self", ".", "gamedays", ".", "each", "do", "|", "gd", "|", "res", "<<", "gd", ".", "date", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", "+", "\"\\n\"", "res", "<<", "\"==========\\n\"", "gd", ".", "games", ".", "sort", "{", "|", "g1", ",", "g2", "|", "g1", ".", "gt", "==", "g2", ".", "gt", "?", "g1", ".", "ps", "<=>", "g2", ".", "ps", ":", "g1", ".", "gt", "<=>", "g2", ".", "gt", "}", ".", "each", "do", "|", "g", "|", "res", "<<", "\"#{g.ta.to_s} VS #{g.tb.to_s} on playing surface #{g.ps} at #{g.gt.strftime(\"%I:%M %p\")}\\n\"", "end", "res", "<<", "\"\\n\"", "end", "res", "end" ]
human readable schedule
[ "human", "readable", "schedule" ]
7b334205e38901786a7569a6e96e49c24f9b425e
https://github.com/flamontagne/rrschedule/blob/7b334205e38901786a7569a6e96e49c24f9b425e/lib/rrschedule.rb#L101-L113
2,099
flamontagne/rrschedule
lib/rrschedule.rb
RRSchedule.Schedule.next_game_date
def next_game_date(dt,wday) dt += 1 until wday == dt.wday && !self.exclude_dates.include?(dt) dt end
ruby
def next_game_date(dt,wday) dt += 1 until wday == dt.wday && !self.exclude_dates.include?(dt) dt end
[ "def", "next_game_date", "(", "dt", ",", "wday", ")", "dt", "+=", "1", "until", "wday", "==", "dt", ".", "wday", "&&", "!", "self", ".", "exclude_dates", ".", "include?", "(", "dt", ")", "dt", "end" ]
get the next gameday
[ "get", "the", "next", "gameday" ]
7b334205e38901786a7569a6e96e49c24f9b425e
https://github.com/flamontagne/rrschedule/blob/7b334205e38901786a7569a6e96e49c24f9b425e/lib/rrschedule.rb#L258-L261