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
ideonetwork/lato-blog
app/models/lato_blog/post/serializer_helpers.rb
LatoBlog.Post::SerializerHelpers.serialize_other_informations
def serialize_other_informations serialized = {} # set pubblication datetime serialized[:publication_datetime] = post_parent.publication_datetime # set translations links serialized[:translations] = {} post_parent.posts.published.each do |post| next if post.id == id serialized[:translations][post.meta_language] = post.serialize_base end # return serialzed informations serialized end
ruby
def serialize_other_informations serialized = {} # set pubblication datetime serialized[:publication_datetime] = post_parent.publication_datetime # set translations links serialized[:translations] = {} post_parent.posts.published.each do |post| next if post.id == id serialized[:translations][post.meta_language] = post.serialize_base end # return serialzed informations serialized end
[ "def", "serialize_other_informations", "serialized", "=", "{", "}", "serialized", "[", ":publication_datetime", "]", "=", "post_parent", ".", "publication_datetime", "serialized", "[", ":translations", "]", "=", "{", "}", "post_parent", ".", "posts", ".", "published", ".", "each", "do", "|", "post", "|", "next", "if", "post", ".", "id", "==", "id", "serialized", "[", ":translations", "]", "[", "post", ".", "meta_language", "]", "=", "post", ".", "serialize_base", "end", "serialized", "end" ]
This function serializes other informations for the post.
[ "This", "function", "serializes", "other", "informations", "for", "the", "post", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/post/serializer_helpers.rb#L80-L95
train
avishekjana/rscratch
app/models/rscratch/exception.rb
Rscratch.Exception.set_attributes_for
def set_attributes_for _exception, _controller, _action, _env self.exception = _exception.class self.message = _exception.message self.controller = _controller self.action = _action self.app_environment = _env end
ruby
def set_attributes_for _exception, _controller, _action, _env self.exception = _exception.class self.message = _exception.message self.controller = _controller self.action = _action self.app_environment = _env end
[ "def", "set_attributes_for", "_exception", ",", "_controller", ",", "_action", ",", "_env", "self", ".", "exception", "=", "_exception", ".", "class", "self", ".", "message", "=", "_exception", ".", "message", "self", ".", "controller", "=", "_controller", "self", ".", "action", "=", "_action", "self", ".", "app_environment", "=", "_env", "end" ]
Sets Exception instance attributes.
[ "Sets", "Exception", "instance", "attributes", "." ]
96493d123473efa2f252d9427455beee947949e1
https://github.com/avishekjana/rscratch/blob/96493d123473efa2f252d9427455beee947949e1/app/models/rscratch/exception.rb#L63-L69
train
sld/astar-15puzzle-solver
lib/fifteen_puzzle.rb
FifteenPuzzle.GameMatrix.moved_matrix_with_parent
def moved_matrix_with_parent( i, j, new_i, new_j, open_list, closed_list ) return nil if !index_exist?( new_i, new_j ) swapped_matrix = swap( i, j, new_i, new_j ) new_depth = @depth + 1 swapped_matrix = GameMatrix.new( swapped_matrix, self, new_depth ) return nil if closed_list.include?( swapped_matrix ) swapped_matrix.calculate_cost open_list_matrix = open_list.find{ |e| e == swapped_matrix } if open_list_matrix && open_list_matrix.cost < swapped_matrix.cost return open_list_matrix elsif open_list_matrix open_list_matrix.parent = self open_list_matrix.depth = new_depth return open_list_matrix else return swapped_matrix end end
ruby
def moved_matrix_with_parent( i, j, new_i, new_j, open_list, closed_list ) return nil if !index_exist?( new_i, new_j ) swapped_matrix = swap( i, j, new_i, new_j ) new_depth = @depth + 1 swapped_matrix = GameMatrix.new( swapped_matrix, self, new_depth ) return nil if closed_list.include?( swapped_matrix ) swapped_matrix.calculate_cost open_list_matrix = open_list.find{ |e| e == swapped_matrix } if open_list_matrix && open_list_matrix.cost < swapped_matrix.cost return open_list_matrix elsif open_list_matrix open_list_matrix.parent = self open_list_matrix.depth = new_depth return open_list_matrix else return swapped_matrix end end
[ "def", "moved_matrix_with_parent", "(", "i", ",", "j", ",", "new_i", ",", "new_j", ",", "open_list", ",", "closed_list", ")", "return", "nil", "if", "!", "index_exist?", "(", "new_i", ",", "new_j", ")", "swapped_matrix", "=", "swap", "(", "i", ",", "j", ",", "new_i", ",", "new_j", ")", "new_depth", "=", "@depth", "+", "1", "swapped_matrix", "=", "GameMatrix", ".", "new", "(", "swapped_matrix", ",", "self", ",", "new_depth", ")", "return", "nil", "if", "closed_list", ".", "include?", "(", "swapped_matrix", ")", "swapped_matrix", ".", "calculate_cost", "open_list_matrix", "=", "open_list", ".", "find", "{", "|", "e", "|", "e", "==", "swapped_matrix", "}", "if", "open_list_matrix", "&&", "open_list_matrix", ".", "cost", "<", "swapped_matrix", ".", "cost", "return", "open_list_matrix", "elsif", "open_list_matrix", "open_list_matrix", ".", "parent", "=", "self", "open_list_matrix", ".", "depth", "=", "new_depth", "return", "open_list_matrix", "else", "return", "swapped_matrix", "end", "end" ]
Get swapped matrix, check him in closed and open list
[ "Get", "swapped", "matrix", "check", "him", "in", "closed", "and", "open", "list" ]
f65cffea0a78c64e6f1f4a5dd694ccddb7fdf3ea
https://github.com/sld/astar-15puzzle-solver/blob/f65cffea0a78c64e6f1f4a5dd694ccddb7fdf3ea/lib/fifteen_puzzle.rb#L213-L233
train
sld/astar-15puzzle-solver
lib/fifteen_puzzle.rb
FifteenPuzzle.GameMatrix.neighbors
def neighbors( open_list=[], closed_list=[] ) i,j = free_cell up = moved_matrix_with_parent(i, j, i-1, j, open_list, closed_list) down = moved_matrix_with_parent(i, j, i+1, j, open_list, closed_list) left = moved_matrix_with_parent(i, j, i, j-1, open_list, closed_list) right = moved_matrix_with_parent(i, j, i, j+1, open_list, closed_list) moved = [] moved << up if !up.nil? moved << down if !down.nil? moved << left if !left.nil? moved << right if !right.nil? return moved end
ruby
def neighbors( open_list=[], closed_list=[] ) i,j = free_cell up = moved_matrix_with_parent(i, j, i-1, j, open_list, closed_list) down = moved_matrix_with_parent(i, j, i+1, j, open_list, closed_list) left = moved_matrix_with_parent(i, j, i, j-1, open_list, closed_list) right = moved_matrix_with_parent(i, j, i, j+1, open_list, closed_list) moved = [] moved << up if !up.nil? moved << down if !down.nil? moved << left if !left.nil? moved << right if !right.nil? return moved end
[ "def", "neighbors", "(", "open_list", "=", "[", "]", ",", "closed_list", "=", "[", "]", ")", "i", ",", "j", "=", "free_cell", "up", "=", "moved_matrix_with_parent", "(", "i", ",", "j", ",", "i", "-", "1", ",", "j", ",", "open_list", ",", "closed_list", ")", "down", "=", "moved_matrix_with_parent", "(", "i", ",", "j", ",", "i", "+", "1", ",", "j", ",", "open_list", ",", "closed_list", ")", "left", "=", "moved_matrix_with_parent", "(", "i", ",", "j", ",", "i", ",", "j", "-", "1", ",", "open_list", ",", "closed_list", ")", "right", "=", "moved_matrix_with_parent", "(", "i", ",", "j", ",", "i", ",", "j", "+", "1", ",", "open_list", ",", "closed_list", ")", "moved", "=", "[", "]", "moved", "<<", "up", "if", "!", "up", ".", "nil?", "moved", "<<", "down", "if", "!", "down", ".", "nil?", "moved", "<<", "left", "if", "!", "left", ".", "nil?", "moved", "<<", "right", "if", "!", "right", ".", "nil?", "return", "moved", "end" ]
Get all possible movement matrixes
[ "Get", "all", "possible", "movement", "matrixes" ]
f65cffea0a78c64e6f1f4a5dd694ccddb7fdf3ea
https://github.com/sld/astar-15puzzle-solver/blob/f65cffea0a78c64e6f1f4a5dd694ccddb7fdf3ea/lib/fifteen_puzzle.rb#L237-L251
train
nolanw/mpq
lib/mpq.rb
MPQ.Archive.read_table
def read_table table table_offset = @archive_header.send "#{table}_table_offset" @io.seek @user_header.archive_header_offset + table_offset table_entries = @archive_header.send "#{table}_table_entries" data = @io.read table_entries * 16 key = Hashing::hash_for :table, "(#{table} table)" data = Hashing::decrypt data, key klass = table == :hash ? HashTableEntry : BlockTableEntry (0...table_entries).map do |i| klass.read(data[i * 16, 16]) end end
ruby
def read_table table table_offset = @archive_header.send "#{table}_table_offset" @io.seek @user_header.archive_header_offset + table_offset table_entries = @archive_header.send "#{table}_table_entries" data = @io.read table_entries * 16 key = Hashing::hash_for :table, "(#{table} table)" data = Hashing::decrypt data, key klass = table == :hash ? HashTableEntry : BlockTableEntry (0...table_entries).map do |i| klass.read(data[i * 16, 16]) end end
[ "def", "read_table", "table", "table_offset", "=", "@archive_header", ".", "send", "\"#{table}_table_offset\"", "@io", ".", "seek", "@user_header", ".", "archive_header_offset", "+", "table_offset", "table_entries", "=", "@archive_header", ".", "send", "\"#{table}_table_entries\"", "data", "=", "@io", ".", "read", "table_entries", "*", "16", "key", "=", "Hashing", "::", "hash_for", ":table", ",", "\"(#{table} table)\"", "data", "=", "Hashing", "::", "decrypt", "data", ",", "key", "klass", "=", "table", "==", ":hash", "?", "HashTableEntry", ":", "BlockTableEntry", "(", "0", "...", "table_entries", ")", ".", "map", "do", "|", "i", "|", "klass", ".", "read", "(", "data", "[", "i", "*", "16", ",", "16", "]", ")", "end", "end" ]
In general, MPQ archives start with either the MPQ header, or they start with a user header which points to the MPQ header. StarCraft 2 replays always have a user header, so we don't even bother to check here. The MPQ header points to two very helpful parts of the MPQ archive: the hash table, which tells us where the contents of files are found, and the block table, which holds said contents of files. That's all we need to read up front. Both the hash and block tables' contents are hashed (in the same way), so we need to decrypt them in order to read their contents.
[ "In", "general", "MPQ", "archives", "start", "with", "either", "the", "MPQ", "header", "or", "they", "start", "with", "a", "user", "header", "which", "points", "to", "the", "MPQ", "header", ".", "StarCraft", "2", "replays", "always", "have", "a", "user", "header", "so", "we", "don", "t", "even", "bother", "to", "check", "here", "." ]
4584611f6cede02807257fcf7defdf93b9b7f7db
https://github.com/nolanw/mpq/blob/4584611f6cede02807257fcf7defdf93b9b7f7db/lib/mpq.rb#L39-L50
train
nolanw/mpq
lib/mpq.rb
MPQ.Archive.read_file
def read_file filename # The first block location is stored in the hash table. hash_a = Hashing::hash_for :hash_a, filename hash_b = Hashing::hash_for :hash_b, filename hash_entry = @hash_table.find do |h| [h.hash_a, h.hash_b] == [hash_a, hash_b] end unless hash_entry return nil end block_entry = @block_table[hash_entry.block_index] unless block_entry.file? return nil end @io.seek @user_header.archive_header_offset + block_entry.block_offset file_data = @io.read block_entry.archived_size # Blocks can be encrypted. Decryption isn't currently implemented as none # of the blocks in a StarCraft 2 replay are encrypted. if block_entry.encrypted? return nil end # Files can consist of one or many blocks. In either case, each block # (or *sector*) is read and individually decompressed if needed, then # stitched together for the final result. if block_entry.single_unit? if block_entry.compressed? if file_data.bytes.next == 16 file_data = Bzip2.uncompress file_data[1, file_data.length] end end return file_data end sector_size = 512 << @archive_header.sector_size_shift sectors = block_entry.size / sector_size + 1 if block_entry.has_checksums sectors += 1 end positions = file_data[0, 4 * (sectors + 1)].unpack "V#{sectors + 1}" sectors = [] positions.each_with_index do |pos, i| break if i + 1 == positions.length sector = file_data[pos, positions[i + 1] - pos] if block_entry.compressed? if block_entry.size > block_entry.archived_size if sector.bytes.next == 16 sector = Bzip2.uncompress sector end end end sectors << sector end sectors.join '' end
ruby
def read_file filename # The first block location is stored in the hash table. hash_a = Hashing::hash_for :hash_a, filename hash_b = Hashing::hash_for :hash_b, filename hash_entry = @hash_table.find do |h| [h.hash_a, h.hash_b] == [hash_a, hash_b] end unless hash_entry return nil end block_entry = @block_table[hash_entry.block_index] unless block_entry.file? return nil end @io.seek @user_header.archive_header_offset + block_entry.block_offset file_data = @io.read block_entry.archived_size # Blocks can be encrypted. Decryption isn't currently implemented as none # of the blocks in a StarCraft 2 replay are encrypted. if block_entry.encrypted? return nil end # Files can consist of one or many blocks. In either case, each block # (or *sector*) is read and individually decompressed if needed, then # stitched together for the final result. if block_entry.single_unit? if block_entry.compressed? if file_data.bytes.next == 16 file_data = Bzip2.uncompress file_data[1, file_data.length] end end return file_data end sector_size = 512 << @archive_header.sector_size_shift sectors = block_entry.size / sector_size + 1 if block_entry.has_checksums sectors += 1 end positions = file_data[0, 4 * (sectors + 1)].unpack "V#{sectors + 1}" sectors = [] positions.each_with_index do |pos, i| break if i + 1 == positions.length sector = file_data[pos, positions[i + 1] - pos] if block_entry.compressed? if block_entry.size > block_entry.archived_size if sector.bytes.next == 16 sector = Bzip2.uncompress sector end end end sectors << sector end sectors.join '' end
[ "def", "read_file", "filename", "hash_a", "=", "Hashing", "::", "hash_for", ":hash_a", ",", "filename", "hash_b", "=", "Hashing", "::", "hash_for", ":hash_b", ",", "filename", "hash_entry", "=", "@hash_table", ".", "find", "do", "|", "h", "|", "[", "h", ".", "hash_a", ",", "h", ".", "hash_b", "]", "==", "[", "hash_a", ",", "hash_b", "]", "end", "unless", "hash_entry", "return", "nil", "end", "block_entry", "=", "@block_table", "[", "hash_entry", ".", "block_index", "]", "unless", "block_entry", ".", "file?", "return", "nil", "end", "@io", ".", "seek", "@user_header", ".", "archive_header_offset", "+", "block_entry", ".", "block_offset", "file_data", "=", "@io", ".", "read", "block_entry", ".", "archived_size", "if", "block_entry", ".", "encrypted?", "return", "nil", "end", "if", "block_entry", ".", "single_unit?", "if", "block_entry", ".", "compressed?", "if", "file_data", ".", "bytes", ".", "next", "==", "16", "file_data", "=", "Bzip2", ".", "uncompress", "file_data", "[", "1", ",", "file_data", ".", "length", "]", "end", "end", "return", "file_data", "end", "sector_size", "=", "512", "<<", "@archive_header", ".", "sector_size_shift", "sectors", "=", "block_entry", ".", "size", "/", "sector_size", "+", "1", "if", "block_entry", ".", "has_checksums", "sectors", "+=", "1", "end", "positions", "=", "file_data", "[", "0", ",", "4", "*", "(", "sectors", "+", "1", ")", "]", ".", "unpack", "\"V#{sectors + 1}\"", "sectors", "=", "[", "]", "positions", ".", "each_with_index", "do", "|", "pos", ",", "i", "|", "break", "if", "i", "+", "1", "==", "positions", ".", "length", "sector", "=", "file_data", "[", "pos", ",", "positions", "[", "i", "+", "1", "]", "-", "pos", "]", "if", "block_entry", ".", "compressed?", "if", "block_entry", ".", "size", ">", "block_entry", ".", "archived_size", "if", "sector", ".", "bytes", ".", "next", "==", "16", "sector", "=", "Bzip2", ".", "uncompress", "sector", "end", "end", "end", "sectors", "<<", "sector", "end", "sectors", ".", "join", "''", "end" ]
To read a file from the MPQ archive, we need to locate its blocks.
[ "To", "read", "a", "file", "from", "the", "MPQ", "archive", "we", "need", "to", "locate", "its", "blocks", "." ]
4584611f6cede02807257fcf7defdf93b9b7f7db
https://github.com/nolanw/mpq/blob/4584611f6cede02807257fcf7defdf93b9b7f7db/lib/mpq.rb#L53-L108
train
Deradon/Rdcpu16
lib/dcpu16/assembler.rb
DCPU16.Assembler.assemble
def assemble location = 0 @labels = {} @body = [] lines.each do |line| # Set label location @labels[line.label] = location if line.label # Skip when no op next if line.op.empty? op = Instruction.create(line.op, line.args, location) @body << op location += op.size end # Apply labels begin @body.each { |op| op.apply_labels(@labels) } rescue Exception => e puts @labels.inspect raise e end end
ruby
def assemble location = 0 @labels = {} @body = [] lines.each do |line| # Set label location @labels[line.label] = location if line.label # Skip when no op next if line.op.empty? op = Instruction.create(line.op, line.args, location) @body << op location += op.size end # Apply labels begin @body.each { |op| op.apply_labels(@labels) } rescue Exception => e puts @labels.inspect raise e end end
[ "def", "assemble", "location", "=", "0", "@labels", "=", "{", "}", "@body", "=", "[", "]", "lines", ".", "each", "do", "|", "line", "|", "@labels", "[", "line", ".", "label", "]", "=", "location", "if", "line", ".", "label", "next", "if", "line", ".", "op", ".", "empty?", "op", "=", "Instruction", ".", "create", "(", "line", ".", "op", ",", "line", ".", "args", ",", "location", ")", "@body", "<<", "op", "location", "+=", "op", ".", "size", "end", "begin", "@body", ".", "each", "{", "|", "op", "|", "op", ".", "apply_labels", "(", "@labels", ")", "}", "rescue", "Exception", "=>", "e", "puts", "@labels", ".", "inspect", "raise", "e", "end", "end" ]
Assemble the given input.
[ "Assemble", "the", "given", "input", "." ]
a4460927aa64c2a514c57993e8ea13f5b48377e9
https://github.com/Deradon/Rdcpu16/blob/a4460927aa64c2a514c57993e8ea13f5b48377e9/lib/dcpu16/assembler.rb#L16-L40
train
avishekjana/rscratch
app/models/rscratch/exception_log.rb
Rscratch.ExceptionLog.set_attributes_for
def set_attributes_for exc, request self.backtrace = exc.backtrace.join("\n"), self.request_url = request.original_url, self.request_method = request.request_method, self.parameters = request.filtered_parameters, self.user_agent = request.user_agent, self.client_ip = request.remote_ip, self.status = "new", self.description = exc.inspect end
ruby
def set_attributes_for exc, request self.backtrace = exc.backtrace.join("\n"), self.request_url = request.original_url, self.request_method = request.request_method, self.parameters = request.filtered_parameters, self.user_agent = request.user_agent, self.client_ip = request.remote_ip, self.status = "new", self.description = exc.inspect end
[ "def", "set_attributes_for", "exc", ",", "request", "self", ".", "backtrace", "=", "exc", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", ",", "self", ".", "request_url", "=", "request", ".", "original_url", ",", "self", ".", "request_method", "=", "request", ".", "request_method", ",", "self", ".", "parameters", "=", "request", ".", "filtered_parameters", ",", "self", ".", "user_agent", "=", "request", ".", "user_agent", ",", "self", ".", "client_ip", "=", "request", ".", "remote_ip", ",", "self", ".", "status", "=", "\"new\"", ",", "self", ".", "description", "=", "exc", ".", "inspect", "end" ]
Sets Log instance attributes.
[ "Sets", "Log", "instance", "attributes", "." ]
96493d123473efa2f252d9427455beee947949e1
https://github.com/avishekjana/rscratch/blob/96493d123473efa2f252d9427455beee947949e1/app/models/rscratch/exception_log.rb#L41-L50
train
mobyinc/Cathode
lib/cathode/create_request.rb
Cathode.CreateRequest.default_action_block
def default_action_block proc do begin create_params = instance_eval(&@strong_params) if resource.singular create_params["#{parent_resource_name}_id"] = parent_resource_id end body model.create(create_params) rescue ActionController::ParameterMissing => error body error.message status :bad_request end end end
ruby
def default_action_block proc do begin create_params = instance_eval(&@strong_params) if resource.singular create_params["#{parent_resource_name}_id"] = parent_resource_id end body model.create(create_params) rescue ActionController::ParameterMissing => error body error.message status :bad_request end end end
[ "def", "default_action_block", "proc", "do", "begin", "create_params", "=", "instance_eval", "(", "&", "@strong_params", ")", "if", "resource", ".", "singular", "create_params", "[", "\"#{parent_resource_name}_id\"", "]", "=", "parent_resource_id", "end", "body", "model", ".", "create", "(", "create_params", ")", "rescue", "ActionController", "::", "ParameterMissing", "=>", "error", "body", "error", ".", "message", "status", ":bad_request", "end", "end", "end" ]
Sets the default action to create a new resource. If the resource is singular, sets the parent resource `id` as well.
[ "Sets", "the", "default", "action", "to", "create", "a", "new", "resource", ".", "If", "the", "resource", "is", "singular", "sets", "the", "parent", "resource", "id", "as", "well", "." ]
e17be4fb62ad61417e2a3a0a77406459015468a1
https://github.com/mobyinc/Cathode/blob/e17be4fb62ad61417e2a3a0a77406459015468a1/lib/cathode/create_request.rb#L6-L19
train
fissionxuiptz/kat
lib/kat/app.rb
Kat.App.running
def running puts set_window_width searching = true [ -> { @kat.search @page searching = false }, -> { i = 0 while searching print "\rSearching...".yellow + '\\|/-'[i % 4] i += 1 sleep 0.1 end } ].map { |w| Thread.new { w.call } }.each(&:join) puts((res = format_results)) if res.size > 1 case (answer = prompt) when 'i' then @show_info = !@show_info when 'n' then @page += 1 if next? when 'p' then @page -= 1 if prev? when 'q' then return false else if ([email protected][@page].size).include?((answer = answer.to_i)) print "\nDownloading".yellow << ": #{ @kat.results[@page][answer - 1][:title] }... " puts download @kat.results[@page][answer - 1] end end true else false end end
ruby
def running puts set_window_width searching = true [ -> { @kat.search @page searching = false }, -> { i = 0 while searching print "\rSearching...".yellow + '\\|/-'[i % 4] i += 1 sleep 0.1 end } ].map { |w| Thread.new { w.call } }.each(&:join) puts((res = format_results)) if res.size > 1 case (answer = prompt) when 'i' then @show_info = !@show_info when 'n' then @page += 1 if next? when 'p' then @page -= 1 if prev? when 'q' then return false else if ([email protected][@page].size).include?((answer = answer.to_i)) print "\nDownloading".yellow << ": #{ @kat.results[@page][answer - 1][:title] }... " puts download @kat.results[@page][answer - 1] end end true else false end end
[ "def", "running", "puts", "set_window_width", "searching", "=", "true", "[", "->", "{", "@kat", ".", "search", "@page", "searching", "=", "false", "}", ",", "->", "{", "i", "=", "0", "while", "searching", "print", "\"\\rSearching...\"", ".", "yellow", "+", "'\\\\|/-'", "[", "i", "%", "4", "]", "i", "+=", "1", "sleep", "0.1", "end", "}", "]", ".", "map", "{", "|", "w", "|", "Thread", ".", "new", "{", "w", ".", "call", "}", "}", ".", "each", "(", "&", ":join", ")", "puts", "(", "(", "res", "=", "format_results", ")", ")", "if", "res", ".", "size", ">", "1", "case", "(", "answer", "=", "prompt", ")", "when", "'i'", "then", "@show_info", "=", "!", "@show_info", "when", "'n'", "then", "@page", "+=", "1", "if", "next?", "when", "'p'", "then", "@page", "-=", "1", "if", "prev?", "when", "'q'", "then", "return", "false", "else", "if", "(", "1", "..", "@kat", ".", "results", "[", "@page", "]", ".", "size", ")", ".", "include?", "(", "(", "answer", "=", "answer", ".", "to_i", ")", ")", "print", "\"\\nDownloading\"", ".", "yellow", "<<", "\": #{ @kat.results[@page][answer - 1][:title] }... \"", "puts", "download", "@kat", ".", "results", "[", "@page", "]", "[", "answer", "-", "1", "]", "end", "end", "true", "else", "false", "end", "end" ]
Do the search, output the results and prompt the user for what to do next. Returns false on error or the user enters 'q', otherwise returns true to signify to the main loop it should run again.
[ "Do", "the", "search", "output", "the", "results", "and", "prompt", "the", "user", "for", "what", "to", "do", "next", ".", "Returns", "false", "on", "error", "or", "the", "user", "enters", "q", "otherwise", "returns", "true", "to", "signify", "to", "the", "main", "loop", "it", "should", "run", "again", "." ]
8f9e43c5dbeb2462e00fd841c208764380f6983b
https://github.com/fissionxuiptz/kat/blob/8f9e43c5dbeb2462e00fd841c208764380f6983b/lib/kat/app.rb#L129-L170
train
fissionxuiptz/kat
lib/kat/app.rb
Kat.App.format_lists
def format_lists(lists) lists.inject([nil]) do |buf, (_, val)| opts = Kat::Search.send(val[:select]) buf << val[:select].to_s.capitalize buf << nil unless opts.values.first.is_a? Array width = opts.keys.sort { |a, b| b.size <=> a.size }.first.size opts.each do |k, v| buf += if v.is_a? Array [nil, "%#{ width }s => #{ v.shift }" % k] + v.map { |e| ' ' * (width + 4) + e } else ["%-#{ width }s => #{ v }" % k] end end buf << nil end end
ruby
def format_lists(lists) lists.inject([nil]) do |buf, (_, val)| opts = Kat::Search.send(val[:select]) buf << val[:select].to_s.capitalize buf << nil unless opts.values.first.is_a? Array width = opts.keys.sort { |a, b| b.size <=> a.size }.first.size opts.each do |k, v| buf += if v.is_a? Array [nil, "%#{ width }s => #{ v.shift }" % k] + v.map { |e| ' ' * (width + 4) + e } else ["%-#{ width }s => #{ v }" % k] end end buf << nil end end
[ "def", "format_lists", "(", "lists", ")", "lists", ".", "inject", "(", "[", "nil", "]", ")", "do", "|", "buf", ",", "(", "_", ",", "val", ")", "|", "opts", "=", "Kat", "::", "Search", ".", "send", "(", "val", "[", ":select", "]", ")", "buf", "<<", "val", "[", ":select", "]", ".", "to_s", ".", "capitalize", "buf", "<<", "nil", "unless", "opts", ".", "values", ".", "first", ".", "is_a?", "Array", "width", "=", "opts", ".", "keys", ".", "sort", "{", "|", "a", ",", "b", "|", "b", ".", "size", "<=>", "a", ".", "size", "}", ".", "first", ".", "size", "opts", ".", "each", "do", "|", "k", ",", "v", "|", "buf", "+=", "if", "v", ".", "is_a?", "Array", "[", "nil", ",", "\"%#{ width }s => #{ v.shift }\"", "%", "k", "]", "+", "v", ".", "map", "{", "|", "e", "|", "' '", "*", "(", "width", "+", "4", ")", "+", "e", "}", "else", "[", "\"%-#{ width }s => #{ v }\"", "%", "k", "]", "end", "end", "buf", "<<", "nil", "end", "end" ]
Format a list of options
[ "Format", "a", "list", "of", "options" ]
8f9e43c5dbeb2462e00fd841c208764380f6983b
https://github.com/fissionxuiptz/kat/blob/8f9e43c5dbeb2462e00fd841c208764380f6983b/lib/kat/app.rb#L175-L191
train
fissionxuiptz/kat
lib/kat/app.rb
Kat.App.format_results
def format_results main_width = @window_width - (!hide_info? || @show_info ? 42 : 4) buf = [] if @kat.error return ["\rConnection failed".red] elsif [email protected][@page] return ["\rNo results ".red] end buf << "\r#{ @kat.message[:message] }\n".red if @kat.message buf << ("\r%-#{ main_width + 5 }s#{ ' Size Age Seeds Leeches' if !hide_info? || @show_info }" % ["Page #{ page + 1 } of #{ @kat.pages }", nil]).yellow @kat.results[@page].each_with_index do |t, i| age = t[:age].split "\xC2\xA0" age = '%3d %-6s' % age # Filter out the crap that invariably infests torrent names title = t[:title].codepoints.map { |c| c > 31 && c < 127 ? c.chr : '?' }.join[0...main_width] buf << ("%2d. %-#{ main_width }s#{ ' %10s %10s %7d %7d' if !hide_info? or @show_info }" % [i + 1, title, t[:size], age, t[:seeds], t[:leeches]]).tap { |s| s.red! if t[:seeds] == 0 } end buf << nil end
ruby
def format_results main_width = @window_width - (!hide_info? || @show_info ? 42 : 4) buf = [] if @kat.error return ["\rConnection failed".red] elsif [email protected][@page] return ["\rNo results ".red] end buf << "\r#{ @kat.message[:message] }\n".red if @kat.message buf << ("\r%-#{ main_width + 5 }s#{ ' Size Age Seeds Leeches' if !hide_info? || @show_info }" % ["Page #{ page + 1 } of #{ @kat.pages }", nil]).yellow @kat.results[@page].each_with_index do |t, i| age = t[:age].split "\xC2\xA0" age = '%3d %-6s' % age # Filter out the crap that invariably infests torrent names title = t[:title].codepoints.map { |c| c > 31 && c < 127 ? c.chr : '?' }.join[0...main_width] buf << ("%2d. %-#{ main_width }s#{ ' %10s %10s %7d %7d' if !hide_info? or @show_info }" % [i + 1, title, t[:size], age, t[:seeds], t[:leeches]]).tap { |s| s.red! if t[:seeds] == 0 } end buf << nil end
[ "def", "format_results", "main_width", "=", "@window_width", "-", "(", "!", "hide_info?", "||", "@show_info", "?", "42", ":", "4", ")", "buf", "=", "[", "]", "if", "@kat", ".", "error", "return", "[", "\"\\rConnection failed\"", ".", "red", "]", "elsif", "!", "@kat", ".", "results", "[", "@page", "]", "return", "[", "\"\\rNo results \"", ".", "red", "]", "end", "buf", "<<", "\"\\r#{ @kat.message[:message] }\\n\"", ".", "red", "if", "@kat", ".", "message", "buf", "<<", "(", "\"\\r%-#{ main_width + 5 }s#{ ' Size Age Seeds Leeches' if !hide_info? || @show_info }\"", "%", "[", "\"Page #{ page + 1 } of #{ @kat.pages }\"", ",", "nil", "]", ")", ".", "yellow", "@kat", ".", "results", "[", "@page", "]", ".", "each_with_index", "do", "|", "t", ",", "i", "|", "age", "=", "t", "[", ":age", "]", ".", "split", "\"\\xC2\\xA0\"", "age", "=", "'%3d %-6s'", "%", "age", "title", "=", "t", "[", ":title", "]", ".", "codepoints", ".", "map", "{", "|", "c", "|", "c", ">", "31", "&&", "c", "<", "127", "?", "c", ".", "chr", ":", "'?'", "}", ".", "join", "[", "0", "...", "main_width", "]", "buf", "<<", "(", "\"%2d. %-#{ main_width }s#{ ' %10s %10s %7d %7d' if !hide_info? or @show_info }\"", "%", "[", "i", "+", "1", ",", "title", ",", "t", "[", ":size", "]", ",", "age", ",", "t", "[", ":seeds", "]", ",", "t", "[", ":leeches", "]", "]", ")", ".", "tap", "{", "|", "s", "|", "s", ".", "red!", "if", "t", "[", ":seeds", "]", "==", "0", "}", "end", "buf", "<<", "nil", "end" ]
Format the list of results with header information
[ "Format", "the", "list", "of", "results", "with", "header", "information" ]
8f9e43c5dbeb2462e00fd841c208764380f6983b
https://github.com/fissionxuiptz/kat/blob/8f9e43c5dbeb2462e00fd841c208764380f6983b/lib/kat/app.rb#L196-L221
train
fissionxuiptz/kat
lib/kat/app.rb
Kat.App.prompt
def prompt n = @kat.results[@page].size @h.ask("1#{ "-#{n}" if n > 1}".cyan(true) << ' to download' << "#{ ', ' << '(n)'.cyan(true) << 'ext' if next? }" << "#{ ', ' << '(p)'.cyan(true) << 'rev' if prev? }" << "#{ ", #{ @show_info ? 'hide' : 'show' } " << '(i)'.cyan(true) << 'nfo' if hide_info? }" << ', ' << '(q)'.cyan(true) << 'uit: ') do |q| q.responses[:not_valid] = 'Invalid option.' q.validate = validation_regex end rescue RegexpError puts((@kat.pages > 0 ? "Error reading the page\n" : "Could not connect to the site\n").red) return 'q' end
ruby
def prompt n = @kat.results[@page].size @h.ask("1#{ "-#{n}" if n > 1}".cyan(true) << ' to download' << "#{ ', ' << '(n)'.cyan(true) << 'ext' if next? }" << "#{ ', ' << '(p)'.cyan(true) << 'rev' if prev? }" << "#{ ", #{ @show_info ? 'hide' : 'show' } " << '(i)'.cyan(true) << 'nfo' if hide_info? }" << ', ' << '(q)'.cyan(true) << 'uit: ') do |q| q.responses[:not_valid] = 'Invalid option.' q.validate = validation_regex end rescue RegexpError puts((@kat.pages > 0 ? "Error reading the page\n" : "Could not connect to the site\n").red) return 'q' end
[ "def", "prompt", "n", "=", "@kat", ".", "results", "[", "@page", "]", ".", "size", "@h", ".", "ask", "(", "\"1#{ \"-#{n}\" if n > 1}\"", ".", "cyan", "(", "true", ")", "<<", "' to download'", "<<", "\"#{ ', ' << '(n)'.cyan(true) << 'ext' if next? }\"", "<<", "\"#{ ', ' << '(p)'.cyan(true) << 'rev' if prev? }\"", "<<", "\"#{ \", #{ @show_info ? 'hide' : 'show' } \" << '(i)'.cyan(true) << 'nfo' if hide_info? }\"", "<<", "', '", "<<", "'(q)'", ".", "cyan", "(", "true", ")", "<<", "'uit: '", ")", "do", "|", "q", "|", "q", ".", "responses", "[", ":not_valid", "]", "=", "'Invalid option.'", "q", ".", "validate", "=", "validation_regex", "end", "rescue", "RegexpError", "puts", "(", "(", "@kat", ".", "pages", ">", "0", "?", "\"Error reading the page\\n\"", ":", "\"Could not connect to the site\\n\"", ")", ".", "red", ")", "return", "'q'", "end" ]
Set the prompt after the results list has been printed
[ "Set", "the", "prompt", "after", "the", "results", "list", "has", "been", "printed" ]
8f9e43c5dbeb2462e00fd841c208764380f6983b
https://github.com/fissionxuiptz/kat/blob/8f9e43c5dbeb2462e00fd841c208764380f6983b/lib/kat/app.rb#L239-L253
train
anvil-src/anvil-core
lib/anvil/cli.rb
Anvil.Cli.run
def run(argv) load_tasks return build_task(argv).run unless argv.empty? print_help_header print_help_body end
ruby
def run(argv) load_tasks return build_task(argv).run unless argv.empty? print_help_header print_help_body end
[ "def", "run", "(", "argv", ")", "load_tasks", "return", "build_task", "(", "argv", ")", ".", "run", "unless", "argv", ".", "empty?", "print_help_header", "print_help_body", "end" ]
Runs a task or prints its help if it needs arguments @param argv [Array] Command line arguments @return [Object, nil] Anything the task returns
[ "Runs", "a", "task", "or", "prints", "its", "help", "if", "it", "needs", "arguments" ]
8322ebd6a2f002e4177b86e707d9c8d5c2a7233d
https://github.com/anvil-src/anvil-core/blob/8322ebd6a2f002e4177b86e707d9c8d5c2a7233d/lib/anvil/cli.rb#L19-L26
train
anvil-src/anvil-core
lib/anvil/cli.rb
Anvil.Cli.build_task
def build_task(argv) arguments = argv.dup task_name = arguments.shift klazz = Task.from_name(task_name) klazz.new(*klazz.parse_options!(arguments)) rescue NameError task_not_found(task_name) exit false rescue ArgumentError bad_arguments(task_name) exit false end
ruby
def build_task(argv) arguments = argv.dup task_name = arguments.shift klazz = Task.from_name(task_name) klazz.new(*klazz.parse_options!(arguments)) rescue NameError task_not_found(task_name) exit false rescue ArgumentError bad_arguments(task_name) exit false end
[ "def", "build_task", "(", "argv", ")", "arguments", "=", "argv", ".", "dup", "task_name", "=", "arguments", ".", "shift", "klazz", "=", "Task", ".", "from_name", "(", "task_name", ")", "klazz", ".", "new", "(", "*", "klazz", ".", "parse_options!", "(", "arguments", ")", ")", "rescue", "NameError", "task_not_found", "(", "task_name", ")", "exit", "false", "rescue", "ArgumentError", "bad_arguments", "(", "task_name", ")", "exit", "false", "end" ]
Builds a task and prepares it to run @param argv [Array] Command line arguments @return [Anvil::Task] A task ready to run
[ "Builds", "a", "task", "and", "prepares", "it", "to", "run" ]
8322ebd6a2f002e4177b86e707d9c8d5c2a7233d
https://github.com/anvil-src/anvil-core/blob/8322ebd6a2f002e4177b86e707d9c8d5c2a7233d/lib/anvil/cli.rb#L36-L47
train
angdraug/syncache
lib/syncache/syncache.rb
SynCache.Cache.flush
def flush(base = nil) debug { 'flush ' << base.to_s } @sync.synchronize do if @flush_delay next_flush = @last_flush + @flush_delay if next_flush > Time.now flush_at(next_flush, base) else flush_now(base) @last_flush = Time.now end else flush_now(base) end end end
ruby
def flush(base = nil) debug { 'flush ' << base.to_s } @sync.synchronize do if @flush_delay next_flush = @last_flush + @flush_delay if next_flush > Time.now flush_at(next_flush, base) else flush_now(base) @last_flush = Time.now end else flush_now(base) end end end
[ "def", "flush", "(", "base", "=", "nil", ")", "debug", "{", "'flush '", "<<", "base", ".", "to_s", "}", "@sync", ".", "synchronize", "do", "if", "@flush_delay", "next_flush", "=", "@last_flush", "+", "@flush_delay", "if", "next_flush", ">", "Time", ".", "now", "flush_at", "(", "next_flush", ",", "base", ")", "else", "flush_now", "(", "base", ")", "@last_flush", "=", "Time", ".", "now", "end", "else", "flush_now", "(", "base", ")", "end", "end", "end" ]
remove all values from cache if _base_ is given, only values with keys matching the base (using <tt>===</tt> operator) are removed
[ "remove", "all", "values", "from", "cache" ]
bb289ed51cce5eff63c7b899f736c184da7922bc
https://github.com/angdraug/syncache/blob/bb289ed51cce5eff63c7b899f736c184da7922bc/lib/syncache/syncache.rb#L102-L121
train
angdraug/syncache
lib/syncache/syncache.rb
SynCache.Cache.[]=
def []=(key, value) debug { '[]= ' << key.to_s } entry = get_locked_entry(key) begin return entry.value = value ensure entry.sync.unlock end end
ruby
def []=(key, value) debug { '[]= ' << key.to_s } entry = get_locked_entry(key) begin return entry.value = value ensure entry.sync.unlock end end
[ "def", "[]=", "(", "key", ",", "value", ")", "debug", "{", "'[]= '", "<<", "key", ".", "to_s", "}", "entry", "=", "get_locked_entry", "(", "key", ")", "begin", "return", "entry", ".", "value", "=", "value", "ensure", "entry", ".", "sync", ".", "unlock", "end", "end" ]
store new value in cache see also Cache#fetch_or_add
[ "store", "new", "value", "in", "cache" ]
bb289ed51cce5eff63c7b899f736c184da7922bc
https://github.com/angdraug/syncache/blob/bb289ed51cce5eff63c7b899f736c184da7922bc/lib/syncache/syncache.rb#L137-L146
train
angdraug/syncache
lib/syncache/syncache.rb
SynCache.Cache.debug
def debug return unless @debug message = Thread.current.to_s + ' ' + yield if defined?(Syslog) and Syslog.opened? Syslog.debug(message) else STDERR << 'syncache: ' + message + "\n" STDERR.flush end end
ruby
def debug return unless @debug message = Thread.current.to_s + ' ' + yield if defined?(Syslog) and Syslog.opened? Syslog.debug(message) else STDERR << 'syncache: ' + message + "\n" STDERR.flush end end
[ "def", "debug", "return", "unless", "@debug", "message", "=", "Thread", ".", "current", ".", "to_s", "+", "' '", "+", "yield", "if", "defined?", "(", "Syslog", ")", "and", "Syslog", ".", "opened?", "Syslog", ".", "debug", "(", "message", ")", "else", "STDERR", "<<", "'syncache: '", "+", "message", "+", "\"\\n\"", "STDERR", ".", "flush", "end", "end" ]
send debug output to syslog if enabled
[ "send", "debug", "output", "to", "syslog", "if", "enabled" ]
bb289ed51cce5eff63c7b899f736c184da7922bc
https://github.com/angdraug/syncache/blob/bb289ed51cce5eff63c7b899f736c184da7922bc/lib/syncache/syncache.rb#L271-L280
train
mooreryan/abort_if
lib/assert/assert.rb
AbortIf.Assert.assert_keys
def assert_keys coll, *keys check_responds_to coll, :[] check_not_empty keys assert keys.all? { |key| coll[key] }, "Expected coll to include all keys" end
ruby
def assert_keys coll, *keys check_responds_to coll, :[] check_not_empty keys assert keys.all? { |key| coll[key] }, "Expected coll to include all keys" end
[ "def", "assert_keys", "coll", ",", "*", "keys", "check_responds_to", "coll", ",", ":[]", "check_not_empty", "keys", "assert", "keys", ".", "all?", "{", "|", "key", "|", "coll", "[", "key", "]", "}", ",", "\"Expected coll to include all keys\"", "end" ]
If any key is not present in coll, raise AssertionFailureError, else return nil. @example Passing assert_keys {a: 2, b: 1}, :a, :b #=> nil @example Failing assert_keys {a: 2, b: 1}, :a, :b, :c # raises AssertionFailureError @param coll [#[]] collection of things @param *keys keys to check for @raise [AssertionFailureError] if coll does include every key @raise [ArgumentError] if coll doesn't respond to :[] @return [nil] if coll has every key
[ "If", "any", "key", "is", "not", "present", "in", "coll", "raise", "AssertionFailureError", "else", "return", "nil", "." ]
80b4631f6722c99ec1a6bc59fe683d5b97fc5ef4
https://github.com/mooreryan/abort_if/blob/80b4631f6722c99ec1a6bc59fe683d5b97fc5ef4/lib/assert/assert.rb#L127-L134
train
mooreryan/abort_if
lib/assert/assert.rb
AbortIf.Assert.assert_length
def assert_length coll, len check_responds_to coll, :length assert coll.length == len, "Expected coll to have %d items", len end
ruby
def assert_length coll, len check_responds_to coll, :length assert coll.length == len, "Expected coll to have %d items", len end
[ "def", "assert_length", "coll", ",", "len", "check_responds_to", "coll", ",", ":length", "assert", "coll", ".", "length", "==", "len", ",", "\"Expected coll to have %d items\"", ",", "len", "end" ]
If coll is given length, return nil, else raise AssertionFailureError. @param coll [#length] anything that responds to :length @param len [Number] the length to check for @raise [AssertionFailureError] if length of coll doesn't match given len @raise [ArgumentError] if coll doesn't respond to :length @return [nil] if length of coll matches given len
[ "If", "coll", "is", "given", "length", "return", "nil", "else", "raise", "AssertionFailureError", "." ]
80b4631f6722c99ec1a6bc59fe683d5b97fc5ef4
https://github.com/mooreryan/abort_if/blob/80b4631f6722c99ec1a6bc59fe683d5b97fc5ef4/lib/assert/assert.rb#L196-L202
train
bcurren/ejs-rcompiler
lib/ejs/compiler.rb
Ejs.Compiler.js_source
def js_source(source_path, namespace = nil, output_as_array = false) template_name = File.basename(source_path, ".ejs") template_name = "#{namespace}.#{template_name}" if namespace js_source_from_string(template_name, File.read(source_path), output_as_array) end
ruby
def js_source(source_path, namespace = nil, output_as_array = false) template_name = File.basename(source_path, ".ejs") template_name = "#{namespace}.#{template_name}" if namespace js_source_from_string(template_name, File.read(source_path), output_as_array) end
[ "def", "js_source", "(", "source_path", ",", "namespace", "=", "nil", ",", "output_as_array", "=", "false", ")", "template_name", "=", "File", ".", "basename", "(", "source_path", ",", "\".ejs\"", ")", "template_name", "=", "\"#{namespace}.#{template_name}\"", "if", "namespace", "js_source_from_string", "(", "template_name", ",", "File", ".", "read", "(", "source_path", ")", ",", "output_as_array", ")", "end" ]
compile a ejs file into javascript
[ "compile", "a", "ejs", "file", "into", "javascript" ]
dae7d6297ff1920a6f01e1095a939a1d54ada28e
https://github.com/bcurren/ejs-rcompiler/blob/dae7d6297ff1920a6f01e1095a939a1d54ada28e/lib/ejs/compiler.rb#L20-L25
train
bcurren/ejs-rcompiler
lib/ejs/compiler.rb
Ejs.Compiler.js_source_from_string
def js_source_from_string(template_name, content, output_as_array = false) buffer = [] parsed = @parser.parse(content) if parsed.nil? raise ParseError.new(@parser.failure_reason, @parser.failure_line, @parser.failure_column) end template_namespace(buffer, template_name) template_header(buffer, template_name) parsed.elements.each do |element| push_content(buffer, element) end template_footer(buffer) output_as_array ? buffer : buffer.join("\n") end
ruby
def js_source_from_string(template_name, content, output_as_array = false) buffer = [] parsed = @parser.parse(content) if parsed.nil? raise ParseError.new(@parser.failure_reason, @parser.failure_line, @parser.failure_column) end template_namespace(buffer, template_name) template_header(buffer, template_name) parsed.elements.each do |element| push_content(buffer, element) end template_footer(buffer) output_as_array ? buffer : buffer.join("\n") end
[ "def", "js_source_from_string", "(", "template_name", ",", "content", ",", "output_as_array", "=", "false", ")", "buffer", "=", "[", "]", "parsed", "=", "@parser", ".", "parse", "(", "content", ")", "if", "parsed", ".", "nil?", "raise", "ParseError", ".", "new", "(", "@parser", ".", "failure_reason", ",", "@parser", ".", "failure_line", ",", "@parser", ".", "failure_column", ")", "end", "template_namespace", "(", "buffer", ",", "template_name", ")", "template_header", "(", "buffer", ",", "template_name", ")", "parsed", ".", "elements", ".", "each", "do", "|", "element", "|", "push_content", "(", "buffer", ",", "element", ")", "end", "template_footer", "(", "buffer", ")", "output_as_array", "?", "buffer", ":", "buffer", ".", "join", "(", "\"\\n\"", ")", "end" ]
compile a string containing ejs source into javascript
[ "compile", "a", "string", "containing", "ejs", "source", "into", "javascript" ]
dae7d6297ff1920a6f01e1095a939a1d54ada28e
https://github.com/bcurren/ejs-rcompiler/blob/dae7d6297ff1920a6f01e1095a939a1d54ada28e/lib/ejs/compiler.rb#L28-L43
train
darrenleeweber/rdf-resource
lib/rdf-resource/resource.rb
RDFResource.Resource.provenance
def provenance s = [rdf_uri, RDF::PROV.SoftwareAgent, @@agent] rdf.insert(s) s = [rdf_uri, RDF::PROV.generatedAtTime, rdf_now] rdf.insert(s) end
ruby
def provenance s = [rdf_uri, RDF::PROV.SoftwareAgent, @@agent] rdf.insert(s) s = [rdf_uri, RDF::PROV.generatedAtTime, rdf_now] rdf.insert(s) end
[ "def", "provenance", "s", "=", "[", "rdf_uri", ",", "RDF", "::", "PROV", ".", "SoftwareAgent", ",", "@@agent", "]", "rdf", ".", "insert", "(", "s", ")", "s", "=", "[", "rdf_uri", ",", "RDF", "::", "PROV", ".", "generatedAtTime", ",", "rdf_now", "]", "rdf", ".", "insert", "(", "s", ")", "end" ]
Assert PROV.SoftwareAgent and PROV.generatedAtTime
[ "Assert", "PROV", ".", "SoftwareAgent", "and", "PROV", ".", "generatedAtTime" ]
132b2b5356d08bc37d873c807e1048a6b7cc7bee
https://github.com/darrenleeweber/rdf-resource/blob/132b2b5356d08bc37d873c807e1048a6b7cc7bee/lib/rdf-resource/resource.rb#L53-L58
train
darrenleeweber/rdf-resource
lib/rdf-resource/resource.rb
RDFResource.Resource.rdf_find_object
def rdf_find_object(id) return nil unless rdf_valid? rdf.each_statement do |s| if s.subject == @iri.to_s return s.object if s.object.to_s =~ Regexp.new(id, Regexp::IGNORECASE) end end nil end
ruby
def rdf_find_object(id) return nil unless rdf_valid? rdf.each_statement do |s| if s.subject == @iri.to_s return s.object if s.object.to_s =~ Regexp.new(id, Regexp::IGNORECASE) end end nil end
[ "def", "rdf_find_object", "(", "id", ")", "return", "nil", "unless", "rdf_valid?", "rdf", ".", "each_statement", "do", "|", "s", "|", "if", "s", ".", "subject", "==", "@iri", ".", "to_s", "return", "s", ".", "object", "if", "s", ".", "object", ".", "to_s", "=~", "Regexp", ".", "new", "(", "id", ",", "Regexp", "::", "IGNORECASE", ")", "end", "end", "nil", "end" ]
Regexp search to find an object matching a string, if it belongs to @iri @param id [String] A string literal used to construct a Regexp @return [RDF::URI] The first object matching the Regexp
[ "Regexp", "search", "to", "find", "an", "object", "matching", "a", "string", "if", "it", "belongs", "to" ]
132b2b5356d08bc37d873c807e1048a6b7cc7bee
https://github.com/darrenleeweber/rdf-resource/blob/132b2b5356d08bc37d873c807e1048a6b7cc7bee/lib/rdf-resource/resource.rb#L101-L109
train
darrenleeweber/rdf-resource
lib/rdf-resource/resource.rb
RDFResource.Resource.rdf_find_subject
def rdf_find_subject(id) return nil unless rdf_valid? rdf.each_subject do |s| return s if s.to_s =~ Regexp.new(id, Regexp::IGNORECASE) end nil end
ruby
def rdf_find_subject(id) return nil unless rdf_valid? rdf.each_subject do |s| return s if s.to_s =~ Regexp.new(id, Regexp::IGNORECASE) end nil end
[ "def", "rdf_find_subject", "(", "id", ")", "return", "nil", "unless", "rdf_valid?", "rdf", ".", "each_subject", "do", "|", "s", "|", "return", "s", "if", "s", ".", "to_s", "=~", "Regexp", ".", "new", "(", "id", ",", "Regexp", "::", "IGNORECASE", ")", "end", "nil", "end" ]
Regexp search to find a subject matching a string @param id [String] A string literal used to construct a Regexp @return [RDF::URI] The first subject matching the Regexp
[ "Regexp", "search", "to", "find", "a", "subject", "matching", "a", "string" ]
132b2b5356d08bc37d873c807e1048a6b7cc7bee
https://github.com/darrenleeweber/rdf-resource/blob/132b2b5356d08bc37d873c807e1048a6b7cc7bee/lib/rdf-resource/resource.rb#L114-L120
train
CDLUC3/merritt-manifest
lib/merritt/manifest.rb
Merritt.Manifest.write_to
def write_to(io) write_sc(io, conformance) write_sc(io, 'profile', profile) prefixes.each { |prefix, url| write_sc(io, 'prefix', "#{prefix}:", url) } write_sc(io, 'fields', *fields) entries.each { |entry| io.puts(entry_line(entry)) } write_sc(io, 'eof') end
ruby
def write_to(io) write_sc(io, conformance) write_sc(io, 'profile', profile) prefixes.each { |prefix, url| write_sc(io, 'prefix', "#{prefix}:", url) } write_sc(io, 'fields', *fields) entries.each { |entry| io.puts(entry_line(entry)) } write_sc(io, 'eof') end
[ "def", "write_to", "(", "io", ")", "write_sc", "(", "io", ",", "conformance", ")", "write_sc", "(", "io", ",", "'profile'", ",", "profile", ")", "prefixes", ".", "each", "{", "|", "prefix", ",", "url", "|", "write_sc", "(", "io", ",", "'prefix'", ",", "\"#{prefix}:\"", ",", "url", ")", "}", "write_sc", "(", "io", ",", "'fields'", ",", "*", "fields", ")", "entries", ".", "each", "{", "|", "entry", "|", "io", ".", "puts", "(", "entry_line", "(", "entry", ")", ")", "}", "write_sc", "(", "io", ",", "'eof'", ")", "end" ]
Creates a new manifest. Note that the prefix, field, and entry arrays are copied on initialization, as are the individual entry hashes. @param conformance [String] the conformance level. Defaults to {CHECKM_0_7}. @param profile [URI, String] the profile URI. Must begin with @param prefixes [Hash{String,Symbol => URI, String}] a map from namespace prefixes to their URIs @param fields Array<String> a list of field names, in the form prefix:fieldname @param entries [Array<Hash<String, Object><] A list of entries, each of which is a hash keyed by a prefixed fieldname defined in `fields`. Nil values are allowed. @raise [ArgumentError] if `profile` does not begin with {PROFILE_BASE_URI} @raise [ArgumentError] if `fields` cannot be parsed as prefix:fieldname, or if one or more prefixes is not mapped to a URI in `prefixes` @raise [URI::InvalidURIError] if `profile` cannot be parsed as a URI Writes this manifest to the specified IO @param io [IO] the IO to write to
[ "Creates", "a", "new", "manifest", ".", "Note", "that", "the", "prefix", "field", "and", "entry", "arrays", "are", "copied", "on", "initialization", "as", "are", "the", "individual", "entry", "hashes", "." ]
395832ace3d2954d71e5dc053ea238dcfda42a48
https://github.com/CDLUC3/merritt-manifest/blob/395832ace3d2954d71e5dc053ea238dcfda42a48/lib/merritt/manifest.rb#L51-L58
train
CDLUC3/merritt-manifest
lib/merritt/manifest.rb
Merritt.Manifest.write_sc
def write_sc(io, comment, *columns) io << '#%' << comment io << COLSEP << columns.join(COLSEP) unless columns.empty? io << "\n" end
ruby
def write_sc(io, comment, *columns) io << '#%' << comment io << COLSEP << columns.join(COLSEP) unless columns.empty? io << "\n" end
[ "def", "write_sc", "(", "io", ",", "comment", ",", "*", "columns", ")", "io", "<<", "'#%'", "<<", "comment", "io", "<<", "COLSEP", "<<", "columns", ".", "join", "(", "COLSEP", ")", "unless", "columns", ".", "empty?", "io", "<<", "\"\\n\"", "end" ]
writes a checkm "structured comment" @param io [IO] the IO to write to @param comment [String] the comment @param columns [nil, Array<String>] columns to follow the initial comment
[ "writes", "a", "checkm", "structured", "comment" ]
395832ace3d2954d71e5dc053ea238dcfda42a48
https://github.com/CDLUC3/merritt-manifest/blob/395832ace3d2954d71e5dc053ea238dcfda42a48/lib/merritt/manifest.rb#L81-L85
train
bernerdschaefer/uninhibited
lib/uninhibited/feature.rb
Uninhibited.Feature.Scenario
def Scenario(*args, &example_group_block) args << {} unless args.last.is_a?(Hash) args.last.update(:scenario => true) describe("Scenario:", *args, &example_group_block) end
ruby
def Scenario(*args, &example_group_block) args << {} unless args.last.is_a?(Hash) args.last.update(:scenario => true) describe("Scenario:", *args, &example_group_block) end
[ "def", "Scenario", "(", "*", "args", ",", "&", "example_group_block", ")", "args", "<<", "{", "}", "unless", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "args", ".", "last", ".", "update", "(", ":scenario", "=>", "true", ")", "describe", "(", "\"Scenario:\"", ",", "*", "args", ",", "&", "example_group_block", ")", "end" ]
Defines a new Scenario group Feature "User signs in" do Scenario "success" do Given "I on the login page" When "I fill in my email and password" end end This will be printed like so: Feature: User signs in Scenario: success Given I am on the login page When I fill in my email and password @param args the description, metadata, etc. as RSpec's #describe method takes. @param example_group_block the block to be executed within the feature
[ "Defines", "a", "new", "Scenario", "group" ]
a45297e127f529ee10719f0306b1ae6721450a33
https://github.com/bernerdschaefer/uninhibited/blob/a45297e127f529ee10719f0306b1ae6721450a33/lib/uninhibited/feature.rb#L26-L30
train
bernerdschaefer/uninhibited
lib/uninhibited/feature.rb
Uninhibited.Feature.skip_examples_after
def skip_examples_after(example, example_group = self) examples = example_group.descendant_filtered_examples.flatten examples[examples.index(example)..-1].each do |e| e.metadata[:pending] = true e.metadata[:skipped] = true end end
ruby
def skip_examples_after(example, example_group = self) examples = example_group.descendant_filtered_examples.flatten examples[examples.index(example)..-1].each do |e| e.metadata[:pending] = true e.metadata[:skipped] = true end end
[ "def", "skip_examples_after", "(", "example", ",", "example_group", "=", "self", ")", "examples", "=", "example_group", ".", "descendant_filtered_examples", ".", "flatten", "examples", "[", "examples", ".", "index", "(", "example", ")", "..", "-", "1", "]", ".", "each", "do", "|", "e", "|", "e", ".", "metadata", "[", ":pending", "]", "=", "true", "e", ".", "metadata", "[", ":skipped", "]", "=", "true", "end", "end" ]
Skip examples after the example provided. @param [Example] example the example to skip after @param [ExampleGroup] example_group the example group of example @api private
[ "Skip", "examples", "after", "the", "example", "provided", "." ]
a45297e127f529ee10719f0306b1ae6721450a33
https://github.com/bernerdschaefer/uninhibited/blob/a45297e127f529ee10719f0306b1ae6721450a33/lib/uninhibited/feature.rb#L136-L142
train
bernerdschaefer/uninhibited
lib/uninhibited/feature.rb
Uninhibited.Feature.handle_exception
def handle_exception(example) if example.instance_variable_get(:@exception) if metadata[:background] skip_examples_after(example, ancestors[1]) else skip_examples_after(example) end end end
ruby
def handle_exception(example) if example.instance_variable_get(:@exception) if metadata[:background] skip_examples_after(example, ancestors[1]) else skip_examples_after(example) end end end
[ "def", "handle_exception", "(", "example", ")", "if", "example", ".", "instance_variable_get", "(", ":@exception", ")", "if", "metadata", "[", ":background", "]", "skip_examples_after", "(", "example", ",", "ancestors", "[", "1", "]", ")", "else", "skip_examples_after", "(", "example", ")", "end", "end", "end" ]
If the example failed or got an error, then skip the dependent examples. If the failure occurred in a background example group, then skip all examples in the feature. @param [Example] example the current example @api private
[ "If", "the", "example", "failed", "or", "got", "an", "error", "then", "skip", "the", "dependent", "examples", ".", "If", "the", "failure", "occurred", "in", "a", "background", "example", "group", "then", "skip", "all", "examples", "in", "the", "feature", "." ]
a45297e127f529ee10719f0306b1ae6721450a33
https://github.com/bernerdschaefer/uninhibited/blob/a45297e127f529ee10719f0306b1ae6721450a33/lib/uninhibited/feature.rb#L150-L158
train
santaux/colonel
lib/colonel/builder.rb
Colonel.Builder.update_job
def update_job(opts={}) index = get_job_index(opts[:id]) job = find_job(opts[:id]) @jobs[index] = job.update(opts) end
ruby
def update_job(opts={}) index = get_job_index(opts[:id]) job = find_job(opts[:id]) @jobs[index] = job.update(opts) end
[ "def", "update_job", "(", "opts", "=", "{", "}", ")", "index", "=", "get_job_index", "(", "opts", "[", ":id", "]", ")", "job", "=", "find_job", "(", "opts", "[", ":id", "]", ")", "@jobs", "[", "index", "]", "=", "job", ".", "update", "(", "opts", ")", "end" ]
Replace job with specified id @param (Integer) :id is index of the job into @jobs array TODO: Refactor it! To complicated!
[ "Replace", "job", "with", "specified", "id" ]
b457c77cf509b0b436d85048a60fc8c8e55a3828
https://github.com/santaux/colonel/blob/b457c77cf509b0b436d85048a60fc8c8e55a3828/lib/colonel/builder.rb#L48-L52
train
santaux/colonel
lib/colonel/builder.rb
Colonel.Builder.add_job
def add_job(opts={}) @jobs << Job.new( Parser::Schedule.new(opts[:schedule]), Parser::Command.new(opts[:command])) end
ruby
def add_job(opts={}) @jobs << Job.new( Parser::Schedule.new(opts[:schedule]), Parser::Command.new(opts[:command])) end
[ "def", "add_job", "(", "opts", "=", "{", "}", ")", "@jobs", "<<", "Job", ".", "new", "(", "Parser", "::", "Schedule", ".", "new", "(", "opts", "[", ":schedule", "]", ")", ",", "Parser", "::", "Command", ".", "new", "(", "opts", "[", ":command", "]", ")", ")", "end" ]
Adds a job to @jobs array @param (Parser::Schedule) :schedule is object of Parser::Schedule class @param (Parser::Command) :command is object of Parser::Command class
[ "Adds", "a", "job", "to" ]
b457c77cf509b0b436d85048a60fc8c8e55a3828
https://github.com/santaux/colonel/blob/b457c77cf509b0b436d85048a60fc8c8e55a3828/lib/colonel/builder.rb#L57-L59
train
NUBIC/aker
lib/aker/rack/setup.rb
Aker::Rack.Setup.call
def call(env) env['aker.configuration'] = @configuration env['aker.authority'] = @configuration.composite_authority env['aker.interactive'] = interactive?(env) @app.call(env) end
ruby
def call(env) env['aker.configuration'] = @configuration env['aker.authority'] = @configuration.composite_authority env['aker.interactive'] = interactive?(env) @app.call(env) end
[ "def", "call", "(", "env", ")", "env", "[", "'aker.configuration'", "]", "=", "@configuration", "env", "[", "'aker.authority'", "]", "=", "@configuration", ".", "composite_authority", "env", "[", "'aker.interactive'", "]", "=", "interactive?", "(", "env", ")", "@app", ".", "call", "(", "env", ")", "end" ]
Creates a new instance of the middleware. @param [#call] app the application this middleware is being wrapped around. @param [Aker::Configuration] configuration the configuration to use for this instance. @see Aker::Rack.use_in Implements the rack middleware behavior. This class exposes three environment variables to downstream middleware and the app: * `"aker.configuration"`: the {Aker::Configuration configuration} for this application. * `"aker.authority"`: the {Aker::Authorities authority} for this application. * `"aker.interactive"`: a boolean indicating whether this request is being treated as an interactive (UI) or non-interactive (API) request [There is a related fourth environment variable: * `"aker.check"`: an instance of {Aker::Rack::Facade} permitting authentication and authorization queries about the current user (if any). This fourth variable is added by the {Authenticate} middleware; see its documentation for more.] @param [Hash] env the rack env @return [Array] the standard rack return
[ "Creates", "a", "new", "instance", "of", "the", "middleware", "." ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/rack/setup.rb#L58-L64
train
ahmadhasankhan/canvas_interactor
lib/canvas_interactor/canvas_api.rb
CanvasInteractor.CanvasApi.hash_csv
def hash_csv(csv_string) require 'csv' csv = CSV.parse(csv_string) headers = csv.shift output = [] csv.each do |row| hash = {} headers.each do |header| hash[header] = row.shift.to_s end output << hash end return output end
ruby
def hash_csv(csv_string) require 'csv' csv = CSV.parse(csv_string) headers = csv.shift output = [] csv.each do |row| hash = {} headers.each do |header| hash[header] = row.shift.to_s end output << hash end return output end
[ "def", "hash_csv", "(", "csv_string", ")", "require", "'csv'", "csv", "=", "CSV", ".", "parse", "(", "csv_string", ")", "headers", "=", "csv", ".", "shift", "output", "=", "[", "]", "csv", ".", "each", "do", "|", "row", "|", "hash", "=", "{", "}", "headers", ".", "each", "do", "|", "header", "|", "hash", "[", "header", "]", "=", "row", ".", "shift", ".", "to_s", "end", "output", "<<", "hash", "end", "return", "output", "end" ]
Needs to be refactored to somewhere more generic
[ "Needs", "to", "be", "refactored", "to", "somewhere", "more", "generic" ]
458c058f1345643bfe8b1e1422d9155e49790193
https://github.com/ahmadhasankhan/canvas_interactor/blob/458c058f1345643bfe8b1e1422d9155e49790193/lib/canvas_interactor/canvas_api.rb#L96-L112
train
plexus/analects
lib/analects/source.rb
Analects.Source.retrieve_save
def retrieve_save(data) File.open(location, 'w') do |f| f << (data.respond_to?(:read) ? data.read : data) end end
ruby
def retrieve_save(data) File.open(location, 'w') do |f| f << (data.respond_to?(:read) ? data.read : data) end end
[ "def", "retrieve_save", "(", "data", ")", "File", ".", "open", "(", "location", ",", "'w'", ")", "do", "|", "f", "|", "f", "<<", "(", "data", ".", "respond_to?", "(", ":read", ")", "?", "data", ".", "read", ":", "data", ")", "end", "end" ]
stream|string -> create data file
[ "stream|string", "-", ">", "create", "data", "file" ]
3ef5c9b54b5d31fd1c3b7143f9e5e4ae40185dd9
https://github.com/plexus/analects/blob/3ef5c9b54b5d31fd1c3b7143f9e5e4ae40185dd9/lib/analects/source.rb#L80-L84
train
markus/breeze
lib/breeze/tasks/server.rb
Breeze.Server.wait_until_host_is_available
def wait_until_host_is_available(host, get_ip=false) resolved_host = Resolv.getaddresses(host).first if resolved_host.nil? print("Waiting for #{host} to resolve") wait_until('ready!') { resolved_host = Resolv.getaddresses(host).first } end host = resolved_host if get_ip unless remote_is_available?(host) print("Waiting for #{host} to accept connections") wait_until('ready!') { remote_is_available?(host) } end return host end
ruby
def wait_until_host_is_available(host, get_ip=false) resolved_host = Resolv.getaddresses(host).first if resolved_host.nil? print("Waiting for #{host} to resolve") wait_until('ready!') { resolved_host = Resolv.getaddresses(host).first } end host = resolved_host if get_ip unless remote_is_available?(host) print("Waiting for #{host} to accept connections") wait_until('ready!') { remote_is_available?(host) } end return host end
[ "def", "wait_until_host_is_available", "(", "host", ",", "get_ip", "=", "false", ")", "resolved_host", "=", "Resolv", ".", "getaddresses", "(", "host", ")", ".", "first", "if", "resolved_host", ".", "nil?", "print", "(", "\"Waiting for #{host} to resolve\"", ")", "wait_until", "(", "'ready!'", ")", "{", "resolved_host", "=", "Resolv", ".", "getaddresses", "(", "host", ")", ".", "first", "}", "end", "host", "=", "resolved_host", "if", "get_ip", "unless", "remote_is_available?", "(", "host", ")", "print", "(", "\"Waiting for #{host} to accept connections\"", ")", "wait_until", "(", "'ready!'", ")", "{", "remote_is_available?", "(", "host", ")", "}", "end", "return", "host", "end" ]
Can take a host name or an ip address. Resolves the host name and returns the ip address if get_ip is passed in as true.
[ "Can", "take", "a", "host", "name", "or", "an", "ip", "address", ".", "Resolves", "the", "host", "name", "and", "returns", "the", "ip", "address", "if", "get_ip", "is", "passed", "in", "as", "true", "." ]
a633783946ed4270354fa1491a9beda4f2bac1f6
https://github.com/markus/breeze/blob/a633783946ed4270354fa1491a9beda4f2bac1f6/lib/breeze/tasks/server.rb#L42-L54
train
colbell/bitsa
lib/bitsa/contacts_cache.rb
Bitsa.ContactsCache.search
def search(qry) rg = Regexp.new(qry || '', Regexp::IGNORECASE) # Flatten to an array with [email1, name1, email2, name2] etc. results = @addresses.values.flatten.each_slice(2).find_all do |e, n| e.match(rg) || n.match(rg) end # Sort by case-insensitive email address results.sort { |a, b| a[0].downcase <=> b[0].downcase } end
ruby
def search(qry) rg = Regexp.new(qry || '', Regexp::IGNORECASE) # Flatten to an array with [email1, name1, email2, name2] etc. results = @addresses.values.flatten.each_slice(2).find_all do |e, n| e.match(rg) || n.match(rg) end # Sort by case-insensitive email address results.sort { |a, b| a[0].downcase <=> b[0].downcase } end
[ "def", "search", "(", "qry", ")", "rg", "=", "Regexp", ".", "new", "(", "qry", "||", "''", ",", "Regexp", "::", "IGNORECASE", ")", "results", "=", "@addresses", ".", "values", ".", "flatten", ".", "each_slice", "(", "2", ")", ".", "find_all", "do", "|", "e", ",", "n", "|", "e", ".", "match", "(", "rg", ")", "||", "n", ".", "match", "(", "rg", ")", "end", "results", ".", "sort", "{", "|", "a", ",", "b", "|", "a", "[", "0", "]", ".", "downcase", "<=>", "b", "[", "0", "]", ".", "downcase", "}", "end" ]
Retrieves name and email addresses that contain the passed string sorted by email adddress @param qry [String] search string @return [[[String, String]]] Array of email addresses and names found. Each element consists of a 2 element array. The first is the email address and the second is the name @example cache.search("smi") #=> [["[email protected]", "Mr Smith"], ["[email protected]", "Mr Smith"]]
[ "Retrieves", "name", "and", "email", "addresses", "that", "contain", "the", "passed", "string", "sorted", "by", "email", "adddress" ]
8b73c4988bde1bf8e64d9cb999164c3e5988dba5
https://github.com/colbell/bitsa/blob/8b73c4988bde1bf8e64d9cb999164c3e5988dba5/lib/bitsa/contacts_cache.rb#L117-L127
train
colbell/bitsa
lib/bitsa/contacts_cache.rb
Bitsa.ContactsCache.update
def update(id, name, addresses) @cache_last_modified = DateTime.now.to_s @addresses[id] = addresses.map { |a| [a, name] } end
ruby
def update(id, name, addresses) @cache_last_modified = DateTime.now.to_s @addresses[id] = addresses.map { |a| [a, name] } end
[ "def", "update", "(", "id", ",", "name", ",", "addresses", ")", "@cache_last_modified", "=", "DateTime", ".", "now", ".", "to_s", "@addresses", "[", "id", "]", "=", "addresses", ".", "map", "{", "|", "a", "|", "[", "a", ",", "name", "]", "}", "end" ]
Update the name and email addresses for the passed GMail ID. @param [String] id ID of contact to be updated @param [String] name new name for contact @param [String[]] addresses array of email addresses @return [[String, String]] Array of email addresses for the <tt>id</tt> after update. Each element consists of a 2 element array. The first is the email address and the second is the name
[ "Update", "the", "name", "and", "email", "addresses", "for", "the", "passed", "GMail", "ID", "." ]
8b73c4988bde1bf8e64d9cb999164c3e5988dba5
https://github.com/colbell/bitsa/blob/8b73c4988bde1bf8e64d9cb999164c3e5988dba5/lib/bitsa/contacts_cache.rb#L140-L143
train
rails-info/rails_info
lib/rails_info/routing.rb
ActionDispatch::Routing.Mapper.mount_rails_info
def mount_rails_info match '/rails/info' => 'rails_info/properties#index', via: :get, via: :get, as: 'rails_info' match '/rails/info/properties' => 'rails_info/properties#index', via: :get, via: :get, as: 'rails_info_properties' match '/rails/info/routes' => 'rails_info/routes#index', via: :get, as: 'rails_info_routes' match '/rails/info/model' => 'rails_info/model#index', via: :get, as: 'rails_info_model' match '/rails/info/data' => 'rails_info/data#index', via: :get, as: 'rails_info_data', via: :get, as: 'rails_info_data' post '/rails/info/data/update_multiple' => 'rails_info/data#update_multiple', via: :post, as: 'rails_update_multiple_rails_info_data' match '/rails/info/logs/server' => 'rails_info/logs/server#new', via: :get, as: 'new_rails_info_server_log' put '/rails/info/logs/server' => 'rails_info/logs/server#update', via: :put, as: 'rails_info_server_log' get '/rails/info/logs/server/big' => 'rails_info/logs/server#big' match '/rails/info/logs/test/rspec' => 'rails_info/logs/test/rspec#new', via: :get, as: 'new_rails_info_rspec_log' put '/rails/info/logs/test/rspec' => 'rails_info/logs/test/rspec#update', via: :put, as: 'rails_info_rspec_log' match '/rails/info/stack_traces/new' => 'rails_info/stack_traces#new', via: :get, as: 'new_rails_info_stack_trace' post '/rails/info/stack_traces' => 'rails_info/stack_traces#create', via: :post, as: 'rails_info_stack_trace' namespace 'rails_info', path: 'rails/info' do namespace 'system' do resources :directories, only: :index end namespace 'version_control' do resources :filters, only: [:new, :create] resources :diffs, only: :new end end end
ruby
def mount_rails_info match '/rails/info' => 'rails_info/properties#index', via: :get, via: :get, as: 'rails_info' match '/rails/info/properties' => 'rails_info/properties#index', via: :get, via: :get, as: 'rails_info_properties' match '/rails/info/routes' => 'rails_info/routes#index', via: :get, as: 'rails_info_routes' match '/rails/info/model' => 'rails_info/model#index', via: :get, as: 'rails_info_model' match '/rails/info/data' => 'rails_info/data#index', via: :get, as: 'rails_info_data', via: :get, as: 'rails_info_data' post '/rails/info/data/update_multiple' => 'rails_info/data#update_multiple', via: :post, as: 'rails_update_multiple_rails_info_data' match '/rails/info/logs/server' => 'rails_info/logs/server#new', via: :get, as: 'new_rails_info_server_log' put '/rails/info/logs/server' => 'rails_info/logs/server#update', via: :put, as: 'rails_info_server_log' get '/rails/info/logs/server/big' => 'rails_info/logs/server#big' match '/rails/info/logs/test/rspec' => 'rails_info/logs/test/rspec#new', via: :get, as: 'new_rails_info_rspec_log' put '/rails/info/logs/test/rspec' => 'rails_info/logs/test/rspec#update', via: :put, as: 'rails_info_rspec_log' match '/rails/info/stack_traces/new' => 'rails_info/stack_traces#new', via: :get, as: 'new_rails_info_stack_trace' post '/rails/info/stack_traces' => 'rails_info/stack_traces#create', via: :post, as: 'rails_info_stack_trace' namespace 'rails_info', path: 'rails/info' do namespace 'system' do resources :directories, only: :index end namespace 'version_control' do resources :filters, only: [:new, :create] resources :diffs, only: :new end end end
[ "def", "mount_rails_info", "match", "'/rails/info'", "=>", "'rails_info/properties#index'", ",", "via", ":", ":get", ",", "via", ":", ":get", ",", "as", ":", "'rails_info'", "match", "'/rails/info/properties'", "=>", "'rails_info/properties#index'", ",", "via", ":", ":get", ",", "via", ":", ":get", ",", "as", ":", "'rails_info_properties'", "match", "'/rails/info/routes'", "=>", "'rails_info/routes#index'", ",", "via", ":", ":get", ",", "as", ":", "'rails_info_routes'", "match", "'/rails/info/model'", "=>", "'rails_info/model#index'", ",", "via", ":", ":get", ",", "as", ":", "'rails_info_model'", "match", "'/rails/info/data'", "=>", "'rails_info/data#index'", ",", "via", ":", ":get", ",", "as", ":", "'rails_info_data'", ",", "via", ":", ":get", ",", "as", ":", "'rails_info_data'", "post", "'/rails/info/data/update_multiple'", "=>", "'rails_info/data#update_multiple'", ",", "via", ":", ":post", ",", "as", ":", "'rails_update_multiple_rails_info_data'", "match", "'/rails/info/logs/server'", "=>", "'rails_info/logs/server#new'", ",", "via", ":", ":get", ",", "as", ":", "'new_rails_info_server_log'", "put", "'/rails/info/logs/server'", "=>", "'rails_info/logs/server#update'", ",", "via", ":", ":put", ",", "as", ":", "'rails_info_server_log'", "get", "'/rails/info/logs/server/big'", "=>", "'rails_info/logs/server#big'", "match", "'/rails/info/logs/test/rspec'", "=>", "'rails_info/logs/test/rspec#new'", ",", "via", ":", ":get", ",", "as", ":", "'new_rails_info_rspec_log'", "put", "'/rails/info/logs/test/rspec'", "=>", "'rails_info/logs/test/rspec#update'", ",", "via", ":", ":put", ",", "as", ":", "'rails_info_rspec_log'", "match", "'/rails/info/stack_traces/new'", "=>", "'rails_info/stack_traces#new'", ",", "via", ":", ":get", ",", "as", ":", "'new_rails_info_stack_trace'", "post", "'/rails/info/stack_traces'", "=>", "'rails_info/stack_traces#create'", ",", "via", ":", ":post", ",", "as", ":", "'rails_info_stack_trace'", "namespace", "'rails_info'", ",", "path", ":", "'rails/info'", "do", "namespace", "'system'", "do", "resources", ":directories", ",", "only", ":", ":index", "end", "namespace", "'version_control'", "do", "resources", ":filters", ",", "only", ":", "[", ":new", ",", ":create", "]", "resources", ":diffs", ",", "only", ":", ":new", "end", "end", "end" ]
Includes mount_sextant method for routes. This method is responsible to generate all needed routes for sextant
[ "Includes", "mount_sextant", "method", "for", "routes", ".", "This", "method", "is", "responsible", "to", "generate", "all", "needed", "routes", "for", "sextant" ]
a940d618043e0707c2c16d2cfe0c10609d54536b
https://github.com/rails-info/rails_info/blob/a940d618043e0707c2c16d2cfe0c10609d54536b/lib/rails_info/routing.rb#L5-L38
train
fauxparse/matchy_matchy
lib/matchy_matchy/matchbook.rb
MatchyMatchy.Matchbook.build_candidates
def build_candidates(candidates) candidates.to_a.map do |object, preferences| candidate(object).tap do |c| c.prefer(*preferences.map { |t| target(t) }) end end end
ruby
def build_candidates(candidates) candidates.to_a.map do |object, preferences| candidate(object).tap do |c| c.prefer(*preferences.map { |t| target(t) }) end end end
[ "def", "build_candidates", "(", "candidates", ")", "candidates", ".", "to_a", ".", "map", "do", "|", "object", ",", "preferences", "|", "candidate", "(", "object", ")", ".", "tap", "do", "|", "c", "|", "c", ".", "prefer", "(", "*", "preferences", ".", "map", "{", "|", "t", "|", "target", "(", "t", ")", "}", ")", "end", "end", "end" ]
Builds a list of candidates for the +MatchMaker+. The parameter is a hash of unwrapped canditate objects to their preferred targets. @example matchbook.build_candidates( 'Harry' => ['Gryffindor', 'Slytherin'], 'Hermione' => ['Ravenclaw', 'Gryffindor'], 'Ron' => ['Gryffindor'], 'Neville' => ['Hufflepuff', 'Gryffindor', 'Ravenclaw', 'Slytherin'] ) @param candidates [Hash<Object, Array<Object>>] Hash of candidate objects to a list of their preferred targets
[ "Builds", "a", "list", "of", "candidates", "for", "the", "+", "MatchMaker", "+", ".", "The", "parameter", "is", "a", "hash", "of", "unwrapped", "canditate", "objects", "to", "their", "preferred", "targets", "." ]
4e11ea438e08c0cc4d04836ffe0c61f196a70b94
https://github.com/fauxparse/matchy_matchy/blob/4e11ea438e08c0cc4d04836ffe0c61f196a70b94/lib/matchy_matchy/matchbook.rb#L65-L71
train
dyoung522/nosequel
lib/nosequel/configuration.rb
NoSequel.Configuration.sequel_url
def sequel_url return '' unless db_type # Start our connection string connect_string = db_type + '://' # Add user:password if supplied unless db_user.nil? connect_string += db_user # Add either a @ or / depending on if a host was provided too connect_string += db_host ? '@' : '/' # Add host:port if supplied connect_string += db_host + '/' if db_host end connect_string + db_name end
ruby
def sequel_url return '' unless db_type # Start our connection string connect_string = db_type + '://' # Add user:password if supplied unless db_user.nil? connect_string += db_user # Add either a @ or / depending on if a host was provided too connect_string += db_host ? '@' : '/' # Add host:port if supplied connect_string += db_host + '/' if db_host end connect_string + db_name end
[ "def", "sequel_url", "return", "''", "unless", "db_type", "connect_string", "=", "db_type", "+", "'://'", "unless", "db_user", ".", "nil?", "connect_string", "+=", "db_user", "connect_string", "+=", "db_host", "?", "'@'", ":", "'/'", "connect_string", "+=", "db_host", "+", "'/'", "if", "db_host", "end", "connect_string", "+", "db_name", "end" ]
Converts the object into a textual string that can be sent to sequel @return A string representing the object in a sequel-connect string format
[ "Converts", "the", "object", "into", "a", "textual", "string", "that", "can", "be", "sent", "to", "sequel" ]
b8788846a36ce03d426bfe3e575a81a6fb3c5c76
https://github.com/dyoung522/nosequel/blob/b8788846a36ce03d426bfe3e575a81a6fb3c5c76/lib/nosequel/configuration.rb#L30-L49
train
finn-francis/ruby-edit
lib/ruby_edit/find.rb
RubyEdit.Find.execute
def execute(output: $stdout, errors: $stderr) if empty_name? output.puts 'No name given' return false end result = run "find #{@path} #{type} -name '#{@name}'" do |_out, err| errors << err if err end # The following line makes the output into something readable # # Before the output would have looked like this: ## ./lib/my_file.rb ## ./lib/folder/my_file.rb # # Whereas it will now look like this: ## ./lib/my_file.rbi NEW_NAME=> ./lib/my_file.rb ## ./lib/folder/my_file.rb NEW_NAME=> ./lib/folder/my_file.rb # # Making it more obvious that the original path is on the left # and the path to edit is on the right @result = result.out.split("\n").map { |path| "#{path} NEW_NAME=> #{path}" }.join("\n") rescue TTY::Command::ExitError => error output.puts error end
ruby
def execute(output: $stdout, errors: $stderr) if empty_name? output.puts 'No name given' return false end result = run "find #{@path} #{type} -name '#{@name}'" do |_out, err| errors << err if err end # The following line makes the output into something readable # # Before the output would have looked like this: ## ./lib/my_file.rb ## ./lib/folder/my_file.rb # # Whereas it will now look like this: ## ./lib/my_file.rbi NEW_NAME=> ./lib/my_file.rb ## ./lib/folder/my_file.rb NEW_NAME=> ./lib/folder/my_file.rb # # Making it more obvious that the original path is on the left # and the path to edit is on the right @result = result.out.split("\n").map { |path| "#{path} NEW_NAME=> #{path}" }.join("\n") rescue TTY::Command::ExitError => error output.puts error end
[ "def", "execute", "(", "output", ":", "$stdout", ",", "errors", ":", "$stderr", ")", "if", "empty_name?", "output", ".", "puts", "'No name given'", "return", "false", "end", "result", "=", "run", "\"find #{@path} #{type} -name '#{@name}'\"", "do", "|", "_out", ",", "err", "|", "errors", "<<", "err", "if", "err", "end", "@result", "=", "result", ".", "out", ".", "split", "(", "\"\\n\"", ")", ".", "map", "{", "|", "path", "|", "\"#{path} NEW_NAME=> #{path}\"", "}", ".", "join", "(", "\"\\n\"", ")", "rescue", "TTY", "::", "Command", "::", "ExitError", "=>", "error", "output", ".", "puts", "error", "end" ]
Performs the find unless no name provided @param output [IO] @param errors [IO]
[ "Performs", "the", "find", "unless", "no", "name", "provided" ]
90022f4de01b420f5321f12c490566d0a1e19a29
https://github.com/finn-francis/ruby-edit/blob/90022f4de01b420f5321f12c490566d0a1e19a29/lib/ruby_edit/find.rb#L22-L45
train
mcspring/denglu
lib/denglu/comment.rb
Denglu.Comment.list
def list(comment_id=0, max=50) req_method = :GET req_uri = '/api/v4/get_comment_list' req_options = { :commentid => comment_id, :count => max } response = request_api(req_method, req_uri, req_options) normalize_comments JSON.parse(response) end
ruby
def list(comment_id=0, max=50) req_method = :GET req_uri = '/api/v4/get_comment_list' req_options = { :commentid => comment_id, :count => max } response = request_api(req_method, req_uri, req_options) normalize_comments JSON.parse(response) end
[ "def", "list", "(", "comment_id", "=", "0", ",", "max", "=", "50", ")", "req_method", "=", ":GET", "req_uri", "=", "'/api/v4/get_comment_list'", "req_options", "=", "{", ":commentid", "=>", "comment_id", ",", ":count", "=>", "max", "}", "response", "=", "request_api", "(", "req_method", ",", "req_uri", ",", "req_options", ")", "normalize_comments", "JSON", ".", "parse", "(", "response", ")", "end" ]
Get comment list This will contains comments' relations in response. Example: >> comment = Denglu::Comment.new => #<#Denglu::Comment...> >> comments = comment.list => [{...}, {...}] Arguments: comment_id: (Integer) The offset marker of response, default to 0 mains from the begining max: (Integer) The max records of response, default to 50
[ "Get", "comment", "list", "This", "will", "contains", "comments", "relations", "in", "response", "." ]
0b8fa7083eb877a20f3eda4119df23b96ada291d
https://github.com/mcspring/denglu/blob/0b8fa7083eb877a20f3eda4119df23b96ada291d/lib/denglu/comment.rb#L20-L31
train
mcspring/denglu
lib/denglu/comment.rb
Denglu.Comment.total
def total(resource=nil) req_method = :GET req_uri = '/api/v4/get_comment_count' req_options = {} case when resource.is_a?(Integer) req_options[:postid] = resource when resource.is_a?(String) req_options[:url] = resource end response = request_api(req_method, req_uri, req_options) response = JSON.parse(response) unless resource.nil? response = response[0] end response end
ruby
def total(resource=nil) req_method = :GET req_uri = '/api/v4/get_comment_count' req_options = {} case when resource.is_a?(Integer) req_options[:postid] = resource when resource.is_a?(String) req_options[:url] = resource end response = request_api(req_method, req_uri, req_options) response = JSON.parse(response) unless resource.nil? response = response[0] end response end
[ "def", "total", "(", "resource", "=", "nil", ")", "req_method", "=", ":GET", "req_uri", "=", "'/api/v4/get_comment_count'", "req_options", "=", "{", "}", "case", "when", "resource", ".", "is_a?", "(", "Integer", ")", "req_options", "[", ":postid", "]", "=", "resource", "when", "resource", ".", "is_a?", "(", "String", ")", "req_options", "[", ":url", "]", "=", "resource", "end", "response", "=", "request_api", "(", "req_method", ",", "req_uri", ",", "req_options", ")", "response", "=", "JSON", ".", "parse", "(", "response", ")", "unless", "resource", ".", "nil?", "response", "=", "response", "[", "0", "]", "end", "response", "end" ]
Get comment count If resource is nil it will return all posts comment count in an array, otherwise just return a hash object. Example: >> comment = Denglu::Comment.new => #<#Denglu::Comment...> >> comments = comment.total => [{"id"=>..., "count"=>..., "url"=>...}, => {...}] Arguments: resource: (Mixed) Integer for resource id or string for uri.
[ "Get", "comment", "count", "If", "resource", "is", "nil", "it", "will", "return", "all", "posts", "comment", "count", "in", "an", "array", "otherwise", "just", "return", "a", "hash", "object", "." ]
0b8fa7083eb877a20f3eda4119df23b96ada291d
https://github.com/mcspring/denglu/blob/0b8fa7083eb877a20f3eda4119df23b96ada291d/lib/denglu/comment.rb#L70-L89
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/posts_controller.rb
LatoBlog.Back::PostsController.index
def index core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:posts]) # find correct status to show @posts_status = 'published' @posts_status = 'drafted' if params[:status] && params[:status] === 'drafted' @posts_status = 'deleted' if params[:status] && params[:status] === 'deleted' # find informations data @posts_informations = { published_length: LatoBlog::Post.published.where(meta_language: cookies[:lato_blog__current_language]).length, drafted_length: LatoBlog::Post.drafted.where(meta_language: cookies[:lato_blog__current_language]).length, deleted_length: LatoBlog::Post.deleted.where(meta_language: cookies[:lato_blog__current_language]).length } # find posts to show @posts = LatoBlog::Post.where(meta_status: @posts_status, meta_language: cookies[:lato_blog__current_language]).joins(:post_parent).order('lato_blog_post_parents.publication_datetime DESC') @widget_index_posts = core__widgets_index(@posts, search: 'title', pagination: 10) end
ruby
def index core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:posts]) # find correct status to show @posts_status = 'published' @posts_status = 'drafted' if params[:status] && params[:status] === 'drafted' @posts_status = 'deleted' if params[:status] && params[:status] === 'deleted' # find informations data @posts_informations = { published_length: LatoBlog::Post.published.where(meta_language: cookies[:lato_blog__current_language]).length, drafted_length: LatoBlog::Post.drafted.where(meta_language: cookies[:lato_blog__current_language]).length, deleted_length: LatoBlog::Post.deleted.where(meta_language: cookies[:lato_blog__current_language]).length } # find posts to show @posts = LatoBlog::Post.where(meta_status: @posts_status, meta_language: cookies[:lato_blog__current_language]).joins(:post_parent).order('lato_blog_post_parents.publication_datetime DESC') @widget_index_posts = core__widgets_index(@posts, search: 'title', pagination: 10) end
[ "def", "index", "core__set_header_active_page_title", "(", "LANGUAGES", "[", ":lato_blog", "]", "[", ":pages", "]", "[", ":posts", "]", ")", "@posts_status", "=", "'published'", "@posts_status", "=", "'drafted'", "if", "params", "[", ":status", "]", "&&", "params", "[", ":status", "]", "===", "'drafted'", "@posts_status", "=", "'deleted'", "if", "params", "[", ":status", "]", "&&", "params", "[", ":status", "]", "===", "'deleted'", "@posts_informations", "=", "{", "published_length", ":", "LatoBlog", "::", "Post", ".", "published", ".", "where", "(", "meta_language", ":", "cookies", "[", ":lato_blog__current_language", "]", ")", ".", "length", ",", "drafted_length", ":", "LatoBlog", "::", "Post", ".", "drafted", ".", "where", "(", "meta_language", ":", "cookies", "[", ":lato_blog__current_language", "]", ")", ".", "length", ",", "deleted_length", ":", "LatoBlog", "::", "Post", ".", "deleted", ".", "where", "(", "meta_language", ":", "cookies", "[", ":lato_blog__current_language", "]", ")", ".", "length", "}", "@posts", "=", "LatoBlog", "::", "Post", ".", "where", "(", "meta_status", ":", "@posts_status", ",", "meta_language", ":", "cookies", "[", ":lato_blog__current_language", "]", ")", ".", "joins", "(", ":post_parent", ")", ".", "order", "(", "'lato_blog_post_parents.publication_datetime DESC'", ")", "@widget_index_posts", "=", "core__widgets_index", "(", "@posts", ",", "search", ":", "'title'", ",", "pagination", ":", "10", ")", "end" ]
This function shows the list of published posts.
[ "This", "function", "shows", "the", "list", "of", "published", "posts", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/posts_controller.rb#L9-L26
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/posts_controller.rb
LatoBlog.Back::PostsController.new
def new core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:posts_new]) @post = LatoBlog::Post.new set_current_language params[:language] if params[:language] if params[:parent] @post_parent = LatoBlog::PostParent.find_by(id: params[:parent]) end fetch_external_objects end
ruby
def new core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:posts_new]) @post = LatoBlog::Post.new set_current_language params[:language] if params[:language] if params[:parent] @post_parent = LatoBlog::PostParent.find_by(id: params[:parent]) end fetch_external_objects end
[ "def", "new", "core__set_header_active_page_title", "(", "LANGUAGES", "[", ":lato_blog", "]", "[", ":pages", "]", "[", ":posts_new", "]", ")", "@post", "=", "LatoBlog", "::", "Post", ".", "new", "set_current_language", "params", "[", ":language", "]", "if", "params", "[", ":language", "]", "if", "params", "[", ":parent", "]", "@post_parent", "=", "LatoBlog", "::", "PostParent", ".", "find_by", "(", "id", ":", "params", "[", ":parent", "]", ")", "end", "fetch_external_objects", "end" ]
This function shows the view to create a new post.
[ "This", "function", "shows", "the", "view", "to", "create", "a", "new", "post", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/posts_controller.rb#L35-L46
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/posts_controller.rb
LatoBlog.Back::PostsController.create
def create @post = LatoBlog::Post.new(new_post_params) unless @post.save flash[:danger] = @post.errors.full_messages.to_sentence redirect_to lato_blog.new_post_path return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:post_create_success] redirect_to lato_blog.post_path(@post.id) end
ruby
def create @post = LatoBlog::Post.new(new_post_params) unless @post.save flash[:danger] = @post.errors.full_messages.to_sentence redirect_to lato_blog.new_post_path return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:post_create_success] redirect_to lato_blog.post_path(@post.id) end
[ "def", "create", "@post", "=", "LatoBlog", "::", "Post", ".", "new", "(", "new_post_params", ")", "unless", "@post", ".", "save", "flash", "[", ":danger", "]", "=", "@post", ".", "errors", ".", "full_messages", ".", "to_sentence", "redirect_to", "lato_blog", ".", "new_post_path", "return", "end", "flash", "[", ":success", "]", "=", "LANGUAGES", "[", ":lato_blog", "]", "[", ":flashes", "]", "[", ":post_create_success", "]", "redirect_to", "lato_blog", ".", "post_path", "(", "@post", ".", "id", ")", "end" ]
This function creates a new post.
[ "This", "function", "creates", "a", "new", "post", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/posts_controller.rb#L49-L60
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/posts_controller.rb
LatoBlog.Back::PostsController.edit
def edit core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:posts_edit]) @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence if @post.meta_language != cookies[:lato_blog__current_language] set_current_language @post.meta_language end fetch_external_objects end
ruby
def edit core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:posts_edit]) @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence if @post.meta_language != cookies[:lato_blog__current_language] set_current_language @post.meta_language end fetch_external_objects end
[ "def", "edit", "core__set_header_active_page_title", "(", "LANGUAGES", "[", ":lato_blog", "]", "[", ":pages", "]", "[", ":posts_edit", "]", ")", "@post", "=", "LatoBlog", "::", "Post", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_post_presence", "if", "@post", ".", "meta_language", "!=", "cookies", "[", ":lato_blog__current_language", "]", "set_current_language", "@post", ".", "meta_language", "end", "fetch_external_objects", "end" ]
This function show the view to edit a post.
[ "This", "function", "show", "the", "view", "to", "edit", "a", "post", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/posts_controller.rb#L63-L73
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/posts_controller.rb
LatoBlog.Back::PostsController.update
def update @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence # update for autosaving autosaving = params[:autosave] && params[:autosave] == 'true' if autosaving @post.update(edit_post_params) update_fields render status: 200, json: {} # render something positive :) return end # check post data update unless @post.update(edit_post_params) flash[:danger] = @post.errors.full_messages.to_sentence redirect_to lato_blog.edit_post_path(@post.id) return end # update single fields unless update_fields flash[:warning] = LANGUAGES[:lato_blog][:flashes][:post_update_fields_warning] redirect_to lato_blog.edit_post_path(@post.id) return end # render positive response flash[:success] = LANGUAGES[:lato_blog][:flashes][:post_update_success] redirect_to lato_blog.post_path(@post.id) end
ruby
def update @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence # update for autosaving autosaving = params[:autosave] && params[:autosave] == 'true' if autosaving @post.update(edit_post_params) update_fields render status: 200, json: {} # render something positive :) return end # check post data update unless @post.update(edit_post_params) flash[:danger] = @post.errors.full_messages.to_sentence redirect_to lato_blog.edit_post_path(@post.id) return end # update single fields unless update_fields flash[:warning] = LANGUAGES[:lato_blog][:flashes][:post_update_fields_warning] redirect_to lato_blog.edit_post_path(@post.id) return end # render positive response flash[:success] = LANGUAGES[:lato_blog][:flashes][:post_update_success] redirect_to lato_blog.post_path(@post.id) end
[ "def", "update", "@post", "=", "LatoBlog", "::", "Post", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_post_presence", "autosaving", "=", "params", "[", ":autosave", "]", "&&", "params", "[", ":autosave", "]", "==", "'true'", "if", "autosaving", "@post", ".", "update", "(", "edit_post_params", ")", "update_fields", "render", "status", ":", "200", ",", "json", ":", "{", "}", "return", "end", "unless", "@post", ".", "update", "(", "edit_post_params", ")", "flash", "[", ":danger", "]", "=", "@post", ".", "errors", ".", "full_messages", ".", "to_sentence", "redirect_to", "lato_blog", ".", "edit_post_path", "(", "@post", ".", "id", ")", "return", "end", "unless", "update_fields", "flash", "[", ":warning", "]", "=", "LANGUAGES", "[", ":lato_blog", "]", "[", ":flashes", "]", "[", ":post_update_fields_warning", "]", "redirect_to", "lato_blog", ".", "edit_post_path", "(", "@post", ".", "id", ")", "return", "end", "flash", "[", ":success", "]", "=", "LANGUAGES", "[", ":lato_blog", "]", "[", ":flashes", "]", "[", ":post_update_success", "]", "redirect_to", "lato_blog", ".", "post_path", "(", "@post", ".", "id", ")", "end" ]
This function updates a post.
[ "This", "function", "updates", "a", "post", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/posts_controller.rb#L76-L106
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/posts_controller.rb
LatoBlog.Back::PostsController.update_status
def update_status @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence @post.update(meta_status: params[:status]) end
ruby
def update_status @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence @post.update(meta_status: params[:status]) end
[ "def", "update_status", "@post", "=", "LatoBlog", "::", "Post", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_post_presence", "@post", ".", "update", "(", "meta_status", ":", "params", "[", ":status", "]", ")", "end" ]
This function updates the status of a post.
[ "This", "function", "updates", "the", "status", "of", "a", "post", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/posts_controller.rb#L109-L114
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/posts_controller.rb
LatoBlog.Back::PostsController.update_categories
def update_categories @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence params[:categories].each do |category_id, value| category = LatoBlog::Category.find_by(id: category_id) next if !category || category.meta_language != @post.meta_language category_post = LatoBlog::CategoryPost.find_by(lato_blog_post_id: @post.id, lato_blog_category_id: category.id) if value == 'true' LatoBlog::CategoryPost.create(lato_blog_post_id: @post.id, lato_blog_category_id: category.id) unless category_post else category_post.destroy if category_post end end end
ruby
def update_categories @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence params[:categories].each do |category_id, value| category = LatoBlog::Category.find_by(id: category_id) next if !category || category.meta_language != @post.meta_language category_post = LatoBlog::CategoryPost.find_by(lato_blog_post_id: @post.id, lato_blog_category_id: category.id) if value == 'true' LatoBlog::CategoryPost.create(lato_blog_post_id: @post.id, lato_blog_category_id: category.id) unless category_post else category_post.destroy if category_post end end end
[ "def", "update_categories", "@post", "=", "LatoBlog", "::", "Post", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_post_presence", "params", "[", ":categories", "]", ".", "each", "do", "|", "category_id", ",", "value", "|", "category", "=", "LatoBlog", "::", "Category", ".", "find_by", "(", "id", ":", "category_id", ")", "next", "if", "!", "category", "||", "category", ".", "meta_language", "!=", "@post", ".", "meta_language", "category_post", "=", "LatoBlog", "::", "CategoryPost", ".", "find_by", "(", "lato_blog_post_id", ":", "@post", ".", "id", ",", "lato_blog_category_id", ":", "category", ".", "id", ")", "if", "value", "==", "'true'", "LatoBlog", "::", "CategoryPost", ".", "create", "(", "lato_blog_post_id", ":", "@post", ".", "id", ",", "lato_blog_category_id", ":", "category", ".", "id", ")", "unless", "category_post", "else", "category_post", ".", "destroy", "if", "category_post", "end", "end", "end" ]
This function updates the categories of a post.
[ "This", "function", "updates", "the", "categories", "of", "a", "post", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/posts_controller.rb#L125-L140
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/posts_controller.rb
LatoBlog.Back::PostsController.update_tags
def update_tags @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence params_tags = params[:tags].map(&:to_i) tag_posts = LatoBlog::TagPost.where(lato_blog_post_id: @post.id) params_tags.each do |tag_id| tag = LatoBlog::Tag.find_by(id: tag_id) next if !tag || tag.meta_language != @post.meta_language tag_post = tag_posts.find_by(lato_blog_tag_id: tag.id) LatoBlog::TagPost.create(lato_blog_post_id: @post.id, lato_blog_tag_id: tag.id) unless tag_post end tag_ids = tag_posts.pluck(:lato_blog_tag_id) tag_ids.each do |tag_id| next if params_tags.include?(tag_id) tag_post = tag_posts.find_by(lato_blog_tag_id: tag_id) tag_post.destroy if tag_post end end
ruby
def update_tags @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence params_tags = params[:tags].map(&:to_i) tag_posts = LatoBlog::TagPost.where(lato_blog_post_id: @post.id) params_tags.each do |tag_id| tag = LatoBlog::Tag.find_by(id: tag_id) next if !tag || tag.meta_language != @post.meta_language tag_post = tag_posts.find_by(lato_blog_tag_id: tag.id) LatoBlog::TagPost.create(lato_blog_post_id: @post.id, lato_blog_tag_id: tag.id) unless tag_post end tag_ids = tag_posts.pluck(:lato_blog_tag_id) tag_ids.each do |tag_id| next if params_tags.include?(tag_id) tag_post = tag_posts.find_by(lato_blog_tag_id: tag_id) tag_post.destroy if tag_post end end
[ "def", "update_tags", "@post", "=", "LatoBlog", "::", "Post", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_post_presence", "params_tags", "=", "params", "[", ":tags", "]", ".", "map", "(", "&", ":to_i", ")", "tag_posts", "=", "LatoBlog", "::", "TagPost", ".", "where", "(", "lato_blog_post_id", ":", "@post", ".", "id", ")", "params_tags", ".", "each", "do", "|", "tag_id", "|", "tag", "=", "LatoBlog", "::", "Tag", ".", "find_by", "(", "id", ":", "tag_id", ")", "next", "if", "!", "tag", "||", "tag", ".", "meta_language", "!=", "@post", ".", "meta_language", "tag_post", "=", "tag_posts", ".", "find_by", "(", "lato_blog_tag_id", ":", "tag", ".", "id", ")", "LatoBlog", "::", "TagPost", ".", "create", "(", "lato_blog_post_id", ":", "@post", ".", "id", ",", "lato_blog_tag_id", ":", "tag", ".", "id", ")", "unless", "tag_post", "end", "tag_ids", "=", "tag_posts", ".", "pluck", "(", ":lato_blog_tag_id", ")", "tag_ids", ".", "each", "do", "|", "tag_id", "|", "next", "if", "params_tags", ".", "include?", "(", "tag_id", ")", "tag_post", "=", "tag_posts", ".", "find_by", "(", "lato_blog_tag_id", ":", "tag_id", ")", "tag_post", ".", "destroy", "if", "tag_post", "end", "end" ]
This function updates the tags of a post.
[ "This", "function", "updates", "the", "tags", "of", "a", "post", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/posts_controller.rb#L143-L164
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/posts_controller.rb
LatoBlog.Back::PostsController.update_seo_description
def update_seo_description @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence @post.update(seo_description: params[:seo_description]) end
ruby
def update_seo_description @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence @post.update(seo_description: params[:seo_description]) end
[ "def", "update_seo_description", "@post", "=", "LatoBlog", "::", "Post", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_post_presence", "@post", ".", "update", "(", "seo_description", ":", "params", "[", ":seo_description", "]", ")", "end" ]
This function updates the seo description of a post.
[ "This", "function", "updates", "the", "seo", "description", "of", "a", "post", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/posts_controller.rb#L167-L172
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/posts_controller.rb
LatoBlog.Back::PostsController.destroy
def destroy @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence unless @post.destroy flash[:danger] = @post.post_parent.errors.full_messages.to_sentence redirect_to lato_blog.edit_post_path(@post.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:post_destroy_success] redirect_to lato_blog.posts_path(status: 'deleted') end
ruby
def destroy @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence unless @post.destroy flash[:danger] = @post.post_parent.errors.full_messages.to_sentence redirect_to lato_blog.edit_post_path(@post.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:post_destroy_success] redirect_to lato_blog.posts_path(status: 'deleted') end
[ "def", "destroy", "@post", "=", "LatoBlog", "::", "Post", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_post_presence", "unless", "@post", ".", "destroy", "flash", "[", ":danger", "]", "=", "@post", ".", "post_parent", ".", "errors", ".", "full_messages", ".", "to_sentence", "redirect_to", "lato_blog", ".", "edit_post_path", "(", "@post", ".", "id", ")", "return", "end", "flash", "[", ":success", "]", "=", "LANGUAGES", "[", ":lato_blog", "]", "[", ":flashes", "]", "[", ":post_destroy_success", "]", "redirect_to", "lato_blog", ".", "posts_path", "(", "status", ":", "'deleted'", ")", "end" ]
This function destroyes a post.
[ "This", "function", "destroyes", "a", "post", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/posts_controller.rb#L175-L187
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/posts_controller.rb
LatoBlog.Back::PostsController.destroy_all_deleted
def destroy_all_deleted @posts = LatoBlog::Post.deleted if !@posts || @posts.empty? flash[:warning] = LANGUAGES[:lato_blog][:flashes][:deleted_posts_not_found] redirect_to lato_blog.posts_path(status: 'deleted') return end @posts.each do |post| unless post.destroy flash[:danger] = post.errors.full_messages.to_sentence redirect_to lato_blog.edit_post_path(post.id) return end end flash[:success] = LANGUAGES[:lato_blog][:flashes][:deleted_posts_destroy_success] redirect_to lato_blog.posts_path(status: 'deleted') end
ruby
def destroy_all_deleted @posts = LatoBlog::Post.deleted if !@posts || @posts.empty? flash[:warning] = LANGUAGES[:lato_blog][:flashes][:deleted_posts_not_found] redirect_to lato_blog.posts_path(status: 'deleted') return end @posts.each do |post| unless post.destroy flash[:danger] = post.errors.full_messages.to_sentence redirect_to lato_blog.edit_post_path(post.id) return end end flash[:success] = LANGUAGES[:lato_blog][:flashes][:deleted_posts_destroy_success] redirect_to lato_blog.posts_path(status: 'deleted') end
[ "def", "destroy_all_deleted", "@posts", "=", "LatoBlog", "::", "Post", ".", "deleted", "if", "!", "@posts", "||", "@posts", ".", "empty?", "flash", "[", ":warning", "]", "=", "LANGUAGES", "[", ":lato_blog", "]", "[", ":flashes", "]", "[", ":deleted_posts_not_found", "]", "redirect_to", "lato_blog", ".", "posts_path", "(", "status", ":", "'deleted'", ")", "return", "end", "@posts", ".", "each", "do", "|", "post", "|", "unless", "post", ".", "destroy", "flash", "[", ":danger", "]", "=", "post", ".", "errors", ".", "full_messages", ".", "to_sentence", "redirect_to", "lato_blog", ".", "edit_post_path", "(", "post", ".", "id", ")", "return", "end", "end", "flash", "[", ":success", "]", "=", "LANGUAGES", "[", ":lato_blog", "]", "[", ":flashes", "]", "[", ":deleted_posts_destroy_success", "]", "redirect_to", "lato_blog", ".", "posts_path", "(", "status", ":", "'deleted'", ")", "end" ]
Tis function destroyes all posts with status deleted.
[ "Tis", "function", "destroyes", "all", "posts", "with", "status", "deleted", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/posts_controller.rb#L190-L209
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/posts_controller.rb
LatoBlog.Back::PostsController.update_field
def update_field(field, value) case field.typology when 'text' update_field_text(field, value) when 'textarea' update_field_textarea(field, value) when 'datetime' update_field_datetime(field, value) when 'editor' update_field_editor(field, value) when 'geolocalization' update_field_geolocalization(field, value) when 'image' update_field_image(field, value) when 'gallery' update_field_gallery(field, value) when 'youtube' update_field_youtube(field, value) when 'composed' update_field_composed(field, value) when 'relay' update_field_relay(field, value) end end
ruby
def update_field(field, value) case field.typology when 'text' update_field_text(field, value) when 'textarea' update_field_textarea(field, value) when 'datetime' update_field_datetime(field, value) when 'editor' update_field_editor(field, value) when 'geolocalization' update_field_geolocalization(field, value) when 'image' update_field_image(field, value) when 'gallery' update_field_gallery(field, value) when 'youtube' update_field_youtube(field, value) when 'composed' update_field_composed(field, value) when 'relay' update_field_relay(field, value) end end
[ "def", "update_field", "(", "field", ",", "value", ")", "case", "field", ".", "typology", "when", "'text'", "update_field_text", "(", "field", ",", "value", ")", "when", "'textarea'", "update_field_textarea", "(", "field", ",", "value", ")", "when", "'datetime'", "update_field_datetime", "(", "field", ",", "value", ")", "when", "'editor'", "update_field_editor", "(", "field", ",", "value", ")", "when", "'geolocalization'", "update_field_geolocalization", "(", "field", ",", "value", ")", "when", "'image'", "update_field_image", "(", "field", ",", "value", ")", "when", "'gallery'", "update_field_gallery", "(", "field", ",", "value", ")", "when", "'youtube'", "update_field_youtube", "(", "field", ",", "value", ")", "when", "'composed'", "update_field_composed", "(", "field", ",", "value", ")", "when", "'relay'", "update_field_relay", "(", "field", ",", "value", ")", "end", "end" ]
This function updates a single field from its key and value.
[ "This", "function", "updates", "a", "single", "field", "from", "its", "key", "and", "value", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/posts_controller.rb#L249-L272
train
kellysutton/bliptv
lib/bliptv/video.rb
BlipTV.Video.get_attributes
def get_attributes url = URI.parse('http://www.blip.tv/') res = Net::HTTP.start(url.host, url.port) {|http| http.get("http://www.blip.tv/file/#{@id.to_s}?skin=api") } hash = Hash.from_xml(res.body) if hash["response"]["status"] != "OK" raise VideoResponseError.new(hash["response"]["notice"]) end if hash["response"]["payload"]["asset"].is_a?(Array) return hash["response"]["payload"]["asset"][0] # there may be several assets. In that case, read the first one else return hash["response"]["payload"]["asset"] end end
ruby
def get_attributes url = URI.parse('http://www.blip.tv/') res = Net::HTTP.start(url.host, url.port) {|http| http.get("http://www.blip.tv/file/#{@id.to_s}?skin=api") } hash = Hash.from_xml(res.body) if hash["response"]["status"] != "OK" raise VideoResponseError.new(hash["response"]["notice"]) end if hash["response"]["payload"]["asset"].is_a?(Array) return hash["response"]["payload"]["asset"][0] # there may be several assets. In that case, read the first one else return hash["response"]["payload"]["asset"] end end
[ "def", "get_attributes", "url", "=", "URI", ".", "parse", "(", "'http://www.blip.tv/'", ")", "res", "=", "Net", "::", "HTTP", ".", "start", "(", "url", ".", "host", ",", "url", ".", "port", ")", "{", "|", "http", "|", "http", ".", "get", "(", "\"http://www.blip.tv/file/#{@id.to_s}?skin=api\"", ")", "}", "hash", "=", "Hash", ".", "from_xml", "(", "res", ".", "body", ")", "if", "hash", "[", "\"response\"", "]", "[", "\"status\"", "]", "!=", "\"OK\"", "raise", "VideoResponseError", ".", "new", "(", "hash", "[", "\"response\"", "]", "[", "\"notice\"", "]", ")", "end", "if", "hash", "[", "\"response\"", "]", "[", "\"payload\"", "]", "[", "\"asset\"", "]", ".", "is_a?", "(", "Array", ")", "return", "hash", "[", "\"response\"", "]", "[", "\"payload\"", "]", "[", "\"asset\"", "]", "[", "0", "]", "else", "return", "hash", "[", "\"response\"", "]", "[", "\"payload\"", "]", "[", "\"asset\"", "]", "end", "end" ]
fire off a HTTP GET response to Blip.tv In the future, this should probably be rolled into the BlipTV::Request class, so that all exception raising and network communication exists in instances of that class.
[ "fire", "off", "a", "HTTP", "GET", "response", "to", "Blip", ".", "tv" ]
4fd0d6132ded3069401d0fdf2f35726b71d3c64d
https://github.com/kellysutton/bliptv/blob/4fd0d6132ded3069401d0fdf2f35726b71d3c64d/lib/bliptv/video.rb#L84-L101
train
kellysutton/bliptv
lib/bliptv/video.rb
BlipTV.Video.delete!
def delete!(creds = {}, section = "file", reason = "because") BlipTV::ApiSpec.check_attributes('videos.delete', creds) reason = reason.gsub(" ", "%20") # TODO write a method to handle this and other illegalities of URL if creds[:username] && !creds[:userlogin] creds[:userlogin] = creds[:username] end url, path = "www.blip.tv", "/?userlogin=#{creds[:userlogin]}&password=#{creds[:password]}&cmd=delete&s=file&id=#{@id}&reason=#{reason}&skin=api" request = Net::HTTP.get(url, path) hash = Hash.from_xml(request) make_sure_video_was_deleted(hash) end
ruby
def delete!(creds = {}, section = "file", reason = "because") BlipTV::ApiSpec.check_attributes('videos.delete', creds) reason = reason.gsub(" ", "%20") # TODO write a method to handle this and other illegalities of URL if creds[:username] && !creds[:userlogin] creds[:userlogin] = creds[:username] end url, path = "www.blip.tv", "/?userlogin=#{creds[:userlogin]}&password=#{creds[:password]}&cmd=delete&s=file&id=#{@id}&reason=#{reason}&skin=api" request = Net::HTTP.get(url, path) hash = Hash.from_xml(request) make_sure_video_was_deleted(hash) end
[ "def", "delete!", "(", "creds", "=", "{", "}", ",", "section", "=", "\"file\"", ",", "reason", "=", "\"because\"", ")", "BlipTV", "::", "ApiSpec", ".", "check_attributes", "(", "'videos.delete'", ",", "creds", ")", "reason", "=", "reason", ".", "gsub", "(", "\" \"", ",", "\"%20\"", ")", "if", "creds", "[", ":username", "]", "&&", "!", "creds", "[", ":userlogin", "]", "creds", "[", ":userlogin", "]", "=", "creds", "[", ":username", "]", "end", "url", ",", "path", "=", "\"www.blip.tv\"", ",", "\"/?userlogin=#{creds[:userlogin]}&password=#{creds[:password]}&cmd=delete&s=file&id=#{@id}&reason=#{reason}&skin=api\"", "request", "=", "Net", "::", "HTTP", ".", "get", "(", "url", ",", "path", ")", "hash", "=", "Hash", ".", "from_xml", "(", "request", ")", "make_sure_video_was_deleted", "(", "hash", ")", "end" ]
delete! will delete the file from Blip.tv
[ "delete!", "will", "delete", "the", "file", "from", "Blip", ".", "tv" ]
4fd0d6132ded3069401d0fdf2f35726b71d3c64d
https://github.com/kellysutton/bliptv/blob/4fd0d6132ded3069401d0fdf2f35726b71d3c64d/lib/bliptv/video.rb#L114-L127
train
payout/rester
lib/rester/service.rb
Rester.Service._response
def _response(status, body=nil, headers={}) body = [body].compact headers = headers.merge("Content-Type" => "application/json") Rack::Response.new(body, status, headers).finish end
ruby
def _response(status, body=nil, headers={}) body = [body].compact headers = headers.merge("Content-Type" => "application/json") Rack::Response.new(body, status, headers).finish end
[ "def", "_response", "(", "status", ",", "body", "=", "nil", ",", "headers", "=", "{", "}", ")", "body", "=", "[", "body", "]", ".", "compact", "headers", "=", "headers", ".", "merge", "(", "\"Content-Type\"", "=>", "\"application/json\"", ")", "Rack", "::", "Response", ".", "new", "(", "body", ",", "status", ",", "headers", ")", ".", "finish", "end" ]
Returns a valid rack response.
[ "Returns", "a", "valid", "rack", "response", "." ]
404a45fa17e7f92e167a08c0bd90382dafd43cc5
https://github.com/payout/rester/blob/404a45fa17e7f92e167a08c0bd90382dafd43cc5/lib/rester/service.rb#L215-L219
train
theablefew/ablerc
lib/ablerc/dsl.rb
Ablerc.DSL.option
def option(name, behaviors = {}, &block) Ablerc.options << Ablerc::Option.new(name, behaviors, &block) end
ruby
def option(name, behaviors = {}, &block) Ablerc.options << Ablerc::Option.new(name, behaviors, &block) end
[ "def", "option", "(", "name", ",", "behaviors", "=", "{", "}", ",", "&", "block", ")", "Ablerc", ".", "options", "<<", "Ablerc", "::", "Option", ".", "new", "(", "name", ",", "behaviors", ",", "&", "block", ")", "end" ]
Describe the options available ==== Parameters * <tt>name</tt> - A valid name for the option * <tt>behaviors</tt> - Behaviors used to for this option * <tt>block</tt> - A proc that should be run against the option value. ==== Options * <tt>allow</tt> - The option value must be in this list * <tt>boolean</tt> - The option will accept <tt>true</tt>, <tt>false</tt>, <tt>0</tt>, <tt>1</tt>
[ "Describe", "the", "options", "available" ]
21ef74d92ef584c82a65b50cf9c908c13864b9e1
https://github.com/theablefew/ablerc/blob/21ef74d92ef584c82a65b50cf9c908c13864b9e1/lib/ablerc/dsl.rb#L35-L37
train
michaelmior/mipper
lib/mipper/variable.rb
MIPPeR.Variable.value
def value # Model must be solved to have a value return nil unless @model && @model.status == :optimized value = @model.variable_value self case @type when :integer value.round when :binary [false, true][value.round] else value end end
ruby
def value # Model must be solved to have a value return nil unless @model && @model.status == :optimized value = @model.variable_value self case @type when :integer value.round when :binary [false, true][value.round] else value end end
[ "def", "value", "return", "nil", "unless", "@model", "&&", "@model", ".", "status", "==", ":optimized", "value", "=", "@model", ".", "variable_value", "self", "case", "@type", "when", ":integer", "value", ".", "round", "when", ":binary", "[", "false", ",", "true", "]", "[", "value", ".", "round", "]", "else", "value", "end", "end" ]
Get the final value of this variable
[ "Get", "the", "final", "value", "of", "this", "variable" ]
4ab7f8b32c27f33fc5121756554a0a28d2077e06
https://github.com/michaelmior/mipper/blob/4ab7f8b32c27f33fc5121756554a0a28d2077e06/lib/mipper/variable.rb#L32-L46
train
mrakobeze/vrtk
src/vrtk/applets/version_applet.rb
VRTK::Applets.VersionApplet.run_parse
def run_parse obj = { 'name' => VRTK::NAME, 'version' => VRTK::VERSION, 'codename' => VRTK::CODENAME, 'ffmpeg' => ffmpeg_version, 'magick' => magick_version, 'license' => VRTK::LICENSE } puts JSON.pretty_unparse obj end
ruby
def run_parse obj = { 'name' => VRTK::NAME, 'version' => VRTK::VERSION, 'codename' => VRTK::CODENAME, 'ffmpeg' => ffmpeg_version, 'magick' => magick_version, 'license' => VRTK::LICENSE } puts JSON.pretty_unparse obj end
[ "def", "run_parse", "obj", "=", "{", "'name'", "=>", "VRTK", "::", "NAME", ",", "'version'", "=>", "VRTK", "::", "VERSION", ",", "'codename'", "=>", "VRTK", "::", "CODENAME", ",", "'ffmpeg'", "=>", "ffmpeg_version", ",", "'magick'", "=>", "magick_version", ",", "'license'", "=>", "VRTK", "::", "LICENSE", "}", "puts", "JSON", ".", "pretty_unparse", "obj", "end" ]
noinspection RubyStringKeysInHashInspection,RubyResolve
[ "noinspection", "RubyStringKeysInHashInspection", "RubyResolve" ]
444052951949e3faab01f6292345dcd0a789f005
https://github.com/mrakobeze/vrtk/blob/444052951949e3faab01f6292345dcd0a789f005/src/vrtk/applets/version_applet.rb#L34-L45
train
justinkim/tf2r
lib/tf2r/scraper.rb
TF2R.Scraper.scrape_main_page
def scrape_main_page page = fetch('http://tf2r.com/raffles.html') # All raffle links begin with 'tf2r.com/k' raffle_links = page.links_with(href: /tf2r\.com\/k/) raffle_links.map! { |x| x.uri.to_s } raffle_links.reverse! end
ruby
def scrape_main_page page = fetch('http://tf2r.com/raffles.html') # All raffle links begin with 'tf2r.com/k' raffle_links = page.links_with(href: /tf2r\.com\/k/) raffle_links.map! { |x| x.uri.to_s } raffle_links.reverse! end
[ "def", "scrape_main_page", "page", "=", "fetch", "(", "'http://tf2r.com/raffles.html'", ")", "raffle_links", "=", "page", ".", "links_with", "(", "href", ":", "/", "\\.", "\\/", "/", ")", "raffle_links", ".", "map!", "{", "|", "x", "|", "x", ".", "uri", ".", "to_s", "}", "raffle_links", ".", "reverse!", "end" ]
Scrapes TF2R for all active raffles. See http://tf2r.com/raffles.html @example s.scrape_main_page #=> ['http://tf2r.com/kold.html', 'http://tf2r.com/knew.html', 'http://tf2r.com/knewest.html'] @return [Hash] String links of all active raffles in chronological order (oldest to newest by creation time).
[ "Scrapes", "TF2R", "for", "all", "active", "raffles", "." ]
20d9648fe1048d9b2a34064821d8c95aaff505da
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/scraper.rb#L59-L66
train
justinkim/tf2r
lib/tf2r/scraper.rb
TF2R.Scraper.scrape_raffle_for_creator
def scrape_raffle_for_creator(page) # Reag classed some things "raffle_infomation". That's spelled right. infos = page.parser.css('.raffle_infomation') # The main 'a' element, containing the creator's username. user_anchor = infos[2].css('a')[0] steam_id = extract_steam_id(user_anchor.attribute('href').to_s) username = user_anchor.text avatar_link = infos[1].css('img')[0].attribute('src').to_s posrep = /(\d+)/.match(infos.css('.upvb').text)[1].to_i negrep = /(\d+)/.match(infos.css('.downvb').text)[1].to_i # The creator's username color. Corresponds to rank. color = extract_color(user_anchor.attribute('style').to_s) {steam_id: steam_id, username: username, avatar_link: avatar_link, posrep: posrep, negrep: negrep, color: color} end
ruby
def scrape_raffle_for_creator(page) # Reag classed some things "raffle_infomation". That's spelled right. infos = page.parser.css('.raffle_infomation') # The main 'a' element, containing the creator's username. user_anchor = infos[2].css('a')[0] steam_id = extract_steam_id(user_anchor.attribute('href').to_s) username = user_anchor.text avatar_link = infos[1].css('img')[0].attribute('src').to_s posrep = /(\d+)/.match(infos.css('.upvb').text)[1].to_i negrep = /(\d+)/.match(infos.css('.downvb').text)[1].to_i # The creator's username color. Corresponds to rank. color = extract_color(user_anchor.attribute('style').to_s) {steam_id: steam_id, username: username, avatar_link: avatar_link, posrep: posrep, negrep: negrep, color: color} end
[ "def", "scrape_raffle_for_creator", "(", "page", ")", "infos", "=", "page", ".", "parser", ".", "css", "(", "'.raffle_infomation'", ")", "user_anchor", "=", "infos", "[", "2", "]", ".", "css", "(", "'a'", ")", "[", "0", "]", "steam_id", "=", "extract_steam_id", "(", "user_anchor", ".", "attribute", "(", "'href'", ")", ".", "to_s", ")", "username", "=", "user_anchor", ".", "text", "avatar_link", "=", "infos", "[", "1", "]", ".", "css", "(", "'img'", ")", "[", "0", "]", ".", "attribute", "(", "'src'", ")", ".", "to_s", "posrep", "=", "/", "\\d", "/", ".", "match", "(", "infos", ".", "css", "(", "'.upvb'", ")", ".", "text", ")", "[", "1", "]", ".", "to_i", "negrep", "=", "/", "\\d", "/", ".", "match", "(", "infos", ".", "css", "(", "'.downvb'", ")", ".", "text", ")", "[", "1", "]", ".", "to_i", "color", "=", "extract_color", "(", "user_anchor", ".", "attribute", "(", "'style'", ")", ".", "to_s", ")", "{", "steam_id", ":", "steam_id", ",", "username", ":", "username", ",", "avatar_link", ":", "avatar_link", ",", "posrep", ":", "posrep", ",", "negrep", ":", "negrep", ",", "color", ":", "color", "}", "end" ]
Scrapes a raffle page for information about the creator. @example p = s.fetch('http://tf2r.com/kstzcbd.html') s.scrape_raffle_for_creator(p) #=> {:steam_id=>76561198061719848, :username=>"Yulli", :avatar_link=>"http://media.steampowered.com/steamcommunity/public/images/avatars/bc/bc9dc4302d23f2e2f37f59c59f29c27dbc8cade6_full.jpg", :posrep=>11458, :negrep=>0, :color=>"70b01b"} @param page [Mechanize::Page] the raffle page. @return [Hash] a representation of a user, the raffle creator. * :steam_id (+Fixnum+) — the creator's SteamID64. * :username (+String+) — the creator's username. * :avatar_link (+String+) — a link to the creator's avatar. * :posrep (+Fixnum+) — the creator's positive rep. * :negrep (+Fixnum+) — the creator's negative rep. * :color (+String+) — hex color code of the creator's username.
[ "Scrapes", "a", "raffle", "page", "for", "information", "about", "the", "creator", "." ]
20d9648fe1048d9b2a34064821d8c95aaff505da
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/scraper.rb#L99-L117
train
justinkim/tf2r
lib/tf2r/scraper.rb
TF2R.Scraper.scrape_raffle_for_raffle
def scrape_raffle_for_raffle(page) # Reag classed some things "raffle_infomation". That's spelled right. infos = page.parser.css('.raffle_infomation') # Elements of the main raffle info table. raffle_tds = infos[3].css('td') # 'kabc123' for http://tf2r.com/kabc123.html' link_snippet = extract_link_snippet(page.uri.path) title = extract_title(infos[0].text) description = raffle_tds[1].text # This doesn't work right now, because Miz just displays "10%" in the # page HTML and updates it with JS after a call to the API. # win_chance = /(.+)%/.match(infos.css('#winc').text)[1].to_f / 100 start_time = extract_start_time(raffle_tds[9]) end_time = extract_end_time(raffle_tds[11]) {link_snippet: link_snippet, title: title, description: description, start_time: start_time, end_time: end_time} end
ruby
def scrape_raffle_for_raffle(page) # Reag classed some things "raffle_infomation". That's spelled right. infos = page.parser.css('.raffle_infomation') # Elements of the main raffle info table. raffle_tds = infos[3].css('td') # 'kabc123' for http://tf2r.com/kabc123.html' link_snippet = extract_link_snippet(page.uri.path) title = extract_title(infos[0].text) description = raffle_tds[1].text # This doesn't work right now, because Miz just displays "10%" in the # page HTML and updates it with JS after a call to the API. # win_chance = /(.+)%/.match(infos.css('#winc').text)[1].to_f / 100 start_time = extract_start_time(raffle_tds[9]) end_time = extract_end_time(raffle_tds[11]) {link_snippet: link_snippet, title: title, description: description, start_time: start_time, end_time: end_time} end
[ "def", "scrape_raffle_for_raffle", "(", "page", ")", "infos", "=", "page", ".", "parser", ".", "css", "(", "'.raffle_infomation'", ")", "raffle_tds", "=", "infos", "[", "3", "]", ".", "css", "(", "'td'", ")", "link_snippet", "=", "extract_link_snippet", "(", "page", ".", "uri", ".", "path", ")", "title", "=", "extract_title", "(", "infos", "[", "0", "]", ".", "text", ")", "description", "=", "raffle_tds", "[", "1", "]", ".", "text", "start_time", "=", "extract_start_time", "(", "raffle_tds", "[", "9", "]", ")", "end_time", "=", "extract_end_time", "(", "raffle_tds", "[", "11", "]", ")", "{", "link_snippet", ":", "link_snippet", ",", "title", ":", "title", ",", "description", ":", "description", ",", "start_time", ":", "start_time", ",", "end_time", ":", "end_time", "}", "end" ]
Scrapes a raffle page for some information about the raffle. The information is incomplete. This should be used in conjunction with the API as part of TF2R::Raffle. @example p = s.fetch('http://tf2r.com/kstzcbd.html') s.scrape_raffle_for_raffle(p) #=> {:link_snippet=>"kstzcbd", :title=>"Just one refined [1 hour]", :description=>"Plain and simple.", :start_time=>2012-10-29 09:51:45 -0400, :end_time=>2012-10-29 09:53:01 -0400} @param page [Mechanize::Page] the raffle page. @return [Hash] a partial representation of the raffle. * :link_snippet (+String+) — the "raffle id" in the URL. * :title (+String+) — the raffle's title. * :description (+String+) — the raffle's "message". * :start_time (+Time+) — the creation time of the raffle. * :end_time (+Time+) — the projects/observed end time for the raffle.
[ "Scrapes", "a", "raffle", "page", "for", "some", "information", "about", "the", "raffle", "." ]
20d9648fe1048d9b2a34064821d8c95aaff505da
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/scraper.rb#L140-L161
train
justinkim/tf2r
lib/tf2r/scraper.rb
TF2R.Scraper.scrape_raffle_for_participants
def scrape_raffle_for_participants(page) participants = [] participant_divs = page.parser.css('.pentry') participant_divs.each do |participant| user_anchor = participant.children[1] steam_id = extract_steam_id(user_anchor.to_s) username = participant.text color = extract_color(user_anchor.children[0].attribute('style')) participants << {steam_id: steam_id, username: username, color: color} end participants.reverse! end
ruby
def scrape_raffle_for_participants(page) participants = [] participant_divs = page.parser.css('.pentry') participant_divs.each do |participant| user_anchor = participant.children[1] steam_id = extract_steam_id(user_anchor.to_s) username = participant.text color = extract_color(user_anchor.children[0].attribute('style')) participants << {steam_id: steam_id, username: username, color: color} end participants.reverse! end
[ "def", "scrape_raffle_for_participants", "(", "page", ")", "participants", "=", "[", "]", "participant_divs", "=", "page", ".", "parser", ".", "css", "(", "'.pentry'", ")", "participant_divs", ".", "each", "do", "|", "participant", "|", "user_anchor", "=", "participant", ".", "children", "[", "1", "]", "steam_id", "=", "extract_steam_id", "(", "user_anchor", ".", "to_s", ")", "username", "=", "participant", ".", "text", "color", "=", "extract_color", "(", "user_anchor", ".", "children", "[", "0", "]", ".", "attribute", "(", "'style'", ")", ")", "participants", "<<", "{", "steam_id", ":", "steam_id", ",", "username", ":", "username", ",", "color", ":", "color", "}", "end", "participants", ".", "reverse!", "end" ]
Scrapes a raffle page for all the participants. This should rarely be used. This will only be necessary in the case that a raffle has maximum entries greater than 2500. @param page [Mechanize::Page] the raffle page. @return [Array] contains Hashes representing each of the participants, in chronological order (first entered to last). * :steam_id (+Fixnum+) — the participant's SteamID64. * :username (+String+) — the participant's username. * :color (+String+) — hex color code of the participant's username.
[ "Scrapes", "a", "raffle", "page", "for", "all", "the", "participants", "." ]
20d9648fe1048d9b2a34064821d8c95aaff505da
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/scraper.rb#L174-L187
train
justinkim/tf2r
lib/tf2r/scraper.rb
TF2R.Scraper.scrape_user
def scrape_user(user_page) if user_page.parser.css('.profile_info').empty? raise InvalidUserPage, 'The given page does not correspond to any user.' else infos = user_page.parser.css('.raffle_infomation') #sic user_anchor = infos[1].css('a')[0] steam_id = extract_steam_id(user_page.uri.to_s) username = /TF2R Item Raffles - (.+)/.match(user_page.title)[1] avatar_link = infos[0].css('img')[0].attribute('src').to_s posrep = infos.css('.upvb').text.to_i negrep = infos.css('.downvb').text.to_i color = extract_color(user_anchor.attribute('style').to_s) end {steam_id: steam_id, username: username, avatar_link: avatar_link, posrep: posrep, negrep: negrep, color: color} end
ruby
def scrape_user(user_page) if user_page.parser.css('.profile_info').empty? raise InvalidUserPage, 'The given page does not correspond to any user.' else infos = user_page.parser.css('.raffle_infomation') #sic user_anchor = infos[1].css('a')[0] steam_id = extract_steam_id(user_page.uri.to_s) username = /TF2R Item Raffles - (.+)/.match(user_page.title)[1] avatar_link = infos[0].css('img')[0].attribute('src').to_s posrep = infos.css('.upvb').text.to_i negrep = infos.css('.downvb').text.to_i color = extract_color(user_anchor.attribute('style').to_s) end {steam_id: steam_id, username: username, avatar_link: avatar_link, posrep: posrep, negrep: negrep, color: color} end
[ "def", "scrape_user", "(", "user_page", ")", "if", "user_page", ".", "parser", ".", "css", "(", "'.profile_info'", ")", ".", "empty?", "raise", "InvalidUserPage", ",", "'The given page does not correspond to any user.'", "else", "infos", "=", "user_page", ".", "parser", ".", "css", "(", "'.raffle_infomation'", ")", "user_anchor", "=", "infos", "[", "1", "]", ".", "css", "(", "'a'", ")", "[", "0", "]", "steam_id", "=", "extract_steam_id", "(", "user_page", ".", "uri", ".", "to_s", ")", "username", "=", "/", "/", ".", "match", "(", "user_page", ".", "title", ")", "[", "1", "]", "avatar_link", "=", "infos", "[", "0", "]", ".", "css", "(", "'img'", ")", "[", "0", "]", ".", "attribute", "(", "'src'", ")", ".", "to_s", "posrep", "=", "infos", ".", "css", "(", "'.upvb'", ")", ".", "text", ".", "to_i", "negrep", "=", "infos", ".", "css", "(", "'.downvb'", ")", ".", "text", ".", "to_i", "color", "=", "extract_color", "(", "user_anchor", ".", "attribute", "(", "'style'", ")", ".", "to_s", ")", "end", "{", "steam_id", ":", "steam_id", ",", "username", ":", "username", ",", "avatar_link", ":", "avatar_link", ",", "posrep", ":", "posrep", ",", "negrep", ":", "negrep", ",", "color", ":", "color", "}", "end" ]
Scrapes a user page for information about the user. @example p = s.fetch('http://tf2r.com/user/76561198061719848.html') s.scrape_user(p) #=> {:steam_id=>76561198061719848, :username=>"Yulli", :avatar_link=>"http://media.steampowered.com/steamcommunity/public/images/avatars/bc/bc9dc4302d23f2e2f37f59c59f29c27dbc8cade6_full.jpg", :posrep=>11459, :negrep=>0, :color=>"70b01b"} @param user_page [Mechanize::Page] the user page. @return [Hash] a representation of the user. * :steam_id (+Fixnum+) — the user's SteamID64. * :username (+String+) — the user's username. * :avatar_link (+String+) — a link to the user's avatar. * :posrep (+Fixnum+) — the user's positive rep. * :negrep (+Fixnum+) — the user's negative rep. * :color (+String+) — hex color code of the user's username.
[ "Scrapes", "a", "user", "page", "for", "information", "about", "the", "user", "." ]
20d9648fe1048d9b2a34064821d8c95aaff505da
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/scraper.rb#L209-L228
train
justinkim/tf2r
lib/tf2r/scraper.rb
TF2R.Scraper.scrape_ranks
def scrape_ranks(info_page) rank_divs = info_page.parser.css('#ranks').children ranks = rank_divs.select { |div| div.children.size == 3 } ranks.map { |div| extract_rank(div) } end
ruby
def scrape_ranks(info_page) rank_divs = info_page.parser.css('#ranks').children ranks = rank_divs.select { |div| div.children.size == 3 } ranks.map { |div| extract_rank(div) } end
[ "def", "scrape_ranks", "(", "info_page", ")", "rank_divs", "=", "info_page", ".", "parser", ".", "css", "(", "'#ranks'", ")", ".", "children", "ranks", "=", "rank_divs", ".", "select", "{", "|", "div", "|", "div", ".", "children", ".", "size", "==", "3", "}", "ranks", ".", "map", "{", "|", "div", "|", "extract_rank", "(", "div", ")", "}", "end" ]
Scrapes the TF2R info page for available user ranks. See http://tf2r.com/info.html. @example p = s.fetch('http://tf2r.com/info.html') s.scrape_user(p) #=> [{:color=>"ebe2ca", :name=>"User", :description=>"Every new or existing user has this rank."}, ...] @param info_page [Mechanize::Page] the info page. @return [Array] contains Hashes representing each of the ranks. * :name (+String+) — the rank's name. * :description (+String+) — the rank's description. * :color (+String+) — the rank's hex color code.
[ "Scrapes", "the", "TF2R", "info", "page", "for", "available", "user", "ranks", "." ]
20d9648fe1048d9b2a34064821d8c95aaff505da
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/scraper.rb#L245-L249
train
betaworks/slack-bot-manager
lib/slack-bot-manager/manager/connection.rb
SlackBotManager.Connection.start
def start # Clear RTM connections storage.delete_all(teams_key) # Start a new connection for each team storage.get_all(tokens_key).each do |id, token| create(id, token) end end
ruby
def start # Clear RTM connections storage.delete_all(teams_key) # Start a new connection for each team storage.get_all(tokens_key).each do |id, token| create(id, token) end end
[ "def", "start", "storage", ".", "delete_all", "(", "teams_key", ")", "storage", ".", "get_all", "(", "tokens_key", ")", ".", "each", "do", "|", "id", ",", "token", "|", "create", "(", "id", ",", "token", ")", "end", "end" ]
Create websocket connections for active tokens
[ "Create", "websocket", "connections", "for", "active", "tokens" ]
cb59bd1c80abd3ede0520017708891486f733e40
https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/manager/connection.rb#L74-L82
train
betaworks/slack-bot-manager
lib/slack-bot-manager/manager/connection.rb
SlackBotManager.Connection.stop
def stop # Thread wrapped to ensure no lock issues on shutdown thr = Thread.new do conns = storage.get_all(teams_key) storage.pipeline do conns.each { |k, _| storage.set(teams_key, k, 'destroy') } end info('Stopped.') end thr.join end
ruby
def stop # Thread wrapped to ensure no lock issues on shutdown thr = Thread.new do conns = storage.get_all(teams_key) storage.pipeline do conns.each { |k, _| storage.set(teams_key, k, 'destroy') } end info('Stopped.') end thr.join end
[ "def", "stop", "thr", "=", "Thread", ".", "new", "do", "conns", "=", "storage", ".", "get_all", "(", "teams_key", ")", "storage", ".", "pipeline", "do", "conns", ".", "each", "{", "|", "k", ",", "_", "|", "storage", ".", "set", "(", "teams_key", ",", "k", ",", "'destroy'", ")", "}", "end", "info", "(", "'Stopped.'", ")", "end", "thr", ".", "join", "end" ]
Remove all connections from app, will disconnect in monitor loop
[ "Remove", "all", "connections", "from", "app", "will", "disconnect", "in", "monitor", "loop" ]
cb59bd1c80abd3ede0520017708891486f733e40
https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/manager/connection.rb#L85-L95
train
betaworks/slack-bot-manager
lib/slack-bot-manager/manager/connection.rb
SlackBotManager.Connection.restart
def restart conns = storage.get_all(teams_key) storage.pipeline do conns.each { |k, _| storage.set(teams_key, k, 'restart') } end end
ruby
def restart conns = storage.get_all(teams_key) storage.pipeline do conns.each { |k, _| storage.set(teams_key, k, 'restart') } end end
[ "def", "restart", "conns", "=", "storage", ".", "get_all", "(", "teams_key", ")", "storage", ".", "pipeline", "do", "conns", ".", "each", "{", "|", "k", ",", "_", "|", "storage", ".", "set", "(", "teams_key", ",", "k", ",", "'restart'", ")", "}", "end", "end" ]
Issue restart status on all RTM connections will re-connect in monitor loop
[ "Issue", "restart", "status", "on", "all", "RTM", "connections", "will", "re", "-", "connect", "in", "monitor", "loop" ]
cb59bd1c80abd3ede0520017708891486f733e40
https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/manager/connection.rb#L99-L104
train
betaworks/slack-bot-manager
lib/slack-bot-manager/manager/connection.rb
SlackBotManager.Connection.find_connection
def find_connection(id) connections.each do |_, conn| return (conn.connected? ? conn : false) if conn && conn.id == id end false end
ruby
def find_connection(id) connections.each do |_, conn| return (conn.connected? ? conn : false) if conn && conn.id == id end false end
[ "def", "find_connection", "(", "id", ")", "connections", ".", "each", "do", "|", "_", ",", "conn", "|", "return", "(", "conn", ".", "connected?", "?", "conn", ":", "false", ")", "if", "conn", "&&", "conn", ".", "id", "==", "id", "end", "false", "end" ]
Find the connection based on id and has active connection
[ "Find", "the", "connection", "based", "on", "id", "and", "has", "active", "connection" ]
cb59bd1c80abd3ede0520017708891486f733e40
https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/manager/connection.rb#L114-L119
train
betaworks/slack-bot-manager
lib/slack-bot-manager/manager/connection.rb
SlackBotManager.Connection.create
def create(id, token) fail SlackBotManager::TokenAlreadyConnected if find_connection(id) # Create connection conn = SlackBotManager::Client.new(token) conn.connect # Add to connections using a uniq token if conn cid = [id, Time.now.to_i].join(':') connections[cid] = conn info("Connected: #{id} (Connection: #{cid})") storage.set(teams_key, id, 'active') end rescue => err on_error(err) end
ruby
def create(id, token) fail SlackBotManager::TokenAlreadyConnected if find_connection(id) # Create connection conn = SlackBotManager::Client.new(token) conn.connect # Add to connections using a uniq token if conn cid = [id, Time.now.to_i].join(':') connections[cid] = conn info("Connected: #{id} (Connection: #{cid})") storage.set(teams_key, id, 'active') end rescue => err on_error(err) end
[ "def", "create", "(", "id", ",", "token", ")", "fail", "SlackBotManager", "::", "TokenAlreadyConnected", "if", "find_connection", "(", "id", ")", "conn", "=", "SlackBotManager", "::", "Client", ".", "new", "(", "token", ")", "conn", ".", "connect", "if", "conn", "cid", "=", "[", "id", ",", "Time", ".", "now", ".", "to_i", "]", ".", "join", "(", "':'", ")", "connections", "[", "cid", "]", "=", "conn", "info", "(", "\"Connected: #{id} (Connection: #{cid})\"", ")", "storage", ".", "set", "(", "teams_key", ",", "id", ",", "'active'", ")", "end", "rescue", "=>", "err", "on_error", "(", "err", ")", "end" ]
Create new connection if not exist
[ "Create", "new", "connection", "if", "not", "exist" ]
cb59bd1c80abd3ede0520017708891486f733e40
https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/manager/connection.rb#L122-L138
train
betaworks/slack-bot-manager
lib/slack-bot-manager/manager/connection.rb
SlackBotManager.Connection.destroy
def destroy(*args) options = args.extract_options! # Get connection or search for connection with cid if options[:cid] conn = connections[options[:cid]] cid = options[:cid] elsif options[:id] conn, cid = find_connection(options[:id]) end return false unless conn && cid # Kill connection, remove from keys, and delete from list begin thr = Thread.new do storage.delete(teams_key, conn.id) rescue nil storage.delete(tokens_key, conn.id) rescue nil if options[:remove_token] end thr.join connections.delete(cid) rescue nil end rescue => err on_error(err) end
ruby
def destroy(*args) options = args.extract_options! # Get connection or search for connection with cid if options[:cid] conn = connections[options[:cid]] cid = options[:cid] elsif options[:id] conn, cid = find_connection(options[:id]) end return false unless conn && cid # Kill connection, remove from keys, and delete from list begin thr = Thread.new do storage.delete(teams_key, conn.id) rescue nil storage.delete(tokens_key, conn.id) rescue nil if options[:remove_token] end thr.join connections.delete(cid) rescue nil end rescue => err on_error(err) end
[ "def", "destroy", "(", "*", "args", ")", "options", "=", "args", ".", "extract_options!", "if", "options", "[", ":cid", "]", "conn", "=", "connections", "[", "options", "[", ":cid", "]", "]", "cid", "=", "options", "[", ":cid", "]", "elsif", "options", "[", ":id", "]", "conn", ",", "cid", "=", "find_connection", "(", "options", "[", ":id", "]", ")", "end", "return", "false", "unless", "conn", "&&", "cid", "begin", "thr", "=", "Thread", ".", "new", "do", "storage", ".", "delete", "(", "teams_key", ",", "conn", ".", "id", ")", "rescue", "nil", "storage", ".", "delete", "(", "tokens_key", ",", "conn", ".", "id", ")", "rescue", "nil", "if", "options", "[", ":remove_token", "]", "end", "thr", ".", "join", "connections", ".", "delete", "(", "cid", ")", "rescue", "nil", "end", "rescue", "=>", "err", "on_error", "(", "err", ")", "end" ]
Disconnect from a RTM connection
[ "Disconnect", "from", "a", "RTM", "connection" ]
cb59bd1c80abd3ede0520017708891486f733e40
https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/manager/connection.rb#L141-L166
train
kristianmandrup/controll
lib/controll/flow/action/path_action.rb
Controll::Flow::Action.PathAction.method_missing
def method_missing(method_name, *args, &block) if controller.respond_to? method_name controller.send method_name, *args, &block else super end end
ruby
def method_missing(method_name, *args, &block) if controller.respond_to? method_name controller.send method_name, *args, &block else super end end
[ "def", "method_missing", "(", "method_name", ",", "*", "args", ",", "&", "block", ")", "if", "controller", ".", "respond_to?", "method_name", "controller", ".", "send", "method_name", ",", "*", "args", ",", "&", "block", "else", "super", "end", "end" ]
useful for path helpers used in event maps
[ "useful", "for", "path", "helpers", "used", "in", "event", "maps" ]
99f25c1153ff7d04fab64391977e7140ce5b3d37
https://github.com/kristianmandrup/controll/blob/99f25c1153ff7d04fab64391977e7140ce5b3d37/lib/controll/flow/action/path_action.rb#L16-L22
train
ashiksp/smart_que
lib/smart_que/publisher.rb
SmartQue.Publisher.publish
def publish(queue, payload = {}) # Check queue name includes in the configured list # Return if queue doesn't exist if queue_list.include? queue # Publish sms to queue begin x_direct.publish( payload.to_json, mandatory: true, routing_key: get_queue(queue).name ) log_message("Publish status: success, Queue : #{queue}, Content : #{payload}") :success rescue => ex log_message("Publish error:#{ex.message}") :error end else log_message("Publish status: failed, Queue(#{queue}) doesn't exist.") log_message("Content : #{payload}") raise QueueNotFoundError end end
ruby
def publish(queue, payload = {}) # Check queue name includes in the configured list # Return if queue doesn't exist if queue_list.include? queue # Publish sms to queue begin x_direct.publish( payload.to_json, mandatory: true, routing_key: get_queue(queue).name ) log_message("Publish status: success, Queue : #{queue}, Content : #{payload}") :success rescue => ex log_message("Publish error:#{ex.message}") :error end else log_message("Publish status: failed, Queue(#{queue}) doesn't exist.") log_message("Content : #{payload}") raise QueueNotFoundError end end
[ "def", "publish", "(", "queue", ",", "payload", "=", "{", "}", ")", "if", "queue_list", ".", "include?", "queue", "begin", "x_direct", ".", "publish", "(", "payload", ".", "to_json", ",", "mandatory", ":", "true", ",", "routing_key", ":", "get_queue", "(", "queue", ")", ".", "name", ")", "log_message", "(", "\"Publish status: success, Queue : #{queue}, Content : #{payload}\"", ")", ":success", "rescue", "=>", "ex", "log_message", "(", "\"Publish error:#{ex.message}\"", ")", ":error", "end", "else", "log_message", "(", "\"Publish status: failed, Queue(#{queue}) doesn't exist.\"", ")", "log_message", "(", "\"Content : #{payload}\"", ")", "raise", "QueueNotFoundError", "end", "end" ]
Initialize Instance methods Publish message to the respective queue
[ "Initialize", "Instance", "methods", "Publish", "message", "to", "the", "respective", "queue" ]
3b16451e38c430f05c0ac5fb111cfc96e4dc34b8
https://github.com/ashiksp/smart_que/blob/3b16451e38c430f05c0ac5fb111cfc96e4dc34b8/lib/smart_que/publisher.rb#L16-L38
train
ashiksp/smart_que
lib/smart_que/publisher.rb
SmartQue.Publisher.unicast
def unicast(q_name, payload = {}) begin x_default.publish( payload.to_json, routing_key: dot_formatted(q_name) ) log_message("unicast status: success, Queue : #{q_name}, Content : #{payload}") :success rescue => ex log_message("Unicast error:#{ex.message}") :error end end
ruby
def unicast(q_name, payload = {}) begin x_default.publish( payload.to_json, routing_key: dot_formatted(q_name) ) log_message("unicast status: success, Queue : #{q_name}, Content : #{payload}") :success rescue => ex log_message("Unicast error:#{ex.message}") :error end end
[ "def", "unicast", "(", "q_name", ",", "payload", "=", "{", "}", ")", "begin", "x_default", ".", "publish", "(", "payload", ".", "to_json", ",", "routing_key", ":", "dot_formatted", "(", "q_name", ")", ")", "log_message", "(", "\"unicast status: success, Queue : #{q_name}, Content : #{payload}\"", ")", ":success", "rescue", "=>", "ex", "log_message", "(", "\"Unicast error:#{ex.message}\"", ")", ":error", "end", "end" ]
unicast message to queues
[ "unicast", "message", "to", "queues" ]
3b16451e38c430f05c0ac5fb111cfc96e4dc34b8
https://github.com/ashiksp/smart_que/blob/3b16451e38c430f05c0ac5fb111cfc96e4dc34b8/lib/smart_que/publisher.rb#L41-L53
train
ashiksp/smart_que
lib/smart_que/publisher.rb
SmartQue.Publisher.multicast
def multicast(topic, payload = {}) begin x_topic.publish( payload.to_json, routing_key: dot_formatted(topic) ) log_message("multicast status: success, Topic : #{topic}, Content : #{payload}") :success rescue => ex log_message("Multicast error:#{ex.message}") :error end end
ruby
def multicast(topic, payload = {}) begin x_topic.publish( payload.to_json, routing_key: dot_formatted(topic) ) log_message("multicast status: success, Topic : #{topic}, Content : #{payload}") :success rescue => ex log_message("Multicast error:#{ex.message}") :error end end
[ "def", "multicast", "(", "topic", ",", "payload", "=", "{", "}", ")", "begin", "x_topic", ".", "publish", "(", "payload", ".", "to_json", ",", "routing_key", ":", "dot_formatted", "(", "topic", ")", ")", "log_message", "(", "\"multicast status: success, Topic : #{topic}, Content : #{payload}\"", ")", ":success", "rescue", "=>", "ex", "log_message", "(", "\"Multicast error:#{ex.message}\"", ")", ":error", "end", "end" ]
multicast message to queues based on topic subscription
[ "multicast", "message", "to", "queues", "based", "on", "topic", "subscription" ]
3b16451e38c430f05c0ac5fb111cfc96e4dc34b8
https://github.com/ashiksp/smart_que/blob/3b16451e38c430f05c0ac5fb111cfc96e4dc34b8/lib/smart_que/publisher.rb#L57-L69
train
celldee/ffi-rxs
lib/ffi-rxs/poll_items.rb
XS.PollItems.clean
def clean if @dirty @store = FFI::MemoryPointer.new @element_size, @items.size, true # copy over offset = 0 @items.each do |item| LibC.memcpy(@store + offset, item.pointer, @element_size) offset += @element_size end @dirty = false end end
ruby
def clean if @dirty @store = FFI::MemoryPointer.new @element_size, @items.size, true # copy over offset = 0 @items.each do |item| LibC.memcpy(@store + offset, item.pointer, @element_size) offset += @element_size end @dirty = false end end
[ "def", "clean", "if", "@dirty", "@store", "=", "FFI", "::", "MemoryPointer", ".", "new", "@element_size", ",", "@items", ".", "size", ",", "true", "offset", "=", "0", "@items", ".", "each", "do", "|", "item", "|", "LibC", ".", "memcpy", "(", "@store", "+", "offset", ",", "item", ".", "pointer", ",", "@element_size", ")", "offset", "+=", "@element_size", "end", "@dirty", "=", "false", "end", "end" ]
Allocate a contiguous chunk of memory and copy over the PollItem structs to this block. Note that the old +@store+ value goes out of scope so when it is garbage collected that native memory should be automatically freed.
[ "Allocate", "a", "contiguous", "chunk", "of", "memory", "and", "copy", "over", "the", "PollItem", "structs", "to", "this", "block", ".", "Note", "that", "the", "old", "+" ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/poll_items.rb#L105-L118
train
pione/ruby-xes
lib/xes/attribute.rb
XES.Attribute.format_value
def format_value case @type when "string" @value when "date" @value.kind_of?(Time) ? @value.iso8601(3) : @value when "int" @value.kind_of?(Integer) ? @value : @value.to_i when "float" @value.kind_of?(Float) ? @value : @value.to_f when "boolean" @value when "id" @value end.to_s end
ruby
def format_value case @type when "string" @value when "date" @value.kind_of?(Time) ? @value.iso8601(3) : @value when "int" @value.kind_of?(Integer) ? @value : @value.to_i when "float" @value.kind_of?(Float) ? @value : @value.to_f when "boolean" @value when "id" @value end.to_s end
[ "def", "format_value", "case", "@type", "when", "\"string\"", "@value", "when", "\"date\"", "@value", ".", "kind_of?", "(", "Time", ")", "?", "@value", ".", "iso8601", "(", "3", ")", ":", "@value", "when", "\"int\"", "@value", ".", "kind_of?", "(", "Integer", ")", "?", "@value", ":", "@value", ".", "to_i", "when", "\"float\"", "@value", ".", "kind_of?", "(", "Float", ")", "?", "@value", ":", "@value", ".", "to_f", "when", "\"boolean\"", "@value", "when", "\"id\"", "@value", "end", ".", "to_s", "end" ]
Format the value. @return [String]
[ "Format", "the", "value", "." ]
61501a8fd8027708f670264a150b1ce74fdccd74
https://github.com/pione/ruby-xes/blob/61501a8fd8027708f670264a150b1ce74fdccd74/lib/xes/attribute.rb#L98-L113
train
choonkeat/active_params
lib/active_params/parser.rb
ActiveParams.Parser.combine_hashes
def combine_hashes(array_of_hashes) array_of_hashes.select {|v| v.kind_of?(Hash) }. inject({}) {|sum, hash| hash.inject(sum) {|sum,(k,v)| sum.merge(k => v) } } end
ruby
def combine_hashes(array_of_hashes) array_of_hashes.select {|v| v.kind_of?(Hash) }. inject({}) {|sum, hash| hash.inject(sum) {|sum,(k,v)| sum.merge(k => v) } } end
[ "def", "combine_hashes", "(", "array_of_hashes", ")", "array_of_hashes", ".", "select", "{", "|", "v", "|", "v", ".", "kind_of?", "(", "Hash", ")", "}", ".", "inject", "(", "{", "}", ")", "{", "|", "sum", ",", "hash", "|", "hash", ".", "inject", "(", "sum", ")", "{", "|", "sum", ",", "(", "k", ",", "v", ")", "|", "sum", ".", "merge", "(", "k", "=>", "v", ")", "}", "}", "end" ]
to obtain a hash of all possible keys
[ "to", "obtain", "a", "hash", "of", "all", "possible", "keys" ]
e0fa9dc928bbb363aa72ee4bb717e75ba6bfc6ce
https://github.com/choonkeat/active_params/blob/e0fa9dc928bbb363aa72ee4bb717e75ba6bfc6ce/lib/active_params/parser.rb#L4-L7
train
NYULibraries/citero-jruby
lib/citero-jruby/base.rb
Citero.Base.from
def from format #Formats are enums in java, so they are all uppercase @citero = @citero::from(Formats::valueOf(format.upcase)) self #rescue any exceptions, if the error is not caught in JAR, most likely a #problem with the data rescue Exception => e raise TypeError, "Mismatched data for #{format}" end
ruby
def from format #Formats are enums in java, so they are all uppercase @citero = @citero::from(Formats::valueOf(format.upcase)) self #rescue any exceptions, if the error is not caught in JAR, most likely a #problem with the data rescue Exception => e raise TypeError, "Mismatched data for #{format}" end
[ "def", "from", "format", "@citero", "=", "@citero", "::", "from", "(", "Formats", "::", "valueOf", "(", "format", ".", "upcase", ")", ")", "self", "rescue", "Exception", "=>", "e", "raise", "TypeError", ",", "\"Mismatched data for #{format}\"", "end" ]
The constructor, takes input data taken from the parent module and creates an instance of the Citero java object. Returns itself for builder patttern. The from method is private, it takes in a format and gets the appropriate Format java class and then calls the from method in the Citero java object and stores its return value in an instance variable. Returns itself.
[ "The", "constructor", "takes", "input", "data", "taken", "from", "the", "parent", "module", "and", "creates", "an", "instance", "of", "the", "Citero", "java", "object", ".", "Returns", "itself", "for", "builder", "patttern", ".", "The", "from", "method", "is", "private", "it", "takes", "in", "a", "format", "and", "gets", "the", "appropriate", "Format", "java", "class", "and", "then", "calls", "the", "from", "method", "in", "the", "Citero", "java", "object", "and", "stores", "its", "return", "value", "in", "an", "instance", "variable", ".", "Returns", "itself", "." ]
ddf1142a8a05cb1e7153d1887239fe913df563ce
https://github.com/NYULibraries/citero-jruby/blob/ddf1142a8a05cb1e7153d1887239fe913df563ce/lib/citero-jruby/base.rb#L54-L62
train
NYULibraries/citero-jruby
lib/citero-jruby/base.rb
Citero.Base.to
def to format #Formats are enums in java, so they are all uppercase if to_formats.include? format @citero::to(Formats::valueOf(format.upcase)) else @citero::to(CitationStyles::valueOf(format.upcase)) end #rescue any exceptions, if the error is not caught in JAR, most likely a #problem with the source format rescue Exception => e raise ArgumentError, "Missing a source format. Use from_[format] first." end
ruby
def to format #Formats are enums in java, so they are all uppercase if to_formats.include? format @citero::to(Formats::valueOf(format.upcase)) else @citero::to(CitationStyles::valueOf(format.upcase)) end #rescue any exceptions, if the error is not caught in JAR, most likely a #problem with the source format rescue Exception => e raise ArgumentError, "Missing a source format. Use from_[format] first." end
[ "def", "to", "format", "if", "to_formats", ".", "include?", "format", "@citero", "::", "to", "(", "Formats", "::", "valueOf", "(", "format", ".", "upcase", ")", ")", "else", "@citero", "::", "to", "(", "CitationStyles", "::", "valueOf", "(", "format", ".", "upcase", ")", ")", "end", "rescue", "Exception", "=>", "e", "raise", "ArgumentError", ",", "\"Missing a source format. Use from_[format] first.\"", "end" ]
The to method is private, it takes in a format and gets the appropriate Format java class and then calls the to method in the Citero java object and returns the return value as a string.
[ "The", "to", "method", "is", "private", "it", "takes", "in", "a", "format", "and", "gets", "the", "appropriate", "Format", "java", "class", "and", "then", "calls", "the", "to", "method", "in", "the", "Citero", "java", "object", "and", "returns", "the", "return", "value", "as", "a", "string", "." ]
ddf1142a8a05cb1e7153d1887239fe913df563ce
https://github.com/NYULibraries/citero-jruby/blob/ddf1142a8a05cb1e7153d1887239fe913df563ce/lib/citero-jruby/base.rb#L69-L80
train
postmodern/data_paths
lib/data_paths/finders.rb
DataPaths.Finders.each_data_path
def each_data_path(path) return enum_for(:each_data_path,path) unless block_given? DataPaths.paths.each do |dir| full_path = File.join(dir,path) yield(full_path) if File.exists?(full_path) end end
ruby
def each_data_path(path) return enum_for(:each_data_path,path) unless block_given? DataPaths.paths.each do |dir| full_path = File.join(dir,path) yield(full_path) if File.exists?(full_path) end end
[ "def", "each_data_path", "(", "path", ")", "return", "enum_for", "(", ":each_data_path", ",", "path", ")", "unless", "block_given?", "DataPaths", ".", "paths", ".", "each", "do", "|", "dir", "|", "full_path", "=", "File", ".", "join", "(", "dir", ",", "path", ")", "yield", "(", "full_path", ")", "if", "File", ".", "exists?", "(", "full_path", ")", "end", "end" ]
Passes all existing data paths for the specified path, within the data directories, to the given block. @param [String] path The path to search for in all data directories. @yield [potential_path] The given block will be passed every existing combination of the given path and the data directories. @yieldparam [String] potential_path An existing data path. @return [Enumerator] If no block is given, an Enumerator object will be returned.
[ "Passes", "all", "existing", "data", "paths", "for", "the", "specified", "path", "within", "the", "data", "directories", "to", "the", "given", "block", "." ]
17938884593b458b90b591a353686945884749d6
https://github.com/postmodern/data_paths/blob/17938884593b458b90b591a353686945884749d6/lib/data_paths/finders.rb#L24-L32
train
postmodern/data_paths
lib/data_paths/finders.rb
DataPaths.Finders.each_data_file
def each_data_file(path) return enum_for(:each_data_file,path) unless block_given? each_data_path(path) do |full_path| yield(full_path) if File.file?(full_path) end end
ruby
def each_data_file(path) return enum_for(:each_data_file,path) unless block_given? each_data_path(path) do |full_path| yield(full_path) if File.file?(full_path) end end
[ "def", "each_data_file", "(", "path", ")", "return", "enum_for", "(", ":each_data_file", ",", "path", ")", "unless", "block_given?", "each_data_path", "(", "path", ")", "do", "|", "full_path", "|", "yield", "(", "full_path", ")", "if", "File", ".", "file?", "(", "full_path", ")", "end", "end" ]
Finds all occurrences of a given file path, within all data directories. @param [String] path The file path to search for. @yield [data_file] If a block is given, it will be passed every found path. @yieldparam [String] data_file The path of a file within a data directory. @return [Enumerator] If no block is given, an Enumerator object will be returned.
[ "Finds", "all", "occurrences", "of", "a", "given", "file", "path", "within", "all", "data", "directories", "." ]
17938884593b458b90b591a353686945884749d6
https://github.com/postmodern/data_paths/blob/17938884593b458b90b591a353686945884749d6/lib/data_paths/finders.rb#L126-L132
train
postmodern/data_paths
lib/data_paths/finders.rb
DataPaths.Finders.each_data_dir
def each_data_dir(path) return enum_for(:each_data_dir,path) unless block_given? each_data_path(path) do |full_path| yield(full_path) if File.directory?(full_path) end end
ruby
def each_data_dir(path) return enum_for(:each_data_dir,path) unless block_given? each_data_path(path) do |full_path| yield(full_path) if File.directory?(full_path) end end
[ "def", "each_data_dir", "(", "path", ")", "return", "enum_for", "(", ":each_data_dir", ",", "path", ")", "unless", "block_given?", "each_data_path", "(", "path", ")", "do", "|", "full_path", "|", "yield", "(", "full_path", ")", "if", "File", ".", "directory?", "(", "full_path", ")", "end", "end" ]
Finds all occurrences of a given directory path, within all data directories. @param [String] path The directory path to search for. @yield [data_dir] If a block is given, it will be passed every found path. @yieldparam [String] data_dir The path of a directory within a data directory. @return [Enumerator] If no block is given, an Enumerator object will be returned.
[ "Finds", "all", "occurrences", "of", "a", "given", "directory", "path", "within", "all", "data", "directories", "." ]
17938884593b458b90b591a353686945884749d6
https://github.com/postmodern/data_paths/blob/17938884593b458b90b591a353686945884749d6/lib/data_paths/finders.rb#L182-L188
train
postmodern/data_paths
lib/data_paths/finders.rb
DataPaths.Finders.glob_data_paths
def glob_data_paths(pattern,&block) return enum_for(:glob_data_paths,pattern).to_a unless block_given? DataPaths.paths.each do |path| Dir.glob(File.join(path,pattern),&block) end end
ruby
def glob_data_paths(pattern,&block) return enum_for(:glob_data_paths,pattern).to_a unless block_given? DataPaths.paths.each do |path| Dir.glob(File.join(path,pattern),&block) end end
[ "def", "glob_data_paths", "(", "pattern", ",", "&", "block", ")", "return", "enum_for", "(", ":glob_data_paths", ",", "pattern", ")", ".", "to_a", "unless", "block_given?", "DataPaths", ".", "paths", ".", "each", "do", "|", "path", "|", "Dir", ".", "glob", "(", "File", ".", "join", "(", "path", ",", "pattern", ")", ",", "&", "block", ")", "end", "end" ]
Finds all paths that match a given pattern, within all data directories. @param [String] pattern The path glob pattern to search with. @yield [path] If a block is given, it will be passed every matching path. @yieldparam [String] path The path of a matching file within a data directory. @return [Array<String>] If no block is given, the matching paths found within all data directories will be returned. @since 0.3.0
[ "Finds", "all", "paths", "that", "match", "a", "given", "pattern", "within", "all", "data", "directories", "." ]
17938884593b458b90b591a353686945884749d6
https://github.com/postmodern/data_paths/blob/17938884593b458b90b591a353686945884749d6/lib/data_paths/finders.rb#L224-L230
train
brianpattison/motion-loco
lib/motion-loco/resizable.rb
Loco.Resizable.initWithFrame
def initWithFrame(properties={}) if properties.is_a? Hash # Set the initial property values from the given hash super(CGRect.new) initialize_bindings set_properties(properties) else super(properties) end view_setup self end
ruby
def initWithFrame(properties={}) if properties.is_a? Hash # Set the initial property values from the given hash super(CGRect.new) initialize_bindings set_properties(properties) else super(properties) end view_setup self end
[ "def", "initWithFrame", "(", "properties", "=", "{", "}", ")", "if", "properties", ".", "is_a?", "Hash", "super", "(", "CGRect", ".", "new", ")", "initialize_bindings", "set_properties", "(", "properties", ")", "else", "super", "(", "properties", ")", "end", "view_setup", "self", "end" ]
Create new instance from a hash of properties with values. @param [Object] frame The CGRect or a Hash of properties.
[ "Create", "new", "instance", "from", "a", "hash", "of", "properties", "with", "values", "." ]
d6f4ca32d6e13dc4d325d2838c0e2685fa0fa4f6
https://github.com/brianpattison/motion-loco/blob/d6f4ca32d6e13dc4d325d2838c0e2685fa0fa4f6/lib/motion-loco/resizable.rb#L113-L125
train
karlfreeman/multi_sync
lib/multi_sync/client.rb
MultiSync.Client.add_target
def add_target(clazz, options = {}) # TODO: friendly pool names? pool_name = Celluloid.uuid supervisor.pool(clazz, as: pool_name, args: [options], size: MultiSync.target_pool_size) pool_name end
ruby
def add_target(clazz, options = {}) # TODO: friendly pool names? pool_name = Celluloid.uuid supervisor.pool(clazz, as: pool_name, args: [options], size: MultiSync.target_pool_size) pool_name end
[ "def", "add_target", "(", "clazz", ",", "options", "=", "{", "}", ")", "pool_name", "=", "Celluloid", ".", "uuid", "supervisor", ".", "pool", "(", "clazz", ",", "as", ":", "pool_name", ",", "args", ":", "[", "options", "]", ",", "size", ":", "MultiSync", ".", "target_pool_size", ")", "pool_name", "end" ]
Initialize a new Client object @param options [Hash]
[ "Initialize", "a", "new", "Client", "object" ]
a24b0865a00093701d2b04888a930b453185686d
https://github.com/karlfreeman/multi_sync/blob/a24b0865a00093701d2b04888a930b453185686d/lib/multi_sync/client.rb#L39-L44
train
charypar/cyclical
lib/cyclical/rules/yearly_rule.rb
Cyclical.YearlyRule.potential_next
def potential_next(current, base) candidate = super(current, base) return candidate if (base.year - candidate.year).to_i % @interval == 0 years = ((base.year - candidate.year).to_i % @interval) (candidate + years.years).beginning_of_year end
ruby
def potential_next(current, base) candidate = super(current, base) return candidate if (base.year - candidate.year).to_i % @interval == 0 years = ((base.year - candidate.year).to_i % @interval) (candidate + years.years).beginning_of_year end
[ "def", "potential_next", "(", "current", ",", "base", ")", "candidate", "=", "super", "(", "current", ",", "base", ")", "return", "candidate", "if", "(", "base", ".", "year", "-", "candidate", ".", "year", ")", ".", "to_i", "%", "@interval", "==", "0", "years", "=", "(", "(", "base", ".", "year", "-", "candidate", ".", "year", ")", ".", "to_i", "%", "@interval", ")", "(", "candidate", "+", "years", ".", "years", ")", ".", "beginning_of_year", "end" ]
closest valid date
[ "closest", "valid", "date" ]
8e45b8f83e2dd59fcad01e220412bb361867f5c6
https://github.com/charypar/cyclical/blob/8e45b8f83e2dd59fcad01e220412bb361867f5c6/lib/cyclical/rules/yearly_rule.rb#L26-L33
train
sanichi/icu_tournament
lib/icu_tournament/tournament.rb
ICU.Tournament.fed=
def fed=(fed) obj = ICU::Federation.find(fed) @fed = obj ? obj.code : nil raise "invalid tournament federation (#{fed})" if @fed.nil? && fed.to_s.strip.length > 0 end
ruby
def fed=(fed) obj = ICU::Federation.find(fed) @fed = obj ? obj.code : nil raise "invalid tournament federation (#{fed})" if @fed.nil? && fed.to_s.strip.length > 0 end
[ "def", "fed", "=", "(", "fed", ")", "obj", "=", "ICU", "::", "Federation", ".", "find", "(", "fed", ")", "@fed", "=", "obj", "?", "obj", ".", "code", ":", "nil", "raise", "\"invalid tournament federation (#{fed})\"", "if", "@fed", ".", "nil?", "&&", "fed", ".", "to_s", ".", "strip", ".", "length", ">", "0", "end" ]
Constructor. Name and start date must be supplied. Other attributes are optional. Set the tournament federation. Can be _nil_.
[ "Constructor", ".", "Name", "and", "start", "date", "must", "be", "supplied", ".", "Other", "attributes", "are", "optional", ".", "Set", "the", "tournament", "federation", ".", "Can", "be", "_nil_", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L218-L222
train
sanichi/icu_tournament
lib/icu_tournament/tournament.rb
ICU.Tournament.add_round_date
def add_round_date(round_date) round_date = round_date.to_s.strip parsed_date = Util::Date.parse(round_date) raise "invalid round date (#{round_date})" unless parsed_date @round_dates << parsed_date end
ruby
def add_round_date(round_date) round_date = round_date.to_s.strip parsed_date = Util::Date.parse(round_date) raise "invalid round date (#{round_date})" unless parsed_date @round_dates << parsed_date end
[ "def", "add_round_date", "(", "round_date", ")", "round_date", "=", "round_date", ".", "to_s", ".", "strip", "parsed_date", "=", "Util", "::", "Date", ".", "parse", "(", "round_date", ")", "raise", "\"invalid round date (#{round_date})\"", "unless", "parsed_date", "@round_dates", "<<", "parsed_date", "end" ]
Add a round date.
[ "Add", "a", "round", "date", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L225-L230
train
sanichi/icu_tournament
lib/icu_tournament/tournament.rb
ICU.Tournament.tie_breaks=
def tie_breaks=(tie_breaks) raise "argument error - always set tie breaks to an array" unless tie_breaks.class == Array @tie_breaks = tie_breaks.map do |str| tb = ICU::TieBreak.identify(str) raise "invalid tie break method '#{str}'" unless tb tb.id end end
ruby
def tie_breaks=(tie_breaks) raise "argument error - always set tie breaks to an array" unless tie_breaks.class == Array @tie_breaks = tie_breaks.map do |str| tb = ICU::TieBreak.identify(str) raise "invalid tie break method '#{str}'" unless tb tb.id end end
[ "def", "tie_breaks", "=", "(", "tie_breaks", ")", "raise", "\"argument error - always set tie breaks to an array\"", "unless", "tie_breaks", ".", "class", "==", "Array", "@tie_breaks", "=", "tie_breaks", ".", "map", "do", "|", "str", "|", "tb", "=", "ICU", "::", "TieBreak", ".", "identify", "(", "str", ")", "raise", "\"invalid tie break method '#{str}'\"", "unless", "tb", "tb", ".", "id", "end", "end" ]
Canonicalise the names in the tie break array.
[ "Canonicalise", "the", "names", "in", "the", "tie", "break", "array", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L271-L278
train
sanichi/icu_tournament
lib/icu_tournament/tournament.rb
ICU.Tournament.add_player
def add_player(player) raise "invalid player" unless player.class == ICU::Player raise "player number (#{player.num}) should be unique" if @player[player.num] @player[player.num] = player end
ruby
def add_player(player) raise "invalid player" unless player.class == ICU::Player raise "player number (#{player.num}) should be unique" if @player[player.num] @player[player.num] = player end
[ "def", "add_player", "(", "player", ")", "raise", "\"invalid player\"", "unless", "player", ".", "class", "==", "ICU", "::", "Player", "raise", "\"player number (#{player.num}) should be unique\"", "if", "@player", "[", "player", ".", "num", "]", "@player", "[", "player", ".", "num", "]", "=", "player", "end" ]
Add a new player to the tournament. Must have a unique player number.
[ "Add", "a", "new", "player", "to", "the", "tournament", ".", "Must", "have", "a", "unique", "player", "number", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L281-L285
train
sanichi/icu_tournament
lib/icu_tournament/tournament.rb
ICU.Tournament.rerank
def rerank tie_break_methods, tie_break_order, tie_break_hash = tie_break_data @player.values.sort do |a,b| cmp = 0 tie_break_methods.each do |m| cmp = (tie_break_hash[m][a.num] <=> tie_break_hash[m][b.num]) * tie_break_order[m] if cmp == 0 end cmp end.each_with_index do |p,i| p.rank = i + 1 end self end
ruby
def rerank tie_break_methods, tie_break_order, tie_break_hash = tie_break_data @player.values.sort do |a,b| cmp = 0 tie_break_methods.each do |m| cmp = (tie_break_hash[m][a.num] <=> tie_break_hash[m][b.num]) * tie_break_order[m] if cmp == 0 end cmp end.each_with_index do |p,i| p.rank = i + 1 end self end
[ "def", "rerank", "tie_break_methods", ",", "tie_break_order", ",", "tie_break_hash", "=", "tie_break_data", "@player", ".", "values", ".", "sort", "do", "|", "a", ",", "b", "|", "cmp", "=", "0", "tie_break_methods", ".", "each", "do", "|", "m", "|", "cmp", "=", "(", "tie_break_hash", "[", "m", "]", "[", "a", ".", "num", "]", "<=>", "tie_break_hash", "[", "m", "]", "[", "b", ".", "num", "]", ")", "*", "tie_break_order", "[", "m", "]", "if", "cmp", "==", "0", "end", "cmp", "end", ".", "each_with_index", "do", "|", "p", ",", "i", "|", "p", ".", "rank", "=", "i", "+", "1", "end", "self", "end" ]
Rerank the tournament by score first and if necessary using a configurable tie breaker method.
[ "Rerank", "the", "tournament", "by", "score", "first", "and", "if", "necessary", "using", "a", "configurable", "tie", "breaker", "method", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L319-L331
train
sanichi/icu_tournament
lib/icu_tournament/tournament.rb
ICU.Tournament.renumber
def renumber(criterion = :rank) if (criterion.class == Hash) # Undocumentted feature - supply your own hash. map = criterion else # Official way of reordering. map = Hash.new # Renumber by rank only if possible. criterion = criterion.to_s.downcase if criterion == 'rank' begin check_ranks rescue criterion = 'name' end end # Decide how to renumber. if criterion == 'rank' # Renumber by rank. @player.values.each{ |p| map[p.num] = p.rank } elsif criterion == 'order' # Just keep the existing numbers in order. @player.values.sort_by{ |p| p.num }.each_with_index{ |p, i| map[p.num] = i + 1 } else # Renumber by name alphabetically. @player.values.sort_by{ |p| p.name }.each_with_index{ |p, i| map[p.num] = i + 1 } end end # Apply renumbering. @teams.each{ |t| t.renumber(map) } @player = @player.values.inject({}) do |hash, player| player.renumber(map) hash[player.num] = player hash end # Return self for chaining. self end
ruby
def renumber(criterion = :rank) if (criterion.class == Hash) # Undocumentted feature - supply your own hash. map = criterion else # Official way of reordering. map = Hash.new # Renumber by rank only if possible. criterion = criterion.to_s.downcase if criterion == 'rank' begin check_ranks rescue criterion = 'name' end end # Decide how to renumber. if criterion == 'rank' # Renumber by rank. @player.values.each{ |p| map[p.num] = p.rank } elsif criterion == 'order' # Just keep the existing numbers in order. @player.values.sort_by{ |p| p.num }.each_with_index{ |p, i| map[p.num] = i + 1 } else # Renumber by name alphabetically. @player.values.sort_by{ |p| p.name }.each_with_index{ |p, i| map[p.num] = i + 1 } end end # Apply renumbering. @teams.each{ |t| t.renumber(map) } @player = @player.values.inject({}) do |hash, player| player.renumber(map) hash[player.num] = player hash end # Return self for chaining. self end
[ "def", "renumber", "(", "criterion", "=", ":rank", ")", "if", "(", "criterion", ".", "class", "==", "Hash", ")", "map", "=", "criterion", "else", "map", "=", "Hash", ".", "new", "criterion", "=", "criterion", ".", "to_s", ".", "downcase", "if", "criterion", "==", "'rank'", "begin", "check_ranks", "rescue", "criterion", "=", "'name'", "end", "end", "if", "criterion", "==", "'rank'", "@player", ".", "values", ".", "each", "{", "|", "p", "|", "map", "[", "p", ".", "num", "]", "=", "p", ".", "rank", "}", "elsif", "criterion", "==", "'order'", "@player", ".", "values", ".", "sort_by", "{", "|", "p", "|", "p", ".", "num", "}", ".", "each_with_index", "{", "|", "p", ",", "i", "|", "map", "[", "p", ".", "num", "]", "=", "i", "+", "1", "}", "else", "@player", ".", "values", ".", "sort_by", "{", "|", "p", "|", "p", ".", "name", "}", ".", "each_with_index", "{", "|", "p", ",", "i", "|", "map", "[", "p", ".", "num", "]", "=", "i", "+", "1", "}", "end", "end", "@teams", ".", "each", "{", "|", "t", "|", "t", ".", "renumber", "(", "map", ")", "}", "@player", "=", "@player", ".", "values", ".", "inject", "(", "{", "}", ")", "do", "|", "hash", ",", "player", "|", "player", ".", "renumber", "(", "map", ")", "hash", "[", "player", ".", "num", "]", "=", "player", "hash", "end", "self", "end" ]
Renumber the players according to a given criterion.
[ "Renumber", "the", "players", "according", "to", "a", "given", "criterion", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L343-L380
train
sanichi/icu_tournament
lib/icu_tournament/tournament.rb
ICU.Tournament.validate!
def validate!(options={}) begin check_ranks rescue rerank end if options[:rerank] check_players check_rounds check_dates check_teams check_ranks(:allow_none => true) check_type(options[:type]) if options[:type] true end
ruby
def validate!(options={}) begin check_ranks rescue rerank end if options[:rerank] check_players check_rounds check_dates check_teams check_ranks(:allow_none => true) check_type(options[:type]) if options[:type] true end
[ "def", "validate!", "(", "options", "=", "{", "}", ")", "begin", "check_ranks", "rescue", "rerank", "end", "if", "options", "[", ":rerank", "]", "check_players", "check_rounds", "check_dates", "check_teams", "check_ranks", "(", ":allow_none", "=>", "true", ")", "check_type", "(", "options", "[", ":type", "]", ")", "if", "options", "[", ":type", "]", "true", "end" ]
Raise an exception if a tournament is not valid. The _rerank_ option can be set to _true_ to rank the tournament just prior to the test if ranking data is missing or inconsistent.
[ "Raise", "an", "exception", "if", "a", "tournament", "is", "not", "valid", ".", "The", "_rerank_", "option", "can", "be", "set", "to", "_true_", "to", "rank", "the", "tournament", "just", "prior", "to", "the", "test", "if", "ranking", "data", "is", "missing", "or", "inconsistent", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L395-L404
train
sanichi/icu_tournament
lib/icu_tournament/tournament.rb
ICU.Tournament.serialize
def serialize(format, arg={}) serializer = case format.to_s.downcase when 'krause' then ICU::Tournament::Krause.new when 'foreigncsv' then ICU::Tournament::ForeignCSV.new when 'spexport' then ICU::Tournament::SPExport.new when '' then raise "no format supplied" else raise "unsupported serialisation format: '#{format}'" end serializer.serialize(self, arg) end
ruby
def serialize(format, arg={}) serializer = case format.to_s.downcase when 'krause' then ICU::Tournament::Krause.new when 'foreigncsv' then ICU::Tournament::ForeignCSV.new when 'spexport' then ICU::Tournament::SPExport.new when '' then raise "no format supplied" else raise "unsupported serialisation format: '#{format}'" end serializer.serialize(self, arg) end
[ "def", "serialize", "(", "format", ",", "arg", "=", "{", "}", ")", "serializer", "=", "case", "format", ".", "to_s", ".", "downcase", "when", "'krause'", "then", "ICU", "::", "Tournament", "::", "Krause", ".", "new", "when", "'foreigncsv'", "then", "ICU", "::", "Tournament", "::", "ForeignCSV", ".", "new", "when", "'spexport'", "then", "ICU", "::", "Tournament", "::", "SPExport", ".", "new", "when", "''", "then", "raise", "\"no format supplied\"", "else", "raise", "\"unsupported serialisation format: '#{format}'\"", "end", "serializer", ".", "serialize", "(", "self", ",", "arg", ")", "end" ]
Convenience method to serialise the tournament into a supported format. Throws an exception unless the name of a supported format is supplied or if the tournament is unsuitable for serialisation in that format.
[ "Convenience", "method", "to", "serialise", "the", "tournament", "into", "a", "supported", "format", ".", "Throws", "an", "exception", "unless", "the", "name", "of", "a", "supported", "format", "is", "supplied", "or", "if", "the", "tournament", "is", "unsuitable", "for", "serialisation", "in", "that", "format", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L423-L432
train
sanichi/icu_tournament
lib/icu_tournament/tournament.rb
ICU.Tournament.check_players
def check_players raise "the number of players (#{@player.size}) must be at least 2" if @player.size < 2 ids = Hash.new fide_ids = Hash.new @player.each do |num, p| if p.id raise "duplicate ICU IDs, players #{p.num} and #{ids[p.id]}" if ids[p.id] ids[p.id] = num end if p.fide_id raise "duplicate FIDE IDs, players #{p.num} and #{fide_ids[p.fide_id]}" if fide_ids[p.fide_id] fide_ids[p.fide_id] = num end return if p.results.size == 0 p.results.each do |r| next unless r.opponent opponent = @player[r.opponent] raise "opponent #{r.opponent} of player #{num} is not in the tournament" unless opponent o = opponent.find_result(r.round) raise "opponent #{r.opponent} of player #{num} has no result in round #{r.round}" unless o score = r.rateable || o.rateable ? [] : [:score] raise "opponent's result (#{o.inspect}) is not reverse of player's (#{r.inspect})" unless o.reverse.eql?(r, :except => score) end end end
ruby
def check_players raise "the number of players (#{@player.size}) must be at least 2" if @player.size < 2 ids = Hash.new fide_ids = Hash.new @player.each do |num, p| if p.id raise "duplicate ICU IDs, players #{p.num} and #{ids[p.id]}" if ids[p.id] ids[p.id] = num end if p.fide_id raise "duplicate FIDE IDs, players #{p.num} and #{fide_ids[p.fide_id]}" if fide_ids[p.fide_id] fide_ids[p.fide_id] = num end return if p.results.size == 0 p.results.each do |r| next unless r.opponent opponent = @player[r.opponent] raise "opponent #{r.opponent} of player #{num} is not in the tournament" unless opponent o = opponent.find_result(r.round) raise "opponent #{r.opponent} of player #{num} has no result in round #{r.round}" unless o score = r.rateable || o.rateable ? [] : [:score] raise "opponent's result (#{o.inspect}) is not reverse of player's (#{r.inspect})" unless o.reverse.eql?(r, :except => score) end end end
[ "def", "check_players", "raise", "\"the number of players (#{@player.size}) must be at least 2\"", "if", "@player", ".", "size", "<", "2", "ids", "=", "Hash", ".", "new", "fide_ids", "=", "Hash", ".", "new", "@player", ".", "each", "do", "|", "num", ",", "p", "|", "if", "p", ".", "id", "raise", "\"duplicate ICU IDs, players #{p.num} and #{ids[p.id]}\"", "if", "ids", "[", "p", ".", "id", "]", "ids", "[", "p", ".", "id", "]", "=", "num", "end", "if", "p", ".", "fide_id", "raise", "\"duplicate FIDE IDs, players #{p.num} and #{fide_ids[p.fide_id]}\"", "if", "fide_ids", "[", "p", ".", "fide_id", "]", "fide_ids", "[", "p", ".", "fide_id", "]", "=", "num", "end", "return", "if", "p", ".", "results", ".", "size", "==", "0", "p", ".", "results", ".", "each", "do", "|", "r", "|", "next", "unless", "r", ".", "opponent", "opponent", "=", "@player", "[", "r", ".", "opponent", "]", "raise", "\"opponent #{r.opponent} of player #{num} is not in the tournament\"", "unless", "opponent", "o", "=", "opponent", ".", "find_result", "(", "r", ".", "round", ")", "raise", "\"opponent #{r.opponent} of player #{num} has no result in round #{r.round}\"", "unless", "o", "score", "=", "r", ".", "rateable", "||", "o", ".", "rateable", "?", "[", "]", ":", "[", ":score", "]", "raise", "\"opponent's result (#{o.inspect}) is not reverse of player's (#{r.inspect})\"", "unless", "o", ".", "reverse", ".", "eql?", "(", "r", ",", ":except", "=>", "score", ")", "end", "end", "end" ]
Check players.
[ "Check", "players", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L449-L473
train
sanichi/icu_tournament
lib/icu_tournament/tournament.rb
ICU.Tournament.check_rounds
def check_rounds round = Hash.new round_last = last_round @player.values.each do |p| p.results.each do |r| round[r.round] = true end end (1..round_last).each { |r| raise "there are no results for round #{r}" unless round[r] } if rounds raise "declared number of rounds is #{rounds} but there are results in later rounds, such as #{round_last}" if rounds < round_last raise "declared number of rounds is #{rounds} but there are no results with rounds greater than #{round_last}" if rounds > round_last else self.rounds = round_last end end
ruby
def check_rounds round = Hash.new round_last = last_round @player.values.each do |p| p.results.each do |r| round[r.round] = true end end (1..round_last).each { |r| raise "there are no results for round #{r}" unless round[r] } if rounds raise "declared number of rounds is #{rounds} but there are results in later rounds, such as #{round_last}" if rounds < round_last raise "declared number of rounds is #{rounds} but there are no results with rounds greater than #{round_last}" if rounds > round_last else self.rounds = round_last end end
[ "def", "check_rounds", "round", "=", "Hash", ".", "new", "round_last", "=", "last_round", "@player", ".", "values", ".", "each", "do", "|", "p", "|", "p", ".", "results", ".", "each", "do", "|", "r", "|", "round", "[", "r", ".", "round", "]", "=", "true", "end", "end", "(", "1", "..", "round_last", ")", ".", "each", "{", "|", "r", "|", "raise", "\"there are no results for round #{r}\"", "unless", "round", "[", "r", "]", "}", "if", "rounds", "raise", "\"declared number of rounds is #{rounds} but there are results in later rounds, such as #{round_last}\"", "if", "rounds", "<", "round_last", "raise", "\"declared number of rounds is #{rounds} but there are no results with rounds greater than #{round_last}\"", "if", "rounds", ">", "round_last", "else", "self", ".", "rounds", "=", "round_last", "end", "end" ]
Round should go from 1 to a maximum, there should be at least one result in every round and, if the number of rounds has been set, it should agree with the largest round from the results.
[ "Round", "should", "go", "from", "1", "to", "a", "maximum", "there", "should", "be", "at", "least", "one", "result", "in", "every", "round", "and", "if", "the", "number", "of", "rounds", "has", "been", "set", "it", "should", "agree", "with", "the", "largest", "round", "from", "the", "results", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament.rb#L477-L492
train