repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
scrapper/perobs
lib/perobs/DynamoDB.rb
PEROBS.DynamoDB.check_db
def check_db(repair = false) unless (item_counter = dynamo_get_item('item_counter')) && item_counter == @item_counter PEROBS.log.error "@item_counter variable (#{@item_counter}) and " + "item_counter table entry (#{item_counter}) don't match" end item_counter = 0 each_item { item_counter += 1 } unless item_counter == @item_counter PEROBS.log.error "Table contains #{item_counter} items but " + "@item_counter is #{@item_counter}" end end
ruby
def check_db(repair = false) unless (item_counter = dynamo_get_item('item_counter')) && item_counter == @item_counter PEROBS.log.error "@item_counter variable (#{@item_counter}) and " + "item_counter table entry (#{item_counter}) don't match" end item_counter = 0 each_item { item_counter += 1 } unless item_counter == @item_counter PEROBS.log.error "Table contains #{item_counter} items but " + "@item_counter is #{@item_counter}" end end
[ "def", "check_db", "(", "repair", "=", "false", ")", "unless", "(", "item_counter", "=", "dynamo_get_item", "(", "'item_counter'", ")", ")", "&&", "item_counter", "==", "@item_counter", "PEROBS", ".", "log", ".", "error", "\"@item_counter variable (#{@item_counter}) and \"", "+", "\"item_counter table entry (#{item_counter}) don't match\"", "end", "item_counter", "=", "0", "each_item", "{", "item_counter", "+=", "1", "}", "unless", "item_counter", "==", "@item_counter", "PEROBS", ".", "log", ".", "error", "\"Table contains #{item_counter} items but \"", "+", "\"@item_counter is #{@item_counter}\"", "end", "end" ]
Basic consistency check. @param repair [TrueClass/FalseClass] True if found errors should be repaired.
[ "Basic", "consistency", "check", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/DynamoDB.rb#L190-L202
train
scrapper/perobs
lib/perobs/ObjectBase.rb
PEROBS.POXReference.method_missing
def method_missing(method_sym, *args, &block) unless (obj = _referenced_object) ::PEROBS.log.fatal "Internal consistency error. No object with ID " + "#{@id} found in the store." end if obj.respond_to?(:is_poxreference?) ::PEROBS.log.fatal "POXReference that references a POXReference found." end obj.send(method_sym, *args, &block) end
ruby
def method_missing(method_sym, *args, &block) unless (obj = _referenced_object) ::PEROBS.log.fatal "Internal consistency error. No object with ID " + "#{@id} found in the store." end if obj.respond_to?(:is_poxreference?) ::PEROBS.log.fatal "POXReference that references a POXReference found." end obj.send(method_sym, *args, &block) end
[ "def", "method_missing", "(", "method_sym", ",", "*", "args", ",", "&", "block", ")", "unless", "(", "obj", "=", "_referenced_object", ")", "::", "PEROBS", ".", "log", ".", "fatal", "\"Internal consistency error. No object with ID \"", "+", "\"#{@id} found in the store.\"", "end", "if", "obj", ".", "respond_to?", "(", ":is_poxreference?", ")", "::", "PEROBS", ".", "log", ".", "fatal", "\"POXReference that references a POXReference found.\"", "end", "obj", ".", "send", "(", "method_sym", ",", "*", "args", ",", "&", "block", ")", "end" ]
Proxy all calls to unknown methods to the referenced object.
[ "Proxy", "all", "calls", "to", "unknown", "methods", "to", "the", "referenced", "object", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/ObjectBase.rb#L49-L58
train
scrapper/perobs
lib/perobs/ObjectBase.rb
PEROBS.ObjectBase._transfer
def _transfer(store) @store = store # Remove the previously defined finalizer as it is attached to the old # store. ObjectSpace.undefine_finalizer(self) # Register the object as in-memory object with the new store. @store._register_in_memory(self, @_id) # Register the finalizer for the new store. ObjectSpace.define_finalizer( self, ObjectBase._finalize(@store, @_id, object_id)) @myself = POXReference.new(@store, @_id) end
ruby
def _transfer(store) @store = store # Remove the previously defined finalizer as it is attached to the old # store. ObjectSpace.undefine_finalizer(self) # Register the object as in-memory object with the new store. @store._register_in_memory(self, @_id) # Register the finalizer for the new store. ObjectSpace.define_finalizer( self, ObjectBase._finalize(@store, @_id, object_id)) @myself = POXReference.new(@store, @_id) end
[ "def", "_transfer", "(", "store", ")", "@store", "=", "store", "ObjectSpace", ".", "undefine_finalizer", "(", "self", ")", "@store", ".", "_register_in_memory", "(", "self", ",", "@_id", ")", "ObjectSpace", ".", "define_finalizer", "(", "self", ",", "ObjectBase", ".", "_finalize", "(", "@store", ",", "@_id", ",", "object_id", ")", ")", "@myself", "=", "POXReference", ".", "new", "(", "@store", ",", "@_id", ")", "end" ]
Library internal method to transfer the Object to a new store. @param store [Store] New store
[ "Library", "internal", "method", "to", "transfer", "the", "Object", "to", "a", "new", "store", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/ObjectBase.rb#L172-L183
train
scrapper/perobs
lib/perobs/ObjectBase.rb
PEROBS.ObjectBase._restore
def _restore(level) # Find the most recently stored state of this object. This could be on # any previous stash level or in the regular object DB. If the object # was created during the transaction, there is not previous state to # restore to. data = nil if @_stash_map (level - 1).downto(0) do |lvl| break if (data = @_stash_map[lvl]) end end if data # We have a stashed version that we can restore from. _deserialize(data) elsif @store.db.include?(@_id) # We have no stashed version but can restore from the database. db_obj = store.db.get_object(@_id) _deserialize(db_obj['data']) end end
ruby
def _restore(level) # Find the most recently stored state of this object. This could be on # any previous stash level or in the regular object DB. If the object # was created during the transaction, there is not previous state to # restore to. data = nil if @_stash_map (level - 1).downto(0) do |lvl| break if (data = @_stash_map[lvl]) end end if data # We have a stashed version that we can restore from. _deserialize(data) elsif @store.db.include?(@_id) # We have no stashed version but can restore from the database. db_obj = store.db.get_object(@_id) _deserialize(db_obj['data']) end end
[ "def", "_restore", "(", "level", ")", "data", "=", "nil", "if", "@_stash_map", "(", "level", "-", "1", ")", ".", "downto", "(", "0", ")", "do", "|", "lvl", "|", "break", "if", "(", "data", "=", "@_stash_map", "[", "lvl", "]", ")", "end", "end", "if", "data", "_deserialize", "(", "data", ")", "elsif", "@store", ".", "db", ".", "include?", "(", "@_id", ")", "db_obj", "=", "store", ".", "db", ".", "get_object", "(", "@_id", ")", "_deserialize", "(", "db_obj", "[", "'data'", "]", ")", "end", "end" ]
Restore the object state from the storage back-end. @param level [Integer] the transaction nesting level
[ "Restore", "the", "object", "state", "from", "the", "storage", "back", "-", "end", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/ObjectBase.rb#L250-L269
train
Absolight/epp-client
lib/epp-client/domain.rb
EPPClient.Domain.domain_check
def domain_check(*domains) domains.flatten! response = send_request(domain_check_xml(*domains)) get_result(:xml => response, :callback => :domain_check_process) end
ruby
def domain_check(*domains) domains.flatten! response = send_request(domain_check_xml(*domains)) get_result(:xml => response, :callback => :domain_check_process) end
[ "def", "domain_check", "(", "*", "domains", ")", "domains", ".", "flatten!", "response", "=", "send_request", "(", "domain_check_xml", "(", "*", "domains", ")", ")", "get_result", "(", ":xml", "=>", "response", ",", ":callback", "=>", ":domain_check_process", ")", "end" ]
Check the availability of domains takes a list of domains as arguments returns an array of hashes containing three fields : [<tt>:name</tt>] The domain name [<tt>:avail</tt>] Wether the domain is available or not. [<tt>:reason</tt>] The reason for non availability, if given.
[ "Check", "the", "availability", "of", "domains" ]
c0025daee5e7087f60b654595a8e7d92e966c54e
https://github.com/Absolight/epp-client/blob/c0025daee5e7087f60b654595a8e7d92e966c54e/lib/epp-client/domain.rb#L29-L34
train
Absolight/epp-client
lib/epp-client/domain.rb
EPPClient.Domain.domain_info
def domain_info(args) args = { :name => args } if args.is_a?(String) response = send_request(domain_info_xml(args)) get_result(:xml => response, :callback => :domain_info_process) end
ruby
def domain_info(args) args = { :name => args } if args.is_a?(String) response = send_request(domain_info_xml(args)) get_result(:xml => response, :callback => :domain_info_process) end
[ "def", "domain_info", "(", "args", ")", "args", "=", "{", ":name", "=>", "args", "}", "if", "args", ".", "is_a?", "(", "String", ")", "response", "=", "send_request", "(", "domain_info_xml", "(", "args", ")", ")", "get_result", "(", ":xml", "=>", "response", ",", ":callback", "=>", ":domain_info_process", ")", "end" ]
Returns the informations about a domain Takes either a unique argument, a string, representing the domain, or a hash with : <tt>:name</tt> the domain name, and optionnaly <tt>:authInfo</tt> the authentication information and possibly <tt>:roid</tt> the contact the authInfo is about. Returned is a hash mapping as closely as possible the result expected from the command as per Section {3.1.2}[https://tools.ietf.org/html/rfc5731#section-3.1.2] of {RFC 5731}[https://tools.ietf.org/html/rfc5731] : [<tt>:name</tt>] The fully qualified name of the domain object. [<tt>:roid</tt>] The Repository Object IDentifier assigned to the domain object when the object was created. [<tt>:status</tt>] an optionnal array of elements that contain the current status descriptors associated with the domain. [<tt>:registrant</tt>] one optionnal registrant nic handle. [<tt>:contacts</tt>] an optionnal hash which keys are choosen between +admin+, +billing+ and +tech+ and which values are arrays of nic handles for the corresponding contact types. [<tt>:ns</tt>] an optional array containing nameservers informations, which can either be an array of strings containing the the fully qualified name of a host, or an array of hashes containing the following keys : [<tt>:hostName</tt>] the fully qualified name of a host. [<tt>:hostAddrv4</tt>] an optionnal array of ipv4 addresses to be associated with the host. [<tt>:hostAddrv6</tt>] an optionnal array of ipv6 addresses to be associated with the host. [<tt>:host</tt>] an optionnal array of fully qualified names of the subordinate host objects that exist under this superordinate domain object. [<tt>:clID</tt>] the identifier of the sponsoring client. [<tt>:crID</tt>] an optional identifier of the client that created the domain object. [<tt>:crDate</tt>] an optional date and time of domain object creation. [<tt>:exDate</tt>] the date and time identifying the end of the domain object's registration period. [<tt>:upID</tt>] the identifier of the client that last updated the domain object. [<tt>:upDate</tt>] the date and time of the most recent domain-object modification. [<tt>:trDate</tt>] the date and time of the most recent successful domain-object transfer. [<tt>:authInfo</tt>] authorization information associated with the domain object.
[ "Returns", "the", "informations", "about", "a", "domain" ]
c0025daee5e7087f60b654595a8e7d92e966c54e
https://github.com/Absolight/epp-client/blob/c0025daee5e7087f60b654595a8e7d92e966c54e/lib/epp-client/domain.rb#L118-L123
train
scrapper/perobs
lib/perobs/EquiBlobsFile.rb
PEROBS.EquiBlobsFile.set_custom_data
def set_custom_data(name, value) unless @custom_data_labels.include?(name) PEROBS.log.fatal "Unknown custom data field #{name}" end @custom_data_values[@custom_data_labels.index(name)] = value write_header if @f end
ruby
def set_custom_data(name, value) unless @custom_data_labels.include?(name) PEROBS.log.fatal "Unknown custom data field #{name}" end @custom_data_values[@custom_data_labels.index(name)] = value write_header if @f end
[ "def", "set_custom_data", "(", "name", ",", "value", ")", "unless", "@custom_data_labels", ".", "include?", "(", "name", ")", "PEROBS", ".", "log", ".", "fatal", "\"Unknown custom data field #{name}\"", "end", "@custom_data_values", "[", "@custom_data_labels", ".", "index", "(", "name", ")", "]", "=", "value", "write_header", "if", "@f", "end" ]
Set the registered custom data field to the given value. @param name [String] Label of the offset @param value [Integer] Value
[ "Set", "the", "registered", "custom", "data", "field", "to", "the", "given", "value", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/EquiBlobsFile.rb#L146-L153
train
scrapper/perobs
lib/perobs/EquiBlobsFile.rb
PEROBS.EquiBlobsFile.free_address
def free_address if @first_space == 0 # There is currently no free entry. Create a new reserved entry at the # end of the file. begin offset = @f.size @f.seek(offset) write_n_bytes([1] + ::Array.new(@entry_bytes, 0)) write_header return offset_to_address(offset) rescue IOError => e PEROBS.log.fatal "Cannot create reserved space at #{@first_space} " + "in EquiBlobsFile #{@file_name}: #{e.message}" end else begin free_space_address = offset_to_address(@first_space) @f.seek(@first_space) marker = read_char @first_space = read_unsigned_int unless marker == 0 PEROBS.log.fatal "Free space list of EquiBlobsFile #{@file_name} " + "points to non-empty entry at address #{@first_space}" end # Mark entry as reserved by setting the mark byte to 1. @f.seek(-(1 + 8), IO::SEEK_CUR) write_char(1) # Update the file header @total_spaces -= 1 write_header return free_space_address rescue IOError => e PEROBS.log.fatal "Cannot mark reserved space at " + "#{free_space_address} in EquiBlobsFile #{@file_name}: " + "#{e.message}" end end end
ruby
def free_address if @first_space == 0 # There is currently no free entry. Create a new reserved entry at the # end of the file. begin offset = @f.size @f.seek(offset) write_n_bytes([1] + ::Array.new(@entry_bytes, 0)) write_header return offset_to_address(offset) rescue IOError => e PEROBS.log.fatal "Cannot create reserved space at #{@first_space} " + "in EquiBlobsFile #{@file_name}: #{e.message}" end else begin free_space_address = offset_to_address(@first_space) @f.seek(@first_space) marker = read_char @first_space = read_unsigned_int unless marker == 0 PEROBS.log.fatal "Free space list of EquiBlobsFile #{@file_name} " + "points to non-empty entry at address #{@first_space}" end # Mark entry as reserved by setting the mark byte to 1. @f.seek(-(1 + 8), IO::SEEK_CUR) write_char(1) # Update the file header @total_spaces -= 1 write_header return free_space_address rescue IOError => e PEROBS.log.fatal "Cannot mark reserved space at " + "#{free_space_address} in EquiBlobsFile #{@file_name}: " + "#{e.message}" end end end
[ "def", "free_address", "if", "@first_space", "==", "0", "begin", "offset", "=", "@f", ".", "size", "@f", ".", "seek", "(", "offset", ")", "write_n_bytes", "(", "[", "1", "]", "+", "::", "Array", ".", "new", "(", "@entry_bytes", ",", "0", ")", ")", "write_header", "return", "offset_to_address", "(", "offset", ")", "rescue", "IOError", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannot create reserved space at #{@first_space} \"", "+", "\"in EquiBlobsFile #{@file_name}: #{e.message}\"", "end", "else", "begin", "free_space_address", "=", "offset_to_address", "(", "@first_space", ")", "@f", ".", "seek", "(", "@first_space", ")", "marker", "=", "read_char", "@first_space", "=", "read_unsigned_int", "unless", "marker", "==", "0", "PEROBS", ".", "log", ".", "fatal", "\"Free space list of EquiBlobsFile #{@file_name} \"", "+", "\"points to non-empty entry at address #{@first_space}\"", "end", "@f", ".", "seek", "(", "-", "(", "1", "+", "8", ")", ",", "IO", "::", "SEEK_CUR", ")", "write_char", "(", "1", ")", "@total_spaces", "-=", "1", "write_header", "return", "free_space_address", "rescue", "IOError", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannot mark reserved space at \"", "+", "\"#{free_space_address} in EquiBlobsFile #{@file_name}: \"", "+", "\"#{e.message}\"", "end", "end", "end" ]
Return the address of a free blob storage space. Addresses start at 0 and increase linearly. @return [Integer] address of a free blob space
[ "Return", "the", "address", "of", "a", "free", "blob", "storage", "space", ".", "Addresses", "start", "at", "0", "and", "increase", "linearly", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/EquiBlobsFile.rb#L204-L242
train
scrapper/perobs
lib/perobs/EquiBlobsFile.rb
PEROBS.EquiBlobsFile.store_blob
def store_blob(address, bytes) unless address >= 0 PEROBS.log.fatal "Blob storage address must be larger than 0, " + "not #{address}" end if bytes.length != @entry_bytes PEROBS.log.fatal "All stack entries must be #{@entry_bytes} " + "long. This entry is #{bytes.length} bytes long." end marker = 1 begin offset = address_to_offset(address) if offset > (file_size = @f.size) PEROBS.log.fatal "Cannot store blob at address #{address} in " + "EquiBlobsFile #{@file_name}. Address is larger than file size. " + "Offset: #{offset} File size: #{file_size}" end @f.seek(offset) # The first byte is the marker byte. It's set to 2 for cells that hold # a blob. 1 for reserved cells and 0 for empty cells. The cell must be # either already be in use or be reserved. It must not be 0. if file_size > offset && (marker = read_char) != 1 && marker != 2 PEROBS.log.fatal "Marker for entry at address #{address} of " + "EquiBlobsFile #{@file_name} must be 1 or 2 but is #{marker}" end @f.seek(offset) write_char(2) @f.write(bytes) @f.flush rescue IOError => e PEROBS.log.fatal "Cannot store blob at address #{address} in " + "EquiBlobsFile #{@file_name}: #{e.message}" end # Update the entries counter if we inserted a new blob. if marker == 1 @total_entries += 1 write_header end end
ruby
def store_blob(address, bytes) unless address >= 0 PEROBS.log.fatal "Blob storage address must be larger than 0, " + "not #{address}" end if bytes.length != @entry_bytes PEROBS.log.fatal "All stack entries must be #{@entry_bytes} " + "long. This entry is #{bytes.length} bytes long." end marker = 1 begin offset = address_to_offset(address) if offset > (file_size = @f.size) PEROBS.log.fatal "Cannot store blob at address #{address} in " + "EquiBlobsFile #{@file_name}. Address is larger than file size. " + "Offset: #{offset} File size: #{file_size}" end @f.seek(offset) # The first byte is the marker byte. It's set to 2 for cells that hold # a blob. 1 for reserved cells and 0 for empty cells. The cell must be # either already be in use or be reserved. It must not be 0. if file_size > offset && (marker = read_char) != 1 && marker != 2 PEROBS.log.fatal "Marker for entry at address #{address} of " + "EquiBlobsFile #{@file_name} must be 1 or 2 but is #{marker}" end @f.seek(offset) write_char(2) @f.write(bytes) @f.flush rescue IOError => e PEROBS.log.fatal "Cannot store blob at address #{address} in " + "EquiBlobsFile #{@file_name}: #{e.message}" end # Update the entries counter if we inserted a new blob. if marker == 1 @total_entries += 1 write_header end end
[ "def", "store_blob", "(", "address", ",", "bytes", ")", "unless", "address", ">=", "0", "PEROBS", ".", "log", ".", "fatal", "\"Blob storage address must be larger than 0, \"", "+", "\"not #{address}\"", "end", "if", "bytes", ".", "length", "!=", "@entry_bytes", "PEROBS", ".", "log", ".", "fatal", "\"All stack entries must be #{@entry_bytes} \"", "+", "\"long. This entry is #{bytes.length} bytes long.\"", "end", "marker", "=", "1", "begin", "offset", "=", "address_to_offset", "(", "address", ")", "if", "offset", ">", "(", "file_size", "=", "@f", ".", "size", ")", "PEROBS", ".", "log", ".", "fatal", "\"Cannot store blob at address #{address} in \"", "+", "\"EquiBlobsFile #{@file_name}. Address is larger than file size. \"", "+", "\"Offset: #{offset} File size: #{file_size}\"", "end", "@f", ".", "seek", "(", "offset", ")", "if", "file_size", ">", "offset", "&&", "(", "marker", "=", "read_char", ")", "!=", "1", "&&", "marker", "!=", "2", "PEROBS", ".", "log", ".", "fatal", "\"Marker for entry at address #{address} of \"", "+", "\"EquiBlobsFile #{@file_name} must be 1 or 2 but is #{marker}\"", "end", "@f", ".", "seek", "(", "offset", ")", "write_char", "(", "2", ")", "@f", ".", "write", "(", "bytes", ")", "@f", ".", "flush", "rescue", "IOError", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannot store blob at address #{address} in \"", "+", "\"EquiBlobsFile #{@file_name}: #{e.message}\"", "end", "if", "marker", "==", "1", "@total_entries", "+=", "1", "write_header", "end", "end" ]
Store the given byte blob at the specified address. If the blob space is already in use the content will be overwritten. @param address [Integer] Address to store the blob @param bytes [String] bytes to store
[ "Store", "the", "given", "byte", "blob", "at", "the", "specified", "address", ".", "If", "the", "blob", "space", "is", "already", "in", "use", "the", "content", "will", "be", "overwritten", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/EquiBlobsFile.rb#L248-L290
train
scrapper/perobs
lib/perobs/EquiBlobsFile.rb
PEROBS.EquiBlobsFile.retrieve_blob
def retrieve_blob(address) unless address > 0 PEROBS.log.fatal "Blob retrieval address must be larger than 0, " + "not #{address}" end begin if (offset = address_to_offset(address)) >= @f.size PEROBS.log.fatal "Cannot retrieve blob at address #{address} " + "of EquiBlobsFile #{@file_name}. Address is beyond end of file." end @f.seek(address_to_offset(address)) if (marker = read_char) != 2 PEROBS.log.fatal "Cannot retrieve blob at address #{address} " + "of EquiBlobsFile #{@file_name}. Blob is " + (marker == 0 ? 'empty' : marker == 1 ? 'reserved' : 'corrupted') + '.' end bytes = @f.read(@entry_bytes) rescue IOError => e PEROBS.log.fatal "Cannot retrieve blob at adress #{address} " + "of EquiBlobsFile #{@file_name}: " + e.message end bytes end
ruby
def retrieve_blob(address) unless address > 0 PEROBS.log.fatal "Blob retrieval address must be larger than 0, " + "not #{address}" end begin if (offset = address_to_offset(address)) >= @f.size PEROBS.log.fatal "Cannot retrieve blob at address #{address} " + "of EquiBlobsFile #{@file_name}. Address is beyond end of file." end @f.seek(address_to_offset(address)) if (marker = read_char) != 2 PEROBS.log.fatal "Cannot retrieve blob at address #{address} " + "of EquiBlobsFile #{@file_name}. Blob is " + (marker == 0 ? 'empty' : marker == 1 ? 'reserved' : 'corrupted') + '.' end bytes = @f.read(@entry_bytes) rescue IOError => e PEROBS.log.fatal "Cannot retrieve blob at adress #{address} " + "of EquiBlobsFile #{@file_name}: " + e.message end bytes end
[ "def", "retrieve_blob", "(", "address", ")", "unless", "address", ">", "0", "PEROBS", ".", "log", ".", "fatal", "\"Blob retrieval address must be larger than 0, \"", "+", "\"not #{address}\"", "end", "begin", "if", "(", "offset", "=", "address_to_offset", "(", "address", ")", ")", ">=", "@f", ".", "size", "PEROBS", ".", "log", ".", "fatal", "\"Cannot retrieve blob at address #{address} \"", "+", "\"of EquiBlobsFile #{@file_name}. Address is beyond end of file.\"", "end", "@f", ".", "seek", "(", "address_to_offset", "(", "address", ")", ")", "if", "(", "marker", "=", "read_char", ")", "!=", "2", "PEROBS", ".", "log", ".", "fatal", "\"Cannot retrieve blob at address #{address} \"", "+", "\"of EquiBlobsFile #{@file_name}. Blob is \"", "+", "(", "marker", "==", "0", "?", "'empty'", ":", "marker", "==", "1", "?", "'reserved'", ":", "'corrupted'", ")", "+", "'.'", "end", "bytes", "=", "@f", ".", "read", "(", "@entry_bytes", ")", "rescue", "IOError", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannot retrieve blob at adress #{address} \"", "+", "\"of EquiBlobsFile #{@file_name}: \"", "+", "e", ".", "message", "end", "bytes", "end" ]
Retrieve a blob from the given address. @param address [Integer] Address to store the blob @return [String] blob bytes
[ "Retrieve", "a", "blob", "from", "the", "given", "address", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/EquiBlobsFile.rb#L295-L321
train
scrapper/perobs
lib/perobs/EquiBlobsFile.rb
PEROBS.EquiBlobsFile.delete_blob
def delete_blob(address) unless address >= 0 PEROBS.log.fatal "Blob address must be larger than 0, " + "not #{address}" end offset = address_to_offset(address) begin @f.seek(offset) if (marker = read_char) != 1 && marker != 2 PEROBS.log.fatal "Cannot delete blob stored at address #{address} " + "of EquiBlobsFile #{@file_name}. Blob is " + (marker == 0 ? 'empty' : 'corrupted') + '.' end @f.seek(address_to_offset(address)) write_char(0) write_unsigned_int(@first_space) rescue IOError => e PEROBS.log.fatal "Cannot delete blob at address #{address}: " + e.message end @first_space = offset @total_spaces += 1 @total_entries -= 1 unless marker == 1 write_header if offset == @f.size - 1 - @entry_bytes # We have deleted the last entry in the file. Make sure that all empty # entries are removed up to the now new last used entry. trim_file end end
ruby
def delete_blob(address) unless address >= 0 PEROBS.log.fatal "Blob address must be larger than 0, " + "not #{address}" end offset = address_to_offset(address) begin @f.seek(offset) if (marker = read_char) != 1 && marker != 2 PEROBS.log.fatal "Cannot delete blob stored at address #{address} " + "of EquiBlobsFile #{@file_name}. Blob is " + (marker == 0 ? 'empty' : 'corrupted') + '.' end @f.seek(address_to_offset(address)) write_char(0) write_unsigned_int(@first_space) rescue IOError => e PEROBS.log.fatal "Cannot delete blob at address #{address}: " + e.message end @first_space = offset @total_spaces += 1 @total_entries -= 1 unless marker == 1 write_header if offset == @f.size - 1 - @entry_bytes # We have deleted the last entry in the file. Make sure that all empty # entries are removed up to the now new last used entry. trim_file end end
[ "def", "delete_blob", "(", "address", ")", "unless", "address", ">=", "0", "PEROBS", ".", "log", ".", "fatal", "\"Blob address must be larger than 0, \"", "+", "\"not #{address}\"", "end", "offset", "=", "address_to_offset", "(", "address", ")", "begin", "@f", ".", "seek", "(", "offset", ")", "if", "(", "marker", "=", "read_char", ")", "!=", "1", "&&", "marker", "!=", "2", "PEROBS", ".", "log", ".", "fatal", "\"Cannot delete blob stored at address #{address} \"", "+", "\"of EquiBlobsFile #{@file_name}. Blob is \"", "+", "(", "marker", "==", "0", "?", "'empty'", ":", "'corrupted'", ")", "+", "'.'", "end", "@f", ".", "seek", "(", "address_to_offset", "(", "address", ")", ")", "write_char", "(", "0", ")", "write_unsigned_int", "(", "@first_space", ")", "rescue", "IOError", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannot delete blob at address #{address}: \"", "+", "e", ".", "message", "end", "@first_space", "=", "offset", "@total_spaces", "+=", "1", "@total_entries", "-=", "1", "unless", "marker", "==", "1", "write_header", "if", "offset", "==", "@f", ".", "size", "-", "1", "-", "@entry_bytes", "trim_file", "end", "end" ]
Delete the blob at the given address. @param address [Integer] Address of blob to delete
[ "Delete", "the", "blob", "at", "the", "given", "address", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/EquiBlobsFile.rb#L325-L357
train
scrapper/perobs
lib/perobs/EquiBlobsFile.rb
PEROBS.EquiBlobsFile.check
def check sync return false unless check_spaces return false unless check_entries expected_size = address_to_offset(@total_entries + @total_spaces + 1) actual_size = @f.size if actual_size != expected_size PEROBS.log.error "Size mismatch in EquiBlobsFile #{@file_name}. " + "Expected #{expected_size} bytes but found #{actual_size} bytes." return false end true end
ruby
def check sync return false unless check_spaces return false unless check_entries expected_size = address_to_offset(@total_entries + @total_spaces + 1) actual_size = @f.size if actual_size != expected_size PEROBS.log.error "Size mismatch in EquiBlobsFile #{@file_name}. " + "Expected #{expected_size} bytes but found #{actual_size} bytes." return false end true end
[ "def", "check", "sync", "return", "false", "unless", "check_spaces", "return", "false", "unless", "check_entries", "expected_size", "=", "address_to_offset", "(", "@total_entries", "+", "@total_spaces", "+", "1", ")", "actual_size", "=", "@f", ".", "size", "if", "actual_size", "!=", "expected_size", "PEROBS", ".", "log", ".", "error", "\"Size mismatch in EquiBlobsFile #{@file_name}. \"", "+", "\"Expected #{expected_size} bytes but found #{actual_size} bytes.\"", "return", "false", "end", "true", "end" ]
Check the file for logical errors. @return [Boolean] true of file has no errors, false otherwise.
[ "Check", "the", "file", "for", "logical", "errors", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/EquiBlobsFile.rb#L361-L376
train
scrapper/perobs
lib/perobs/Log.rb
PEROBS.ILogger.open
def open(io) begin @@logger = Logger.new(io, *@@options) rescue IOError => e @@logger = Logger.new($stderr) $stderr.puts "Cannot open log file: #{e.message}" end @@logger.level = @@level @@logger.formatter = @@formatter end
ruby
def open(io) begin @@logger = Logger.new(io, *@@options) rescue IOError => e @@logger = Logger.new($stderr) $stderr.puts "Cannot open log file: #{e.message}" end @@logger.level = @@level @@logger.formatter = @@formatter end
[ "def", "open", "(", "io", ")", "begin", "@@logger", "=", "Logger", ".", "new", "(", "io", ",", "*", "@@options", ")", "rescue", "IOError", "=>", "e", "@@logger", "=", "Logger", ".", "new", "(", "$stderr", ")", "$stderr", ".", "puts", "\"Cannot open log file: #{e.message}\"", "end", "@@logger", ".", "level", "=", "@@level", "@@logger", ".", "formatter", "=", "@@formatter", "end" ]
Redirect all log messages to the given IO. @param io [IO] Output file descriptor
[ "Redirect", "all", "log", "messages", "to", "the", "given", "IO", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Log.rb#L81-L90
train
scrapper/perobs
lib/perobs/ClassMap.rb
PEROBS.ClassMap.rename
def rename(rename_map) @by_id.each.with_index do |klass, id| # Some entries can be nil. Ignore them. next unless klass if (new_name = rename_map[klass]) # We have a rename request. Update the current @by_id entry. @by_id[id] = new_name # Remove the old class name from @by_class hash. @by_class.delete(klass) # Insert the new one with the current ID. @by_class[new_name] = id end end end
ruby
def rename(rename_map) @by_id.each.with_index do |klass, id| # Some entries can be nil. Ignore them. next unless klass if (new_name = rename_map[klass]) # We have a rename request. Update the current @by_id entry. @by_id[id] = new_name # Remove the old class name from @by_class hash. @by_class.delete(klass) # Insert the new one with the current ID. @by_class[new_name] = id end end end
[ "def", "rename", "(", "rename_map", ")", "@by_id", ".", "each", ".", "with_index", "do", "|", "klass", ",", "id", "|", "next", "unless", "klass", "if", "(", "new_name", "=", "rename_map", "[", "klass", "]", ")", "@by_id", "[", "id", "]", "=", "new_name", "@by_class", ".", "delete", "(", "klass", ")", "@by_class", "[", "new_name", "]", "=", "id", "end", "end", "end" ]
Rename a set of classes to new names. @param rename_map [Hash] Hash that maps old names to new names
[ "Rename", "a", "set", "of", "classes", "to", "new", "names", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/ClassMap.rb#L65-L79
train
scrapper/perobs
lib/perobs/ClassMap.rb
PEROBS.ClassMap.keep
def keep(classes) @by_id.each.with_index do |klass, id| unless classes.include?(klass) # Delete the class from the @by_id list by setting the entry to nil. @by_id[id] = nil # Delete the corresponding @by_class entry as well. @by_class.delete(klass) end end end
ruby
def keep(classes) @by_id.each.with_index do |klass, id| unless classes.include?(klass) # Delete the class from the @by_id list by setting the entry to nil. @by_id[id] = nil # Delete the corresponding @by_class entry as well. @by_class.delete(klass) end end end
[ "def", "keep", "(", "classes", ")", "@by_id", ".", "each", ".", "with_index", "do", "|", "klass", ",", "id", "|", "unless", "classes", ".", "include?", "(", "klass", ")", "@by_id", "[", "id", "]", "=", "nil", "@by_class", ".", "delete", "(", "klass", ")", "end", "end", "end" ]
Delete all classes unless they are contained in _classes_. @param classes [Array of String] List of the class names
[ "Delete", "all", "classes", "unless", "they", "are", "contained", "in", "_classes_", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/ClassMap.rb#L83-L92
train
mreq/wmctile
lib/wmctile/memory.rb
Wmctile.Memory.read_file
def read_file @file_path = '~/.local/share/wmctile' @file_name = 'memory.yml' @file_full = File.expand_path([@file_path, @file_name].join('/')) if File.exist? @file_full file_contents = File.read(@file_full) @memory = YAML.load(file_contents) else create_file write_file end end
ruby
def read_file @file_path = '~/.local/share/wmctile' @file_name = 'memory.yml' @file_full = File.expand_path([@file_path, @file_name].join('/')) if File.exist? @file_full file_contents = File.read(@file_full) @memory = YAML.load(file_contents) else create_file write_file end end
[ "def", "read_file", "@file_path", "=", "'~/.local/share/wmctile'", "@file_name", "=", "'memory.yml'", "@file_full", "=", "File", ".", "expand_path", "(", "[", "@file_path", ",", "@file_name", "]", ".", "join", "(", "'/'", ")", ")", "if", "File", ".", "exist?", "@file_full", "file_contents", "=", "File", ".", "read", "(", "@file_full", ")", "@memory", "=", "YAML", ".", "load", "(", "file_contents", ")", "else", "create_file", "write_file", "end", "end" ]
Memory init function. Creates a default yaml file if it's non-existent. Reads the yaml file, creating it if non-existent. @return [void]
[ "Memory", "init", "function", ".", "Creates", "a", "default", "yaml", "file", "if", "it", "s", "non", "-", "existent", "." ]
a41af5afa310b09c8ba1bd45a134b9b2a87d1a35
https://github.com/mreq/wmctile/blob/a41af5afa310b09c8ba1bd45a134b9b2a87d1a35/lib/wmctile/memory.rb#L20-L32
train
sethvargo/community-zero
lib/community_zero/endpoint.rb
CommunityZero.Endpoint.call
def call(request) m = request.method.downcase.to_sym # Only respond to listed methods unless respond_to?(m) allowed = METHODS.select { |m| respond_to?(m) }.map(&:upcase).join(', ') return [ 405, { 'Content-Type' => 'text/plain', 'Allow' => allowed }, "Method not allowed: '#{request.env['REQUEST_METHOD']}'" ] end begin send(m, request) rescue RestError => e error(e.response_code, e.error) end end
ruby
def call(request) m = request.method.downcase.to_sym # Only respond to listed methods unless respond_to?(m) allowed = METHODS.select { |m| respond_to?(m) }.map(&:upcase).join(', ') return [ 405, { 'Content-Type' => 'text/plain', 'Allow' => allowed }, "Method not allowed: '#{request.env['REQUEST_METHOD']}'" ] end begin send(m, request) rescue RestError => e error(e.response_code, e.error) end end
[ "def", "call", "(", "request", ")", "m", "=", "request", ".", "method", ".", "downcase", ".", "to_sym", "unless", "respond_to?", "(", "m", ")", "allowed", "=", "METHODS", ".", "select", "{", "|", "m", "|", "respond_to?", "(", "m", ")", "}", ".", "map", "(", "&", ":upcase", ")", ".", "join", "(", "', '", ")", "return", "[", "405", ",", "{", "'Content-Type'", "=>", "'text/plain'", ",", "'Allow'", "=>", "allowed", "}", ",", "\"Method not allowed: '#{request.env['REQUEST_METHOD']}'\"", "]", "end", "begin", "send", "(", "m", ",", "request", ")", "rescue", "RestError", "=>", "e", "error", "(", "e", ".", "response_code", ",", "e", ".", "error", ")", "end", "end" ]
Call the request. @param [CommunityZero::Request] request the request object
[ "Call", "the", "request", "." ]
08a22c47c865deb6a5f931cb4d9f747a2b9d3459
https://github.com/sethvargo/community-zero/blob/08a22c47c865deb6a5f931cb4d9f747a2b9d3459/lib/community_zero/endpoint.rb#L76-L94
train
code-and-effect/effective_pages
app/models/effective/page.rb
Effective.Page.duplicate!
def duplicate! Page.new(attributes.except('id', 'updated_at', 'created_at')).tap do |page| page.title = page.title + ' (Copy)' page.slug = page.slug + '-copy' page.draft = true regions.each do |region| page.regions.build(region.attributes.except('id', 'updated_at', 'created_at')) end page.save! end end
ruby
def duplicate! Page.new(attributes.except('id', 'updated_at', 'created_at')).tap do |page| page.title = page.title + ' (Copy)' page.slug = page.slug + '-copy' page.draft = true regions.each do |region| page.regions.build(region.attributes.except('id', 'updated_at', 'created_at')) end page.save! end end
[ "def", "duplicate!", "Page", ".", "new", "(", "attributes", ".", "except", "(", "'id'", ",", "'updated_at'", ",", "'created_at'", ")", ")", ".", "tap", "do", "|", "page", "|", "page", ".", "title", "=", "page", ".", "title", "+", "' (Copy)'", "page", ".", "slug", "=", "page", ".", "slug", "+", "'-copy'", "page", ".", "draft", "=", "true", "regions", ".", "each", "do", "|", "region", "|", "page", ".", "regions", ".", "build", "(", "region", ".", "attributes", ".", "except", "(", "'id'", ",", "'updated_at'", ",", "'created_at'", ")", ")", "end", "page", ".", "save!", "end", "end" ]
Returns a duplicated post object, or throws an exception
[ "Returns", "a", "duplicated", "post", "object", "or", "throws", "an", "exception" ]
ff00e2d76055985ab65f570747bc9a5f2748f817
https://github.com/code-and-effect/effective_pages/blob/ff00e2d76055985ab65f570747bc9a5f2748f817/app/models/effective/page.rb#L46-L58
train
sagmor/yard-mruby
lib/yard/mruby/parser/c/header_parser.rb
YARD::MRuby::Parser::C.HeaderParser.consume_directive
def consume_directive super if @in_body_statements @newline = false start = @index line = @line statement = DirectiveStatement.new(nil, @file, line) @statements << statement attach_comment(statement) multiline = false advance_loop do chr = char case chr when '\\'; multiline=true; advance when /\s/; consume_whitespace else advance end if @newline if multiline multiline = false else break end end end decl = @content[start...@index] statement.declaration = decl end
ruby
def consume_directive super if @in_body_statements @newline = false start = @index line = @line statement = DirectiveStatement.new(nil, @file, line) @statements << statement attach_comment(statement) multiline = false advance_loop do chr = char case chr when '\\'; multiline=true; advance when /\s/; consume_whitespace else advance end if @newline if multiline multiline = false else break end end end decl = @content[start...@index] statement.declaration = decl end
[ "def", "consume_directive", "super", "if", "@in_body_statements", "@newline", "=", "false", "start", "=", "@index", "line", "=", "@line", "statement", "=", "DirectiveStatement", ".", "new", "(", "nil", ",", "@file", ",", "line", ")", "@statements", "<<", "statement", "attach_comment", "(", "statement", ")", "multiline", "=", "false", "advance_loop", "do", "chr", "=", "char", "case", "chr", "when", "'\\\\'", ";", "multiline", "=", "true", ";", "advance", "when", "/", "\\s", "/", ";", "consume_whitespace", "else", "advance", "end", "if", "@newline", "if", "multiline", "multiline", "=", "false", "else", "break", "end", "end", "end", "decl", "=", "@content", "[", "start", "...", "@index", "]", "statement", ".", "declaration", "=", "decl", "end" ]
Consumes a directive and generates a DirectiveStatement
[ "Consumes", "a", "directive", "and", "generates", "a", "DirectiveStatement" ]
c20c2f415d15235fdc96ac177cb008eb3e11358a
https://github.com/sagmor/yard-mruby/blob/c20c2f415d15235fdc96ac177cb008eb3e11358a/lib/yard/mruby/parser/c/header_parser.rb#L5-L36
train
r7kamura/xrc
lib/xrc/client.rb
Xrc.Client.reply
def reply(options) say( body: options[:body], from: options[:to].to, to: options[:to].from, type: options[:to].type, ) end
ruby
def reply(options) say( body: options[:body], from: options[:to].to, to: options[:to].from, type: options[:to].type, ) end
[ "def", "reply", "(", "options", ")", "say", "(", "body", ":", "options", "[", ":body", "]", ",", "from", ":", "options", "[", ":to", "]", ".", "to", ",", "to", ":", "options", "[", ":to", "]", ".", "from", ",", "type", ":", "options", "[", ":to", "]", ".", "type", ",", ")", "end" ]
Replies to given message @option options [Xrc::Messages::Base] :to A message object given from server @option options [String] :body A text to be sent to server @return [REXML::Element] Returns an element sent to server @example client.reply(body: "Thanks", to: message)
[ "Replies", "to", "given", "message" ]
ddc0af9682fc2cdaf851f88a3f0953a1478f1954
https://github.com/r7kamura/xrc/blob/ddc0af9682fc2cdaf851f88a3f0953a1478f1954/lib/xrc/client.rb#L106-L113
train
r7kamura/xrc
lib/xrc/client.rb
Xrc.Client.say
def say(options) post Elements::Message.new( body: options[:body], from: options[:from], to: options[:to], type: options[:type], ) end
ruby
def say(options) post Elements::Message.new( body: options[:body], from: options[:from], to: options[:to], type: options[:type], ) end
[ "def", "say", "(", "options", ")", "post", "Elements", "::", "Message", ".", "new", "(", "body", ":", "options", "[", ":body", "]", ",", "from", ":", "options", "[", ":from", "]", ",", "to", ":", "options", "[", ":to", "]", ",", "type", ":", "options", "[", ":type", "]", ",", ")", "end" ]
Send a message @option options [String] :body Message body @option options [String] :from Sender's JID @option options [String] :to Address JID @option options [String] :type Message type (e.g. chat, groupchat) @return [REXML::Element] Returns an element sent to server @example client.say(body: "Thanks", from: "[email protected]", to: "[email protected]", type: "chat")
[ "Send", "a", "message" ]
ddc0af9682fc2cdaf851f88a3f0953a1478f1954
https://github.com/r7kamura/xrc/blob/ddc0af9682fc2cdaf851f88a3f0953a1478f1954/lib/xrc/client.rb#L123-L130
train
scrapper/perobs
lib/perobs/BigArray.rb
PEROBS.BigArray.[]=
def []=(index, value) index = validate_index_range(index) @store.transaction do if index < @entry_counter # Overwrite of an existing element @root.set(index, value) elsif index == @entry_counter # Append right at the end @root.insert(index, value) self.entry_counter += 1 else # Append with nil padding @entry_counter.upto(index - 1) do |i| @root.insert(i, nil) end @root.insert(index, value) self.entry_counter = index + 1 end end end
ruby
def []=(index, value) index = validate_index_range(index) @store.transaction do if index < @entry_counter # Overwrite of an existing element @root.set(index, value) elsif index == @entry_counter # Append right at the end @root.insert(index, value) self.entry_counter += 1 else # Append with nil padding @entry_counter.upto(index - 1) do |i| @root.insert(i, nil) end @root.insert(index, value) self.entry_counter = index + 1 end end end
[ "def", "[]=", "(", "index", ",", "value", ")", "index", "=", "validate_index_range", "(", "index", ")", "@store", ".", "transaction", "do", "if", "index", "<", "@entry_counter", "@root", ".", "set", "(", "index", ",", "value", ")", "elsif", "index", "==", "@entry_counter", "@root", ".", "insert", "(", "index", ",", "value", ")", "self", ".", "entry_counter", "+=", "1", "else", "@entry_counter", ".", "upto", "(", "index", "-", "1", ")", "do", "|", "i", "|", "@root", ".", "insert", "(", "i", ",", "nil", ")", "end", "@root", ".", "insert", "(", "index", ",", "value", ")", "self", ".", "entry_counter", "=", "index", "+", "1", "end", "end", "end" ]
Store the value at the given index. If the index already exists the old value will be overwritten. @param index [Integer] Position in the array @param value [Integer] value
[ "Store", "the", "value", "at", "the", "given", "index", ".", "If", "the", "index", "already", "exists", "the", "old", "value", "will", "be", "overwritten", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigArray.rb#L78-L98
train
scrapper/perobs
lib/perobs/BigArray.rb
PEROBS.BigArray.insert
def insert(index, value) index = validate_index_range(index) if index < @entry_counter # Insert in between existing elements @store.transaction do @root.insert(index, value) self.entry_counter += 1 end else self[index] = value end end
ruby
def insert(index, value) index = validate_index_range(index) if index < @entry_counter # Insert in between existing elements @store.transaction do @root.insert(index, value) self.entry_counter += 1 end else self[index] = value end end
[ "def", "insert", "(", "index", ",", "value", ")", "index", "=", "validate_index_range", "(", "index", ")", "if", "index", "<", "@entry_counter", "@store", ".", "transaction", "do", "@root", ".", "insert", "(", "index", ",", "value", ")", "self", ".", "entry_counter", "+=", "1", "end", "else", "self", "[", "index", "]", "=", "value", "end", "end" ]
Insert the value at the given index. If the index already exists the old value will be overwritten. @param index [Integer] Position in the array @param value [Integer] value
[ "Insert", "the", "value", "at", "the", "given", "index", ".", "If", "the", "index", "already", "exists", "the", "old", "value", "will", "be", "overwritten", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigArray.rb#L108-L120
train
scrapper/perobs
lib/perobs/BigArray.rb
PEROBS.BigArray.delete_if
def delete_if old_root = @root clear old_root.each do |k, v| if !yield(k, v) insert(k, v) end end end
ruby
def delete_if old_root = @root clear old_root.each do |k, v| if !yield(k, v) insert(k, v) end end end
[ "def", "delete_if", "old_root", "=", "@root", "clear", "old_root", ".", "each", "do", "|", "k", ",", "v", "|", "if", "!", "yield", "(", "k", ",", "v", ")", "insert", "(", "k", ",", "v", ")", "end", "end", "end" ]
Delete all entries for which the passed block yields true. The implementation is optimized for large bulk deletes. It rebuilds a new BTree for the elements to keep. If only few elements are deleted the overhead of rebuilding the BTree is rather high. @yield [key, value]
[ "Delete", "all", "entries", "for", "which", "the", "passed", "block", "yields", "true", ".", "The", "implementation", "is", "optimized", "for", "large", "bulk", "deletes", ".", "It", "rebuilds", "a", "new", "BTree", "for", "the", "elements", "to", "keep", ".", "If", "only", "few", "elements", "are", "deleted", "the", "overhead", "of", "rebuilding", "the", "BTree", "is", "rather", "high", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigArray.rb#L171-L179
train
scrapper/perobs
lib/perobs/BigArray.rb
PEROBS.BigArray.each
def each(&block) node = @first_leaf while node break unless node.each(&block) node = node.next_sibling end end
ruby
def each(&block) node = @first_leaf while node break unless node.each(&block) node = node.next_sibling end end
[ "def", "each", "(", "&", "block", ")", "node", "=", "@first_leaf", "while", "node", "break", "unless", "node", ".", "each", "(", "&", "block", ")", "node", "=", "node", ".", "next_sibling", "end", "end" ]
Iterate over all entries in the tree. Entries are always sorted by the key. @yield [key, value]
[ "Iterate", "over", "all", "entries", "in", "the", "tree", ".", "Entries", "are", "always", "sorted", "by", "the", "key", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigArray.rb#L196-L202
train
scrapper/perobs
lib/perobs/BigArray.rb
PEROBS.BigArray.reverse_each
def reverse_each(&block) node = @last_leaf while node break unless node.reverse_each(&block) node = node.prev_sibling end end
ruby
def reverse_each(&block) node = @last_leaf while node break unless node.reverse_each(&block) node = node.prev_sibling end end
[ "def", "reverse_each", "(", "&", "block", ")", "node", "=", "@last_leaf", "while", "node", "break", "unless", "node", ".", "reverse_each", "(", "&", "block", ")", "node", "=", "node", ".", "prev_sibling", "end", "end" ]
Iterate over all entries in the tree in reverse order. Entries are always sorted by the key. @yield [key, value]
[ "Iterate", "over", "all", "entries", "in", "the", "tree", "in", "reverse", "order", ".", "Entries", "are", "always", "sorted", "by", "the", "key", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigArray.rb#L207-L213
train
scrapper/perobs
lib/perobs/BigArray.rb
PEROBS.BigArray.to_a
def to_a ary = [] node = @first_leaf while node do ary += node.values node = node.next_sibling end ary end
ruby
def to_a ary = [] node = @first_leaf while node do ary += node.values node = node.next_sibling end ary end
[ "def", "to_a", "ary", "=", "[", "]", "node", "=", "@first_leaf", "while", "node", "do", "ary", "+=", "node", ".", "values", "node", "=", "node", ".", "next_sibling", "end", "ary", "end" ]
Convert the BigArray into a Ruby Array. This is primarily intended for debugging as real-world BigArray objects are likely too big to fit into memory.
[ "Convert", "the", "BigArray", "into", "a", "Ruby", "Array", ".", "This", "is", "primarily", "intended", "for", "debugging", "as", "real", "-", "world", "BigArray", "objects", "are", "likely", "too", "big", "to", "fit", "into", "memory", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigArray.rb#L218-L227
train
scrapper/perobs
lib/perobs/SpaceTreeNode.rb
PEROBS.SpaceTreeNode.save
def save bytes = [ @blob_address, @size, @parent ? @parent.node_address : 0, @smaller ? @smaller.node_address : 0, @equal ? @equal.node_address : 0, @larger ? @larger.node_address : 0].pack(NODE_BYTES_FORMAT) @tree.nodes.store_blob(@node_address, bytes) end
ruby
def save bytes = [ @blob_address, @size, @parent ? @parent.node_address : 0, @smaller ? @smaller.node_address : 0, @equal ? @equal.node_address : 0, @larger ? @larger.node_address : 0].pack(NODE_BYTES_FORMAT) @tree.nodes.store_blob(@node_address, bytes) end
[ "def", "save", "bytes", "=", "[", "@blob_address", ",", "@size", ",", "@parent", "?", "@parent", ".", "node_address", ":", "0", ",", "@smaller", "?", "@smaller", ".", "node_address", ":", "0", ",", "@equal", "?", "@equal", ".", "node_address", ":", "0", ",", "@larger", "?", "@larger", ".", "node_address", ":", "0", "]", ".", "pack", "(", "NODE_BYTES_FORMAT", ")", "@tree", ".", "nodes", ".", "store_blob", "(", "@node_address", ",", "bytes", ")", "end" ]
Save the node into the blob file.
[ "Save", "the", "node", "into", "the", "blob", "file", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/SpaceTreeNode.rb#L128-L135
train
scrapper/perobs
lib/perobs/SpaceTreeNode.rb
PEROBS.SpaceTreeNode.add_space
def add_space(address, size) node = self loop do if node.size == 0 # This happens only for the root node if the tree is empty. node.set_size_and_address(size, address) break elsif size < node.size # The new size is smaller than this node. if node.smaller # There is already a smaller node, so pass it on. node = node.smaller else # There is no smaller node yet, so we create a new one as a # smaller child of the current node. node.set_link('@smaller', SpaceTreeNode::create(@tree, address, size, node)) break end elsif size > node.size # The new size is larger than this node. if node.larger # There is already a larger node, so pass it on. node = node.larger else # There is no larger node yet, so we create a new one as a larger # child of the current node. node.set_link('@larger', SpaceTreeNode::create(@tree, address, size, node)) break end else # Same size as current node. Insert new node as equal child at top of # equal list. new_node = SpaceTreeNode::create(@tree, address, size, node) new_node.set_link('@equal', node.equal) node.set_link('@equal', new_node) break end end end
ruby
def add_space(address, size) node = self loop do if node.size == 0 # This happens only for the root node if the tree is empty. node.set_size_and_address(size, address) break elsif size < node.size # The new size is smaller than this node. if node.smaller # There is already a smaller node, so pass it on. node = node.smaller else # There is no smaller node yet, so we create a new one as a # smaller child of the current node. node.set_link('@smaller', SpaceTreeNode::create(@tree, address, size, node)) break end elsif size > node.size # The new size is larger than this node. if node.larger # There is already a larger node, so pass it on. node = node.larger else # There is no larger node yet, so we create a new one as a larger # child of the current node. node.set_link('@larger', SpaceTreeNode::create(@tree, address, size, node)) break end else # Same size as current node. Insert new node as equal child at top of # equal list. new_node = SpaceTreeNode::create(@tree, address, size, node) new_node.set_link('@equal', node.equal) node.set_link('@equal', new_node) break end end end
[ "def", "add_space", "(", "address", ",", "size", ")", "node", "=", "self", "loop", "do", "if", "node", ".", "size", "==", "0", "node", ".", "set_size_and_address", "(", "size", ",", "address", ")", "break", "elsif", "size", "<", "node", ".", "size", "if", "node", ".", "smaller", "node", "=", "node", ".", "smaller", "else", "node", ".", "set_link", "(", "'@smaller'", ",", "SpaceTreeNode", "::", "create", "(", "@tree", ",", "address", ",", "size", ",", "node", ")", ")", "break", "end", "elsif", "size", ">", "node", ".", "size", "if", "node", ".", "larger", "node", "=", "node", ".", "larger", "else", "node", ".", "set_link", "(", "'@larger'", ",", "SpaceTreeNode", "::", "create", "(", "@tree", ",", "address", ",", "size", ",", "node", ")", ")", "break", "end", "else", "new_node", "=", "SpaceTreeNode", "::", "create", "(", "@tree", ",", "address", ",", "size", ",", "node", ")", "new_node", ".", "set_link", "(", "'@equal'", ",", "node", ".", "equal", ")", "node", ".", "set_link", "(", "'@equal'", ",", "new_node", ")", "break", "end", "end", "end" ]
Add a new node for the given address and size to the tree. @param address [Integer] address of the free space @param size [Integer] size of the free space
[ "Add", "a", "new", "node", "for", "the", "given", "address", "and", "size", "to", "the", "tree", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/SpaceTreeNode.rb#L140-L183
train
scrapper/perobs
lib/perobs/SpaceTreeNode.rb
PEROBS.SpaceTreeNode.has_space?
def has_space?(address, size) node = self loop do if node.blob_address == address return size == node.size elsif size < node.size && node.smaller node = node.smaller elsif size > node.size && node.larger node = node.larger elsif size == node.size && node.equal node = node.equal else return false end end end
ruby
def has_space?(address, size) node = self loop do if node.blob_address == address return size == node.size elsif size < node.size && node.smaller node = node.smaller elsif size > node.size && node.larger node = node.larger elsif size == node.size && node.equal node = node.equal else return false end end end
[ "def", "has_space?", "(", "address", ",", "size", ")", "node", "=", "self", "loop", "do", "if", "node", ".", "blob_address", "==", "address", "return", "size", "==", "node", ".", "size", "elsif", "size", "<", "node", ".", "size", "&&", "node", ".", "smaller", "node", "=", "node", ".", "smaller", "elsif", "size", ">", "node", ".", "size", "&&", "node", ".", "larger", "node", "=", "node", ".", "larger", "elsif", "size", "==", "node", ".", "size", "&&", "node", ".", "equal", "node", "=", "node", ".", "equal", "else", "return", "false", "end", "end", "end" ]
Check if this node or any sub-node has an entry for the given address and size. @param address [Integer] address of the free space @param size [Integer] size of the free space @return [Boolean] True if found, otherwise false
[ "Check", "if", "this", "node", "or", "any", "sub", "-", "node", "has", "an", "entry", "for", "the", "given", "address", "and", "size", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/SpaceTreeNode.rb#L190-L205
train
scrapper/perobs
lib/perobs/SpaceTreeNode.rb
PEROBS.SpaceTreeNode.relink_parent
def relink_parent(node) if @parent if @parent.smaller == self @parent.set_link('@smaller', node) elsif @parent.equal == self @parent.set_link('@equal', node) elsif @parent.larger == self @parent.set_link('@larger', node) else PEROBS.log.fatal "Cannot relink unknown child node with address " + "#{node.node_address} from #{parent.to_s}" end else if node @tree.set_root(node) node.parent = nil else set_size_and_address(0, 0) end end end
ruby
def relink_parent(node) if @parent if @parent.smaller == self @parent.set_link('@smaller', node) elsif @parent.equal == self @parent.set_link('@equal', node) elsif @parent.larger == self @parent.set_link('@larger', node) else PEROBS.log.fatal "Cannot relink unknown child node with address " + "#{node.node_address} from #{parent.to_s}" end else if node @tree.set_root(node) node.parent = nil else set_size_and_address(0, 0) end end end
[ "def", "relink_parent", "(", "node", ")", "if", "@parent", "if", "@parent", ".", "smaller", "==", "self", "@parent", ".", "set_link", "(", "'@smaller'", ",", "node", ")", "elsif", "@parent", ".", "equal", "==", "self", "@parent", ".", "set_link", "(", "'@equal'", ",", "node", ")", "elsif", "@parent", ".", "larger", "==", "self", "@parent", ".", "set_link", "(", "'@larger'", ",", "node", ")", "else", "PEROBS", ".", "log", ".", "fatal", "\"Cannot relink unknown child node with address \"", "+", "\"#{node.node_address} from #{parent.to_s}\"", "end", "else", "if", "node", "@tree", ".", "set_root", "(", "node", ")", "node", ".", "parent", "=", "nil", "else", "set_size_and_address", "(", "0", ",", "0", ")", "end", "end", "end" ]
Replace the link in the parent node of the current node that points to the current node with the given node. @param node [SpaceTreeNode]
[ "Replace", "the", "link", "in", "the", "parent", "node", "of", "the", "current", "node", "that", "points", "to", "the", "current", "node", "with", "the", "given", "node", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/SpaceTreeNode.rb#L382-L402
train
scrapper/perobs
lib/perobs/SpaceTreeNode.rb
PEROBS.SpaceTreeNode.to_a
def to_a ary = [] each do |node, mode, stack| if mode == :on_enter ary << [ node.blob_address, node.size ] end end ary end
ruby
def to_a ary = [] each do |node, mode, stack| if mode == :on_enter ary << [ node.blob_address, node.size ] end end ary end
[ "def", "to_a", "ary", "=", "[", "]", "each", "do", "|", "node", ",", "mode", ",", "stack", "|", "if", "mode", "==", ":on_enter", "ary", "<<", "[", "node", ".", "blob_address", ",", "node", ".", "size", "]", "end", "end", "ary", "end" ]
Compare this node to another node. @return [Boolean] true if node address is identical, false otherwise Collects address and size touples of all nodes in the tree with a depth-first strategy and stores them in an Array. @return [Array] Array with [ address, size ] touples.
[ "Compare", "this", "node", "to", "another", "node", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/SpaceTreeNode.rb#L467-L477
train
scrapper/perobs
lib/perobs/SpaceTreeNode.rb
PEROBS.SpaceTreeNode.check
def check(flat_file, count) node_counter = 0 max_depth = 0 @tree.progressmeter.start('Checking space list entries', count) do |pm| each do |node, mode, stack| max_depth = stack.size if stack.size > max_depth case mode when :smaller if node.smaller return false unless node.check_node_link('smaller', stack) smaller_node = node.smaller if smaller_node.size >= node.size PEROBS.log.error "Smaller SpaceTreeNode size " + "(#{smaller_node}) is not smaller than #{node}" return false end end when :equal if node.equal return false unless node.check_node_link('equal', stack) equal_node = node.equal if equal_node.smaller || equal_node.larger PEROBS.log.error "Equal node #{equal_node} must not have " + "smaller/larger childs" return false end if node.size != equal_node.size PEROBS.log.error "Equal SpaceTreeNode size (#{equal_node}) " + "is not equal parent node #{node}" return false end end when :larger if node.larger return false unless node.check_node_link('larger', stack) larger_node = node.larger if larger_node.size <= node.size PEROBS.log.error "Larger SpaceTreeNode size " + "(#{larger_node}) is not larger than #{node}" return false end end when :on_exit if flat_file && !flat_file.has_space?(node.blob_address, node.size) PEROBS.log.error "SpaceTreeNode has space at offset " + "#{node.blob_address} of size #{node.size} that isn't " + "available in the FlatFile." return false end pm.update(node_counter += 1) end end end PEROBS.log.debug "#{node_counter} SpaceTree nodes checked" PEROBS.log.debug "Maximum tree depth is #{max_depth}" return true end
ruby
def check(flat_file, count) node_counter = 0 max_depth = 0 @tree.progressmeter.start('Checking space list entries', count) do |pm| each do |node, mode, stack| max_depth = stack.size if stack.size > max_depth case mode when :smaller if node.smaller return false unless node.check_node_link('smaller', stack) smaller_node = node.smaller if smaller_node.size >= node.size PEROBS.log.error "Smaller SpaceTreeNode size " + "(#{smaller_node}) is not smaller than #{node}" return false end end when :equal if node.equal return false unless node.check_node_link('equal', stack) equal_node = node.equal if equal_node.smaller || equal_node.larger PEROBS.log.error "Equal node #{equal_node} must not have " + "smaller/larger childs" return false end if node.size != equal_node.size PEROBS.log.error "Equal SpaceTreeNode size (#{equal_node}) " + "is not equal parent node #{node}" return false end end when :larger if node.larger return false unless node.check_node_link('larger', stack) larger_node = node.larger if larger_node.size <= node.size PEROBS.log.error "Larger SpaceTreeNode size " + "(#{larger_node}) is not larger than #{node}" return false end end when :on_exit if flat_file && !flat_file.has_space?(node.blob_address, node.size) PEROBS.log.error "SpaceTreeNode has space at offset " + "#{node.blob_address} of size #{node.size} that isn't " + "available in the FlatFile." return false end pm.update(node_counter += 1) end end end PEROBS.log.debug "#{node_counter} SpaceTree nodes checked" PEROBS.log.debug "Maximum tree depth is #{max_depth}" return true end
[ "def", "check", "(", "flat_file", ",", "count", ")", "node_counter", "=", "0", "max_depth", "=", "0", "@tree", ".", "progressmeter", ".", "start", "(", "'Checking space list entries'", ",", "count", ")", "do", "|", "pm", "|", "each", "do", "|", "node", ",", "mode", ",", "stack", "|", "max_depth", "=", "stack", ".", "size", "if", "stack", ".", "size", ">", "max_depth", "case", "mode", "when", ":smaller", "if", "node", ".", "smaller", "return", "false", "unless", "node", ".", "check_node_link", "(", "'smaller'", ",", "stack", ")", "smaller_node", "=", "node", ".", "smaller", "if", "smaller_node", ".", "size", ">=", "node", ".", "size", "PEROBS", ".", "log", ".", "error", "\"Smaller SpaceTreeNode size \"", "+", "\"(#{smaller_node}) is not smaller than #{node}\"", "return", "false", "end", "end", "when", ":equal", "if", "node", ".", "equal", "return", "false", "unless", "node", ".", "check_node_link", "(", "'equal'", ",", "stack", ")", "equal_node", "=", "node", ".", "equal", "if", "equal_node", ".", "smaller", "||", "equal_node", ".", "larger", "PEROBS", ".", "log", ".", "error", "\"Equal node #{equal_node} must not have \"", "+", "\"smaller/larger childs\"", "return", "false", "end", "if", "node", ".", "size", "!=", "equal_node", ".", "size", "PEROBS", ".", "log", ".", "error", "\"Equal SpaceTreeNode size (#{equal_node}) \"", "+", "\"is not equal parent node #{node}\"", "return", "false", "end", "end", "when", ":larger", "if", "node", ".", "larger", "return", "false", "unless", "node", ".", "check_node_link", "(", "'larger'", ",", "stack", ")", "larger_node", "=", "node", ".", "larger", "if", "larger_node", ".", "size", "<=", "node", ".", "size", "PEROBS", ".", "log", ".", "error", "\"Larger SpaceTreeNode size \"", "+", "\"(#{larger_node}) is not larger than #{node}\"", "return", "false", "end", "end", "when", ":on_exit", "if", "flat_file", "&&", "!", "flat_file", ".", "has_space?", "(", "node", ".", "blob_address", ",", "node", ".", "size", ")", "PEROBS", ".", "log", ".", "error", "\"SpaceTreeNode has space at offset \"", "+", "\"#{node.blob_address} of size #{node.size} that isn't \"", "+", "\"available in the FlatFile.\"", "return", "false", "end", "pm", ".", "update", "(", "node_counter", "+=", "1", ")", "end", "end", "end", "PEROBS", ".", "log", ".", "debug", "\"#{node_counter} SpaceTree nodes checked\"", "PEROBS", ".", "log", ".", "debug", "\"Maximum tree depth is #{max_depth}\"", "return", "true", "end" ]
Check this node and all sub nodes for possible structural or logical errors. @param flat_file [FlatFile] If given, check that the space is also present in the given flat file. @param count [Integer] The total number of entries in the tree @return [false,true] True if OK, false otherwise
[ "Check", "this", "node", "and", "all", "sub", "nodes", "for", "possible", "structural", "or", "logical", "errors", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/SpaceTreeNode.rb#L523-L586
train
scrapper/perobs
lib/perobs/SpaceTreeNode.rb
PEROBS.SpaceTreeNode.check_node_link
def check_node_link(link, stack) if (node = instance_variable_get('@' + link)) # Node links must only be of class SpaceTreeNodeLink unless node.nil? || node.is_a?(SpaceTreeNodeLink) PEROBS.log.error "Node link #{link} of node #{to_s} " + "is of class #{node.class}" return false end # Link must not point back to self. if node == self PEROBS.log.error "#{link} address of node " + "#{node.to_s} points to self #{to_s}" return false end # Link must not point to any of the parent nodes. if stack.include?(node) PEROBS.log.error "#{link} address of node #{to_s} " + "points to parent node #{node}" return false end # Parent link of node must point back to self. if node.parent != self PEROBS.log.error "@#{link} node #{node.to_s} does not have parent " + "link pointing " + "to parent node #{to_s}. Pointing at " + "#{node.parent.nil? ? 'nil' : node.parent.to_s} instead." return false end end true end
ruby
def check_node_link(link, stack) if (node = instance_variable_get('@' + link)) # Node links must only be of class SpaceTreeNodeLink unless node.nil? || node.is_a?(SpaceTreeNodeLink) PEROBS.log.error "Node link #{link} of node #{to_s} " + "is of class #{node.class}" return false end # Link must not point back to self. if node == self PEROBS.log.error "#{link} address of node " + "#{node.to_s} points to self #{to_s}" return false end # Link must not point to any of the parent nodes. if stack.include?(node) PEROBS.log.error "#{link} address of node #{to_s} " + "points to parent node #{node}" return false end # Parent link of node must point back to self. if node.parent != self PEROBS.log.error "@#{link} node #{node.to_s} does not have parent " + "link pointing " + "to parent node #{to_s}. Pointing at " + "#{node.parent.nil? ? 'nil' : node.parent.to_s} instead." return false end end true end
[ "def", "check_node_link", "(", "link", ",", "stack", ")", "if", "(", "node", "=", "instance_variable_get", "(", "'@'", "+", "link", ")", ")", "unless", "node", ".", "nil?", "||", "node", ".", "is_a?", "(", "SpaceTreeNodeLink", ")", "PEROBS", ".", "log", ".", "error", "\"Node link #{link} of node #{to_s} \"", "+", "\"is of class #{node.class}\"", "return", "false", "end", "if", "node", "==", "self", "PEROBS", ".", "log", ".", "error", "\"#{link} address of node \"", "+", "\"#{node.to_s} points to self #{to_s}\"", "return", "false", "end", "if", "stack", ".", "include?", "(", "node", ")", "PEROBS", ".", "log", ".", "error", "\"#{link} address of node #{to_s} \"", "+", "\"points to parent node #{node}\"", "return", "false", "end", "if", "node", ".", "parent", "!=", "self", "PEROBS", ".", "log", ".", "error", "\"@#{link} node #{node.to_s} does not have parent \"", "+", "\"link pointing \"", "+", "\"to parent node #{to_s}. Pointing at \"", "+", "\"#{node.parent.nil? ? 'nil' : node.parent.to_s} instead.\"", "return", "false", "end", "end", "true", "end" ]
Check the integrity of the given sub-node link and the parent link pointing back to this node. @param link [String] 'smaller', 'equal' or 'larger' @param stack [Array] List of parent nodes [ address, mode ] touples @return [Boolean] true of OK, false otherwise
[ "Check", "the", "integrity", "of", "the", "given", "sub", "-", "node", "link", "and", "the", "parent", "link", "pointing", "back", "to", "this", "node", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/SpaceTreeNode.rb#L593-L629
train
scrapper/perobs
lib/perobs/SpaceTreeNode.rb
PEROBS.SpaceTreeNode.to_tree_s
def to_tree_s str = '' each do |node, mode, stack| if mode == :on_enter begin branch_mark = node.parent.nil? ? '' : node.parent.smaller == node ? '<' : node.parent.equal == node ? '=' : node.parent.larger == node ? '>' : '@' str += "#{node.text_tree_prefix}#{branch_mark}-" + "#{node.smaller || node.equal || node.larger ? 'v-' : '--'}" + "#{node.to_s}\n" rescue str += "#{node.text_tree_prefix}- @@@@@@@@@@\n" end end end str end
ruby
def to_tree_s str = '' each do |node, mode, stack| if mode == :on_enter begin branch_mark = node.parent.nil? ? '' : node.parent.smaller == node ? '<' : node.parent.equal == node ? '=' : node.parent.larger == node ? '>' : '@' str += "#{node.text_tree_prefix}#{branch_mark}-" + "#{node.smaller || node.equal || node.larger ? 'v-' : '--'}" + "#{node.to_s}\n" rescue str += "#{node.text_tree_prefix}- @@@@@@@@@@\n" end end end str end
[ "def", "to_tree_s", "str", "=", "''", "each", "do", "|", "node", ",", "mode", ",", "stack", "|", "if", "mode", "==", ":on_enter", "begin", "branch_mark", "=", "node", ".", "parent", ".", "nil?", "?", "''", ":", "node", ".", "parent", ".", "smaller", "==", "node", "?", "'<'", ":", "node", ".", "parent", ".", "equal", "==", "node", "?", "'='", ":", "node", ".", "parent", ".", "larger", "==", "node", "?", "'>'", ":", "'@'", "str", "+=", "\"#{node.text_tree_prefix}#{branch_mark}-\"", "+", "\"#{node.smaller || node.equal || node.larger ? 'v-' : '--'}\"", "+", "\"#{node.to_s}\\n\"", "rescue", "str", "+=", "\"#{node.text_tree_prefix}- @@@@@@@@@@\\n\"", "end", "end", "end", "str", "end" ]
Convert the node and all child nodes into a tree like text form. @return [String]
[ "Convert", "the", "node", "and", "all", "child", "nodes", "into", "a", "tree", "like", "text", "form", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/SpaceTreeNode.rb#L633-L654
train
scrapper/perobs
lib/perobs/SpaceTreeNode.rb
PEROBS.SpaceTreeNode.text_tree_prefix
def text_tree_prefix if (node = @parent) str = '+' else # Prefix start for root node line str = 'o' end while node last_child = false if node.parent if node.parent.smaller == node last_child = node.parent.equal.nil? && node.parent.larger.nil? elsif node.parent.equal == node last_child = node.parent.larger.nil? elsif node.parent.larger == node last_child = true end else # Padding for the root node str = ' ' + str break end str = (last_child ? ' ' : '| ') + str node = node.parent end str end
ruby
def text_tree_prefix if (node = @parent) str = '+' else # Prefix start for root node line str = 'o' end while node last_child = false if node.parent if node.parent.smaller == node last_child = node.parent.equal.nil? && node.parent.larger.nil? elsif node.parent.equal == node last_child = node.parent.larger.nil? elsif node.parent.larger == node last_child = true end else # Padding for the root node str = ' ' + str break end str = (last_child ? ' ' : '| ') + str node = node.parent end str end
[ "def", "text_tree_prefix", "if", "(", "node", "=", "@parent", ")", "str", "=", "'+'", "else", "str", "=", "'o'", "end", "while", "node", "last_child", "=", "false", "if", "node", ".", "parent", "if", "node", ".", "parent", ".", "smaller", "==", "node", "last_child", "=", "node", ".", "parent", ".", "equal", ".", "nil?", "&&", "node", ".", "parent", ".", "larger", ".", "nil?", "elsif", "node", ".", "parent", ".", "equal", "==", "node", "last_child", "=", "node", ".", "parent", ".", "larger", ".", "nil?", "elsif", "node", ".", "parent", ".", "larger", "==", "node", "last_child", "=", "true", "end", "else", "str", "=", "' '", "+", "str", "break", "end", "str", "=", "(", "last_child", "?", "' '", ":", "'| '", ")", "+", "str", "node", "=", "node", ".", "parent", "end", "str", "end" ]
The indentation and arch routing for the text tree. @return [String]
[ "The", "indentation", "and", "arch", "routing", "for", "the", "text", "tree", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/SpaceTreeNode.rb#L658-L687
train
scrapper/perobs
lib/perobs/PersistentObjectCacheLine.rb
PEROBS.PersistentObjectCacheLine.flush
def flush(now) if now || @entries.length > WATERMARK @entries.each do |e| if e.modified e.obj.save e.modified = false end end # Delete all but the first WATERMARK entry. @entries = @entries[0..WATERMARK - 1] if @entries.length > WATERMARK end end
ruby
def flush(now) if now || @entries.length > WATERMARK @entries.each do |e| if e.modified e.obj.save e.modified = false end end # Delete all but the first WATERMARK entry. @entries = @entries[0..WATERMARK - 1] if @entries.length > WATERMARK end end
[ "def", "flush", "(", "now", ")", "if", "now", "||", "@entries", ".", "length", ">", "WATERMARK", "@entries", ".", "each", "do", "|", "e", "|", "if", "e", ".", "modified", "e", ".", "obj", ".", "save", "e", ".", "modified", "=", "false", "end", "end", "@entries", "=", "@entries", "[", "0", "..", "WATERMARK", "-", "1", "]", "if", "@entries", ".", "length", ">", "WATERMARK", "end", "end" ]
Save all modified entries and delete all but the most recently added.
[ "Save", "all", "modified", "entries", "and", "delete", "all", "but", "the", "most", "recently", "added", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/PersistentObjectCacheLine.rb#L82-L94
train
Absolight/epp-client
lib/epp-client/contact.rb
EPPClient.Contact.contact_check
def contact_check(*contacts) contacts.flatten! response = send_request(contact_check_xml(*contacts)) get_result(:xml => response, :callback => :contact_check_process) end
ruby
def contact_check(*contacts) contacts.flatten! response = send_request(contact_check_xml(*contacts)) get_result(:xml => response, :callback => :contact_check_process) end
[ "def", "contact_check", "(", "*", "contacts", ")", "contacts", ".", "flatten!", "response", "=", "send_request", "(", "contact_check_xml", "(", "*", "contacts", ")", ")", "get_result", "(", ":xml", "=>", "response", ",", ":callback", "=>", ":contact_check_process", ")", "end" ]
Check the availability of contacts takes list of contacts as arguments returns an array of hashes containing three fields : [<tt>:id</tt>] the contact id [<tt>:avail</tt>] wether the contact id can be provisionned. [<tt>:reason</tt>] the server-specific text to help explain why the object cannot be provisioned.
[ "Check", "the", "availability", "of", "contacts" ]
c0025daee5e7087f60b654595a8e7d92e966c54e
https://github.com/Absolight/epp-client/blob/c0025daee5e7087f60b654595a8e7d92e966c54e/lib/epp-client/contact.rb#L31-L36
train
Absolight/epp-client
lib/epp-client/contact.rb
EPPClient.Contact.contact_info
def contact_info(args) args = { :id => args } if args.is_a?(String) response = send_request(contact_info_xml(args)) get_result(:xml => response, :callback => :contact_info_process) end
ruby
def contact_info(args) args = { :id => args } if args.is_a?(String) response = send_request(contact_info_xml(args)) get_result(:xml => response, :callback => :contact_info_process) end
[ "def", "contact_info", "(", "args", ")", "args", "=", "{", ":id", "=>", "args", "}", "if", "args", ".", "is_a?", "(", "String", ")", "response", "=", "send_request", "(", "contact_info_xml", "(", "args", ")", ")", "get_result", "(", ":xml", "=>", "response", ",", ":callback", "=>", ":contact_info_process", ")", "end" ]
Returns the informations about a contact Takes either a unique argument, either a string, representing the contact id or a hash with the following keys : [<tt>:id</tt>] the contact id, and optionnaly [<tt>:authInfo</tt>] an optional authentication information. Returned is a hash mapping as closely as possible the result expected from the command as per Section 3.1.2 of RFC 5733 : [<tt>:id</tt>] the server-unique identifier of the contact object. Most of the time, the nic handle. [<tt>:roid</tt>] the Repository Object IDentifier assigned to the contact object when the object was created. [<tt>:status</tt>] the status of the contact object. [<tt>:postalInfo</tt>] a hash containing one or two keys, +loc+ and +int+ representing the localized and internationalized version of the postal address information. The value is a hash with the following keys : [<tt>:name</tt>] the name of the individual or role represented by the contact. [<tt>:org</tt>] the name of the organization with which the contact is affiliated. [<tt>:addr</tt>] a hash with the following keys : [<tt>:street</tt>] an array that contains the contact's street address. [<tt>:city</tt>] the contact's city. [<tt>:sp</tt>] the contact's state or province. [<tt>:pc</tt>] the contact's postal code. [<tt>:cc</tt>] the contact's country code. [<tt>:voice</tt>] the contact's optional voice telephone number. [<tt>:fax</tt>] the contact's optional facsimile telephone number. [<tt>:email</tt>] the contact's email address. [<tt>:clID</tt>] the identifier of the sponsoring client. [<tt>:crID</tt>] the identifier of the client that created the contact object. [<tt>:crDate</tt>] the date and time of contact-object creation. [<tt>:upID</tt>] the optional identifier of the client that last updated the contact object. [<tt>:upDate</tt>] the optional date and time of the most recent contact-object modification. [<tt>:trDate</tt>] the optional date and time of the most recent successful contact-object transfer. [<tt>:authInfo</tt>] authorization information associated with the contact object. [<tt>:disclose</tt>] an optional array that identifies elements that require exceptional server-operator handling to allow or restrict disclosure to third parties. See {section 2.9 of RFC 5733}[http://tools.ietf.org/html/rfc5733#section-2.9] for details.
[ "Returns", "the", "informations", "about", "a", "contact" ]
c0025daee5e7087f60b654595a8e7d92e966c54e
https://github.com/Absolight/epp-client/blob/c0025daee5e7087f60b654595a8e7d92e966c54e/lib/epp-client/contact.rb#L122-L127
train
mreq/wmctile
lib/wmctile/window.rb
Wmctile.Window.find_window
def find_window(current_workspace_only = false) @matching_windows = Wmctile.window_list.grep(@regexp_string) filter_out_workspaces if current_workspace_only if @matching_windows.count > 1 filter_more_matching_windows elsif @matching_windows.count == 1 @matching_line = @matching_windows[0] else fail Errors::WindowNotFound, @window_string end extract_matching_line_information end
ruby
def find_window(current_workspace_only = false) @matching_windows = Wmctile.window_list.grep(@regexp_string) filter_out_workspaces if current_workspace_only if @matching_windows.count > 1 filter_more_matching_windows elsif @matching_windows.count == 1 @matching_line = @matching_windows[0] else fail Errors::WindowNotFound, @window_string end extract_matching_line_information end
[ "def", "find_window", "(", "current_workspace_only", "=", "false", ")", "@matching_windows", "=", "Wmctile", ".", "window_list", ".", "grep", "(", "@regexp_string", ")", "filter_out_workspaces", "if", "current_workspace_only", "if", "@matching_windows", ".", "count", ">", "1", "filter_more_matching_windows", "elsif", "@matching_windows", ".", "count", "==", "1", "@matching_line", "=", "@matching_windows", "[", "0", "]", "else", "fail", "Errors", "::", "WindowNotFound", ",", "@window_string", "end", "extract_matching_line_information", "end" ]
Window init function. Tries to find an id. @param [Hash] arguments command line options @param [String] window_string command line string given Filters down the window_list to @matching_windows. @param [Boolean] current_workspace_only Should only the current workspace be used? @return [void]
[ "Window", "init", "function", ".", "Tries", "to", "find", "an", "id", "." ]
a41af5afa310b09c8ba1bd45a134b9b2a87d1a35
https://github.com/mreq/wmctile/blob/a41af5afa310b09c8ba1bd45a134b9b2a87d1a35/lib/wmctile/window.rb#L26-L37
train
xinminlabs/synvert-core
lib/synvert/core/rewriter/action/replace_erb_stmt_with_expr_action.rb
Synvert::Core.Rewriter::ReplaceErbStmtWithExprAction.begin_pos
def begin_pos node_begin_pos = @node.loc.expression.begin_pos while @node.loc.expression.source_buffer.source[node_begin_pos -= 1] == ' ' end node_begin_pos - Engine::ERUBY_STMT_SPLITTER.length + 1 end
ruby
def begin_pos node_begin_pos = @node.loc.expression.begin_pos while @node.loc.expression.source_buffer.source[node_begin_pos -= 1] == ' ' end node_begin_pos - Engine::ERUBY_STMT_SPLITTER.length + 1 end
[ "def", "begin_pos", "node_begin_pos", "=", "@node", ".", "loc", ".", "expression", ".", "begin_pos", "while", "@node", ".", "loc", ".", "expression", ".", "source_buffer", ".", "source", "[", "node_begin_pos", "-=", "1", "]", "==", "' '", "end", "node_begin_pos", "-", "Engine", "::", "ERUBY_STMT_SPLITTER", ".", "length", "+", "1", "end" ]
Begin position of code to replace. @return [Integer] begin position.
[ "Begin", "position", "of", "code", "to", "replace", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/rewriter/action/replace_erb_stmt_with_expr_action.rb#L14-L19
train
xinminlabs/synvert-core
lib/synvert/core/rewriter/action/replace_erb_stmt_with_expr_action.rb
Synvert::Core.Rewriter::ReplaceErbStmtWithExprAction.end_pos
def end_pos node_begin_pos = @node.loc.expression.begin_pos node_begin_pos += @node.loc.expression.source.index "do" while @node.loc.expression.source_buffer.source[node_begin_pos += 1] != '@' end node_begin_pos end
ruby
def end_pos node_begin_pos = @node.loc.expression.begin_pos node_begin_pos += @node.loc.expression.source.index "do" while @node.loc.expression.source_buffer.source[node_begin_pos += 1] != '@' end node_begin_pos end
[ "def", "end_pos", "node_begin_pos", "=", "@node", ".", "loc", ".", "expression", ".", "begin_pos", "node_begin_pos", "+=", "@node", ".", "loc", ".", "expression", ".", "source", ".", "index", "\"do\"", "while", "@node", ".", "loc", ".", "expression", ".", "source_buffer", ".", "source", "[", "node_begin_pos", "+=", "1", "]", "!=", "'@'", "end", "node_begin_pos", "end" ]
End position of code to replace. @return [Integer] end position.
[ "End", "position", "of", "code", "to", "replace", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/rewriter/action/replace_erb_stmt_with_expr_action.rb#L24-L30
train
xinminlabs/synvert-core
lib/synvert/core/rewriter/action/replace_erb_stmt_with_expr_action.rb
Synvert::Core.Rewriter::ReplaceErbStmtWithExprAction.rewritten_code
def rewritten_code @node.loc.expression.source_buffer.source[begin_pos...end_pos].sub(Engine::ERUBY_STMT_SPLITTER, "@output_buffer.append= ") .sub(Engine::ERUBY_STMT_SPLITTER, Engine::ERUBY_EXPR_SPLITTER) end
ruby
def rewritten_code @node.loc.expression.source_buffer.source[begin_pos...end_pos].sub(Engine::ERUBY_STMT_SPLITTER, "@output_buffer.append= ") .sub(Engine::ERUBY_STMT_SPLITTER, Engine::ERUBY_EXPR_SPLITTER) end
[ "def", "rewritten_code", "@node", ".", "loc", ".", "expression", ".", "source_buffer", ".", "source", "[", "begin_pos", "...", "end_pos", "]", ".", "sub", "(", "Engine", "::", "ERUBY_STMT_SPLITTER", ",", "\"@output_buffer.append= \"", ")", ".", "sub", "(", "Engine", "::", "ERUBY_STMT_SPLITTER", ",", "Engine", "::", "ERUBY_EXPR_SPLITTER", ")", "end" ]
The rewritten erb expr code. @return [String] rewritten code.
[ "The", "rewritten", "erb", "expr", "code", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/rewriter/action/replace_erb_stmt_with_expr_action.rb#L35-L38
train
jeffnyman/tapestry
lib/tapestry/factory.rb
Tapestry.Factory.verify_page
def verify_page(context) return if context.url_match_attribute.nil? return if context.has_correct_url? raise Tapestry::Errors::PageURLFromFactoryNotVerified end
ruby
def verify_page(context) return if context.url_match_attribute.nil? return if context.has_correct_url? raise Tapestry::Errors::PageURLFromFactoryNotVerified end
[ "def", "verify_page", "(", "context", ")", "return", "if", "context", ".", "url_match_attribute", ".", "nil?", "return", "if", "context", ".", "has_correct_url?", "raise", "Tapestry", "::", "Errors", "::", "PageURLFromFactoryNotVerified", "end" ]
This method is used to provide a means for checking if a page has been navigated to correctly as part of a context. This is useful because the context signature should remain highly readable, and checks for whether a given page has been reached would make the context definition look sloppy.
[ "This", "method", "is", "used", "to", "provide", "a", "means", "for", "checking", "if", "a", "page", "has", "been", "navigated", "to", "correctly", "as", "part", "of", "a", "context", ".", "This", "is", "useful", "because", "the", "context", "signature", "should", "remain", "highly", "readable", "and", "checks", "for", "whether", "a", "given", "page", "has", "been", "reached", "would", "make", "the", "context", "definition", "look", "sloppy", "." ]
da28652dd6de71e415cd2c01afd89f641938a05b
https://github.com/jeffnyman/tapestry/blob/da28652dd6de71e415cd2c01afd89f641938a05b/lib/tapestry/factory.rb#L86-L90
train
scrapper/perobs
lib/perobs/Cache.rb
PEROBS.Cache.cache_read
def cache_read(obj) # This is just a safety check. It can probably be disabled in the future # to increase performance. if obj.respond_to?(:is_poxreference?) # If this condition triggers, we have a bug in the library. PEROBS.log.fatal "POXReference objects should never be cached" end @reads[index(obj)] = obj end
ruby
def cache_read(obj) # This is just a safety check. It can probably be disabled in the future # to increase performance. if obj.respond_to?(:is_poxreference?) # If this condition triggers, we have a bug in the library. PEROBS.log.fatal "POXReference objects should never be cached" end @reads[index(obj)] = obj end
[ "def", "cache_read", "(", "obj", ")", "if", "obj", ".", "respond_to?", "(", ":is_poxreference?", ")", "PEROBS", ".", "log", ".", "fatal", "\"POXReference objects should never be cached\"", "end", "@reads", "[", "index", "(", "obj", ")", "]", "=", "obj", "end" ]
Create a new Cache object. @param bits [Integer] Number of bits for the cache index. This parameter heavilty affects the performance and memory consumption of the cache. Add an PEROBS::Object to the read cache. @param obj [PEROBS::ObjectBase]
[ "Create", "a", "new", "Cache", "object", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Cache.rb#L54-L62
train
scrapper/perobs
lib/perobs/Cache.rb
PEROBS.Cache.begin_transaction
def begin_transaction if @transaction_stack.empty? # The new transaction is the top-level transaction. Flush the write # buffer to save the current state of all objects. flush else # Save a copy of all objects that were modified during the enclosing # transaction. @transaction_stack.last.each do |id| @transaction_objects[id]._stash(@transaction_stack.length - 1) end end # Push a transaction buffer onto the transaction stack. This buffer will # hold a reference to all objects modified during this transaction. @transaction_stack.push(::Array.new) end
ruby
def begin_transaction if @transaction_stack.empty? # The new transaction is the top-level transaction. Flush the write # buffer to save the current state of all objects. flush else # Save a copy of all objects that were modified during the enclosing # transaction. @transaction_stack.last.each do |id| @transaction_objects[id]._stash(@transaction_stack.length - 1) end end # Push a transaction buffer onto the transaction stack. This buffer will # hold a reference to all objects modified during this transaction. @transaction_stack.push(::Array.new) end
[ "def", "begin_transaction", "if", "@transaction_stack", ".", "empty?", "flush", "else", "@transaction_stack", ".", "last", ".", "each", "do", "|", "id", "|", "@transaction_objects", "[", "id", "]", ".", "_stash", "(", "@transaction_stack", ".", "length", "-", "1", ")", "end", "end", "@transaction_stack", ".", "push", "(", "::", "Array", ".", "new", ")", "end" ]
Tell the cache to start a new transaction. If no other transaction is active, the write cache is flushed before the transaction is started.
[ "Tell", "the", "cache", "to", "start", "a", "new", "transaction", ".", "If", "no", "other", "transaction", "is", "active", "the", "write", "cache", "is", "flushed", "before", "the", "transaction", "is", "started", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Cache.rb#L128-L143
train
scrapper/perobs
lib/perobs/Cache.rb
PEROBS.Cache.end_transaction
def end_transaction case @transaction_stack.length when 0 PEROBS.log.fatal 'No ongoing transaction to end' when 1 # All transactions completed successfully. Write all modified objects # into the backend storage. @transaction_stack.pop.each { |id| @transaction_objects[id]._sync } @transaction_objects = ::Hash.new else # A nested transaction completed successfully. We add the list of # modified objects to the list of the enclosing transaction. transactions = @transaction_stack.pop # Merge the two lists @transaction_stack.push(@transaction_stack.pop + transactions) # Ensure that each object is only included once in the list. @transaction_stack.last.uniq! end end
ruby
def end_transaction case @transaction_stack.length when 0 PEROBS.log.fatal 'No ongoing transaction to end' when 1 # All transactions completed successfully. Write all modified objects # into the backend storage. @transaction_stack.pop.each { |id| @transaction_objects[id]._sync } @transaction_objects = ::Hash.new else # A nested transaction completed successfully. We add the list of # modified objects to the list of the enclosing transaction. transactions = @transaction_stack.pop # Merge the two lists @transaction_stack.push(@transaction_stack.pop + transactions) # Ensure that each object is only included once in the list. @transaction_stack.last.uniq! end end
[ "def", "end_transaction", "case", "@transaction_stack", ".", "length", "when", "0", "PEROBS", ".", "log", ".", "fatal", "'No ongoing transaction to end'", "when", "1", "@transaction_stack", ".", "pop", ".", "each", "{", "|", "id", "|", "@transaction_objects", "[", "id", "]", ".", "_sync", "}", "@transaction_objects", "=", "::", "Hash", ".", "new", "else", "transactions", "=", "@transaction_stack", ".", "pop", "@transaction_stack", ".", "push", "(", "@transaction_stack", ".", "pop", "+", "transactions", ")", "@transaction_stack", ".", "last", ".", "uniq!", "end", "end" ]
Tell the cache to end the currently active transaction. All write operations of the current transaction will be synced to the storage back-end.
[ "Tell", "the", "cache", "to", "end", "the", "currently", "active", "transaction", ".", "All", "write", "operations", "of", "the", "current", "transaction", "will", "be", "synced", "to", "the", "storage", "back", "-", "end", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Cache.rb#L148-L166
train
scrapper/perobs
lib/perobs/Cache.rb
PEROBS.Cache.abort_transaction
def abort_transaction if @transaction_stack.empty? PEROBS.log.fatal 'No ongoing transaction to abort' end @transaction_stack.pop.each do |id| @transaction_objects[id]._restore(@transaction_stack.length) end end
ruby
def abort_transaction if @transaction_stack.empty? PEROBS.log.fatal 'No ongoing transaction to abort' end @transaction_stack.pop.each do |id| @transaction_objects[id]._restore(@transaction_stack.length) end end
[ "def", "abort_transaction", "if", "@transaction_stack", ".", "empty?", "PEROBS", ".", "log", ".", "fatal", "'No ongoing transaction to abort'", "end", "@transaction_stack", ".", "pop", ".", "each", "do", "|", "id", "|", "@transaction_objects", "[", "id", "]", ".", "_restore", "(", "@transaction_stack", ".", "length", ")", "end", "end" ]
Tell the cache to abort the currently active transaction. All modified objects will be restored from the storage back-end to their state before the transaction started.
[ "Tell", "the", "cache", "to", "abort", "the", "currently", "active", "transaction", ".", "All", "modified", "objects", "will", "be", "restored", "from", "the", "storage", "back", "-", "end", "to", "their", "state", "before", "the", "transaction", "started", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/Cache.rb#L171-L178
train
proglottis/glicko2
lib/glicko2/player.rb
Glicko2.Player.update_obj
def update_obj mean, sd = rating.to_glicko_rating @obj.rating = mean @obj.rating_deviation = sd @obj.volatility = volatility end
ruby
def update_obj mean, sd = rating.to_glicko_rating @obj.rating = mean @obj.rating_deviation = sd @obj.volatility = volatility end
[ "def", "update_obj", "mean", ",", "sd", "=", "rating", ".", "to_glicko_rating", "@obj", ".", "rating", "=", "mean", "@obj", ".", "rating_deviation", "=", "sd", "@obj", ".", "volatility", "=", "volatility", "end" ]
Update seed object with this player's values
[ "Update", "seed", "object", "with", "this", "player", "s", "values" ]
8ede9a758a1a35b2bc5e6d4706aad856ec8f7812
https://github.com/proglottis/glicko2/blob/8ede9a758a1a35b2bc5e6d4706aad856ec8f7812/lib/glicko2/player.rb#L22-L27
train
dirkholzapfel/abuelo
lib/abuelo/graph.rb
Abuelo.Graph.add_node
def add_node(node) raise Abuelo::Exceptions::NodeAlreadyExistsError if has_node?(node) @nodes[node.name] = node node.graph = self self end
ruby
def add_node(node) raise Abuelo::Exceptions::NodeAlreadyExistsError if has_node?(node) @nodes[node.name] = node node.graph = self self end
[ "def", "add_node", "(", "node", ")", "raise", "Abuelo", "::", "Exceptions", "::", "NodeAlreadyExistsError", "if", "has_node?", "(", "node", ")", "@nodes", "[", "node", ".", "name", "]", "=", "node", "node", ".", "graph", "=", "self", "self", "end" ]
Adds a node to the graph. @param [Abuelo::Node] node to add @return [Abuelo::Graph] the graph @raise [Abuelo::Exceptions::NodeAlreadyExistsError] if the node is already contained in the graph
[ "Adds", "a", "node", "to", "the", "graph", "." ]
3395b4ea386a12dfe747228eaf400029bcc1143a
https://github.com/dirkholzapfel/abuelo/blob/3395b4ea386a12dfe747228eaf400029bcc1143a/lib/abuelo/graph.rb#L80-L87
train
dirkholzapfel/abuelo
lib/abuelo/graph.rb
Abuelo.Graph.add_edge
def add_edge(edge, opts = {}) raise Abuelo::Exceptions::EdgeAlreadyExistsError if has_edge?(edge) @edges[edge.node_1] ||= {} @edges[edge.node_1][edge.node_2] = edge if undirected? && !opts[:symmetric] add_edge(edge.symmetric, symmetric: true) end self end
ruby
def add_edge(edge, opts = {}) raise Abuelo::Exceptions::EdgeAlreadyExistsError if has_edge?(edge) @edges[edge.node_1] ||= {} @edges[edge.node_1][edge.node_2] = edge if undirected? && !opts[:symmetric] add_edge(edge.symmetric, symmetric: true) end self end
[ "def", "add_edge", "(", "edge", ",", "opts", "=", "{", "}", ")", "raise", "Abuelo", "::", "Exceptions", "::", "EdgeAlreadyExistsError", "if", "has_edge?", "(", "edge", ")", "@edges", "[", "edge", ".", "node_1", "]", "||=", "{", "}", "@edges", "[", "edge", ".", "node_1", "]", "[", "edge", ".", "node_2", "]", "=", "edge", "if", "undirected?", "&&", "!", "opts", "[", ":symmetric", "]", "add_edge", "(", "edge", ".", "symmetric", ",", "symmetric", ":", "true", ")", "end", "self", "end" ]
Adds an edge to the graph. Auto-adds the symmetric counterpart if graph is undirected. @param [Abuelo::Edge] edge to add @return [Abuelo::Graph] the graph @raise [Abuelo::Exceptions::EdgeAlreadyExistsError] if the edge is already contained in the graph
[ "Adds", "an", "edge", "to", "the", "graph", ".", "Auto", "-", "adds", "the", "symmetric", "counterpart", "if", "graph", "is", "undirected", "." ]
3395b4ea386a12dfe747228eaf400029bcc1143a
https://github.com/dirkholzapfel/abuelo/blob/3395b4ea386a12dfe747228eaf400029bcc1143a/lib/abuelo/graph.rb#L154-L165
train
xinminlabs/synvert-core
lib/synvert/core/rewriter/instance.rb
Synvert::Core.Rewriter::Instance.process
def process file_pattern = File.join(Configuration.instance.get(:path), @file_pattern) Dir.glob(file_pattern).each do |file_path| unless Configuration.instance.get(:skip_files).include? file_path begin conflict_actions = [] source = self.class.file_source(file_path) ast = self.class.file_ast(file_path) @current_file = file_path self.process_with_node ast do begin instance_eval &@block rescue NoMethodError puts @current_node.debug_info raise end end if @actions.length > 0 @actions.sort_by! { |action| action.send(@options[:sort_by]) } conflict_actions = get_conflict_actions @actions.reverse.each do |action| source[action.begin_pos...action.end_pos] = action.rewritten_code source = remove_code_or_whole_line(source, action.line) end @actions = [] self.class.write_file(file_path, source) end rescue Parser::SyntaxError puts "[Warn] file #{file_path} was not parsed correctly." # do nothing, iterate next file end while !conflict_actions.empty? end end end
ruby
def process file_pattern = File.join(Configuration.instance.get(:path), @file_pattern) Dir.glob(file_pattern).each do |file_path| unless Configuration.instance.get(:skip_files).include? file_path begin conflict_actions = [] source = self.class.file_source(file_path) ast = self.class.file_ast(file_path) @current_file = file_path self.process_with_node ast do begin instance_eval &@block rescue NoMethodError puts @current_node.debug_info raise end end if @actions.length > 0 @actions.sort_by! { |action| action.send(@options[:sort_by]) } conflict_actions = get_conflict_actions @actions.reverse.each do |action| source[action.begin_pos...action.end_pos] = action.rewritten_code source = remove_code_or_whole_line(source, action.line) end @actions = [] self.class.write_file(file_path, source) end rescue Parser::SyntaxError puts "[Warn] file #{file_path} was not parsed correctly." # do nothing, iterate next file end while !conflict_actions.empty? end end end
[ "def", "process", "file_pattern", "=", "File", ".", "join", "(", "Configuration", ".", "instance", ".", "get", "(", ":path", ")", ",", "@file_pattern", ")", "Dir", ".", "glob", "(", "file_pattern", ")", ".", "each", "do", "|", "file_path", "|", "unless", "Configuration", ".", "instance", ".", "get", "(", ":skip_files", ")", ".", "include?", "file_path", "begin", "conflict_actions", "=", "[", "]", "source", "=", "self", ".", "class", ".", "file_source", "(", "file_path", ")", "ast", "=", "self", ".", "class", ".", "file_ast", "(", "file_path", ")", "@current_file", "=", "file_path", "self", ".", "process_with_node", "ast", "do", "begin", "instance_eval", "&", "@block", "rescue", "NoMethodError", "puts", "@current_node", ".", "debug_info", "raise", "end", "end", "if", "@actions", ".", "length", ">", "0", "@actions", ".", "sort_by!", "{", "|", "action", "|", "action", ".", "send", "(", "@options", "[", ":sort_by", "]", ")", "}", "conflict_actions", "=", "get_conflict_actions", "@actions", ".", "reverse", ".", "each", "do", "|", "action", "|", "source", "[", "action", ".", "begin_pos", "...", "action", ".", "end_pos", "]", "=", "action", ".", "rewritten_code", "source", "=", "remove_code_or_whole_line", "(", "source", ",", "action", ".", "line", ")", "end", "@actions", "=", "[", "]", "self", ".", "class", ".", "write_file", "(", "file_path", ",", "source", ")", "end", "rescue", "Parser", "::", "SyntaxError", "puts", "\"[Warn] file #{file_path} was not parsed correctly.\"", "end", "while", "!", "conflict_actions", ".", "empty?", "end", "end", "end" ]
Initialize an instance. @param rewriter [Synvert::Core::Rewriter] @param file_pattern [String] pattern to find files, e.g. spec/**/*_spec.rb @param options [Hash] instance options, it includes :sort_by. @param block [Block] block code to find nodes, match conditions and rewrite code. @return [Synvert::Core::Rewriter::Instance] Process the instance. It finds all files, for each file, it executes the block code, gets all rewrite actions, and rewrite source code back to original file.
[ "Initialize", "an", "instance", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/rewriter/instance.rb#L88-L125
train
xinminlabs/synvert-core
lib/synvert/core/rewriter/instance.rb
Synvert::Core.Rewriter::Instance.get_conflict_actions
def get_conflict_actions i = @actions.length - 1 j = i - 1 conflict_actions = [] return if i < 0 begin_pos = @actions[i].begin_pos while j > -1 if begin_pos <= @actions[j].end_pos conflict_actions << @actions.delete_at(j) else i = j begin_pos = @actions[i].begin_pos end j -= 1 end conflict_actions end
ruby
def get_conflict_actions i = @actions.length - 1 j = i - 1 conflict_actions = [] return if i < 0 begin_pos = @actions[i].begin_pos while j > -1 if begin_pos <= @actions[j].end_pos conflict_actions << @actions.delete_at(j) else i = j begin_pos = @actions[i].begin_pos end j -= 1 end conflict_actions end
[ "def", "get_conflict_actions", "i", "=", "@actions", ".", "length", "-", "1", "j", "=", "i", "-", "1", "conflict_actions", "=", "[", "]", "return", "if", "i", "<", "0", "begin_pos", "=", "@actions", "[", "i", "]", ".", "begin_pos", "while", "j", ">", "-", "1", "if", "begin_pos", "<=", "@actions", "[", "j", "]", ".", "end_pos", "conflict_actions", "<<", "@actions", ".", "delete_at", "(", "j", ")", "else", "i", "=", "j", "begin_pos", "=", "@actions", "[", "i", "]", ".", "begin_pos", "end", "j", "-=", "1", "end", "conflict_actions", "end" ]
It changes source code from bottom to top, and it can change source code twice at the same time, So if there is an overlap between two actions, it removes the conflict actions and operate them in the next loop.
[ "It", "changes", "source", "code", "from", "bottom", "to", "top", "and", "it", "can", "change", "source", "code", "twice", "at", "the", "same", "time", "So", "if", "there", "is", "an", "overlap", "between", "two", "actions", "it", "removes", "the", "conflict", "actions", "and", "operate", "them", "in", "the", "next", "loop", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/rewriter/instance.rb#L265-L282
train
xinminlabs/synvert-core
lib/synvert/core/rewriter/instance.rb
Synvert::Core.Rewriter::Instance.remove_code_or_whole_line
def remove_code_or_whole_line(source, line) newline_at_end_of_line = source[-1] == "\n" source_arr = source.split("\n") if source_arr[line - 1] && source_arr[line - 1].strip.empty? source_arr.delete_at(line - 1) if source_arr[line - 2] && source_arr[line - 2].strip.empty? && source_arr[line - 1] && source_arr[line - 1].strip.empty? source_arr.delete_at(line - 1) end source_arr.join("\n") + (newline_at_end_of_line ? "\n" : '') else source end end
ruby
def remove_code_or_whole_line(source, line) newline_at_end_of_line = source[-1] == "\n" source_arr = source.split("\n") if source_arr[line - 1] && source_arr[line - 1].strip.empty? source_arr.delete_at(line - 1) if source_arr[line - 2] && source_arr[line - 2].strip.empty? && source_arr[line - 1] && source_arr[line - 1].strip.empty? source_arr.delete_at(line - 1) end source_arr.join("\n") + (newline_at_end_of_line ? "\n" : '') else source end end
[ "def", "remove_code_or_whole_line", "(", "source", ",", "line", ")", "newline_at_end_of_line", "=", "source", "[", "-", "1", "]", "==", "\"\\n\"", "source_arr", "=", "source", ".", "split", "(", "\"\\n\"", ")", "if", "source_arr", "[", "line", "-", "1", "]", "&&", "source_arr", "[", "line", "-", "1", "]", ".", "strip", ".", "empty?", "source_arr", ".", "delete_at", "(", "line", "-", "1", ")", "if", "source_arr", "[", "line", "-", "2", "]", "&&", "source_arr", "[", "line", "-", "2", "]", ".", "strip", ".", "empty?", "&&", "source_arr", "[", "line", "-", "1", "]", "&&", "source_arr", "[", "line", "-", "1", "]", ".", "strip", ".", "empty?", "source_arr", ".", "delete_at", "(", "line", "-", "1", ")", "end", "source_arr", ".", "join", "(", "\"\\n\"", ")", "+", "(", "newline_at_end_of_line", "?", "\"\\n\"", ":", "''", ")", "else", "source", "end", "end" ]
It checks if code is removed and that line is empty. @param source [String] source code of file @param line [String] the line number
[ "It", "checks", "if", "code", "is", "removed", "and", "that", "line", "is", "empty", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/rewriter/instance.rb#L288-L300
train
SmallLars/openssl-ccm
lib/openssl/ccm.rb
OpenSSL.CCM.encrypt
def encrypt(data, nonce, additional_data = '') valid?(data, nonce, additional_data) crypt(data, nonce) + mac(data, nonce, additional_data) end
ruby
def encrypt(data, nonce, additional_data = '') valid?(data, nonce, additional_data) crypt(data, nonce) + mac(data, nonce, additional_data) end
[ "def", "encrypt", "(", "data", ",", "nonce", ",", "additional_data", "=", "''", ")", "valid?", "(", "data", ",", "nonce", ",", "additional_data", ")", "crypt", "(", "data", ",", "nonce", ")", "+", "mac", "(", "data", ",", "nonce", ",", "additional_data", ")", "end" ]
Creates a new CCM object. @param cipher [String] one of the supported algorithms like 'AES' @param key [String] the key used for encryption and decryption @param mac_len [Number] the length of the mac. needs to be in 4, 6, 8, 10, 12, 14, 16 @return [Object] the new CCM object Encrypts the input data and appends mac for authentication. If there is additional data, its included into mac calculation. @param data [String] the data to encrypt @param nonce [String] the nonce used for encryption @param additional_data [String] additional data to authenticate with mac (not part of the output) @return [String] the encrypted data with appended mac
[ "Creates", "a", "new", "CCM", "object", "." ]
15f258f0db5779a3fb186ab7f957eb8c2bcef13a
https://github.com/SmallLars/openssl-ccm/blob/15f258f0db5779a3fb186ab7f957eb8c2bcef13a/lib/openssl/ccm.rb#L68-L72
train
PublicHealthEngland/ndr_support
lib/ndr_support/utf8_encoding/force_binary.rb
UTF8Encoding.ForceBinary.binary_encode_if_any_high_ascii
def binary_encode_if_any_high_ascii(string) string = ensure_utf8(string) string.force_encoding('BINARY') if string.bytes.detect { |byte| byte > 127 } string end
ruby
def binary_encode_if_any_high_ascii(string) string = ensure_utf8(string) string.force_encoding('BINARY') if string.bytes.detect { |byte| byte > 127 } string end
[ "def", "binary_encode_if_any_high_ascii", "(", "string", ")", "string", "=", "ensure_utf8", "(", "string", ")", "string", ".", "force_encoding", "(", "'BINARY'", ")", "if", "string", ".", "bytes", ".", "detect", "{", "|", "byte", "|", "byte", ">", "127", "}", "string", "end" ]
Returns a BINARY-encoded version of `string`, if is cannot be represented as 7bit ASCII.
[ "Returns", "a", "BINARY", "-", "encoded", "version", "of", "string", "if", "is", "cannot", "be", "represented", "as", "7bit", "ASCII", "." ]
6daf98ca972e79de1c8457eb720f058b03ead21c
https://github.com/PublicHealthEngland/ndr_support/blob/6daf98ca972e79de1c8457eb720f058b03ead21c/lib/ndr_support/utf8_encoding/force_binary.rb#L28-L32
train
PublicHealthEngland/ndr_support
lib/ndr_support/utf8_encoding/force_binary.rb
UTF8Encoding.ForceBinary.binary_encode_any_high_ascii_in_hash
def binary_encode_any_high_ascii_in_hash(hash) Hash[hash.map { |key, value| [key, binary_encode_any_high_ascii(value)] }] end
ruby
def binary_encode_any_high_ascii_in_hash(hash) Hash[hash.map { |key, value| [key, binary_encode_any_high_ascii(value)] }] end
[ "def", "binary_encode_any_high_ascii_in_hash", "(", "hash", ")", "Hash", "[", "hash", ".", "map", "{", "|", "key", ",", "value", "|", "[", "key", ",", "binary_encode_any_high_ascii", "(", "value", ")", "]", "}", "]", "end" ]
Ensures all values of the given `hash` are BINARY-encoded, if necessary.
[ "Ensures", "all", "values", "of", "the", "given", "hash", "are", "BINARY", "-", "encoded", "if", "necessary", "." ]
6daf98ca972e79de1c8457eb720f058b03ead21c
https://github.com/PublicHealthEngland/ndr_support/blob/6daf98ca972e79de1c8457eb720f058b03ead21c/lib/ndr_support/utf8_encoding/force_binary.rb#L35-L37
train
xinminlabs/synvert-core
lib/synvert/core/node_ext.rb
Parser::AST.Node.has_key?
def has_key?(key) if :hash == self.type self.children.any? { |pair_node| pair_node.key.to_value == key } else raise Synvert::Core::MethodNotSupported.new "has_key? is not handled for #{self.debug_info}" end end
ruby
def has_key?(key) if :hash == self.type self.children.any? { |pair_node| pair_node.key.to_value == key } else raise Synvert::Core::MethodNotSupported.new "has_key? is not handled for #{self.debug_info}" end end
[ "def", "has_key?", "(", "key", ")", "if", ":hash", "==", "self", ".", "type", "self", ".", "children", ".", "any?", "{", "|", "pair_node", "|", "pair_node", ".", "key", ".", "to_value", "==", "key", "}", "else", "raise", "Synvert", "::", "Core", "::", "MethodNotSupported", ".", "new", "\"has_key? is not handled for #{self.debug_info}\"", "end", "end" ]
Test if hash node contains specified key. @param [Object] key value. @return [Boolean] true if specified key exists. @raise [Synvert::Core::MethodNotSupported] if calls on other node.
[ "Test", "if", "hash", "node", "contains", "specified", "key", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L186-L192
train
xinminlabs/synvert-core
lib/synvert/core/node_ext.rb
Parser::AST.Node.hash_value
def hash_value(key) if :hash == self.type value_node = self.children.find { |pair_node| pair_node.key.to_value == key } value_node ? value_node.value : nil else raise Synvert::Core::MethodNotSupported.new "has_key? is not handled for #{self.debug_info}" end end
ruby
def hash_value(key) if :hash == self.type value_node = self.children.find { |pair_node| pair_node.key.to_value == key } value_node ? value_node.value : nil else raise Synvert::Core::MethodNotSupported.new "has_key? is not handled for #{self.debug_info}" end end
[ "def", "hash_value", "(", "key", ")", "if", ":hash", "==", "self", ".", "type", "value_node", "=", "self", ".", "children", ".", "find", "{", "|", "pair_node", "|", "pair_node", ".", "key", ".", "to_value", "==", "key", "}", "value_node", "?", "value_node", ".", "value", ":", "nil", "else", "raise", "Synvert", "::", "Core", "::", "MethodNotSupported", ".", "new", "\"has_key? is not handled for #{self.debug_info}\"", "end", "end" ]
Get hash value node according to specified key. @param [Object] key value. @return [Parser::AST::Node] value node. @raise [Synvert::Core::MethodNotSupported] if calls on other node.
[ "Get", "hash", "value", "node", "according", "to", "specified", "key", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L199-L206
train
xinminlabs/synvert-core
lib/synvert/core/node_ext.rb
Parser::AST.Node.to_value
def to_value case self.type when :int, :str, :sym self.children.last when :true true when :false false when :array self.children.map(&:to_value) when :irange (self.children.first.to_value..self.children.last.to_value) when :begin self.children.first.to_value else raise Synvert::Core::MethodNotSupported.new "to_value is not handled for #{self.debug_info}" end end
ruby
def to_value case self.type when :int, :str, :sym self.children.last when :true true when :false false when :array self.children.map(&:to_value) when :irange (self.children.first.to_value..self.children.last.to_value) when :begin self.children.first.to_value else raise Synvert::Core::MethodNotSupported.new "to_value is not handled for #{self.debug_info}" end end
[ "def", "to_value", "case", "self", ".", "type", "when", ":int", ",", ":str", ",", ":sym", "self", ".", "children", ".", "last", "when", ":true", "true", "when", ":false", "false", "when", ":array", "self", ".", "children", ".", "map", "(", "&", ":to_value", ")", "when", ":irange", "(", "self", ".", "children", ".", "first", ".", "to_value", "..", "self", ".", "children", ".", "last", ".", "to_value", ")", "when", ":begin", "self", ".", "children", ".", "first", ".", "to_value", "else", "raise", "Synvert", "::", "Core", "::", "MethodNotSupported", ".", "new", "\"to_value is not handled for #{self.debug_info}\"", "end", "end" ]
Return the exact value. @return [Object] exact value. @raise [Synvert::Core::MethodNotSupported] if calls on other node.
[ "Return", "the", "exact", "value", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L260-L277
train
xinminlabs/synvert-core
lib/synvert/core/node_ext.rb
Parser::AST.Node.recursive_children
def recursive_children self.children.each do |child| if Parser::AST::Node === child yield child child.recursive_children { |c| yield c } end end end
ruby
def recursive_children self.children.each do |child| if Parser::AST::Node === child yield child child.recursive_children { |c| yield c } end end end
[ "def", "recursive_children", "self", ".", "children", ".", "each", "do", "|", "child", "|", "if", "Parser", "::", "AST", "::", "Node", "===", "child", "yield", "child", "child", ".", "recursive_children", "{", "|", "c", "|", "yield", "c", "}", "end", "end", "end" ]
Recursively iterate all child nodes of current node. @yield [child] Gives a child node. @yieldparam child [Parser::AST::Node] child node
[ "Recursively", "iterate", "all", "child", "nodes", "of", "current", "node", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L321-L328
train
xinminlabs/synvert-core
lib/synvert/core/node_ext.rb
Parser::AST.Node.match?
def match?(rules) flat_hash(rules).keys.all? do |multi_keys| if multi_keys.last == :any actual_values = actual_value(self, multi_keys[0...-1]) expected = expected_value(rules, multi_keys) actual_values.any? { |actual| match_value?(actual, expected) } elsif multi_keys.last == :not actual = actual_value(self, multi_keys[0...-1]) expected = expected_value(rules, multi_keys) !match_value?(actual, expected) else actual = actual_value(self, multi_keys) expected = expected_value(rules, multi_keys) match_value?(actual, expected) end end end
ruby
def match?(rules) flat_hash(rules).keys.all? do |multi_keys| if multi_keys.last == :any actual_values = actual_value(self, multi_keys[0...-1]) expected = expected_value(rules, multi_keys) actual_values.any? { |actual| match_value?(actual, expected) } elsif multi_keys.last == :not actual = actual_value(self, multi_keys[0...-1]) expected = expected_value(rules, multi_keys) !match_value?(actual, expected) else actual = actual_value(self, multi_keys) expected = expected_value(rules, multi_keys) match_value?(actual, expected) end end end
[ "def", "match?", "(", "rules", ")", "flat_hash", "(", "rules", ")", ".", "keys", ".", "all?", "do", "|", "multi_keys", "|", "if", "multi_keys", ".", "last", "==", ":any", "actual_values", "=", "actual_value", "(", "self", ",", "multi_keys", "[", "0", "...", "-", "1", "]", ")", "expected", "=", "expected_value", "(", "rules", ",", "multi_keys", ")", "actual_values", ".", "any?", "{", "|", "actual", "|", "match_value?", "(", "actual", ",", "expected", ")", "}", "elsif", "multi_keys", ".", "last", "==", ":not", "actual", "=", "actual_value", "(", "self", ",", "multi_keys", "[", "0", "...", "-", "1", "]", ")", "expected", "=", "expected_value", "(", "rules", ",", "multi_keys", ")", "!", "match_value?", "(", "actual", ",", "expected", ")", "else", "actual", "=", "actual_value", "(", "self", ",", "multi_keys", ")", "expected", "=", "expected_value", "(", "rules", ",", "multi_keys", ")", "match_value?", "(", "actual", ",", "expected", ")", "end", "end", "end" ]
Match current node with rules. @param rules [Hash] rules to match. @return true if matches.
[ "Match", "current", "node", "with", "rules", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L334-L350
train
xinminlabs/synvert-core
lib/synvert/core/node_ext.rb
Parser::AST.Node.match_value?
def match_value?(actual, expected) case expected when Symbol if Parser::AST::Node === actual actual.to_source == ":#{expected}" else actual.to_sym == expected end when String if Parser::AST::Node === actual actual.to_source == expected || (actual.to_source[0] == ':' && actual.to_source[1..-1] == expected) || actual.to_source[1...-1] == expected else actual.to_s == expected end when Regexp if Parser::AST::Node === actual actual.to_source =~ Regexp.new(expected.to_s, Regexp::MULTILINE) else actual.to_s =~ Regexp.new(expected.to_s, Regexp::MULTILINE) end when Array return false unless expected.length == actual.length actual.zip(expected).all? { |a, e| match_value?(a, e) } when NilClass actual.nil? when Numeric if Parser::AST::Node === actual actual.children[0] == expected else actual == expected end when TrueClass :true == actual.type when FalseClass :false == actual.type when Parser::AST::Node actual == expected else raise Synvert::Core::MethodNotSupported.new "#{expected.class} is not handled for match_value?" end end
ruby
def match_value?(actual, expected) case expected when Symbol if Parser::AST::Node === actual actual.to_source == ":#{expected}" else actual.to_sym == expected end when String if Parser::AST::Node === actual actual.to_source == expected || (actual.to_source[0] == ':' && actual.to_source[1..-1] == expected) || actual.to_source[1...-1] == expected else actual.to_s == expected end when Regexp if Parser::AST::Node === actual actual.to_source =~ Regexp.new(expected.to_s, Regexp::MULTILINE) else actual.to_s =~ Regexp.new(expected.to_s, Regexp::MULTILINE) end when Array return false unless expected.length == actual.length actual.zip(expected).all? { |a, e| match_value?(a, e) } when NilClass actual.nil? when Numeric if Parser::AST::Node === actual actual.children[0] == expected else actual == expected end when TrueClass :true == actual.type when FalseClass :false == actual.type when Parser::AST::Node actual == expected else raise Synvert::Core::MethodNotSupported.new "#{expected.class} is not handled for match_value?" end end
[ "def", "match_value?", "(", "actual", ",", "expected", ")", "case", "expected", "when", "Symbol", "if", "Parser", "::", "AST", "::", "Node", "===", "actual", "actual", ".", "to_source", "==", "\":#{expected}\"", "else", "actual", ".", "to_sym", "==", "expected", "end", "when", "String", "if", "Parser", "::", "AST", "::", "Node", "===", "actual", "actual", ".", "to_source", "==", "expected", "||", "(", "actual", ".", "to_source", "[", "0", "]", "==", "':'", "&&", "actual", ".", "to_source", "[", "1", "..", "-", "1", "]", "==", "expected", ")", "||", "actual", ".", "to_source", "[", "1", "...", "-", "1", "]", "==", "expected", "else", "actual", ".", "to_s", "==", "expected", "end", "when", "Regexp", "if", "Parser", "::", "AST", "::", "Node", "===", "actual", "actual", ".", "to_source", "=~", "Regexp", ".", "new", "(", "expected", ".", "to_s", ",", "Regexp", "::", "MULTILINE", ")", "else", "actual", ".", "to_s", "=~", "Regexp", ".", "new", "(", "expected", ".", "to_s", ",", "Regexp", "::", "MULTILINE", ")", "end", "when", "Array", "return", "false", "unless", "expected", ".", "length", "==", "actual", ".", "length", "actual", ".", "zip", "(", "expected", ")", ".", "all?", "{", "|", "a", ",", "e", "|", "match_value?", "(", "a", ",", "e", ")", "}", "when", "NilClass", "actual", ".", "nil?", "when", "Numeric", "if", "Parser", "::", "AST", "::", "Node", "===", "actual", "actual", ".", "children", "[", "0", "]", "==", "expected", "else", "actual", "==", "expected", "end", "when", "TrueClass", ":true", "==", "actual", ".", "type", "when", "FalseClass", ":false", "==", "actual", ".", "type", "when", "Parser", "::", "AST", "::", "Node", "actual", "==", "expected", "else", "raise", "Synvert", "::", "Core", "::", "MethodNotSupported", ".", "new", "\"#{expected.class} is not handled for match_value?\"", "end", "end" ]
Compare actual value with expected value. @param actual [Object] actual value. @param expected [Object] expected value. @return [Integer] -1, 0 or 1. @raise [Synvert::Core::MethodNotSupported] if expected class is not supported.
[ "Compare", "actual", "value", "with", "expected", "value", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L404-L446
train
xinminlabs/synvert-core
lib/synvert/core/node_ext.rb
Parser::AST.Node.flat_hash
def flat_hash(h, k = []) new_hash = {} h.each_pair do |key, val| if val.is_a?(Hash) new_hash.merge!(flat_hash(val, k + [key])) else new_hash[k + [key]] = val end end new_hash end
ruby
def flat_hash(h, k = []) new_hash = {} h.each_pair do |key, val| if val.is_a?(Hash) new_hash.merge!(flat_hash(val, k + [key])) else new_hash[k + [key]] = val end end new_hash end
[ "def", "flat_hash", "(", "h", ",", "k", "=", "[", "]", ")", "new_hash", "=", "{", "}", "h", ".", "each_pair", "do", "|", "key", ",", "val", "|", "if", "val", ".", "is_a?", "(", "Hash", ")", "new_hash", ".", "merge!", "(", "flat_hash", "(", "val", ",", "k", "+", "[", "key", "]", ")", ")", "else", "new_hash", "[", "k", "+", "[", "key", "]", "]", "=", "val", "end", "end", "new_hash", "end" ]
Convert a hash to flat one. @example flat_hash(type: 'block', caller: {type: 'send', receiver: 'RSpec'}) #=> {[:type] => 'block', [:caller, :type] => 'send', [:caller, :receiver] => 'RSpec'} @param h [Hash] original hash. @return flatten hash.
[ "Convert", "a", "hash", "to", "flat", "one", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L455-L465
train
xinminlabs/synvert-core
lib/synvert/core/node_ext.rb
Parser::AST.Node.actual_value
def actual_value(node, multi_keys) multi_keys.inject(node) { |n, key| if n key == :source ? n.send(key) : n.send(key) end } end
ruby
def actual_value(node, multi_keys) multi_keys.inject(node) { |n, key| if n key == :source ? n.send(key) : n.send(key) end } end
[ "def", "actual_value", "(", "node", ",", "multi_keys", ")", "multi_keys", ".", "inject", "(", "node", ")", "{", "|", "n", ",", "key", "|", "if", "n", "key", "==", ":source", "?", "n", ".", "send", "(", "key", ")", ":", "n", ".", "send", "(", "key", ")", "end", "}", "end" ]
Get actual value from the node. @param node [Parser::AST::Node] @param multi_keys [Array<Symbol>] @return [Object] actual value.
[ "Get", "actual", "value", "from", "the", "node", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L472-L478
train
xinminlabs/synvert-core
lib/synvert/core/node_ext.rb
Parser::AST.Node.expected_value
def expected_value(rules, multi_keys) multi_keys.inject(rules) { |o, key| o[key] } end
ruby
def expected_value(rules, multi_keys) multi_keys.inject(rules) { |o, key| o[key] } end
[ "def", "expected_value", "(", "rules", ",", "multi_keys", ")", "multi_keys", ".", "inject", "(", "rules", ")", "{", "|", "o", ",", "key", "|", "o", "[", "key", "]", "}", "end" ]
Get expected value from rules. @param rules [Hash] @param multi_keys [Array<Symbol>] @return [Object] expected value.
[ "Get", "expected", "value", "from", "rules", "." ]
a490bfd30eaec81002d10f8fb61b49138708e46c
https://github.com/xinminlabs/synvert-core/blob/a490bfd30eaec81002d10f8fb61b49138708e46c/lib/synvert/core/node_ext.rb#L485-L487
train
scrapper/perobs
lib/perobs/BigArrayNode.rb
PEROBS.BigArrayNode.set
def set(index, value) node = self # Traverse the tree to find the right node to add or replace the value. while node do # Once we have reached a leaf node we can insert or replace the value. if node.is_leaf? if index >= node.values.size node.fatal "Set index (#{index}) larger than values array " + "(#{node.values.size})." end node.values[index] = value return else # Descend into the right child node to add the value to. cidx = node.search_child_index(index) index -= node.offsets[cidx] node = node.children[cidx] end end node.fatal "Could not find proper node to set the value while " + "looking for index #{index}" end
ruby
def set(index, value) node = self # Traverse the tree to find the right node to add or replace the value. while node do # Once we have reached a leaf node we can insert or replace the value. if node.is_leaf? if index >= node.values.size node.fatal "Set index (#{index}) larger than values array " + "(#{node.values.size})." end node.values[index] = value return else # Descend into the right child node to add the value to. cidx = node.search_child_index(index) index -= node.offsets[cidx] node = node.children[cidx] end end node.fatal "Could not find proper node to set the value while " + "looking for index #{index}" end
[ "def", "set", "(", "index", ",", "value", ")", "node", "=", "self", "while", "node", "do", "if", "node", ".", "is_leaf?", "if", "index", ">=", "node", ".", "values", ".", "size", "node", ".", "fatal", "\"Set index (#{index}) larger than values array \"", "+", "\"(#{node.values.size}).\"", "end", "node", ".", "values", "[", "index", "]", "=", "value", "return", "else", "cidx", "=", "node", ".", "search_child_index", "(", "index", ")", "index", "-=", "node", ".", "offsets", "[", "cidx", "]", "node", "=", "node", ".", "children", "[", "cidx", "]", "end", "end", "node", ".", "fatal", "\"Could not find proper node to set the value while \"", "+", "\"looking for index #{index}\"", "end" ]
Set the given value at the given index. @param index [Integer] Position to insert at @param value [Integer] value to insert
[ "Set", "the", "given", "value", "at", "the", "given", "index", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigArrayNode.rb#L134-L157
train
scrapper/perobs
lib/perobs/BigArrayNode.rb
PEROBS.BigArrayNode.insert
def insert(index, value) node = self cidx = nil # Traverse the tree to find the right node to add or replace the value. while node do # All nodes that we find on the way that are full will be split into # two half-full nodes. if node.size >= @tree.node_size # Re-add the index from the last parent node since we will descent # into one of the split nodes. index += node.parent.offsets[cidx] if node.parent node = node.split_node end # Once we have reached a leaf node we can insert or replace the value. if node.is_leaf? node.values.insert(index, value) node.parent.adjust_offsets(node, 1) if node.parent return else # Descend into the right child node to add the value to. cidx = node.search_child_index(index) if (index -= node.offsets[cidx]) < 0 node.fatal "Index (#{index}) became negative" end node = node.children[cidx] end end node.fatal "Could not find proper node to insert the value while " + "looking for index #{index}" end
ruby
def insert(index, value) node = self cidx = nil # Traverse the tree to find the right node to add or replace the value. while node do # All nodes that we find on the way that are full will be split into # two half-full nodes. if node.size >= @tree.node_size # Re-add the index from the last parent node since we will descent # into one of the split nodes. index += node.parent.offsets[cidx] if node.parent node = node.split_node end # Once we have reached a leaf node we can insert or replace the value. if node.is_leaf? node.values.insert(index, value) node.parent.adjust_offsets(node, 1) if node.parent return else # Descend into the right child node to add the value to. cidx = node.search_child_index(index) if (index -= node.offsets[cidx]) < 0 node.fatal "Index (#{index}) became negative" end node = node.children[cidx] end end node.fatal "Could not find proper node to insert the value while " + "looking for index #{index}" end
[ "def", "insert", "(", "index", ",", "value", ")", "node", "=", "self", "cidx", "=", "nil", "while", "node", "do", "if", "node", ".", "size", ">=", "@tree", ".", "node_size", "index", "+=", "node", ".", "parent", ".", "offsets", "[", "cidx", "]", "if", "node", ".", "parent", "node", "=", "node", ".", "split_node", "end", "if", "node", ".", "is_leaf?", "node", ".", "values", ".", "insert", "(", "index", ",", "value", ")", "node", ".", "parent", ".", "adjust_offsets", "(", "node", ",", "1", ")", "if", "node", ".", "parent", "return", "else", "cidx", "=", "node", ".", "search_child_index", "(", "index", ")", "if", "(", "index", "-=", "node", ".", "offsets", "[", "cidx", "]", ")", "<", "0", "node", ".", "fatal", "\"Index (#{index}) became negative\"", "end", "node", "=", "node", ".", "children", "[", "cidx", "]", "end", "end", "node", ".", "fatal", "\"Could not find proper node to insert the value while \"", "+", "\"looking for index #{index}\"", "end" ]
Insert the given value at the given index. All following values will be pushed to a higher index. @param index [Integer] Position to insert at @param value [Integer] value to insert
[ "Insert", "the", "given", "value", "at", "the", "given", "index", ".", "All", "following", "values", "will", "be", "pushed", "to", "a", "higher", "index", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigArrayNode.rb#L163-L195
train
scrapper/perobs
lib/perobs/BigArrayNode.rb
PEROBS.BigArrayNode.value_index
def value_index(idx) node = self while node.parent idx += node.parent.offsets[node.index_in_parent_node] node = node.parent end idx end
ruby
def value_index(idx) node = self while node.parent idx += node.parent.offsets[node.index_in_parent_node] node = node.parent end idx end
[ "def", "value_index", "(", "idx", ")", "node", "=", "self", "while", "node", ".", "parent", "idx", "+=", "node", ".", "parent", ".", "offsets", "[", "node", ".", "index_in_parent_node", "]", "node", "=", "node", ".", "parent", "end", "idx", "end" ]
Compute the array index of the value with the given index in the current node. @param idx [Integer] Index of the value in the current node @return [Integer] Array index of the value
[ "Compute", "the", "array", "index", "of", "the", "value", "with", "the", "given", "index", "in", "the", "current", "node", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigArrayNode.rb#L647-L655
train
scrapper/perobs
lib/perobs/BigArrayNode.rb
PEROBS.BigArrayNode.move_first_element_of_successor_to_child
def move_first_element_of_successor_to_child(child_index) child = @children[child_index] succ = @children[child_index + 1] if child.is_leaf? # Adjust offset for the successor node @offsets[child_index + 1] += 1 # Move the value child.values << succ.values.shift else # Before: # # Root Node +--------------------------------+ # Offsets | 0 7 | # Children | | # child v succ v # Level 1 +---------------++-------------------------------------+ # Offsets | 0 4 || 0 4 6 9 | # Children | | | | | | # v v v v v v # Leaves +---------++-------++----------++-------++----------++-------+ # Values | A B C D || E F G || H I J K || L M || N O P || Q R | # # Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # # After: # # Root Node +--------------------------------+ # Offsets | 0 11 | # Children | | # child v succ v # Level 1 +--------------------------++--------------------------+ # Offsets | 0 4 7 || 0 2 5 | # Children | | | | | | # v v v v v v # Leaves +---------++-------++----------++-------++----------++-------+ # Values | A B C D || E F G || H I J K || L M || N O P || Q R | # # Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # # Adjust the offsets of the successor. The 2nd original offset # determines the delta for the parent node. succ.offsets.shift delta = succ.offsets.first succ.offsets.map! { |o| o -= delta } # The additional child offset can be taken from the parent node # reference. child.offsets << @offsets[child_index + 1] # The parent node offset of the successor needs to be corrected by the # delta value. @offsets[child_index + 1] += delta # Move the child reference child.children << succ.children.shift child.children.last.parent = child end end
ruby
def move_first_element_of_successor_to_child(child_index) child = @children[child_index] succ = @children[child_index + 1] if child.is_leaf? # Adjust offset for the successor node @offsets[child_index + 1] += 1 # Move the value child.values << succ.values.shift else # Before: # # Root Node +--------------------------------+ # Offsets | 0 7 | # Children | | # child v succ v # Level 1 +---------------++-------------------------------------+ # Offsets | 0 4 || 0 4 6 9 | # Children | | | | | | # v v v v v v # Leaves +---------++-------++----------++-------++----------++-------+ # Values | A B C D || E F G || H I J K || L M || N O P || Q R | # # Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # # After: # # Root Node +--------------------------------+ # Offsets | 0 11 | # Children | | # child v succ v # Level 1 +--------------------------++--------------------------+ # Offsets | 0 4 7 || 0 2 5 | # Children | | | | | | # v v v v v v # Leaves +---------++-------++----------++-------++----------++-------+ # Values | A B C D || E F G || H I J K || L M || N O P || Q R | # # Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # # Adjust the offsets of the successor. The 2nd original offset # determines the delta for the parent node. succ.offsets.shift delta = succ.offsets.first succ.offsets.map! { |o| o -= delta } # The additional child offset can be taken from the parent node # reference. child.offsets << @offsets[child_index + 1] # The parent node offset of the successor needs to be corrected by the # delta value. @offsets[child_index + 1] += delta # Move the child reference child.children << succ.children.shift child.children.last.parent = child end end
[ "def", "move_first_element_of_successor_to_child", "(", "child_index", ")", "child", "=", "@children", "[", "child_index", "]", "succ", "=", "@children", "[", "child_index", "+", "1", "]", "if", "child", ".", "is_leaf?", "@offsets", "[", "child_index", "+", "1", "]", "+=", "1", "child", ".", "values", "<<", "succ", ".", "values", ".", "shift", "else", "succ", ".", "offsets", ".", "shift", "delta", "=", "succ", ".", "offsets", ".", "first", "succ", ".", "offsets", ".", "map!", "{", "|", "o", "|", "o", "-=", "delta", "}", "child", ".", "offsets", "<<", "@offsets", "[", "child_index", "+", "1", "]", "@offsets", "[", "child_index", "+", "1", "]", "+=", "delta", "child", ".", "children", "<<", "succ", ".", "children", ".", "shift", "child", ".", "children", ".", "last", ".", "parent", "=", "child", "end", "end" ]
Move first element of successor to end of child node @param child_index [Integer] index of the child
[ "Move", "first", "element", "of", "successor", "to", "end", "of", "child", "node" ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigArrayNode.rb#L824-L879
train
scrapper/perobs
lib/perobs/BigArrayNode.rb
PEROBS.BigArrayNode.move_last_element_of_predecessor_to_child
def move_last_element_of_predecessor_to_child(child_index) pred = @children[child_index - 1] child = @children[child_index] if child.is_leaf? # Adjust offset for the predecessor node @offsets[child_index] -= 1 # Move the value child.values.unshift(pred.values.pop) else # Before: # # Root Node +--------------------------------+ # Offsets | 0 13 | # Children | | # pred v child v # Level 1 +---------------------------------++-------------------+ # Offsets | 0 4 7 11 || 0 3 | # Children | | | | | | # v v v v v v # Leaves +---------++-------++----------++-------++----------++-------+ # Values | A B C D || E F G || H I J K || L M || N O P || Q R | # # Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # # After: # # Root Node +--------------------------------+ # Offsets | 0 11 | # Children | | # prepd v child v # Level 1 +--------------------------++--------------------------+ # Offsets | 0 4 7 || 0 2 5 | # Children | | | | | | # v v v v v v # Leaves +---------++-------++----------++-------++----------++-------+ # Values | A B C D || E F G || H I J K || L M || N O P || Q R | # # Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # # Remove the last predecessor offset and update the child offset with # it delta = @offsets[child_index] - pred.offsets.last @offsets[child_index] = pred.offsets.pop # Adjust all the offsets of the child child.offsets.map! { |o| o += delta } # And prepend the 0 offset child.offsets.unshift(0) # Move the child reference child.children.unshift(pred.children.pop) child.children.first.parent = child end end
ruby
def move_last_element_of_predecessor_to_child(child_index) pred = @children[child_index - 1] child = @children[child_index] if child.is_leaf? # Adjust offset for the predecessor node @offsets[child_index] -= 1 # Move the value child.values.unshift(pred.values.pop) else # Before: # # Root Node +--------------------------------+ # Offsets | 0 13 | # Children | | # pred v child v # Level 1 +---------------------------------++-------------------+ # Offsets | 0 4 7 11 || 0 3 | # Children | | | | | | # v v v v v v # Leaves +---------++-------++----------++-------++----------++-------+ # Values | A B C D || E F G || H I J K || L M || N O P || Q R | # # Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # # After: # # Root Node +--------------------------------+ # Offsets | 0 11 | # Children | | # prepd v child v # Level 1 +--------------------------++--------------------------+ # Offsets | 0 4 7 || 0 2 5 | # Children | | | | | | # v v v v v v # Leaves +---------++-------++----------++-------++----------++-------+ # Values | A B C D || E F G || H I J K || L M || N O P || Q R | # # Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # # Remove the last predecessor offset and update the child offset with # it delta = @offsets[child_index] - pred.offsets.last @offsets[child_index] = pred.offsets.pop # Adjust all the offsets of the child child.offsets.map! { |o| o += delta } # And prepend the 0 offset child.offsets.unshift(0) # Move the child reference child.children.unshift(pred.children.pop) child.children.first.parent = child end end
[ "def", "move_last_element_of_predecessor_to_child", "(", "child_index", ")", "pred", "=", "@children", "[", "child_index", "-", "1", "]", "child", "=", "@children", "[", "child_index", "]", "if", "child", ".", "is_leaf?", "@offsets", "[", "child_index", "]", "-=", "1", "child", ".", "values", ".", "unshift", "(", "pred", ".", "values", ".", "pop", ")", "else", "delta", "=", "@offsets", "[", "child_index", "]", "-", "pred", ".", "offsets", ".", "last", "@offsets", "[", "child_index", "]", "=", "pred", ".", "offsets", ".", "pop", "child", ".", "offsets", ".", "map!", "{", "|", "o", "|", "o", "+=", "delta", "}", "child", ".", "offsets", ".", "unshift", "(", "0", ")", "child", ".", "children", ".", "unshift", "(", "pred", ".", "children", ".", "pop", ")", "child", ".", "children", ".", "first", ".", "parent", "=", "child", "end", "end" ]
Move last element of predecessor node to child @param child_index [Integer] index of the child
[ "Move", "last", "element", "of", "predecessor", "node", "to", "child" ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigArrayNode.rb#L883-L935
train
scrapper/perobs
lib/perobs/BigHash.rb
PEROBS.BigHash.[]=
def []=(key, value) hashed_key = hash_key(key) @store.transaction do entry = @store.new(Entry, key, value) if (existing_entry = @btree.get(hashed_key)) # There is already an existing entry for this hashed key. if existing_entry.is_a?(Collisions) # Find the right index to insert the new entry. If there is # already an entry with the same key overwrite that entry. index_to_insert = 0 overwrite = false existing_entry.each do |ae| if ae.key == key overwrite = true break end index_to_insert += 1 end self.entry_counter += 1 unless overwrite existing_entry[index_to_insert] = entry elsif existing_entry.key == key # The existing value is for the identical key. We can safely # overwrite @btree.insert(hashed_key, entry) else # There is a single existing entry, but for a different key. Create # a new PEROBS::Array and store both entries. array_entry = @store.new(Collisions) array_entry << existing_entry array_entry << entry @btree.insert(hashed_key, array_entry) self.entry_counter += 1 end else # No existing entry. Insert the new entry. @btree.insert(hashed_key, entry) self.entry_counter += 1 end end end
ruby
def []=(key, value) hashed_key = hash_key(key) @store.transaction do entry = @store.new(Entry, key, value) if (existing_entry = @btree.get(hashed_key)) # There is already an existing entry for this hashed key. if existing_entry.is_a?(Collisions) # Find the right index to insert the new entry. If there is # already an entry with the same key overwrite that entry. index_to_insert = 0 overwrite = false existing_entry.each do |ae| if ae.key == key overwrite = true break end index_to_insert += 1 end self.entry_counter += 1 unless overwrite existing_entry[index_to_insert] = entry elsif existing_entry.key == key # The existing value is for the identical key. We can safely # overwrite @btree.insert(hashed_key, entry) else # There is a single existing entry, but for a different key. Create # a new PEROBS::Array and store both entries. array_entry = @store.new(Collisions) array_entry << existing_entry array_entry << entry @btree.insert(hashed_key, array_entry) self.entry_counter += 1 end else # No existing entry. Insert the new entry. @btree.insert(hashed_key, entry) self.entry_counter += 1 end end end
[ "def", "[]=", "(", "key", ",", "value", ")", "hashed_key", "=", "hash_key", "(", "key", ")", "@store", ".", "transaction", "do", "entry", "=", "@store", ".", "new", "(", "Entry", ",", "key", ",", "value", ")", "if", "(", "existing_entry", "=", "@btree", ".", "get", "(", "hashed_key", ")", ")", "if", "existing_entry", ".", "is_a?", "(", "Collisions", ")", "index_to_insert", "=", "0", "overwrite", "=", "false", "existing_entry", ".", "each", "do", "|", "ae", "|", "if", "ae", ".", "key", "==", "key", "overwrite", "=", "true", "break", "end", "index_to_insert", "+=", "1", "end", "self", ".", "entry_counter", "+=", "1", "unless", "overwrite", "existing_entry", "[", "index_to_insert", "]", "=", "entry", "elsif", "existing_entry", ".", "key", "==", "key", "@btree", ".", "insert", "(", "hashed_key", ",", "entry", ")", "else", "array_entry", "=", "@store", ".", "new", "(", "Collisions", ")", "array_entry", "<<", "existing_entry", "array_entry", "<<", "entry", "@btree", ".", "insert", "(", "hashed_key", ",", "array_entry", ")", "self", ".", "entry_counter", "+=", "1", "end", "else", "@btree", ".", "insert", "(", "hashed_key", ",", "entry", ")", "self", ".", "entry_counter", "+=", "1", "end", "end", "end" ]
Insert a value that is associated with the given key. If a value for this key already exists, the value will be overwritten with the newly provided value. @param key [Integer or String] @param value [Any PEROBS storable object]
[ "Insert", "a", "value", "that", "is", "associated", "with", "the", "given", "key", ".", "If", "a", "value", "for", "this", "key", "already", "exists", "the", "value", "will", "be", "overwritten", "with", "the", "newly", "provided", "value", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigHash.rb#L90-L130
train
scrapper/perobs
lib/perobs/BigHash.rb
PEROBS.BigHash.[]
def [](key) hashed_key = hash_key(key) unless (entry = @btree.get(hashed_key)) return nil end if entry.is_a?(PEROBS::Array) entry.each do |ae| return ae.value if ae.key == key end else return entry.value if entry.key == key end nil end
ruby
def [](key) hashed_key = hash_key(key) unless (entry = @btree.get(hashed_key)) return nil end if entry.is_a?(PEROBS::Array) entry.each do |ae| return ae.value if ae.key == key end else return entry.value if entry.key == key end nil end
[ "def", "[]", "(", "key", ")", "hashed_key", "=", "hash_key", "(", "key", ")", "unless", "(", "entry", "=", "@btree", ".", "get", "(", "hashed_key", ")", ")", "return", "nil", "end", "if", "entry", ".", "is_a?", "(", "PEROBS", "::", "Array", ")", "entry", ".", "each", "do", "|", "ae", "|", "return", "ae", ".", "value", "if", "ae", ".", "key", "==", "key", "end", "else", "return", "entry", ".", "value", "if", "entry", ".", "key", "==", "key", "end", "nil", "end" ]
Retrieve the value for the given key. If no value for the key is found nil is returned. @param key [Integer or String] @return [Any PEROBS storable object]
[ "Retrieve", "the", "value", "for", "the", "given", "key", ".", "If", "no", "value", "for", "the", "key", "is", "found", "nil", "is", "returned", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigHash.rb#L136-L151
train
scrapper/perobs
lib/perobs/BigHash.rb
PEROBS.BigHash.has_key?
def has_key?(key) hashed_key = hash_key(key) unless (entry = @btree.get(hashed_key)) return false end if entry.is_a?(PEROBS::Array) entry.each do |ae| return true if ae.key == key end else return true if entry.key == key end false end
ruby
def has_key?(key) hashed_key = hash_key(key) unless (entry = @btree.get(hashed_key)) return false end if entry.is_a?(PEROBS::Array) entry.each do |ae| return true if ae.key == key end else return true if entry.key == key end false end
[ "def", "has_key?", "(", "key", ")", "hashed_key", "=", "hash_key", "(", "key", ")", "unless", "(", "entry", "=", "@btree", ".", "get", "(", "hashed_key", ")", ")", "return", "false", "end", "if", "entry", ".", "is_a?", "(", "PEROBS", "::", "Array", ")", "entry", ".", "each", "do", "|", "ae", "|", "return", "true", "if", "ae", ".", "key", "==", "key", "end", "else", "return", "true", "if", "entry", ".", "key", "==", "key", "end", "false", "end" ]
Check if the is a value stored for the given key. @param key [Integer or String] @return [TrueClass or FalseClass]
[ "Check", "if", "the", "is", "a", "value", "stored", "for", "the", "given", "key", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigHash.rb#L156-L171
train
scrapper/perobs
lib/perobs/BigHash.rb
PEROBS.BigHash.delete
def delete(key) hashed_key = hash_key(key) unless (entry = @btree.get(hashed_key)) return nil end if entry.is_a?(PEROBS::Array) entry.each_with_index do |ae, i| if ae.key == key self.entry_counter -= 1 return entry.delete_at(i).value end end else return entry.value if entry.key == key end nil end
ruby
def delete(key) hashed_key = hash_key(key) unless (entry = @btree.get(hashed_key)) return nil end if entry.is_a?(PEROBS::Array) entry.each_with_index do |ae, i| if ae.key == key self.entry_counter -= 1 return entry.delete_at(i).value end end else return entry.value if entry.key == key end nil end
[ "def", "delete", "(", "key", ")", "hashed_key", "=", "hash_key", "(", "key", ")", "unless", "(", "entry", "=", "@btree", ".", "get", "(", "hashed_key", ")", ")", "return", "nil", "end", "if", "entry", ".", "is_a?", "(", "PEROBS", "::", "Array", ")", "entry", ".", "each_with_index", "do", "|", "ae", ",", "i", "|", "if", "ae", ".", "key", "==", "key", "self", ".", "entry_counter", "-=", "1", "return", "entry", ".", "delete_at", "(", "i", ")", ".", "value", "end", "end", "else", "return", "entry", ".", "value", "if", "entry", ".", "key", "==", "key", "end", "nil", "end" ]
Delete and return the entry for the given key. Return nil if no matching entry exists. @param key [Integer or String] @return [Object] Deleted entry
[ "Delete", "and", "return", "the", "entry", "for", "the", "given", "key", ".", "Return", "nil", "if", "no", "matching", "entry", "exists", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigHash.rb#L177-L195
train
scrapper/perobs
lib/perobs/BigHash.rb
PEROBS.BigHash.check
def check return false unless @btree.check i = 0 each do |k, v| i += 1 end unless @entry_counter == i PEROBS.log.error "BigHash contains #{i} values but entry counter " + "is #{@entry_counter}" return false end true end
ruby
def check return false unless @btree.check i = 0 each do |k, v| i += 1 end unless @entry_counter == i PEROBS.log.error "BigHash contains #{i} values but entry counter " + "is #{@entry_counter}" return false end true end
[ "def", "check", "return", "false", "unless", "@btree", ".", "check", "i", "=", "0", "each", "do", "|", "k", ",", "v", "|", "i", "+=", "1", "end", "unless", "@entry_counter", "==", "i", "PEROBS", ".", "log", ".", "error", "\"BigHash contains #{i} values but entry counter \"", "+", "\"is #{@entry_counter}\"", "return", "false", "end", "true", "end" ]
Check if the data structure contains any errors. @return [Boolean] true if no erros were found, false otherwise
[ "Check", "if", "the", "data", "structure", "contains", "any", "errors", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/BigHash.rb#L236-L251
train
regru/reg_api2-ruby
lib/reg_api2/sym_hash.rb
RegApi2.SymHash.method_missing
def method_missing(key, *args, &block) if key.to_s =~ /\A(.+)=\z/ self[$1] = args.first return args.first end if key.to_s =~ /\A(.+)\?\z/ return !!self[$1] end return self[key] if has_key?(key) nil end
ruby
def method_missing(key, *args, &block) if key.to_s =~ /\A(.+)=\z/ self[$1] = args.first return args.first end if key.to_s =~ /\A(.+)\?\z/ return !!self[$1] end return self[key] if has_key?(key) nil end
[ "def", "method_missing", "(", "key", ",", "*", "args", ",", "&", "block", ")", "if", "key", ".", "to_s", "=~", "/", "\\A", "\\z", "/", "self", "[", "$1", "]", "=", "args", ".", "first", "return", "args", ".", "first", "end", "if", "key", ".", "to_s", "=~", "/", "\\A", "\\?", "\\z", "/", "return", "!", "!", "self", "[", "$1", "]", "end", "return", "self", "[", "key", "]", "if", "has_key?", "(", "key", ")", "nil", "end" ]
Sets or gets field in the hash.
[ "Sets", "or", "gets", "field", "in", "the", "hash", "." ]
82fadffc9da6534761003b8a33edb77ab617df70
https://github.com/regru/reg_api2-ruby/blob/82fadffc9da6534761003b8a33edb77ab617df70/lib/reg_api2/sym_hash.rb#L52-L62
train
scrapper/perobs
lib/perobs/SpaceTree.rb
PEROBS.SpaceTree.open
def open @nodes.open @cache.clear node = @nodes.total_entries == 0 ? SpaceTreeNode::create(self) : SpaceTreeNode::load(self, @nodes.first_entry) @root_address = node.node_address end
ruby
def open @nodes.open @cache.clear node = @nodes.total_entries == 0 ? SpaceTreeNode::create(self) : SpaceTreeNode::load(self, @nodes.first_entry) @root_address = node.node_address end
[ "def", "open", "@nodes", ".", "open", "@cache", ".", "clear", "node", "=", "@nodes", ".", "total_entries", "==", "0", "?", "SpaceTreeNode", "::", "create", "(", "self", ")", ":", "SpaceTreeNode", "::", "load", "(", "self", ",", "@nodes", ".", "first_entry", ")", "@root_address", "=", "node", ".", "node_address", "end" ]
Manage the free spaces tree in the specified directory @param dir [String] directory path of an existing directory Open the SpaceTree file.
[ "Manage", "the", "free", "spaces", "tree", "in", "the", "specified", "directory" ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/SpaceTree.rb#L61-L68
train
scrapper/perobs
lib/perobs/SpaceTree.rb
PEROBS.SpaceTree.add_space
def add_space(address, size) if size <= 0 PEROBS.log.fatal "Size (#{size}) must be larger than 0." end # The following check is fairly costly and should never trigger unless # there is a bug in the PEROBS code. Only use this for debugging. #if has_space?(address, size) # PEROBS.log.fatal "The space with address #{address} and size " + # "#{size} can't be added twice." #end root.add_space(address, size) end
ruby
def add_space(address, size) if size <= 0 PEROBS.log.fatal "Size (#{size}) must be larger than 0." end # The following check is fairly costly and should never trigger unless # there is a bug in the PEROBS code. Only use this for debugging. #if has_space?(address, size) # PEROBS.log.fatal "The space with address #{address} and size " + # "#{size} can't be added twice." #end root.add_space(address, size) end
[ "def", "add_space", "(", "address", ",", "size", ")", "if", "size", "<=", "0", "PEROBS", ".", "log", ".", "fatal", "\"Size (#{size}) must be larger than 0.\"", "end", "root", ".", "add_space", "(", "address", ",", "size", ")", "end" ]
Add a new space with a given address and size. @param address [Integer] Starting address of the space @param size [Integer] size of the space in bytes
[ "Add", "a", "new", "space", "with", "a", "given", "address", "and", "size", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/SpaceTree.rb#L110-L121
train
scrapper/perobs
lib/perobs/SpaceTree.rb
PEROBS.SpaceTree.get_space
def get_space(size) if size <= 0 PEROBS.log.fatal "Size (#{size}) must be larger than 0." end if (address_size = root.find_matching_space(size)) # First we try to find an exact match. return address_size elsif (address_size = root.find_equal_or_larger_space(size)) return address_size else return nil end end
ruby
def get_space(size) if size <= 0 PEROBS.log.fatal "Size (#{size}) must be larger than 0." end if (address_size = root.find_matching_space(size)) # First we try to find an exact match. return address_size elsif (address_size = root.find_equal_or_larger_space(size)) return address_size else return nil end end
[ "def", "get_space", "(", "size", ")", "if", "size", "<=", "0", "PEROBS", ".", "log", ".", "fatal", "\"Size (#{size}) must be larger than 0.\"", "end", "if", "(", "address_size", "=", "root", ".", "find_matching_space", "(", "size", ")", ")", "return", "address_size", "elsif", "(", "address_size", "=", "root", ".", "find_equal_or_larger_space", "(", "size", ")", ")", "return", "address_size", "else", "return", "nil", "end", "end" ]
Get a space that has at least the requested size. @param size [Integer] Required size in bytes @return [Array] Touple with address and actual size of the space.
[ "Get", "a", "space", "that", "has", "at", "least", "the", "requested", "size", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/SpaceTree.rb#L126-L139
train
scrapper/perobs
lib/perobs/SpaceTree.rb
PEROBS.SpaceTree.each
def each root.each do |node, mode, stack| if mode == :on_enter yield(node.blob_address, node.size) end end end
ruby
def each root.each do |node, mode, stack| if mode == :on_enter yield(node.blob_address, node.size) end end end
[ "def", "each", "root", ".", "each", "do", "|", "node", ",", "mode", ",", "stack", "|", "if", "mode", "==", ":on_enter", "yield", "(", "node", ".", "blob_address", ",", "node", ".", "size", ")", "end", "end", "end" ]
Iterate over all entries and yield address and size.
[ "Iterate", "over", "all", "entries", "and", "yield", "address", "and", "size", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/SpaceTree.rb#L174-L180
train
Absolight/epp-client
lib/epp-client/afnic.rb
EPPClient.AFNIC.legalEntityInfos
def legalEntityInfos(leI) #:nodoc: ret = {} ret[:legalStatus] = leI.xpath('frnic:legalStatus', EPPClient::SCHEMAS_URL).attr('s').value unless (r = leI.xpath('frnic:idStatus', EPPClient::SCHEMAS_URL)).empty? ret[:idStatus] = { :value => r.text } ret[:idStatus][:when] = r.attr('when').value if r.attr('when') ret[:idStatus][:source] = r.attr('source').value if r.attr('source') end %w(siren VAT trademark DUNS local).each do |val| unless (r = leI.xpath("frnic:#{val}", EPPClient::SCHEMAS_URL)).empty? ret[val.to_sym] = r.text end end unless (asso = leI.xpath('frnic:asso', EPPClient::SCHEMAS_URL)).empty? ret[:asso] = {} if !(r = asso.xpath('frnic:waldec', EPPClient::SCHEMAS_URL)).empty? ret[:asso][:waldec] = r.text else unless (decl = asso.xpath('frnic:decl', EPPClient::SCHEMAS_URL)).empty? ret[:asso][:decl] = Date.parse(decl.text) end publ = asso.xpath('frnic:publ', EPPClient::SCHEMAS_URL) ret[:asso][:publ] = { :date => Date.parse(publ.text), :page => publ.attr('page').value, } if (announce = publ.attr('announce')) && announce.value != '0' ret[:asso][:publ][:announce] = announce.value end end end ret end
ruby
def legalEntityInfos(leI) #:nodoc: ret = {} ret[:legalStatus] = leI.xpath('frnic:legalStatus', EPPClient::SCHEMAS_URL).attr('s').value unless (r = leI.xpath('frnic:idStatus', EPPClient::SCHEMAS_URL)).empty? ret[:idStatus] = { :value => r.text } ret[:idStatus][:when] = r.attr('when').value if r.attr('when') ret[:idStatus][:source] = r.attr('source').value if r.attr('source') end %w(siren VAT trademark DUNS local).each do |val| unless (r = leI.xpath("frnic:#{val}", EPPClient::SCHEMAS_URL)).empty? ret[val.to_sym] = r.text end end unless (asso = leI.xpath('frnic:asso', EPPClient::SCHEMAS_URL)).empty? ret[:asso] = {} if !(r = asso.xpath('frnic:waldec', EPPClient::SCHEMAS_URL)).empty? ret[:asso][:waldec] = r.text else unless (decl = asso.xpath('frnic:decl', EPPClient::SCHEMAS_URL)).empty? ret[:asso][:decl] = Date.parse(decl.text) end publ = asso.xpath('frnic:publ', EPPClient::SCHEMAS_URL) ret[:asso][:publ] = { :date => Date.parse(publ.text), :page => publ.attr('page').value, } if (announce = publ.attr('announce')) && announce.value != '0' ret[:asso][:publ][:announce] = announce.value end end end ret end
[ "def", "legalEntityInfos", "(", "leI", ")", "ret", "=", "{", "}", "ret", "[", ":legalStatus", "]", "=", "leI", ".", "xpath", "(", "'frnic:legalStatus'", ",", "EPPClient", "::", "SCHEMAS_URL", ")", ".", "attr", "(", "'s'", ")", ".", "value", "unless", "(", "r", "=", "leI", ".", "xpath", "(", "'frnic:idStatus'", ",", "EPPClient", "::", "SCHEMAS_URL", ")", ")", ".", "empty?", "ret", "[", ":idStatus", "]", "=", "{", ":value", "=>", "r", ".", "text", "}", "ret", "[", ":idStatus", "]", "[", ":when", "]", "=", "r", ".", "attr", "(", "'when'", ")", ".", "value", "if", "r", ".", "attr", "(", "'when'", ")", "ret", "[", ":idStatus", "]", "[", ":source", "]", "=", "r", ".", "attr", "(", "'source'", ")", ".", "value", "if", "r", ".", "attr", "(", "'source'", ")", "end", "%w(", "siren", "VAT", "trademark", "DUNS", "local", ")", ".", "each", "do", "|", "val", "|", "unless", "(", "r", "=", "leI", ".", "xpath", "(", "\"frnic:#{val}\"", ",", "EPPClient", "::", "SCHEMAS_URL", ")", ")", ".", "empty?", "ret", "[", "val", ".", "to_sym", "]", "=", "r", ".", "text", "end", "end", "unless", "(", "asso", "=", "leI", ".", "xpath", "(", "'frnic:asso'", ",", "EPPClient", "::", "SCHEMAS_URL", ")", ")", ".", "empty?", "ret", "[", ":asso", "]", "=", "{", "}", "if", "!", "(", "r", "=", "asso", ".", "xpath", "(", "'frnic:waldec'", ",", "EPPClient", "::", "SCHEMAS_URL", ")", ")", ".", "empty?", "ret", "[", ":asso", "]", "[", ":waldec", "]", "=", "r", ".", "text", "else", "unless", "(", "decl", "=", "asso", ".", "xpath", "(", "'frnic:decl'", ",", "EPPClient", "::", "SCHEMAS_URL", ")", ")", ".", "empty?", "ret", "[", ":asso", "]", "[", ":decl", "]", "=", "Date", ".", "parse", "(", "decl", ".", "text", ")", "end", "publ", "=", "asso", ".", "xpath", "(", "'frnic:publ'", ",", "EPPClient", "::", "SCHEMAS_URL", ")", "ret", "[", ":asso", "]", "[", ":publ", "]", "=", "{", ":date", "=>", "Date", ".", "parse", "(", "publ", ".", "text", ")", ",", ":page", "=>", "publ", ".", "attr", "(", "'page'", ")", ".", "value", ",", "}", "if", "(", "announce", "=", "publ", ".", "attr", "(", "'announce'", ")", ")", "&&", "announce", ".", "value", "!=", "'0'", "ret", "[", ":asso", "]", "[", ":publ", "]", "[", ":announce", "]", "=", "announce", ".", "value", "end", "end", "end", "ret", "end" ]
parse legalEntityInfos content.
[ "parse", "legalEntityInfos", "content", "." ]
c0025daee5e7087f60b654595a8e7d92e966c54e
https://github.com/Absolight/epp-client/blob/c0025daee5e7087f60b654595a8e7d92e966c54e/lib/epp-client/afnic.rb#L82-L114
train
scrapper/perobs
lib/perobs/IDList.rb
PEROBS.IDList.insert
def insert(id) # Find the index of the page that should hold ID. index = @page_records.bsearch_index { |pr| pr.max_id >= id } # Get the corresponding IDListPageRecord object. page = @page_records[index] # In case the page is already full we'll have to create a new page. # There is no guarantee that a split will yield an page with space as we # split by ID range, not by distributing the values evenly across the # two pages. while page.is_full? new_page = page.split # Store the newly created page into the page_records list. @page_records.insert(index + 1, new_page) if id >= new_page.min_id # We need to insert the ID into the newly created page. Adjust index # and page reference accordingly. index += 1 page = new_page end end # Insert the ID into the page. page.insert(id) end
ruby
def insert(id) # Find the index of the page that should hold ID. index = @page_records.bsearch_index { |pr| pr.max_id >= id } # Get the corresponding IDListPageRecord object. page = @page_records[index] # In case the page is already full we'll have to create a new page. # There is no guarantee that a split will yield an page with space as we # split by ID range, not by distributing the values evenly across the # two pages. while page.is_full? new_page = page.split # Store the newly created page into the page_records list. @page_records.insert(index + 1, new_page) if id >= new_page.min_id # We need to insert the ID into the newly created page. Adjust index # and page reference accordingly. index += 1 page = new_page end end # Insert the ID into the page. page.insert(id) end
[ "def", "insert", "(", "id", ")", "index", "=", "@page_records", ".", "bsearch_index", "{", "|", "pr", "|", "pr", ".", "max_id", ">=", "id", "}", "page", "=", "@page_records", "[", "index", "]", "while", "page", ".", "is_full?", "new_page", "=", "page", ".", "split", "@page_records", ".", "insert", "(", "index", "+", "1", ",", "new_page", ")", "if", "id", ">=", "new_page", ".", "min_id", "index", "+=", "1", "page", "=", "new_page", "end", "end", "page", ".", "insert", "(", "id", ")", "end" ]
Create a new IDList object. The data that can't be kept in memory will be stored in the specified directory under the given name. @param dir [String] Path of the directory @param name [String] Name of the file @param max_in_memory [Integer] Specifies the maximum number of values that will be kept in memory. If the list is larger, values will be cached in the specified file. @param page_size [Integer] The number of values per page. The default value is 32 which was found the best performing config in tests. Insert a new value into the list. @param id [Integer] The value to add
[ "Create", "a", "new", "IDList", "object", ".", "The", "data", "that", "can", "t", "be", "kept", "in", "memory", "will", "be", "stored", "in", "the", "specified", "directory", "under", "the", "given", "name", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/IDList.rb#L59-L83
train
scrapper/perobs
lib/perobs/IDList.rb
PEROBS.IDList.check
def check last_max = -1 unless (min_id = @page_records.first.min_id) == 0 raise RuntimeError, "min_id of first record (#{min_id}) " + "must be 0." end @page_records.each do |pr| unless pr.min_id == last_max + 1 raise RuntimeError, "max_id of previous record (#{last_max}) " + "must be exactly 1 smaller than current record (#{pr.min_id})." end last_max = pr.max_id pr.check end unless last_max == 2 ** 64 raise RuntimeError, "max_id of last records " + "(#{@page_records.last.max_id}) must be #{2 ** 64})." end end
ruby
def check last_max = -1 unless (min_id = @page_records.first.min_id) == 0 raise RuntimeError, "min_id of first record (#{min_id}) " + "must be 0." end @page_records.each do |pr| unless pr.min_id == last_max + 1 raise RuntimeError, "max_id of previous record (#{last_max}) " + "must be exactly 1 smaller than current record (#{pr.min_id})." end last_max = pr.max_id pr.check end unless last_max == 2 ** 64 raise RuntimeError, "max_id of last records " + "(#{@page_records.last.max_id}) must be #{2 ** 64})." end end
[ "def", "check", "last_max", "=", "-", "1", "unless", "(", "min_id", "=", "@page_records", ".", "first", ".", "min_id", ")", "==", "0", "raise", "RuntimeError", ",", "\"min_id of first record (#{min_id}) \"", "+", "\"must be 0.\"", "end", "@page_records", ".", "each", "do", "|", "pr", "|", "unless", "pr", ".", "min_id", "==", "last_max", "+", "1", "raise", "RuntimeError", ",", "\"max_id of previous record (#{last_max}) \"", "+", "\"must be exactly 1 smaller than current record (#{pr.min_id}).\"", "end", "last_max", "=", "pr", ".", "max_id", "pr", ".", "check", "end", "unless", "last_max", "==", "2", "**", "64", "raise", "RuntimeError", ",", "\"max_id of last records \"", "+", "\"(#{@page_records.last.max_id}) must be #{2 ** 64}).\"", "end", "end" ]
Perform some consistency checks on the internal data structures. Raises a RuntimeError in case a problem is found.
[ "Perform", "some", "consistency", "checks", "on", "the", "internal", "data", "structures", ".", "Raises", "a", "RuntimeError", "in", "case", "a", "problem", "is", "found", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/IDList.rb#L107-L127
train
louismrose/lncs
lib/lncs/paper.rb
LNCS.Paper.paths_to_pdfs
def paths_to_pdfs paths = [] Zip::ZipFile.open(path) do |zipfile| zipfile.select { |file| zipfile.get_entry(file).file? }.each do |file| paths << file.name if file.name.end_with? ".pdf" end end paths end
ruby
def paths_to_pdfs paths = [] Zip::ZipFile.open(path) do |zipfile| zipfile.select { |file| zipfile.get_entry(file).file? }.each do |file| paths << file.name if file.name.end_with? ".pdf" end end paths end
[ "def", "paths_to_pdfs", "paths", "=", "[", "]", "Zip", "::", "ZipFile", ".", "open", "(", "path", ")", "do", "|", "zipfile", "|", "zipfile", ".", "select", "{", "|", "file", "|", "zipfile", ".", "get_entry", "(", "file", ")", ".", "file?", "}", ".", "each", "do", "|", "file", "|", "paths", "<<", "file", ".", "name", "if", "file", ".", "name", ".", "end_with?", "\".pdf\"", "end", "end", "paths", "end" ]
Locate all PDF files within the ZIP
[ "Locate", "all", "PDF", "files", "within", "the", "ZIP" ]
88dc0f95c294a9a319407a65c3b9891b54d16e59
https://github.com/louismrose/lncs/blob/88dc0f95c294a9a319407a65c3b9891b54d16e59/lib/lncs/paper.rb#L104-L114
train
jwood/tenacity
lib/tenacity/class_methods.rb
Tenacity.ClassMethods.t_has_one
def t_has_one(name, options={}) extend(Associations::HasOne::ClassMethods) association = _t_create_association(:t_has_one, name, options) initialize_has_one_association(association) define_method(association.name) do |*params| get_associate(association, params) do has_one_associate(association) end end define_method("#{association.name}=") do |associate| set_associate(association, associate) do set_has_one_associate(association, associate) end end end
ruby
def t_has_one(name, options={}) extend(Associations::HasOne::ClassMethods) association = _t_create_association(:t_has_one, name, options) initialize_has_one_association(association) define_method(association.name) do |*params| get_associate(association, params) do has_one_associate(association) end end define_method("#{association.name}=") do |associate| set_associate(association, associate) do set_has_one_associate(association, associate) end end end
[ "def", "t_has_one", "(", "name", ",", "options", "=", "{", "}", ")", "extend", "(", "Associations", "::", "HasOne", "::", "ClassMethods", ")", "association", "=", "_t_create_association", "(", ":t_has_one", ",", "name", ",", "options", ")", "initialize_has_one_association", "(", "association", ")", "define_method", "(", "association", ".", "name", ")", "do", "|", "*", "params", "|", "get_associate", "(", "association", ",", "params", ")", "do", "has_one_associate", "(", "association", ")", "end", "end", "define_method", "(", "\"#{association.name}=\"", ")", "do", "|", "associate", "|", "set_associate", "(", "association", ",", "associate", ")", "do", "set_has_one_associate", "(", "association", ",", "associate", ")", "end", "end", "end" ]
Specifies a one-to-one association with another class. This method should only be used if the other class contains the foreign key. If the current class contains the foreign key, then you should use +t_belongs_to+ instead. The following methods for retrieval and query of a single associated object will be added: [association(force_reload = false)] Returns the associated object. +nil+ is returned if none is found. [association=(associate)] Assigns the associate object, extracts the primary key, sets it as the foreign key, and saves the associate object. (+association+ is replaced with the symbol passed as the first argument, so <tt>t_has_one :manager</tt> would add among others <tt>manager.nil?</tt>.) === Example An Account class declares <tt>t_has_one :beneficiary</tt>, which will add: * <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.find(:first, :conditions => "account_id = #{id}")</tt>) * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>) === Supported options [:class_name] Specify the class name of the association. Use it only if that name can't be inferred from the association name. So <tt>t_has_one :manager</tt> will by default be linked to the Manager class, but if the real class name is Person, you'll have to specify it with this option. [:foreign_key] Specify the foreign key used for the association. By default this is guessed to be the name of this class in lower-case and "_id" suffixed. So a Person class that makes a +t_has_one+ association will use "person_id" as the default <tt>:foreign_key</tt>. [:dependent] If set to <tt>:destroy</tt>, the associated object is deleted when this object is, and all delete callbacks are called. If set to <tt>:delete</tt>, the associated object is deleted *without* calling any of its delete callbacks. If set to <tt>:nullify</tt>, the associated object's foreign key is set to +NULL+. [:readonly] If true, the associated object is readonly through the association. [:autosave] If true, always save the associated object or destroy it if marked for destruction, when saving the parent object. Off by default. [:as] Specifies a polymorphic interface (See <tt>t_belongs_to</tt>). [:disable_foreign_key_constraints] If true, bypass foreign key constraints, like verifying no other objects are storing the key of the source object before deleting it. Defaults to false. Option examples: t_has_one :credit_card, :dependent => :destroy # destroys the associated credit card t_has_one :credit_card, :dependent => :nullify # updates the associated records foreign key value to NULL rather than destroying it t_has_one :project_manager, :class_name => "Person" t_has_one :project_manager, :foreign_key => "project_id" # within class named SecretProject t_has_one :boss, :readonly => :true t_has_one :attachment, :as => :attachable
[ "Specifies", "a", "one", "-", "to", "-", "one", "association", "with", "another", "class", ".", "This", "method", "should", "only", "be", "used", "if", "the", "other", "class", "contains", "the", "foreign", "key", ".", "If", "the", "current", "class", "contains", "the", "foreign", "key", "then", "you", "should", "use", "+", "t_belongs_to", "+", "instead", "." ]
2094c926dd14779f69c70e59fb20fdda3ae819cf
https://github.com/jwood/tenacity/blob/2094c926dd14779f69c70e59fb20fdda3ae819cf/lib/tenacity/class_methods.rb#L198-L214
train
jwood/tenacity
lib/tenacity/class_methods.rb
Tenacity.ClassMethods.t_belongs_to
def t_belongs_to(name, options={}) extend(Associations::BelongsTo::ClassMethods) association = _t_create_association(:t_belongs_to, name, options) initialize_belongs_to_association(association) define_method(association.name) do |*params| get_associate(association, params) do belongs_to_associate(association) end end define_method("#{association.name}=") do |associate| set_associate(association, associate) do set_belongs_to_associate(association, associate) end end end
ruby
def t_belongs_to(name, options={}) extend(Associations::BelongsTo::ClassMethods) association = _t_create_association(:t_belongs_to, name, options) initialize_belongs_to_association(association) define_method(association.name) do |*params| get_associate(association, params) do belongs_to_associate(association) end end define_method("#{association.name}=") do |associate| set_associate(association, associate) do set_belongs_to_associate(association, associate) end end end
[ "def", "t_belongs_to", "(", "name", ",", "options", "=", "{", "}", ")", "extend", "(", "Associations", "::", "BelongsTo", "::", "ClassMethods", ")", "association", "=", "_t_create_association", "(", ":t_belongs_to", ",", "name", ",", "options", ")", "initialize_belongs_to_association", "(", "association", ")", "define_method", "(", "association", ".", "name", ")", "do", "|", "*", "params", "|", "get_associate", "(", "association", ",", "params", ")", "do", "belongs_to_associate", "(", "association", ")", "end", "end", "define_method", "(", "\"#{association.name}=\"", ")", "do", "|", "associate", "|", "set_associate", "(", "association", ",", "associate", ")", "do", "set_belongs_to_associate", "(", "association", ",", "associate", ")", "end", "end", "end" ]
Specifies a one-to-one association with another class. This method should only be used if this class contains the foreign key. If the other class contains the foreign key, then you should use +t_has_one+ instead. Methods will be added for retrieval and query for a single associated object, for which this object holds an id: [association(force_reload = false)] Returns the associated object. +nil+ is returned if none is found. [association=(associate)] Assigns the associate object, extracts the primary key, and sets it as the foreign key. (+association+ is replaced with the symbol passed as the first argument, so <tt>t_belongs_to :author</tt> would add among others <tt>author.nil?</tt>.) === Example A Post class declares <tt>t_belongs_to :author</tt>, which will add: * <tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>) * <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>) === Supported options [:class_name] Specify the class name of the association. Use it only if that name can't be inferred from the association name. So <tt>t_belongs_to :manager</tt> will by default be linked to the Manager class, but if the real class name is Person, you'll have to specify it with this option. [:foreign_key] Specify the foreign key used for the association. By default this is guessed to be the name of the association with an "_id" suffix. So a class that defines a <tt>t_belongs_to :person</tt> association will use "person_id" as the default <tt>:foreign_key</tt>. Similarly, <tt>t_belongs_to :favorite_person, :class_name => "Person"</tt> will use a foreign key of "favorite_person_id". [:dependent] If set to <tt>:destroy</tt>, the associated object is deleted when this object is, calling all delete callbacks. If set to <tt>:delete</tt>, the associated object is deleted *without* calling any of its delete callbacks. This option should not be specified when <tt>t_belongs_to</tt> is used in conjuction with a <tt>t_has_many</tt> relationship on another class because of the potential to leave orphaned records behind. [:readonly] If true, the associated object is readonly through the association. [:autosave] If true, always save the associated object or destroy it if marked for destruction, when saving the parent object. Off by default. [:polymorphic] Specify this association is a polymorphic association by passing +true+. (*Note*: IDs for polymorphic associations are always stored as strings in the database.) [:disable_foreign_key_constraints] If true, bypass foreign key constraints, like verifying the target object exists when the relationship is created. Defaults to false. Option examples: t_belongs_to :project_manager, :class_name => "Person" t_belongs_to :valid_coupon, :class_name => "Coupon", :foreign_key => "coupon_id" t_belongs_to :project, :readonly => true t_belongs_to :attachable, :polymorphic => true
[ "Specifies", "a", "one", "-", "to", "-", "one", "association", "with", "another", "class", ".", "This", "method", "should", "only", "be", "used", "if", "this", "class", "contains", "the", "foreign", "key", ".", "If", "the", "other", "class", "contains", "the", "foreign", "key", "then", "you", "should", "use", "+", "t_has_one", "+", "instead", "." ]
2094c926dd14779f69c70e59fb20fdda3ae819cf
https://github.com/jwood/tenacity/blob/2094c926dd14779f69c70e59fb20fdda3ae819cf/lib/tenacity/class_methods.rb#L271-L287
train
jwood/tenacity
lib/tenacity/class_methods.rb
Tenacity.ClassMethods.t_has_many
def t_has_many(name, options={}) extend(Associations::HasMany::ClassMethods) association = _t_create_association(:t_has_many, name, options) initialize_has_many_association(association) define_method(association.name) do |*params| get_associate(association, params) do has_many_associates(association) end end define_method("#{association.name}=") do |associates| _t_mark_dirty if respond_to?(:_t_mark_dirty) set_associate(association, associates) do set_has_many_associates(association, associates) end end define_method("#{ActiveSupport::Inflector.singularize(association.name.to_s)}_ids") do has_many_associate_ids(association) end define_method("#{ActiveSupport::Inflector.singularize(association.name.to_s)}_ids=") do |associate_ids| _t_mark_dirty if respond_to?(:_t_mark_dirty) set_has_many_associate_ids(association, associate_ids) end private define_method(:_t_save_without_callback) do save_without_callback end end
ruby
def t_has_many(name, options={}) extend(Associations::HasMany::ClassMethods) association = _t_create_association(:t_has_many, name, options) initialize_has_many_association(association) define_method(association.name) do |*params| get_associate(association, params) do has_many_associates(association) end end define_method("#{association.name}=") do |associates| _t_mark_dirty if respond_to?(:_t_mark_dirty) set_associate(association, associates) do set_has_many_associates(association, associates) end end define_method("#{ActiveSupport::Inflector.singularize(association.name.to_s)}_ids") do has_many_associate_ids(association) end define_method("#{ActiveSupport::Inflector.singularize(association.name.to_s)}_ids=") do |associate_ids| _t_mark_dirty if respond_to?(:_t_mark_dirty) set_has_many_associate_ids(association, associate_ids) end private define_method(:_t_save_without_callback) do save_without_callback end end
[ "def", "t_has_many", "(", "name", ",", "options", "=", "{", "}", ")", "extend", "(", "Associations", "::", "HasMany", "::", "ClassMethods", ")", "association", "=", "_t_create_association", "(", ":t_has_many", ",", "name", ",", "options", ")", "initialize_has_many_association", "(", "association", ")", "define_method", "(", "association", ".", "name", ")", "do", "|", "*", "params", "|", "get_associate", "(", "association", ",", "params", ")", "do", "has_many_associates", "(", "association", ")", "end", "end", "define_method", "(", "\"#{association.name}=\"", ")", "do", "|", "associates", "|", "_t_mark_dirty", "if", "respond_to?", "(", ":_t_mark_dirty", ")", "set_associate", "(", "association", ",", "associates", ")", "do", "set_has_many_associates", "(", "association", ",", "associates", ")", "end", "end", "define_method", "(", "\"#{ActiveSupport::Inflector.singularize(association.name.to_s)}_ids\"", ")", "do", "has_many_associate_ids", "(", "association", ")", "end", "define_method", "(", "\"#{ActiveSupport::Inflector.singularize(association.name.to_s)}_ids=\"", ")", "do", "|", "associate_ids", "|", "_t_mark_dirty", "if", "respond_to?", "(", ":_t_mark_dirty", ")", "set_has_many_associate_ids", "(", "association", ",", "associate_ids", ")", "end", "private", "define_method", "(", ":_t_save_without_callback", ")", "do", "save_without_callback", "end", "end" ]
Specifies a one-to-many association. The following methods for retrieval and query of collections of associated objects will be added: [collection(force_reload = false)] Returns an array of all the associated objects. An empty array is returned if none are found. [collection<<(object, ...)] Adds one or more objects to the collection by setting their foreign keys to the collection's primary key. [collection.push(object, ...)] Adds one or more objects to the collection by setting their foreign keys to the collection's primary key. [collection.concat(other_array)] Adds the objects in the other array to the collection by setting their foreign keys to the collection's primary key. [collection.delete(object, ...)] Removes one or more objects from the collection by setting their foreign keys to +NULL+. Objects will be in addition deleted and callbacks called if they're associated with <tt>:dependent => :destroy</tt>, and deleted and callbacks skipped if they're associated with <tt>:dependent => :delete_all</tt>. [collection.destroy_all] Removes all objects from the collection, and deletes them from their respective database. If the deleted objects have any delete callbacks defined, they will be called. [collection.delete_all] Removes all objects from the collection, and deletes them from their respective database. No delete callbacks will be called, regardless of whether or not they are defined. [collection=objects] Replaces the collections content by setting it to the list of specified objects. [collection_singular_ids] Returns an array of the associated objects' ids [collection_singular_ids=ids] Replace the collection with the objects identified by the primary keys in +ids+. [collection.clear] Removes every object from the collection. This deletes the associated objects and issues callbacks if they are associated with <tt>:dependent => :destroy</tt>, deletes them directly from the database without calling any callbacks if <tt>:dependent => :delete_all</tt>, otherwise sets their foreign keys to +NULL+. [collection.empty?] Returns +true+ if there are no associated objects. [collection.size] Returns the number of associated objects. (*Note*: +collection+ is replaced with the symbol passed as the first argument, so <tt>t_has_many :clients</tt> would add among others <tt>clients.empty?</tt>.) === Example Example: A Firm class declares <tt>t_has_many :clients</tt>, which will add: * <tt>Firm#clients</tt> (similar to <tt>Clients.find :all, :conditions => ["firm_id = ?", id]</tt>) * <tt>Firm#clients<<</tt> * <tt>Firm#clients.delete</tt> * <tt>Firm#clients=</tt> * <tt>Firm#client_ids</tt> * <tt>Firm#client_ids=</tt> * <tt>Firm#clients.clear</tt> * <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>) * <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>) === Supported options [:class_name] Specify the class name of the association. Use it only if that name can't be inferred from the association name. So <tt>t_has_many :products</tt> will by default be linked to the Product class, but if the real class name is SpecialProduct, you'll have to specify it with this option. [:foreign_key] Specify the foreign key used for the association. By default this is guessed to be the name of this class in lower-case and "_id" suffixed. So a Person class that makes a +t_has_many+ association will use "person_id" as the default <tt>:foreign_key</tt>. [:dependent] If set to <tt>:destroy</tt> all the associated objects are deleted alongside this object in addition to calling their delete callbacks. If set to <tt>:delete_all</tt> all associated objects are deleted *without* calling their delete callbacks. If set to <tt>:nullify</tt> all associated objects' foreign keys are set to +NULL+ *without* calling their save backs. [:readonly] If true, all the associated objects are readonly through the association. [:limit] An integer determining the limit on the number of rows that should be returned. Results are ordered by a string representation of the id. [:offset] An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows. Results are ordered by a string representation of the id. [:autosave] If true, always save any loaded members and destroy members marked for destruction, when saving the parent object. Off by default. [:as] Specifies a polymorphic interface (See <tt>t_belongs_to</tt>). [:disable_foreign_key_constraints] If true, bypass foreign key constraints, like verifying no other objects are storing the key of the source object before deleting it. Defaults to false. Option examples: t_has_many :products, :class_name => "SpecialProduct" t_has_many :engineers, :foreign_key => "project_id" # within class named SecretProject t_has_many :tasks, :dependent => :destroy t_has_many :reports, :readonly => true t_has_many :tags, :as => :taggable
[ "Specifies", "a", "one", "-", "to", "-", "many", "association", "." ]
2094c926dd14779f69c70e59fb20fdda3ae819cf
https://github.com/jwood/tenacity/blob/2094c926dd14779f69c70e59fb20fdda3ae819cf/lib/tenacity/class_methods.rb#L383-L415
train
sagmor/yard-mruby
lib/yard/mruby/code_objects/function_object.rb
YARD::MRuby::CodeObjects.FunctionObject.aliases
def aliases list = [] return list unless namespace.is_a?(HeaderObject) namespace.aliases.each do |o, aname| list << o if aname == name && o.scope == scope end list end
ruby
def aliases list = [] return list unless namespace.is_a?(HeaderObject) namespace.aliases.each do |o, aname| list << o if aname == name && o.scope == scope end list end
[ "def", "aliases", "list", "=", "[", "]", "return", "list", "unless", "namespace", ".", "is_a?", "(", "HeaderObject", ")", "namespace", ".", "aliases", ".", "each", "do", "|", "o", ",", "aname", "|", "list", "<<", "o", "if", "aname", "==", "name", "&&", "o", ".", "scope", "==", "scope", "end", "list", "end" ]
Returns all alias names of the object @return [Array<Symbol>] the alias names
[ "Returns", "all", "alias", "names", "of", "the", "object" ]
c20c2f415d15235fdc96ac177cb008eb3e11358a
https://github.com/sagmor/yard-mruby/blob/c20c2f415d15235fdc96ac177cb008eb3e11358a/lib/yard/mruby/code_objects/function_object.rb#L62-L69
train
proglottis/glicko2
lib/glicko2/rating_period.rb
Glicko2.RatingPeriod.game
def game(game_seeds, ranks) game_seeds.each_with_index do |iseed, i| game_seeds.each_with_index do |jseed, j| next if i == j @raters[iseed].add(player(jseed).rating, Util.ranks_to_score(ranks[i], ranks[j])) end end end
ruby
def game(game_seeds, ranks) game_seeds.each_with_index do |iseed, i| game_seeds.each_with_index do |jseed, j| next if i == j @raters[iseed].add(player(jseed).rating, Util.ranks_to_score(ranks[i], ranks[j])) end end end
[ "def", "game", "(", "game_seeds", ",", "ranks", ")", "game_seeds", ".", "each_with_index", "do", "|", "iseed", ",", "i", "|", "game_seeds", ".", "each_with_index", "do", "|", "jseed", ",", "j", "|", "next", "if", "i", "==", "j", "@raters", "[", "iseed", "]", ".", "add", "(", "player", "(", "jseed", ")", ".", "rating", ",", "Util", ".", "ranks_to_score", "(", "ranks", "[", "i", "]", ",", "ranks", "[", "j", "]", ")", ")", "end", "end", "end" ]
Register a game with this rating period @param [Array<#rating,#rating_deviation,#volatility>] game_seeds ratings participating in a game @param [Array<Integer>] ranks corresponding ranks
[ "Register", "a", "game", "with", "this", "rating", "period" ]
8ede9a758a1a35b2bc5e6d4706aad856ec8f7812
https://github.com/proglottis/glicko2/blob/8ede9a758a1a35b2bc5e6d4706aad856ec8f7812/lib/glicko2/rating_period.rb#L35-L42
train
holtrop/ruby-gnucash
lib/gnucash/value.rb
Gnucash.Value.+
def +(other) if other.is_a?(Value) lcm_div = @div.lcm(other.div) Value.new((@val * (lcm_div / @div)) + (other.val * (lcm_div / other.div)), lcm_div) elsif other.is_a?(Numeric) to_f + other else raise "Unexpected argument" end end
ruby
def +(other) if other.is_a?(Value) lcm_div = @div.lcm(other.div) Value.new((@val * (lcm_div / @div)) + (other.val * (lcm_div / other.div)), lcm_div) elsif other.is_a?(Numeric) to_f + other else raise "Unexpected argument" end end
[ "def", "+", "(", "other", ")", "if", "other", ".", "is_a?", "(", "Value", ")", "lcm_div", "=", "@div", ".", "lcm", "(", "other", ".", "div", ")", "Value", ".", "new", "(", "(", "@val", "*", "(", "lcm_div", "/", "@div", ")", ")", "+", "(", "other", ".", "val", "*", "(", "lcm_div", "/", "other", ".", "div", ")", ")", ",", "lcm_div", ")", "elsif", "other", ".", "is_a?", "(", "Numeric", ")", "to_f", "+", "other", "else", "raise", "\"Unexpected argument\"", "end", "end" ]
Construct a Value object. @param val [String, Integer] Either a String in the form "1234/100" or an integer containing the raw value. @param div [Integer] The divisor value to use (when +val+ is given as a Integer). Add to a Value object. @param other [Value, Numeric] @return [Value] Result of addition.
[ "Construct", "a", "Value", "object", "." ]
a233cc4da0f36b13bc3f7a17264adb82c8a12c6b
https://github.com/holtrop/ruby-gnucash/blob/a233cc4da0f36b13bc3f7a17264adb82c8a12c6b/lib/gnucash/value.rb#L49-L58
train
holtrop/ruby-gnucash
lib/gnucash/value.rb
Gnucash.Value.*
def *(other) if other.is_a?(Value) other = other.to_f end if other.is_a?(Numeric) to_f * other else raise "Unexpected argument (#{other.inspect})" end end
ruby
def *(other) if other.is_a?(Value) other = other.to_f end if other.is_a?(Numeric) to_f * other else raise "Unexpected argument (#{other.inspect})" end end
[ "def", "*", "(", "other", ")", "if", "other", ".", "is_a?", "(", "Value", ")", "other", "=", "other", ".", "to_f", "end", "if", "other", ".", "is_a?", "(", "Numeric", ")", "to_f", "*", "other", "else", "raise", "\"Unexpected argument (#{other.inspect})\"", "end", "end" ]
Multiply a Value object. @param other [Numeric, Value] Multiplier. @return [Numeric] Result of multiplication.
[ "Multiply", "a", "Value", "object", "." ]
a233cc4da0f36b13bc3f7a17264adb82c8a12c6b
https://github.com/holtrop/ruby-gnucash/blob/a233cc4da0f36b13bc3f7a17264adb82c8a12c6b/lib/gnucash/value.rb#L88-L97
train
notonthehighstreet/chicago
lib/chicago/star_schema.rb
Chicago.StarSchema.add
def add(schema_table) if schema_table.kind_of? Schema::Fact collection = @facts elsif schema_table.kind_of? Schema::Dimension collection = @dimensions end add_to_collection collection, schema_table end
ruby
def add(schema_table) if schema_table.kind_of? Schema::Fact collection = @facts elsif schema_table.kind_of? Schema::Dimension collection = @dimensions end add_to_collection collection, schema_table end
[ "def", "add", "(", "schema_table", ")", "if", "schema_table", ".", "kind_of?", "Schema", "::", "Fact", "collection", "=", "@facts", "elsif", "schema_table", ".", "kind_of?", "Schema", "::", "Dimension", "collection", "=", "@dimensions", "end", "add_to_collection", "collection", ",", "schema_table", "end" ]
Adds a prebuilt schema table to the schema Schema tables may not be dupliates of already present tables in the schema. TODO: figure out how to deal with linked dimensions when adding facts.
[ "Adds", "a", "prebuilt", "schema", "table", "to", "the", "schema" ]
428e94f8089d2f36fdcff2e27ea2af572b816def
https://github.com/notonthehighstreet/chicago/blob/428e94f8089d2f36fdcff2e27ea2af572b816def/lib/chicago/star_schema.rb#L62-L70
train
notonthehighstreet/chicago
lib/chicago/star_schema.rb
Chicago.StarSchema.define_fact
def define_fact(name, &block) add Schema::Builders::FactBuilder.new(self).build(name, &block) end
ruby
def define_fact(name, &block) add Schema::Builders::FactBuilder.new(self).build(name, &block) end
[ "def", "define_fact", "(", "name", ",", "&", "block", ")", "add", "Schema", "::", "Builders", "::", "FactBuilder", ".", "new", "(", "self", ")", ".", "build", "(", "name", ",", "&", "block", ")", "end" ]
Defines a fact table named +name+ in this schema. @see Chicago::Schema::Builders::FactBuilder @return [Chicago::Schema::Fact] the defined fact. @raise Chicago::MissingDefinitionError
[ "Defines", "a", "fact", "table", "named", "+", "name", "+", "in", "this", "schema", "." ]
428e94f8089d2f36fdcff2e27ea2af572b816def
https://github.com/notonthehighstreet/chicago/blob/428e94f8089d2f36fdcff2e27ea2af572b816def/lib/chicago/star_schema.rb#L77-L79
train
notonthehighstreet/chicago
lib/chicago/star_schema.rb
Chicago.StarSchema.define_dimension
def define_dimension(name, &block) add Schema::Builders::DimensionBuilder.new(self).build(name, &block) end
ruby
def define_dimension(name, &block) add Schema::Builders::DimensionBuilder.new(self).build(name, &block) end
[ "def", "define_dimension", "(", "name", ",", "&", "block", ")", "add", "Schema", "::", "Builders", "::", "DimensionBuilder", ".", "new", "(", "self", ")", ".", "build", "(", "name", ",", "&", "block", ")", "end" ]
Defines a dimension table named +name+ in this schema. For example: @schema.define_dimension(:date) do columns do date :date year :year string :month ... end natural_key :date null_record :id => 1, :month => "Unknown Month" end @see Chicago::Schema::Builders::DimensionBuilder @return [Chicago::Schema::Dimension] the defined dimension.
[ "Defines", "a", "dimension", "table", "named", "+", "name", "+", "in", "this", "schema", "." ]
428e94f8089d2f36fdcff2e27ea2af572b816def
https://github.com/notonthehighstreet/chicago/blob/428e94f8089d2f36fdcff2e27ea2af572b816def/lib/chicago/star_schema.rb#L99-L101
train
notonthehighstreet/chicago
lib/chicago/star_schema.rb
Chicago.StarSchema.define_shrunken_dimension
def define_shrunken_dimension(name, base_name, &block) add Schema::Builders::ShrunkenDimensionBuilder.new(self, base_name). build(name, &block) end
ruby
def define_shrunken_dimension(name, base_name, &block) add Schema::Builders::ShrunkenDimensionBuilder.new(self, base_name). build(name, &block) end
[ "def", "define_shrunken_dimension", "(", "name", ",", "base_name", ",", "&", "block", ")", "add", "Schema", "::", "Builders", "::", "ShrunkenDimensionBuilder", ".", "new", "(", "self", ",", "base_name", ")", ".", "build", "(", "name", ",", "&", "block", ")", "end" ]
Defines a shrunken dimension table named +name+ in this schema. +base_name+ is the name of the base dimension that the shrunken dimension is derived from; this base dimention must already be defined. @see Chicago::Schema::Builders::ShrunkenDimensionBuilder @raise [Chicago::MissingDefinitionError] if the base dimension is not defined. @return [Chicago::Schema::Dimension] the defined dimension.
[ "Defines", "a", "shrunken", "dimension", "table", "named", "+", "name", "+", "in", "this", "schema", "." ]
428e94f8089d2f36fdcff2e27ea2af572b816def
https://github.com/notonthehighstreet/chicago/blob/428e94f8089d2f36fdcff2e27ea2af572b816def/lib/chicago/star_schema.rb#L112-L115
train
jeffnyman/tapestry
lib/tapestry/extensions/data_setter.rb
Tapestry.DataSetter.use_data_with
def use_data_with(key, value) element = send(key.to_s.tr(' ', '_')) set_and_select(key, element, value) check_and_uncheck(key, element, value) end
ruby
def use_data_with(key, value) element = send(key.to_s.tr(' ', '_')) set_and_select(key, element, value) check_and_uncheck(key, element, value) end
[ "def", "use_data_with", "(", "key", ",", "value", ")", "element", "=", "send", "(", "key", ".", "to_s", ".", "tr", "(", "' '", ",", "'_'", ")", ")", "set_and_select", "(", "key", ",", "element", ",", "value", ")", "check_and_uncheck", "(", "key", ",", "element", ",", "value", ")", "end" ]
This is the method that is delegated to in order to make sure that elements are interacted with appropriately. This will in turn delegate to `set_and_select` and `check_and_uncheck`, which determines what actions are viable based on the type of element that is being dealt with. These aspects are what tie this particular implementation to Watir.
[ "This", "is", "the", "method", "that", "is", "delegated", "to", "in", "order", "to", "make", "sure", "that", "elements", "are", "interacted", "with", "appropriately", ".", "This", "will", "in", "turn", "delegate", "to", "set_and_select", "and", "check_and_uncheck", "which", "determines", "what", "actions", "are", "viable", "based", "on", "the", "type", "of", "element", "that", "is", "being", "dealt", "with", ".", "These", "aspects", "are", "what", "tie", "this", "particular", "implementation", "to", "Watir", "." ]
da28652dd6de71e415cd2c01afd89f641938a05b
https://github.com/jeffnyman/tapestry/blob/da28652dd6de71e415cd2c01afd89f641938a05b/lib/tapestry/extensions/data_setter.rb#L79-L83
train
tagoh/ruby-bugzilla
lib/bugzilla/bugzilla.rb
Bugzilla.Bugzilla.requires_version
def requires_version(cmd, version_) v = check_version(version_) raise NoMethodError, sprintf("%s is not supported in Bugzilla %s", cmd, v[1]) unless v[0] end
ruby
def requires_version(cmd, version_) v = check_version(version_) raise NoMethodError, sprintf("%s is not supported in Bugzilla %s", cmd, v[1]) unless v[0] end
[ "def", "requires_version", "(", "cmd", ",", "version_", ")", "v", "=", "check_version", "(", "version_", ")", "raise", "NoMethodError", ",", "sprintf", "(", "\"%s is not supported in Bugzilla %s\"", ",", "cmd", ",", "v", "[", "1", "]", ")", "unless", "v", "[", "0", "]", "end" ]
def check_version =begin rdoc ==== Bugzilla::Bugzilla#requires_version(cmd, version_) Raise an exception if the Bugzilla doesn't satisfy the requirement of the _version_. =end
[ "def", "check_version", "=", "begin", "rdoc" ]
5aabec1b045473bcd6e6ac7427b68adb3e3b4886
https://github.com/tagoh/ruby-bugzilla/blob/5aabec1b045473bcd6e6ac7427b68adb3e3b4886/lib/bugzilla/bugzilla.rb#L65-L68
train
scrapper/perobs
lib/perobs/IDListPageFile.rb
PEROBS.IDListPageFile.load
def load(page_idx, record) # The IDListPageRecord will tell us the actual number of values stored # in this page. values = [] unless (entries = record.page_entries) == 0 begin @f.seek(page_idx * @page_size * 8) values = @f.read(entries * 8).unpack("Q#{entries}") rescue IOError => e PEROBS.log.fatal "Cannot read cache file #{@file_name}: #{e.message}" end end # Create the IDListPage object with the given values. p = IDListPage.new(self, record, page_idx, values) @pages.insert(p, false) p end
ruby
def load(page_idx, record) # The IDListPageRecord will tell us the actual number of values stored # in this page. values = [] unless (entries = record.page_entries) == 0 begin @f.seek(page_idx * @page_size * 8) values = @f.read(entries * 8).unpack("Q#{entries}") rescue IOError => e PEROBS.log.fatal "Cannot read cache file #{@file_name}: #{e.message}" end end # Create the IDListPage object with the given values. p = IDListPage.new(self, record, page_idx, values) @pages.insert(p, false) p end
[ "def", "load", "(", "page_idx", ",", "record", ")", "values", "=", "[", "]", "unless", "(", "entries", "=", "record", ".", "page_entries", ")", "==", "0", "begin", "@f", ".", "seek", "(", "page_idx", "*", "@page_size", "*", "8", ")", "values", "=", "@f", ".", "read", "(", "entries", "*", "8", ")", ".", "unpack", "(", "\"Q#{entries}\"", ")", "rescue", "IOError", "=>", "e", "PEROBS", ".", "log", ".", "fatal", "\"Cannot read cache file #{@file_name}: #{e.message}\"", "end", "end", "p", "=", "IDListPage", ".", "new", "(", "self", ",", "record", ",", "page_idx", ",", "values", ")", "@pages", ".", "insert", "(", "p", ",", "false", ")", "p", "end" ]
Create a new IDListPageFile object that uses the given file in the given directory as cache file. @param list [IDList] The IDList object that caches pages here @param dir [String] An existing directory @param name [String] A file name (without path) @param max_in_memory [Integer] Maximum number of pages to keep in memory @param page_size [Integer] The number of values in each page Load the IDListPage from the cache file. @param page_idx [Integer] The page index in the page file @param record [IDListPageRecord] the corresponding IDListPageRecord @return [IDListPage] The loaded values
[ "Create", "a", "new", "IDListPageFile", "object", "that", "uses", "the", "given", "file", "in", "the", "given", "directory", "as", "cache", "file", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/IDListPageFile.rb#L66-L84
train
scrapper/perobs
lib/perobs/IDListPageFile.rb
PEROBS.IDListPageFile.new_page
def new_page(record, values = []) idx = @page_counter @page_counter += 1 mark_page_as_modified(IDListPage.new(self, record, idx, values)) idx end
ruby
def new_page(record, values = []) idx = @page_counter @page_counter += 1 mark_page_as_modified(IDListPage.new(self, record, idx, values)) idx end
[ "def", "new_page", "(", "record", ",", "values", "=", "[", "]", ")", "idx", "=", "@page_counter", "@page_counter", "+=", "1", "mark_page_as_modified", "(", "IDListPage", ".", "new", "(", "self", ",", "record", ",", "idx", ",", "values", ")", ")", "idx", "end" ]
Create a new IDListPage and register it. @param record [IDListPageRecord] The corresponding record. @param values [Array of Integer] The values stored in the page @return [IDListPage]
[ "Create", "a", "new", "IDListPage", "and", "register", "it", "." ]
1c9327656912cf96683849f92d260546af856adf
https://github.com/scrapper/perobs/blob/1c9327656912cf96683849f92d260546af856adf/lib/perobs/IDListPageFile.rb#L95-L100
train