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
SpeciesFileGroup/taxonifi
lib/taxonifi/export/format/species_file.rb
Taxonifi::Export.SpeciesFile.tblRefs
def tblRefs sql = [] @headers = %w{RefID ActualYear Title PubID Verbatim} @name_collection.ref_collection.collection.each_with_index do |r,i| # Assumes the 0 "null" pub id is there pub_id = @pub_collection[r.publication] ? @pub_collection[r.publication] : 0 # Build a note based on "unused" properties note = [] if r.properties r.properties.keys.each do |k| note.push "#{k}: #{r.properties[k]}" if r.properties[k] && r.properties.length > 0 end end note = note.join("; ") note = @empty_quotes if note.length == 0 cols = { RefID: r.id, ContainingRefID: 0, Title: (r.title.nil? ? @empty_quotes : r.title), PubID: pub_id, Series: @empty_quotes, Volume: (r.volume ? r.volume : @empty_quotes), Issue: (r.number ? r.number : @empty_quotes), RefPages: r.page_string, # always a strings ActualYear: (r.year ? r.year : @empty_quotes), StatedYear: @empty_quotes, AccessCode: 0, Flags: 0, Note: note, LastUpdate: @time, LinkID: 0, ModifiedBy: @authorized_user_id, CiteDataStatus: 0, Verbatim: (r.full_citation ? r.full_citation : @empty_quotes) } sql << sql_insert_statement('tblRefs', cols) end sql.join("\n") end
ruby
def tblRefs sql = [] @headers = %w{RefID ActualYear Title PubID Verbatim} @name_collection.ref_collection.collection.each_with_index do |r,i| # Assumes the 0 "null" pub id is there pub_id = @pub_collection[r.publication] ? @pub_collection[r.publication] : 0 # Build a note based on "unused" properties note = [] if r.properties r.properties.keys.each do |k| note.push "#{k}: #{r.properties[k]}" if r.properties[k] && r.properties.length > 0 end end note = note.join("; ") note = @empty_quotes if note.length == 0 cols = { RefID: r.id, ContainingRefID: 0, Title: (r.title.nil? ? @empty_quotes : r.title), PubID: pub_id, Series: @empty_quotes, Volume: (r.volume ? r.volume : @empty_quotes), Issue: (r.number ? r.number : @empty_quotes), RefPages: r.page_string, # always a strings ActualYear: (r.year ? r.year : @empty_quotes), StatedYear: @empty_quotes, AccessCode: 0, Flags: 0, Note: note, LastUpdate: @time, LinkID: 0, ModifiedBy: @authorized_user_id, CiteDataStatus: 0, Verbatim: (r.full_citation ? r.full_citation : @empty_quotes) } sql << sql_insert_statement('tblRefs', cols) end sql.join("\n") end
[ "def", "tblRefs", "sql", "=", "[", "]", "@headers", "=", "%w{", "RefID", "ActualYear", "Title", "PubID", "Verbatim", "}", "@name_collection", ".", "ref_collection", ".", "collection", ".", "each_with_index", "do", "|", "r", ",", "i", "|", "pub_id", "=", "@pub_collection", "[", "r", ".", "publication", "]", "?", "@pub_collection", "[", "r", ".", "publication", "]", ":", "0", "note", "=", "[", "]", "if", "r", ".", "properties", "r", ".", "properties", ".", "keys", ".", "each", "do", "|", "k", "|", "note", ".", "push", "\"#{k}: #{r.properties[k]}\"", "if", "r", ".", "properties", "[", "k", "]", "&&", "r", ".", "properties", ".", "length", ">", "0", "end", "end", "note", "=", "note", ".", "join", "(", "\"; \"", ")", "note", "=", "@empty_quotes", "if", "note", ".", "length", "==", "0", "cols", "=", "{", "RefID", ":", "r", ".", "id", ",", "ContainingRefID", ":", "0", ",", "Title", ":", "(", "r", ".", "title", ".", "nil?", "?", "@empty_quotes", ":", "r", ".", "title", ")", ",", "PubID", ":", "pub_id", ",", "Series", ":", "@empty_quotes", ",", "Volume", ":", "(", "r", ".", "volume", "?", "r", ".", "volume", ":", "@empty_quotes", ")", ",", "Issue", ":", "(", "r", ".", "number", "?", "r", ".", "number", ":", "@empty_quotes", ")", ",", "RefPages", ":", "r", ".", "page_string", ",", "ActualYear", ":", "(", "r", ".", "year", "?", "r", ".", "year", ":", "@empty_quotes", ")", ",", "StatedYear", ":", "@empty_quotes", ",", "AccessCode", ":", "0", ",", "Flags", ":", "0", ",", "Note", ":", "note", ",", "LastUpdate", ":", "@time", ",", "LinkID", ":", "0", ",", "ModifiedBy", ":", "@authorized_user_id", ",", "CiteDataStatus", ":", "0", ",", "Verbatim", ":", "(", "r", ".", "full_citation", "?", "r", ".", "full_citation", ":", "@empty_quotes", ")", "}", "sql", "<<", "sql_insert_statement", "(", "'tblRefs'", ",", "cols", ")", "end", "sql", ".", "join", "(", "\"\\n\"", ")", "end" ]
Generate a tblRefs string.
[ "Generate", "a", "tblRefs", "string", "." ]
100dc94e7ffd378f6a81381c13768e35b2b65bf2
https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/export/format/species_file.rb#L202-L242
train
SpeciesFileGroup/taxonifi
lib/taxonifi/export/format/species_file.rb
Taxonifi::Export.SpeciesFile.tblPubs
def tblPubs sql = [] @headers = %w{PubID PrefID PubType ShortName FullName Note LastUpdate ModifiedBy Publisher PlacePublished PubRegID Status StartYear EndYear BHL} # Hackish should build this elsewhere, but degrades OK pubs = @name_collection.ref_collection.collection.collect{|r| r.publication}.compact.uniq pubs.each_with_index do |p, i| cols = { PubID: i + 1, PrefID: 0, PubType: 1, ShortName: "unknown_#{i}", # Unique constraint FullName: p, Note: @empty_quotes, LastUpdate: @time, ModifiedBy: @authorized_user_id, Publisher: @empty_quotes, PlacePublished: @empty_quotes, PubRegID: 0, Status: 0, StartYear: 0, EndYear: 0, BHL: 0 } @pub_collection.merge!(p => i + 1) sql << sql_insert_statement('tblPubs', cols) end sql.join("\n") end
ruby
def tblPubs sql = [] @headers = %w{PubID PrefID PubType ShortName FullName Note LastUpdate ModifiedBy Publisher PlacePublished PubRegID Status StartYear EndYear BHL} # Hackish should build this elsewhere, but degrades OK pubs = @name_collection.ref_collection.collection.collect{|r| r.publication}.compact.uniq pubs.each_with_index do |p, i| cols = { PubID: i + 1, PrefID: 0, PubType: 1, ShortName: "unknown_#{i}", # Unique constraint FullName: p, Note: @empty_quotes, LastUpdate: @time, ModifiedBy: @authorized_user_id, Publisher: @empty_quotes, PlacePublished: @empty_quotes, PubRegID: 0, Status: 0, StartYear: 0, EndYear: 0, BHL: 0 } @pub_collection.merge!(p => i + 1) sql << sql_insert_statement('tblPubs', cols) end sql.join("\n") end
[ "def", "tblPubs", "sql", "=", "[", "]", "@headers", "=", "%w{", "PubID", "PrefID", "PubType", "ShortName", "FullName", "Note", "LastUpdate", "ModifiedBy", "Publisher", "PlacePublished", "PubRegID", "Status", "StartYear", "EndYear", "BHL", "}", "pubs", "=", "@name_collection", ".", "ref_collection", ".", "collection", ".", "collect", "{", "|", "r", "|", "r", ".", "publication", "}", ".", "compact", ".", "uniq", "pubs", ".", "each_with_index", "do", "|", "p", ",", "i", "|", "cols", "=", "{", "PubID", ":", "i", "+", "1", ",", "PrefID", ":", "0", ",", "PubType", ":", "1", ",", "ShortName", ":", "\"unknown_#{i}\"", ",", "FullName", ":", "p", ",", "Note", ":", "@empty_quotes", ",", "LastUpdate", ":", "@time", ",", "ModifiedBy", ":", "@authorized_user_id", ",", "Publisher", ":", "@empty_quotes", ",", "PlacePublished", ":", "@empty_quotes", ",", "PubRegID", ":", "0", ",", "Status", ":", "0", ",", "StartYear", ":", "0", ",", "EndYear", ":", "0", ",", "BHL", ":", "0", "}", "@pub_collection", ".", "merge!", "(", "p", "=>", "i", "+", "1", ")", "sql", "<<", "sql_insert_statement", "(", "'tblPubs'", ",", "cols", ")", "end", "sql", ".", "join", "(", "\"\\n\"", ")", "end" ]
Generate tblPubs SQL
[ "Generate", "tblPubs", "SQL" ]
100dc94e7ffd378f6a81381c13768e35b2b65bf2
https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/export/format/species_file.rb#L245-L274
train
SpeciesFileGroup/taxonifi
lib/taxonifi/export/format/species_file.rb
Taxonifi::Export.SpeciesFile.tblPeople
def tblPeople @headers = %w{PersonID FamilyName GivenNames GivenInitials Suffix Role LastUpdate ModifiedBy} sql = [] @name_collection.ref_collection.all_authors.each do |a| cols = { PersonID: a.id, FamilyName: (a.last_name.length > 0 ? a.last_name : "Unknown"), GivenNames: a.first_name || @empty_quotes, GivenInitials: a.initials_string || @empty_quotes, Suffix: a.suffix || @empty_quotes, Role: 1, # authors LastUpdate: @time, ModifiedBy: @authorized_user_id } sql << sql_insert_statement('tblPeople', cols) end sql.join("\n") end
ruby
def tblPeople @headers = %w{PersonID FamilyName GivenNames GivenInitials Suffix Role LastUpdate ModifiedBy} sql = [] @name_collection.ref_collection.all_authors.each do |a| cols = { PersonID: a.id, FamilyName: (a.last_name.length > 0 ? a.last_name : "Unknown"), GivenNames: a.first_name || @empty_quotes, GivenInitials: a.initials_string || @empty_quotes, Suffix: a.suffix || @empty_quotes, Role: 1, # authors LastUpdate: @time, ModifiedBy: @authorized_user_id } sql << sql_insert_statement('tblPeople', cols) end sql.join("\n") end
[ "def", "tblPeople", "@headers", "=", "%w{", "PersonID", "FamilyName", "GivenNames", "GivenInitials", "Suffix", "Role", "LastUpdate", "ModifiedBy", "}", "sql", "=", "[", "]", "@name_collection", ".", "ref_collection", ".", "all_authors", ".", "each", "do", "|", "a", "|", "cols", "=", "{", "PersonID", ":", "a", ".", "id", ",", "FamilyName", ":", "(", "a", ".", "last_name", ".", "length", ">", "0", "?", "a", ".", "last_name", ":", "\"Unknown\"", ")", ",", "GivenNames", ":", "a", ".", "first_name", "||", "@empty_quotes", ",", "GivenInitials", ":", "a", ".", "initials_string", "||", "@empty_quotes", ",", "Suffix", ":", "a", ".", "suffix", "||", "@empty_quotes", ",", "Role", ":", "1", ",", "LastUpdate", ":", "@time", ",", "ModifiedBy", ":", "@authorized_user_id", "}", "sql", "<<", "sql_insert_statement", "(", "'tblPeople'", ",", "cols", ")", "end", "sql", ".", "join", "(", "\"\\n\"", ")", "end" ]
Generate tblPeople string.
[ "Generate", "tblPeople", "string", "." ]
100dc94e7ffd378f6a81381c13768e35b2b65bf2
https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/export/format/species_file.rb#L277-L294
train
SpeciesFileGroup/taxonifi
lib/taxonifi/export/format/species_file.rb
Taxonifi::Export.SpeciesFile.tblRefAuthors
def tblRefAuthors @headers = %w{RefID PersonID SeqNum AuthorCount LastUpdate ModifiedBy} sql = [] @name_collection.ref_collection.collection.each do |r| r.authors.each_with_index do |x, i| cols = { RefID: r.id, PersonID: x.id, SeqNum: i + 1, AuthorCount: r.authors.size + 1, LastUpdate: @time, ModifiedBy: @authorized_user_id } sql << sql_insert_statement('tblRefAuthors', cols) end end sql.join("\n") end
ruby
def tblRefAuthors @headers = %w{RefID PersonID SeqNum AuthorCount LastUpdate ModifiedBy} sql = [] @name_collection.ref_collection.collection.each do |r| r.authors.each_with_index do |x, i| cols = { RefID: r.id, PersonID: x.id, SeqNum: i + 1, AuthorCount: r.authors.size + 1, LastUpdate: @time, ModifiedBy: @authorized_user_id } sql << sql_insert_statement('tblRefAuthors', cols) end end sql.join("\n") end
[ "def", "tblRefAuthors", "@headers", "=", "%w{", "RefID", "PersonID", "SeqNum", "AuthorCount", "LastUpdate", "ModifiedBy", "}", "sql", "=", "[", "]", "@name_collection", ".", "ref_collection", ".", "collection", ".", "each", "do", "|", "r", "|", "r", ".", "authors", ".", "each_with_index", "do", "|", "x", ",", "i", "|", "cols", "=", "{", "RefID", ":", "r", ".", "id", ",", "PersonID", ":", "x", ".", "id", ",", "SeqNum", ":", "i", "+", "1", ",", "AuthorCount", ":", "r", ".", "authors", ".", "size", "+", "1", ",", "LastUpdate", ":", "@time", ",", "ModifiedBy", ":", "@authorized_user_id", "}", "sql", "<<", "sql_insert_statement", "(", "'tblRefAuthors'", ",", "cols", ")", "end", "end", "sql", ".", "join", "(", "\"\\n\"", ")", "end" ]
Generate tblRefAuthors string.
[ "Generate", "tblRefAuthors", "string", "." ]
100dc94e7ffd378f6a81381c13768e35b2b65bf2
https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/export/format/species_file.rb#L297-L314
train
SpeciesFileGroup/taxonifi
lib/taxonifi/export/format/species_file.rb
Taxonifi::Export.SpeciesFile.tblCites
def tblCites @headers = %w{TaxonNameID SeqNum RefID NomenclatorID LastUpdate ModifiedBy NewNameStatus CitePages Note TypeClarification CurrentConcept ConceptChange InfoFlags InfoFlagStatus PolynomialStatus} sql = [] @name_collection.citations.keys.each do |name_id| seq_num = 1 @name_collection.citations[name_id].each do |ref_id, nomenclator_index, properties| cols = { TaxonNameID: name_id, SeqNum: seq_num, RefID: ref_id, NomenclatorID: nomenclator_index, LastUpdate: @time, ModifiedBy: @authorized_user_id, CitePages: (properties[:cite_pages] ? properties[:cite_pages] : @empty_quotes), NewNameStatus: 0, Note: (properties[:note] ? properties[:note] : @empty_quotes), TypeClarification: 0, # We might derive more data from this CurrentConcept: (properties[:current_concept] == true ? 1 : 0), # Boolean, right? ConceptChange: 0, # Unspecified InfoFlags: 0, # InfoFlagStatus: 1, # 1 => needs review PolynomialStatus: 0 } sql << sql_insert_statement('tblCites', cols) seq_num += 1 end end sql.join("\n") end
ruby
def tblCites @headers = %w{TaxonNameID SeqNum RefID NomenclatorID LastUpdate ModifiedBy NewNameStatus CitePages Note TypeClarification CurrentConcept ConceptChange InfoFlags InfoFlagStatus PolynomialStatus} sql = [] @name_collection.citations.keys.each do |name_id| seq_num = 1 @name_collection.citations[name_id].each do |ref_id, nomenclator_index, properties| cols = { TaxonNameID: name_id, SeqNum: seq_num, RefID: ref_id, NomenclatorID: nomenclator_index, LastUpdate: @time, ModifiedBy: @authorized_user_id, CitePages: (properties[:cite_pages] ? properties[:cite_pages] : @empty_quotes), NewNameStatus: 0, Note: (properties[:note] ? properties[:note] : @empty_quotes), TypeClarification: 0, # We might derive more data from this CurrentConcept: (properties[:current_concept] == true ? 1 : 0), # Boolean, right? ConceptChange: 0, # Unspecified InfoFlags: 0, # InfoFlagStatus: 1, # 1 => needs review PolynomialStatus: 0 } sql << sql_insert_statement('tblCites', cols) seq_num += 1 end end sql.join("\n") end
[ "def", "tblCites", "@headers", "=", "%w{", "TaxonNameID", "SeqNum", "RefID", "NomenclatorID", "LastUpdate", "ModifiedBy", "NewNameStatus", "CitePages", "Note", "TypeClarification", "CurrentConcept", "ConceptChange", "InfoFlags", "InfoFlagStatus", "PolynomialStatus", "}", "sql", "=", "[", "]", "@name_collection", ".", "citations", ".", "keys", ".", "each", "do", "|", "name_id", "|", "seq_num", "=", "1", "@name_collection", ".", "citations", "[", "name_id", "]", ".", "each", "do", "|", "ref_id", ",", "nomenclator_index", ",", "properties", "|", "cols", "=", "{", "TaxonNameID", ":", "name_id", ",", "SeqNum", ":", "seq_num", ",", "RefID", ":", "ref_id", ",", "NomenclatorID", ":", "nomenclator_index", ",", "LastUpdate", ":", "@time", ",", "ModifiedBy", ":", "@authorized_user_id", ",", "CitePages", ":", "(", "properties", "[", ":cite_pages", "]", "?", "properties", "[", ":cite_pages", "]", ":", "@empty_quotes", ")", ",", "NewNameStatus", ":", "0", ",", "Note", ":", "(", "properties", "[", ":note", "]", "?", "properties", "[", ":note", "]", ":", "@empty_quotes", ")", ",", "TypeClarification", ":", "0", ",", "CurrentConcept", ":", "(", "properties", "[", ":current_concept", "]", "==", "true", "?", "1", ":", "0", ")", ",", "ConceptChange", ":", "0", ",", "InfoFlags", ":", "0", ",", "InfoFlagStatus", ":", "1", ",", "PolynomialStatus", ":", "0", "}", "sql", "<<", "sql_insert_statement", "(", "'tblCites'", ",", "cols", ")", "seq_num", "+=", "1", "end", "end", "sql", ".", "join", "(", "\"\\n\"", ")", "end" ]
Generate tblCites string.
[ "Generate", "tblCites", "string", "." ]
100dc94e7ffd378f6a81381c13768e35b2b65bf2
https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/export/format/species_file.rb#L317-L346
train
SpeciesFileGroup/taxonifi
lib/taxonifi/export/format/species_file.rb
Taxonifi::Export.SpeciesFile.tblTypeSpecies
def tblTypeSpecies @headers = %w{GenusNameID SpeciesNameID Reason AuthorityRefID FirstFamGrpNameID LastUpdate ModifiedBy NewID} sql = [] names = @name_collection.names_at_rank('genus') + @name_collection.names_at_rank('subgenus') names.each do |n| if n.properties[:type_species_id] ref = get_ref(n) # ref = @by_author_reference_index[n.author_year_index] next if ref.nil? cols = { GenusNameID: n.id , SpeciesNameID: n.properties[:type_species_id], Reason: 0 , AuthorityRefID: 0 , FirstFamGrpNameID: 0 , LastUpdate: @time , ModifiedBy: @authorized_user_id , NewID: 0 # What is this? } sql << sql_insert_statement('tblTypeSpecies', cols) end end sql.join("\n") end
ruby
def tblTypeSpecies @headers = %w{GenusNameID SpeciesNameID Reason AuthorityRefID FirstFamGrpNameID LastUpdate ModifiedBy NewID} sql = [] names = @name_collection.names_at_rank('genus') + @name_collection.names_at_rank('subgenus') names.each do |n| if n.properties[:type_species_id] ref = get_ref(n) # ref = @by_author_reference_index[n.author_year_index] next if ref.nil? cols = { GenusNameID: n.id , SpeciesNameID: n.properties[:type_species_id], Reason: 0 , AuthorityRefID: 0 , FirstFamGrpNameID: 0 , LastUpdate: @time , ModifiedBy: @authorized_user_id , NewID: 0 # What is this? } sql << sql_insert_statement('tblTypeSpecies', cols) end end sql.join("\n") end
[ "def", "tblTypeSpecies", "@headers", "=", "%w{", "GenusNameID", "SpeciesNameID", "Reason", "AuthorityRefID", "FirstFamGrpNameID", "LastUpdate", "ModifiedBy", "NewID", "}", "sql", "=", "[", "]", "names", "=", "@name_collection", ".", "names_at_rank", "(", "'genus'", ")", "+", "@name_collection", ".", "names_at_rank", "(", "'subgenus'", ")", "names", ".", "each", "do", "|", "n", "|", "if", "n", ".", "properties", "[", ":type_species_id", "]", "ref", "=", "get_ref", "(", "n", ")", "next", "if", "ref", ".", "nil?", "cols", "=", "{", "GenusNameID", ":", "n", ".", "id", ",", "SpeciesNameID", ":", "n", ".", "properties", "[", ":type_species_id", "]", ",", "Reason", ":", "0", ",", "AuthorityRefID", ":", "0", ",", "FirstFamGrpNameID", ":", "0", ",", "LastUpdate", ":", "@time", ",", "ModifiedBy", ":", "@authorized_user_id", ",", "NewID", ":", "0", "}", "sql", "<<", "sql_insert_statement", "(", "'tblTypeSpecies'", ",", "cols", ")", "end", "end", "sql", ".", "join", "(", "\"\\n\"", ")", "end" ]
Generate tblTypeSpecies string.
[ "Generate", "tblTypeSpecies", "string", "." ]
100dc94e7ffd378f6a81381c13768e35b2b65bf2
https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/export/format/species_file.rb#L349-L374
train
SpeciesFileGroup/taxonifi
lib/taxonifi/export/format/species_file.rb
Taxonifi::Export.SpeciesFile.tblNomenclator
def tblNomenclator @headers = %w{NomenclatorID GenusNameID SubgenusNameID SpeciesNameID SubspeciesNameID LastUpdate ModifiedBy SuitableForGenus SuitableForSpecies InfrasubspeciesNameID InfrasubKind} sql = [] i = 1 # Ugh, move build from here @name_collection.nomenclators.keys.each do |i| name = @name_collection.nomenclators[i] genus_id = @genus_names[name[0]] genus_id ||= 0 subgenus_id = @genus_names[name[1]] subgenus_id ||= 0 species_id = @species_names[name[2]] species_id ||= 0 subspecies_id = @species_names[name[3]] subspecies_id ||= 0 variety_id = @species_names[name[4]] variety_id ||= 0 cols = { NomenclatorID: i, GenusNameID: genus_id, SubgenusNameID: subgenus_id, SpeciesNameID: species_id, SubspeciesNameID: subspecies_id, InfrasubspeciesNameID: variety_id, InfrasubKind: (variety_id == 0 ? 0 : 2), LastUpdate: @time, ModifiedBy: @authorized_user_id, SuitableForGenus: 0, # Set in SF w test SuitableForSpecies: 0 # Set in SF w test } i += 1 sql << sql_insert_statement('tblNomenclator', cols) end sql.join("\n") end
ruby
def tblNomenclator @headers = %w{NomenclatorID GenusNameID SubgenusNameID SpeciesNameID SubspeciesNameID LastUpdate ModifiedBy SuitableForGenus SuitableForSpecies InfrasubspeciesNameID InfrasubKind} sql = [] i = 1 # Ugh, move build from here @name_collection.nomenclators.keys.each do |i| name = @name_collection.nomenclators[i] genus_id = @genus_names[name[0]] genus_id ||= 0 subgenus_id = @genus_names[name[1]] subgenus_id ||= 0 species_id = @species_names[name[2]] species_id ||= 0 subspecies_id = @species_names[name[3]] subspecies_id ||= 0 variety_id = @species_names[name[4]] variety_id ||= 0 cols = { NomenclatorID: i, GenusNameID: genus_id, SubgenusNameID: subgenus_id, SpeciesNameID: species_id, SubspeciesNameID: subspecies_id, InfrasubspeciesNameID: variety_id, InfrasubKind: (variety_id == 0 ? 0 : 2), LastUpdate: @time, ModifiedBy: @authorized_user_id, SuitableForGenus: 0, # Set in SF w test SuitableForSpecies: 0 # Set in SF w test } i += 1 sql << sql_insert_statement('tblNomenclator', cols) end sql.join("\n") end
[ "def", "tblNomenclator", "@headers", "=", "%w{", "NomenclatorID", "GenusNameID", "SubgenusNameID", "SpeciesNameID", "SubspeciesNameID", "LastUpdate", "ModifiedBy", "SuitableForGenus", "SuitableForSpecies", "InfrasubspeciesNameID", "InfrasubKind", "}", "sql", "=", "[", "]", "i", "=", "1", "@name_collection", ".", "nomenclators", ".", "keys", ".", "each", "do", "|", "i", "|", "name", "=", "@name_collection", ".", "nomenclators", "[", "i", "]", "genus_id", "=", "@genus_names", "[", "name", "[", "0", "]", "]", "genus_id", "||=", "0", "subgenus_id", "=", "@genus_names", "[", "name", "[", "1", "]", "]", "subgenus_id", "||=", "0", "species_id", "=", "@species_names", "[", "name", "[", "2", "]", "]", "species_id", "||=", "0", "subspecies_id", "=", "@species_names", "[", "name", "[", "3", "]", "]", "subspecies_id", "||=", "0", "variety_id", "=", "@species_names", "[", "name", "[", "4", "]", "]", "variety_id", "||=", "0", "cols", "=", "{", "NomenclatorID", ":", "i", ",", "GenusNameID", ":", "genus_id", ",", "SubgenusNameID", ":", "subgenus_id", ",", "SpeciesNameID", ":", "species_id", ",", "SubspeciesNameID", ":", "subspecies_id", ",", "InfrasubspeciesNameID", ":", "variety_id", ",", "InfrasubKind", ":", "(", "variety_id", "==", "0", "?", "0", ":", "2", ")", ",", "LastUpdate", ":", "@time", ",", "ModifiedBy", ":", "@authorized_user_id", ",", "SuitableForGenus", ":", "0", ",", "SuitableForSpecies", ":", "0", "}", "i", "+=", "1", "sql", "<<", "sql_insert_statement", "(", "'tblNomenclator'", ",", "cols", ")", "end", "sql", ".", "join", "(", "\"\\n\"", ")", "end" ]
Must be called post tblGenusNames and tblSpeciesNames. Some records are not used but can be cleaned by SF
[ "Must", "be", "called", "post", "tblGenusNames", "and", "tblSpeciesNames", ".", "Some", "records", "are", "not", "used", "but", "can", "be", "cleaned", "by", "SF" ]
100dc94e7ffd378f6a81381c13768e35b2b65bf2
https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/export/format/species_file.rb#L411-L448
train
jmcaffee/exceltocsv
lib/exceltocsv/excel_file.rb
ExcelToCsv.ExcelFile.empty_row?
def empty_row?(row) is_empty = true row.each do |item| is_empty = false if item && !item.empty? end is_empty end
ruby
def empty_row?(row) is_empty = true row.each do |item| is_empty = false if item && !item.empty? end is_empty end
[ "def", "empty_row?", "(", "row", ")", "is_empty", "=", "true", "row", ".", "each", "do", "|", "item", "|", "is_empty", "=", "false", "if", "item", "&&", "!", "item", ".", "empty?", "end", "is_empty", "end" ]
Return true if row contains no data
[ "Return", "true", "if", "row", "contains", "no", "data" ]
e93baed66baf4d7a0e341d8504bed3a9bf55ff55
https://github.com/jmcaffee/exceltocsv/blob/e93baed66baf4d7a0e341d8504bed3a9bf55ff55/lib/exceltocsv/excel_file.rb#L176-L182
train
jmcaffee/exceltocsv
lib/exceltocsv/excel_file.rb
ExcelToCsv.ExcelFile.truncate_decimal
def truncate_decimal(a_cell) if(a_cell.is_a?(Numeric)) a_cell = truncate_decimal_to_string(a_cell, 3) # Truncate zeros (unless there is only 1 decimal place) # eg. 12.10 => 12.1 # 12.0 => 12.0 a_cell = BigDecimal.new(a_cell).to_s("F") end a_cell end
ruby
def truncate_decimal(a_cell) if(a_cell.is_a?(Numeric)) a_cell = truncate_decimal_to_string(a_cell, 3) # Truncate zeros (unless there is only 1 decimal place) # eg. 12.10 => 12.1 # 12.0 => 12.0 a_cell = BigDecimal.new(a_cell).to_s("F") end a_cell end
[ "def", "truncate_decimal", "(", "a_cell", ")", "if", "(", "a_cell", ".", "is_a?", "(", "Numeric", ")", ")", "a_cell", "=", "truncate_decimal_to_string", "(", "a_cell", ",", "3", ")", "a_cell", "=", "BigDecimal", ".", "new", "(", "a_cell", ")", ".", "to_s", "(", "\"F\"", ")", "end", "a_cell", "end" ]
Truncates a decimal to 3 decimal places if numeric and remove trailing zeros, if more than one decimal place. returns a string
[ "Truncates", "a", "decimal", "to", "3", "decimal", "places", "if", "numeric", "and", "remove", "trailing", "zeros", "if", "more", "than", "one", "decimal", "place", ".", "returns", "a", "string" ]
e93baed66baf4d7a0e341d8504bed3a9bf55ff55
https://github.com/jmcaffee/exceltocsv/blob/e93baed66baf4d7a0e341d8504bed3a9bf55ff55/lib/exceltocsv/excel_file.rb#L206-L215
train
jmcaffee/exceltocsv
lib/exceltocsv/excel_file.rb
ExcelToCsv.ExcelFile.clean_int_value
def clean_int_value(a_cell) if(a_cell.match(/\.[0]+$/)) cary = a_cell.split(".") a_cell = cary[0] end a_cell end
ruby
def clean_int_value(a_cell) if(a_cell.match(/\.[0]+$/)) cary = a_cell.split(".") a_cell = cary[0] end a_cell end
[ "def", "clean_int_value", "(", "a_cell", ")", "if", "(", "a_cell", ".", "match", "(", "/", "\\.", "/", ")", ")", "cary", "=", "a_cell", ".", "split", "(", "\".\"", ")", "a_cell", "=", "cary", "[", "0", "]", "end", "a_cell", "end" ]
If the result is n.000... Remove the unecessary zeros.
[ "If", "the", "result", "is", "n", ".", "000", "...", "Remove", "the", "unecessary", "zeros", "." ]
e93baed66baf4d7a0e341d8504bed3a9bf55ff55
https://github.com/jmcaffee/exceltocsv/blob/e93baed66baf4d7a0e341d8504bed3a9bf55ff55/lib/exceltocsv/excel_file.rb#L225-L231
train
rsb/fuelcell
lib/fuelcell/cli.rb
Fuelcell.Cli.parse
def parse(raw_args) cmd_args = cmd_args_extractor.call(raw_args) cmd = root.locate(cmd_args, raw_args) root.add_global_options(cmd) begin parser.call(cmd, cmd_args, raw_args) rescue => e shell.error e.message shell.failure_exit end end
ruby
def parse(raw_args) cmd_args = cmd_args_extractor.call(raw_args) cmd = root.locate(cmd_args, raw_args) root.add_global_options(cmd) begin parser.call(cmd, cmd_args, raw_args) rescue => e shell.error e.message shell.failure_exit end end
[ "def", "parse", "(", "raw_args", ")", "cmd_args", "=", "cmd_args_extractor", ".", "call", "(", "raw_args", ")", "cmd", "=", "root", ".", "locate", "(", "cmd_args", ",", "raw_args", ")", "root", ".", "add_global_options", "(", "cmd", ")", "begin", "parser", ".", "call", "(", "cmd", ",", "cmd_args", ",", "raw_args", ")", "rescue", "=>", "e", "shell", ".", "error", "e", ".", "message", "shell", ".", "failure_exit", "end", "end" ]
Initializes with a root command object When nothing is given we default to the script name otherwise you choose the name of the root command or the command itself Delegates all parsing responsiblities to a series of handlers, returning a structured hash needed to execute a command. The command being executed is determined by the CmdArgsStrategy unless you override it, it extracts all args upto the first option or ignore. The RootCommand is used to find the command using the extracted args, it accounts for sub commands. The parser Parser::ParsingStategy handles processing opts, args and ignored args @param raw_args [Array] cli args usually from ARGV @return [Hash] structured context for executing a command
[ "Initializes", "with", "a", "root", "command", "object" ]
2eaa994170fa2b9243e7dee6d7c2b21e12274f6e
https://github.com/rsb/fuelcell/blob/2eaa994170fa2b9243e7dee6d7c2b21e12274f6e/lib/fuelcell/cli.rb#L38-L48
train
rsb/fuelcell
lib/fuelcell/cli.rb
Fuelcell.Cli.execute
def execute(context) cmd = context[:cmd] opts = context[:opts] || {} args = context[:args] || [] cmd_args = context[:cmd_args] cli_shell = context[:shell] || shell unless cmd.callable? return root['help'].call(opts, cmd_args, shell) end cmd = handle_callable_option(root, cmd) cmd.call(opts, args, cli_shell) end
ruby
def execute(context) cmd = context[:cmd] opts = context[:opts] || {} args = context[:args] || [] cmd_args = context[:cmd_args] cli_shell = context[:shell] || shell unless cmd.callable? return root['help'].call(opts, cmd_args, shell) end cmd = handle_callable_option(root, cmd) cmd.call(opts, args, cli_shell) end
[ "def", "execute", "(", "context", ")", "cmd", "=", "context", "[", ":cmd", "]", "opts", "=", "context", "[", ":opts", "]", "||", "{", "}", "args", "=", "context", "[", ":args", "]", "||", "[", "]", "cmd_args", "=", "context", "[", ":cmd_args", "]", "cli_shell", "=", "context", "[", ":shell", "]", "||", "shell", "unless", "cmd", ".", "callable?", "return", "root", "[", "'help'", "]", ".", "call", "(", "opts", ",", "cmd_args", ",", "shell", ")", "end", "cmd", "=", "handle_callable_option", "(", "root", ",", "cmd", ")", "cmd", ".", "call", "(", "opts", ",", "args", ",", "cli_shell", ")", "end" ]
Executes the callable object in a command. All command callable object expect to be called the the options hash, arg hash and shell object. @param context [Hash] @return [Integer]
[ "Executes", "the", "callable", "object", "in", "a", "command", ".", "All", "command", "callable", "object", "expect", "to", "be", "called", "the", "the", "options", "hash", "arg", "hash", "and", "shell", "object", "." ]
2eaa994170fa2b9243e7dee6d7c2b21e12274f6e
https://github.com/rsb/fuelcell/blob/2eaa994170fa2b9243e7dee6d7c2b21e12274f6e/lib/fuelcell/cli.rb#L55-L69
train
gr4y/streambot
lib/streambot/oauth.rb
StreamBot.OAuth.get_access_token
def get_access_token # get saved access token if ::File.exists?(ACCESS_TOKEN) @access_token = ::YAML.load_file(ACCESS_TOKEN) end # if access token is nil, # then get a new initial token if @access_token.nil? get_initial_token ::File.open(ACCESS_TOKEN, 'w') do |out| YAML.dump(@access_token, out) end end end
ruby
def get_access_token # get saved access token if ::File.exists?(ACCESS_TOKEN) @access_token = ::YAML.load_file(ACCESS_TOKEN) end # if access token is nil, # then get a new initial token if @access_token.nil? get_initial_token ::File.open(ACCESS_TOKEN, 'w') do |out| YAML.dump(@access_token, out) end end end
[ "def", "get_access_token", "if", "::", "File", ".", "exists?", "(", "ACCESS_TOKEN", ")", "@access_token", "=", "::", "YAML", ".", "load_file", "(", "ACCESS_TOKEN", ")", "end", "if", "@access_token", ".", "nil?", "get_initial_token", "::", "File", ".", "open", "(", "ACCESS_TOKEN", ",", "'w'", ")", "do", "|", "out", "|", "YAML", ".", "dump", "(", "@access_token", ",", "out", ")", "end", "end", "end" ]
get the access token
[ "get", "the", "access", "token" ]
3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375
https://github.com/gr4y/streambot/blob/3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375/lib/streambot/oauth.rb#L52-L65
train
gr4y/streambot
lib/streambot/oauth.rb
StreamBot.OAuth.get_initial_token
def get_initial_token @request_token = get_request_token puts "Place \"#{@request_token.authorize_url}\" in your browser" print "Enter the number they give you: " pin = STDIN.readline.chomp @access_token = @request_token.get_access_token(:oauth_verifier => pin) end
ruby
def get_initial_token @request_token = get_request_token puts "Place \"#{@request_token.authorize_url}\" in your browser" print "Enter the number they give you: " pin = STDIN.readline.chomp @access_token = @request_token.get_access_token(:oauth_verifier => pin) end
[ "def", "get_initial_token", "@request_token", "=", "get_request_token", "puts", "\"Place \\\"#{@request_token.authorize_url}\\\" in your browser\"", "print", "\"Enter the number they give you: \"", "pin", "=", "STDIN", ".", "readline", ".", "chomp", "@access_token", "=", "@request_token", ".", "get_access_token", "(", ":oauth_verifier", "=>", "pin", ")", "end" ]
get the initial access token
[ "get", "the", "initial", "access", "token" ]
3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375
https://github.com/gr4y/streambot/blob/3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375/lib/streambot/oauth.rb#L68-L74
train
mccraigmccraig/rsxml
lib/rsxml/sexp.rb
Rsxml.Sexp.traverse
def traverse(sexp, visitor, context=Visitor::Context.new) element_name, attrs, children = decompose_sexp(sexp) non_ns_attrs, ns_bindings = Namespace::non_ns_attrs_ns_bindings(context.ns_stack, element_name, attrs) context.ns_stack.push(ns_bindings) eelement_name = Namespace::explode_qname(context.ns_stack, element_name) eattrs = Namespace::explode_attr_qnames(context.ns_stack, non_ns_attrs) begin visitor.element(context, eelement_name, eattrs, ns_bindings) do children.each_with_index do |child, i| if child.is_a?(Array) traverse(child, visitor, context) else visitor.text(context, child) end end end ensure context.ns_stack.pop end visitor end
ruby
def traverse(sexp, visitor, context=Visitor::Context.new) element_name, attrs, children = decompose_sexp(sexp) non_ns_attrs, ns_bindings = Namespace::non_ns_attrs_ns_bindings(context.ns_stack, element_name, attrs) context.ns_stack.push(ns_bindings) eelement_name = Namespace::explode_qname(context.ns_stack, element_name) eattrs = Namespace::explode_attr_qnames(context.ns_stack, non_ns_attrs) begin visitor.element(context, eelement_name, eattrs, ns_bindings) do children.each_with_index do |child, i| if child.is_a?(Array) traverse(child, visitor, context) else visitor.text(context, child) end end end ensure context.ns_stack.pop end visitor end
[ "def", "traverse", "(", "sexp", ",", "visitor", ",", "context", "=", "Visitor", "::", "Context", ".", "new", ")", "element_name", ",", "attrs", ",", "children", "=", "decompose_sexp", "(", "sexp", ")", "non_ns_attrs", ",", "ns_bindings", "=", "Namespace", "::", "non_ns_attrs_ns_bindings", "(", "context", ".", "ns_stack", ",", "element_name", ",", "attrs", ")", "context", ".", "ns_stack", ".", "push", "(", "ns_bindings", ")", "eelement_name", "=", "Namespace", "::", "explode_qname", "(", "context", ".", "ns_stack", ",", "element_name", ")", "eattrs", "=", "Namespace", "::", "explode_attr_qnames", "(", "context", ".", "ns_stack", ",", "non_ns_attrs", ")", "begin", "visitor", ".", "element", "(", "context", ",", "eelement_name", ",", "eattrs", ",", "ns_bindings", ")", "do", "children", ".", "each_with_index", "do", "|", "child", ",", "i", "|", "if", "child", ".", "is_a?", "(", "Array", ")", "traverse", "(", "child", ",", "visitor", ",", "context", ")", "else", "visitor", ".", "text", "(", "context", ",", "child", ")", "end", "end", "end", "ensure", "context", ".", "ns_stack", ".", "pop", "end", "visitor", "end" ]
pre-order traversal of the sexp, calling methods on the visitor with each node
[ "pre", "-", "order", "traversal", "of", "the", "sexp", "calling", "methods", "on", "the", "visitor", "with", "each", "node" ]
3699c186f01be476a5942d64cd5c39f4d6bbe175
https://github.com/mccraigmccraig/rsxml/blob/3699c186f01be476a5942d64cd5c39f4d6bbe175/lib/rsxml/sexp.rb#L8-L33
train
logankoester/errship
lib/errship.rb
Errship.Rescuers.errship_standard
def errship_standard(errship_scope = false) flash[:error] ||= I18n.t('errship.standard') render :template => '/errship/standard.html.erb', :layout => 'application', :locals => { :status_code => 500, :errship_scope => errship_scope }, :status => (Errship.status_code_success ? 200 : 500) end
ruby
def errship_standard(errship_scope = false) flash[:error] ||= I18n.t('errship.standard') render :template => '/errship/standard.html.erb', :layout => 'application', :locals => { :status_code => 500, :errship_scope => errship_scope }, :status => (Errship.status_code_success ? 200 : 500) end
[ "def", "errship_standard", "(", "errship_scope", "=", "false", ")", "flash", "[", ":error", "]", "||=", "I18n", ".", "t", "(", "'errship.standard'", ")", "render", ":template", "=>", "'/errship/standard.html.erb'", ",", ":layout", "=>", "'application'", ",", ":locals", "=>", "{", ":status_code", "=>", "500", ",", ":errship_scope", "=>", "errship_scope", "}", ",", ":status", "=>", "(", "Errship", ".", "status_code_success", "?", "200", ":", "500", ")", "end" ]
A blank page with just the layout and flash message, which can be redirected to when all else fails.
[ "A", "blank", "page", "with", "just", "the", "layout", "and", "flash", "message", "which", "can", "be", "redirected", "to", "when", "all", "else", "fails", "." ]
9e344c25a5c6b619af1b9b177ad4f40b415b2182
https://github.com/logankoester/errship/blob/9e344c25a5c6b619af1b9b177ad4f40b415b2182/lib/errship.rb#L41-L47
train
logankoester/errship
lib/errship.rb
Errship.Rescuers.flashback
def flashback(error_message, exception = nil) airbrake_class.send(:notify, exception) if airbrake_class flash[:error] = error_message begin redirect_to :back rescue ActionController::RedirectBackError redirect_to error_path end end
ruby
def flashback(error_message, exception = nil) airbrake_class.send(:notify, exception) if airbrake_class flash[:error] = error_message begin redirect_to :back rescue ActionController::RedirectBackError redirect_to error_path end end
[ "def", "flashback", "(", "error_message", ",", "exception", "=", "nil", ")", "airbrake_class", ".", "send", "(", ":notify", ",", "exception", ")", "if", "airbrake_class", "flash", "[", ":error", "]", "=", "error_message", "begin", "redirect_to", ":back", "rescue", "ActionController", "::", "RedirectBackError", "redirect_to", "error_path", "end", "end" ]
Set the error flash and attempt to redirect back. If RedirectBackError is raised, redirect to error_path instead.
[ "Set", "the", "error", "flash", "and", "attempt", "to", "redirect", "back", ".", "If", "RedirectBackError", "is", "raised", "redirect", "to", "error_path", "instead", "." ]
9e344c25a5c6b619af1b9b177ad4f40b415b2182
https://github.com/logankoester/errship/blob/9e344c25a5c6b619af1b9b177ad4f40b415b2182/lib/errship.rb#L51-L59
train
devver/sdbtools
lib/sdbtools/operation.rb
SDBTools.Operation.each
def each Transaction.open(":#{method} operation") do |t| next_token = starting_token begin args = @args.dup args << next_token results = @sdb.send(@method, *args) yield(results, self) next_token = results[:next_token] end while next_token end end
ruby
def each Transaction.open(":#{method} operation") do |t| next_token = starting_token begin args = @args.dup args << next_token results = @sdb.send(@method, *args) yield(results, self) next_token = results[:next_token] end while next_token end end
[ "def", "each", "Transaction", ".", "open", "(", "\":#{method} operation\"", ")", "do", "|", "t", "|", "next_token", "=", "starting_token", "begin", "args", "=", "@args", ".", "dup", "args", "<<", "next_token", "results", "=", "@sdb", ".", "send", "(", "@method", ",", "*", "args", ")", "yield", "(", "results", ",", "self", ")", "next_token", "=", "results", "[", ":next_token", "]", "end", "while", "next_token", "end", "end" ]
Yields once for each result set, until there is no next token.
[ "Yields", "once", "for", "each", "result", "set", "until", "there", "is", "no", "next", "token", "." ]
194c082bf3f67eac6d5eb40cbc392957db4da269
https://github.com/devver/sdbtools/blob/194c082bf3f67eac6d5eb40cbc392957db4da269/lib/sdbtools/operation.rb#L20-L31
train
populr/subdomainbox
lib/subdomainbox/secure_csrf_token.rb
ActionController.RequestForgeryProtection.form_authenticity_token
def form_authenticity_token raise 'CSRF token secret must be defined' if CSRF_TOKEN_SECRET.nil? || CSRF_TOKEN_SECRET.empty? if request.session_options[:id].nil? || request.session_options[:id].empty? original_form_authenticity_token else Digest::SHA1.hexdigest("#{CSRF_TOKEN_SECRET}#{request.session_options[:id]}#{request.subdomain}") end end
ruby
def form_authenticity_token raise 'CSRF token secret must be defined' if CSRF_TOKEN_SECRET.nil? || CSRF_TOKEN_SECRET.empty? if request.session_options[:id].nil? || request.session_options[:id].empty? original_form_authenticity_token else Digest::SHA1.hexdigest("#{CSRF_TOKEN_SECRET}#{request.session_options[:id]}#{request.subdomain}") end end
[ "def", "form_authenticity_token", "raise", "'CSRF token secret must be defined'", "if", "CSRF_TOKEN_SECRET", ".", "nil?", "||", "CSRF_TOKEN_SECRET", ".", "empty?", "if", "request", ".", "session_options", "[", ":id", "]", ".", "nil?", "||", "request", ".", "session_options", "[", ":id", "]", ".", "empty?", "original_form_authenticity_token", "else", "Digest", "::", "SHA1", ".", "hexdigest", "(", "\"#{CSRF_TOKEN_SECRET}#{request.session_options[:id]}#{request.subdomain}\"", ")", "end", "end" ]
Sets the token value for the current session.
[ "Sets", "the", "token", "value", "for", "the", "current", "session", "." ]
b29730ba14a2fa0b62759422d1cef78646d96a93
https://github.com/populr/subdomainbox/blob/b29730ba14a2fa0b62759422d1cef78646d96a93/lib/subdomainbox/secure_csrf_token.rb#L11-L18
train
hubb/putio.rb
lib/putio/configurable.rb
Putio.Configurable.reset!
def reset! Putio::Configurable.keys.each do |key| public_send("#{key}=".to_sym, Putio::Defaults.options[key]) end self end
ruby
def reset! Putio::Configurable.keys.each do |key| public_send("#{key}=".to_sym, Putio::Defaults.options[key]) end self end
[ "def", "reset!", "Putio", "::", "Configurable", ".", "keys", ".", "each", "do", "|", "key", "|", "public_send", "(", "\"#{key}=\"", ".", "to_sym", ",", "Putio", "::", "Defaults", ".", "options", "[", "key", "]", ")", "end", "self", "end" ]
Reset configuration options to default values
[ "Reset", "configuration", "options", "to", "default", "values" ]
83c12aa81cdb99aaeb767e9cd27bd92f14abffeb
https://github.com/hubb/putio.rb/blob/83c12aa81cdb99aaeb767e9cd27bd92f14abffeb/lib/putio/configurable.rb#L32-L37
train
petebrowne/machined
lib/machined/context.rb
Machined.Context.add_machined_helpers
def add_machined_helpers # :nodoc: machined.context_helpers.each do |helper| case helper when Proc instance_eval &helper when Module extend helper end end end
ruby
def add_machined_helpers # :nodoc: machined.context_helpers.each do |helper| case helper when Proc instance_eval &helper when Module extend helper end end end
[ "def", "add_machined_helpers", "machined", ".", "context_helpers", ".", "each", "do", "|", "helper", "|", "case", "helper", "when", "Proc", "instance_eval", "&", "helper", "when", "Module", "extend", "helper", "end", "end", "end" ]
Loops through the helpers added to the Machined environment and adds them to the Context. Supports blocks and Modules.
[ "Loops", "through", "the", "helpers", "added", "to", "the", "Machined", "environment", "and", "adds", "them", "to", "the", "Context", ".", "Supports", "blocks", "and", "Modules", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/context.rb#L43-L52
train
mgsnova/crisp
lib/crisp/shell.rb
Crisp.Shell.run
def run runtime = Runtime.new buffer = '' while (line = Readline.readline(buffer.empty? ? ">> " : "?> ", true)) begin buffer << line ast = Parser.new.parse(buffer) puts "=> " + runtime.run(ast).to_s buffer = '' rescue Crisp::SyntaxError => e # noop end end end
ruby
def run runtime = Runtime.new buffer = '' while (line = Readline.readline(buffer.empty? ? ">> " : "?> ", true)) begin buffer << line ast = Parser.new.parse(buffer) puts "=> " + runtime.run(ast).to_s buffer = '' rescue Crisp::SyntaxError => e # noop end end end
[ "def", "run", "runtime", "=", "Runtime", ".", "new", "buffer", "=", "''", "while", "(", "line", "=", "Readline", ".", "readline", "(", "buffer", ".", "empty?", "?", "\">> \"", ":", "\"?> \"", ",", "true", ")", ")", "begin", "buffer", "<<", "line", "ast", "=", "Parser", ".", "new", ".", "parse", "(", "buffer", ")", "puts", "\"=> \"", "+", "runtime", ".", "run", "(", "ast", ")", ".", "to_s", "buffer", "=", "''", "rescue", "Crisp", "::", "SyntaxError", "=>", "e", "end", "end", "end" ]
start the shell
[ "start", "the", "shell" ]
0b3695de59258971b8b39998602c5b6e9f10623b
https://github.com/mgsnova/crisp/blob/0b3695de59258971b8b39998602c5b6e9f10623b/lib/crisp/shell.rb#L9-L23
train
mtnsat/zerg
zerg/lib/zerg/gem_plugin.rb
ZergGemPlugin.Manager.load
def load(needs = {}) needs = needs.merge({"zergrush" => INCLUDE}) Gem::Specification.each { |gem| # don't load gems more than once next if @gems.has_key? gem.name check = needs.dup # rolls through the depends and inverts anything it finds gem.dependencies.each do |dep| # this will fail if a gem is depended more than once if check.has_key? dep.name check[dep.name] = !check[dep.name] end end # now since excluded gems start as true, inverting them # makes them false so we'll skip this gem if any excludes are found if (check.select {|name,test| !test}).length == 0 # looks like no needs were set to false, so it's good if gem.metadata["zergrushplugin"] != nil require File.join(gem.gem_dir, "lib", gem.name, "init.rb") @gems[gem.name] = gem.gem_dir end end } return nil end
ruby
def load(needs = {}) needs = needs.merge({"zergrush" => INCLUDE}) Gem::Specification.each { |gem| # don't load gems more than once next if @gems.has_key? gem.name check = needs.dup # rolls through the depends and inverts anything it finds gem.dependencies.each do |dep| # this will fail if a gem is depended more than once if check.has_key? dep.name check[dep.name] = !check[dep.name] end end # now since excluded gems start as true, inverting them # makes them false so we'll skip this gem if any excludes are found if (check.select {|name,test| !test}).length == 0 # looks like no needs were set to false, so it's good if gem.metadata["zergrushplugin"] != nil require File.join(gem.gem_dir, "lib", gem.name, "init.rb") @gems[gem.name] = gem.gem_dir end end } return nil end
[ "def", "load", "(", "needs", "=", "{", "}", ")", "needs", "=", "needs", ".", "merge", "(", "{", "\"zergrush\"", "=>", "INCLUDE", "}", ")", "Gem", "::", "Specification", ".", "each", "{", "|", "gem", "|", "next", "if", "@gems", ".", "has_key?", "gem", ".", "name", "check", "=", "needs", ".", "dup", "gem", ".", "dependencies", ".", "each", "do", "|", "dep", "|", "if", "check", ".", "has_key?", "dep", ".", "name", "check", "[", "dep", ".", "name", "]", "=", "!", "check", "[", "dep", ".", "name", "]", "end", "end", "if", "(", "check", ".", "select", "{", "|", "name", ",", "test", "|", "!", "test", "}", ")", ".", "length", "==", "0", "if", "gem", ".", "metadata", "[", "\"zergrushplugin\"", "]", "!=", "nil", "require", "File", ".", "join", "(", "gem", ".", "gem_dir", ",", "\"lib\"", ",", "gem", ".", "name", ",", "\"init.rb\"", ")", "@gems", "[", "gem", ".", "name", "]", "=", "gem", ".", "gem_dir", "end", "end", "}", "return", "nil", "end" ]
Responsible for going through the list of available gems and loading any plugins requested. It keeps track of what it's loaded already and won't load them again. It accepts one parameter which is a hash of gem depends that should include or exclude a gem from being loaded. A gem must depend on zergrush to be considered, but then each system has to add it's own INCLUDE to make sure that only plugins related to it are loaded. An example again comes from Mongrel. In order to load all Mongrel plugins: GemPlugin::Manager.instance.load "mongrel" => GemPlugin::INCLUDE Which will load all plugins that depend on mongrel AND zergrush. Now, one extra thing we do is we delay loading Rails Mongrel plugins until after rails is configured. Do do this the mongrel_rails script has: GemPlugin::Manager.instance.load "mongrel" => GemPlugin::INCLUDE, "rails" => GemPlugin::EXCLUDE The only thing to remember is that this is saying "include a plugin if it depends on zergrush, mongrel, but NOT rails". If a plugin also depends on other stuff then it's loaded just fine. Only zergrush, mongrel, and rails are ever used to determine if it should be included. NOTE: Currently RubyGems will run autorequire on gems that get required AND on their dependencies. This really messes with people running edge rails since activerecord or other stuff gets loaded for just touching a gem plugin. To prevent this load requires the full path to the "init.rb" file, which avoids the RubyGems autorequire magic.
[ "Responsible", "for", "going", "through", "the", "list", "of", "available", "gems", "and", "loading", "any", "plugins", "requested", ".", "It", "keeps", "track", "of", "what", "it", "s", "loaded", "already", "and", "won", "t", "load", "them", "again", "." ]
dd497665795c7b51a984ae050987a9c5421cd5eb
https://github.com/mtnsat/zerg/blob/dd497665795c7b51a984ae050987a9c5421cd5eb/zerg/lib/zerg/gem_plugin.rb#L161-L189
train
jmettraux/rufus-cloche
lib/rufus/cloche.rb
Rufus.Cloche.put
def put(doc, opts={}) opts = opts.inject({}) { |h, (k, v)| h[k.to_s] = v; h } doc = Rufus::Json.dup(doc) unless opts['update_rev'] # work with a copy, don't touch original type, key = doc['type'], doc['_id'] raise( ArgumentError.new("missing values for keys 'type' and/or '_id'") ) if type.nil? || key.nil? rev = (doc['_rev'] ||= -1) raise( ArgumentError.new("values for '_rev' must be positive integers") ) if rev.class != Fixnum && rev.class != Bignum r = lock(rev == -1 ? :create : :write, type, key) do |file| cur = do_get(file) return cur if cur && cur['_rev'] != doc['_rev'] return true if cur.nil? && doc['_rev'] != -1 doc['_rev'] += 1 File.open(file.path, 'wb') { |io| io.write(Rufus::Json.encode(doc)) } end r == false ? true : nil end
ruby
def put(doc, opts={}) opts = opts.inject({}) { |h, (k, v)| h[k.to_s] = v; h } doc = Rufus::Json.dup(doc) unless opts['update_rev'] # work with a copy, don't touch original type, key = doc['type'], doc['_id'] raise( ArgumentError.new("missing values for keys 'type' and/or '_id'") ) if type.nil? || key.nil? rev = (doc['_rev'] ||= -1) raise( ArgumentError.new("values for '_rev' must be positive integers") ) if rev.class != Fixnum && rev.class != Bignum r = lock(rev == -1 ? :create : :write, type, key) do |file| cur = do_get(file) return cur if cur && cur['_rev'] != doc['_rev'] return true if cur.nil? && doc['_rev'] != -1 doc['_rev'] += 1 File.open(file.path, 'wb') { |io| io.write(Rufus::Json.encode(doc)) } end r == false ? true : nil end
[ "def", "put", "(", "doc", ",", "opts", "=", "{", "}", ")", "opts", "=", "opts", ".", "inject", "(", "{", "}", ")", "{", "|", "h", ",", "(", "k", ",", "v", ")", "|", "h", "[", "k", ".", "to_s", "]", "=", "v", ";", "h", "}", "doc", "=", "Rufus", "::", "Json", ".", "dup", "(", "doc", ")", "unless", "opts", "[", "'update_rev'", "]", "type", ",", "key", "=", "doc", "[", "'type'", "]", ",", "doc", "[", "'_id'", "]", "raise", "(", "ArgumentError", ".", "new", "(", "\"missing values for keys 'type' and/or '_id'\"", ")", ")", "if", "type", ".", "nil?", "||", "key", ".", "nil?", "rev", "=", "(", "doc", "[", "'_rev'", "]", "||=", "-", "1", ")", "raise", "(", "ArgumentError", ".", "new", "(", "\"values for '_rev' must be positive integers\"", ")", ")", "if", "rev", ".", "class", "!=", "Fixnum", "&&", "rev", ".", "class", "!=", "Bignum", "r", "=", "lock", "(", "rev", "==", "-", "1", "?", ":create", ":", ":write", ",", "type", ",", "key", ")", "do", "|", "file", "|", "cur", "=", "do_get", "(", "file", ")", "return", "cur", "if", "cur", "&&", "cur", "[", "'_rev'", "]", "!=", "doc", "[", "'_rev'", "]", "return", "true", "if", "cur", ".", "nil?", "&&", "doc", "[", "'_rev'", "]", "!=", "-", "1", "doc", "[", "'_rev'", "]", "+=", "1", "File", ".", "open", "(", "file", ".", "path", ",", "'wb'", ")", "{", "|", "io", "|", "io", ".", "write", "(", "Rufus", "::", "Json", ".", "encode", "(", "doc", ")", ")", "}", "end", "r", "==", "false", "?", "true", ":", "nil", "end" ]
Creates a new 'cloche'. There are 2 options : * :dir : to specify the directory into which the cloche data is store * :nolock : when set to true, no flock is used On the Windows platform, :nolock is set to true automatically. Puts a document (Hash) under the cloche. If the document is brand new, it will be given a revision number '_rev' of 0. If the document already exists in the cloche and the version to put has an older (different) revision number than the one currently stored, put will fail and return the current version of the doc. If the put is successful, nil is returned.
[ "Creates", "a", "new", "cloche", "." ]
e038fa69ded7d3de85f151d12d111466aef97aab
https://github.com/jmettraux/rufus-cloche/blob/e038fa69ded7d3de85f151d12d111466aef97aab/lib/rufus/cloche.rb#L75-L108
train
jmettraux/rufus-cloche
lib/rufus/cloche.rb
Rufus.Cloche.get_many
def get_many(type, regex=nil, opts={}) opts = opts.inject({}) { |h, (k, v)| h[k.to_s] = v; h } d = dir_for(type) return (opts['count'] ? 0 : []) unless File.exist?(d) regexes = regex ? Array(regex) : nil docs = [] skipped = 0 limit = opts['limit'] skip = opts['skip'] count = opts['count'] ? 0 : nil files = Dir[File.join(d, '**', '*.json')].sort_by { |f| File.basename(f) } files = files.reverse if opts['descending'] files.each do |fn| key = File.basename(fn, '.json') if regexes.nil? or match?(key, regexes) skipped = skipped + 1 next if skip and skipped <= skip doc = get(type, key) next unless doc if count count = count + 1 else docs << doc end break if limit and docs.size >= limit end end # WARNING : there is a twist here, the filenames may have a different # sort order from actual _ids... #docs.sort { |doc0, doc1| doc0['_id'] <=> doc1['_id'] } # let's trust filename order count ? count : docs end
ruby
def get_many(type, regex=nil, opts={}) opts = opts.inject({}) { |h, (k, v)| h[k.to_s] = v; h } d = dir_for(type) return (opts['count'] ? 0 : []) unless File.exist?(d) regexes = regex ? Array(regex) : nil docs = [] skipped = 0 limit = opts['limit'] skip = opts['skip'] count = opts['count'] ? 0 : nil files = Dir[File.join(d, '**', '*.json')].sort_by { |f| File.basename(f) } files = files.reverse if opts['descending'] files.each do |fn| key = File.basename(fn, '.json') if regexes.nil? or match?(key, regexes) skipped = skipped + 1 next if skip and skipped <= skip doc = get(type, key) next unless doc if count count = count + 1 else docs << doc end break if limit and docs.size >= limit end end # WARNING : there is a twist here, the filenames may have a different # sort order from actual _ids... #docs.sort { |doc0, doc1| doc0['_id'] <=> doc1['_id'] } # let's trust filename order count ? count : docs end
[ "def", "get_many", "(", "type", ",", "regex", "=", "nil", ",", "opts", "=", "{", "}", ")", "opts", "=", "opts", ".", "inject", "(", "{", "}", ")", "{", "|", "h", ",", "(", "k", ",", "v", ")", "|", "h", "[", "k", ".", "to_s", "]", "=", "v", ";", "h", "}", "d", "=", "dir_for", "(", "type", ")", "return", "(", "opts", "[", "'count'", "]", "?", "0", ":", "[", "]", ")", "unless", "File", ".", "exist?", "(", "d", ")", "regexes", "=", "regex", "?", "Array", "(", "regex", ")", ":", "nil", "docs", "=", "[", "]", "skipped", "=", "0", "limit", "=", "opts", "[", "'limit'", "]", "skip", "=", "opts", "[", "'skip'", "]", "count", "=", "opts", "[", "'count'", "]", "?", "0", ":", "nil", "files", "=", "Dir", "[", "File", ".", "join", "(", "d", ",", "'**'", ",", "'*.json'", ")", "]", ".", "sort_by", "{", "|", "f", "|", "File", ".", "basename", "(", "f", ")", "}", "files", "=", "files", ".", "reverse", "if", "opts", "[", "'descending'", "]", "files", ".", "each", "do", "|", "fn", "|", "key", "=", "File", ".", "basename", "(", "fn", ",", "'.json'", ")", "if", "regexes", ".", "nil?", "or", "match?", "(", "key", ",", "regexes", ")", "skipped", "=", "skipped", "+", "1", "next", "if", "skip", "and", "skipped", "<=", "skip", "doc", "=", "get", "(", "type", ",", "key", ")", "next", "unless", "doc", "if", "count", "count", "=", "count", "+", "1", "else", "docs", "<<", "doc", "end", "break", "if", "limit", "and", "docs", ".", "size", ">=", "limit", "end", "end", "count", "?", "count", ":", "docs", "end" ]
Given a type, this method will return an array of all the documents for that type. A optional second parameter may be used to select, based on a regular expression, which documents to include (match on the key '_id'). Will return an empty Hash if there is no documents for a given type. == opts :skip and :limit are understood (pagination). If :count => true, the query will simply return the number of documents that matched.
[ "Given", "a", "type", "this", "method", "will", "return", "an", "array", "of", "all", "the", "documents", "for", "that", "type", "." ]
e038fa69ded7d3de85f151d12d111466aef97aab
https://github.com/jmettraux/rufus-cloche/blob/e038fa69ded7d3de85f151d12d111466aef97aab/lib/rufus/cloche.rb#L174-L223
train
Hermanverschooten/jquery_datepick
lib/jquery_datepick/form_helper.rb
JqueryDatepick.FormHelper.datepicker
def datepicker(object_name, method, options = {}, timepicker = false) input_tag = JqueryDatepick::Tags.new(object_name, method, self, options) dp_options, tf_options = input_tag.split_options(options) tf_options[:value] = input_tag.format_date(tf_options[:value], String.new(dp_options[:dateFormat])) if tf_options[:value] && !tf_options[:value].empty? && dp_options.has_key?(:dateFormat) html = input_tag.render method = timepicker ? "datetimepicker" : "datepicker" html += javascript_tag("jQuery(document).ready(function(){jQuery('##{input_tag.get_name_and_id(tf_options.stringify_keys)["id"]}').#{method}(#{dp_options.to_json})});") html.html_safe end
ruby
def datepicker(object_name, method, options = {}, timepicker = false) input_tag = JqueryDatepick::Tags.new(object_name, method, self, options) dp_options, tf_options = input_tag.split_options(options) tf_options[:value] = input_tag.format_date(tf_options[:value], String.new(dp_options[:dateFormat])) if tf_options[:value] && !tf_options[:value].empty? && dp_options.has_key?(:dateFormat) html = input_tag.render method = timepicker ? "datetimepicker" : "datepicker" html += javascript_tag("jQuery(document).ready(function(){jQuery('##{input_tag.get_name_and_id(tf_options.stringify_keys)["id"]}').#{method}(#{dp_options.to_json})});") html.html_safe end
[ "def", "datepicker", "(", "object_name", ",", "method", ",", "options", "=", "{", "}", ",", "timepicker", "=", "false", ")", "input_tag", "=", "JqueryDatepick", "::", "Tags", ".", "new", "(", "object_name", ",", "method", ",", "self", ",", "options", ")", "dp_options", ",", "tf_options", "=", "input_tag", ".", "split_options", "(", "options", ")", "tf_options", "[", ":value", "]", "=", "input_tag", ".", "format_date", "(", "tf_options", "[", ":value", "]", ",", "String", ".", "new", "(", "dp_options", "[", ":dateFormat", "]", ")", ")", "if", "tf_options", "[", ":value", "]", "&&", "!", "tf_options", "[", ":value", "]", ".", "empty?", "&&", "dp_options", ".", "has_key?", "(", ":dateFormat", ")", "html", "=", "input_tag", ".", "render", "method", "=", "timepicker", "?", "\"datetimepicker\"", ":", "\"datepicker\"", "html", "+=", "javascript_tag", "(", "\"jQuery(document).ready(function(){jQuery('##{input_tag.get_name_and_id(tf_options.stringify_keys)[\"id\"]}').#{method}(#{dp_options.to_json})});\"", ")", "html", ".", "html_safe", "end" ]
Mehtod that generates datepicker input field inside a form
[ "Mehtod", "that", "generates", "datepicker", "input", "field", "inside", "a", "form" ]
22fd5f4a1d5a95fb942427ae08e5078b293c969b
https://github.com/Hermanverschooten/jquery_datepick/blob/22fd5f4a1d5a95fb942427ae08e5078b293c969b/lib/jquery_datepick/form_helper.rb#L8-L16
train
richo/twat
lib/twat/options.rb
Twat.Options.default=
def default=(value) value = value.to_sym unless config.accounts.include?(value) raise NoSuchAccount end config[:default] = value config.save! end
ruby
def default=(value) value = value.to_sym unless config.accounts.include?(value) raise NoSuchAccount end config[:default] = value config.save! end
[ "def", "default", "=", "(", "value", ")", "value", "=", "value", ".", "to_sym", "unless", "config", ".", "accounts", ".", "include?", "(", "value", ")", "raise", "NoSuchAccount", "end", "config", "[", ":default", "]", "=", "value", "config", ".", "save!", "end" ]
This is deliberately not abstracted (it could be easily accessed from withing the method_missing method, but that will just lead to nastiness later when I implement colors, for example.
[ "This", "is", "deliberately", "not", "abstracted", "(", "it", "could", "be", "easily", "accessed", "from", "withing", "the", "method_missing", "method", "but", "that", "will", "just", "lead", "to", "nastiness", "later", "when", "I", "implement", "colors", "for", "example", "." ]
0354059c2d9643a8c3b855dbb18105fa80bf651e
https://github.com/richo/twat/blob/0354059c2d9643a8c3b855dbb18105fa80bf651e/lib/twat/options.rb#L55-L63
train
vojto/active_harmony
lib/active_harmony/queue.rb
ActiveHarmony.Queue.queue_push
def queue_push(object) queue_item = QueueItem.new( :kind => "push", :object_type => object.class.name, :object_local_id => object.id, :state => "new" ) queue_item.save end
ruby
def queue_push(object) queue_item = QueueItem.new( :kind => "push", :object_type => object.class.name, :object_local_id => object.id, :state => "new" ) queue_item.save end
[ "def", "queue_push", "(", "object", ")", "queue_item", "=", "QueueItem", ".", "new", "(", ":kind", "=>", "\"push\"", ",", ":object_type", "=>", "object", ".", "class", ".", "name", ",", ":object_local_id", "=>", "object", ".", "id", ",", ":state", "=>", "\"new\"", ")", "queue_item", ".", "save", "end" ]
Queues object for push @param [Object] Object
[ "Queues", "object", "for", "push" ]
03e5c67ea7a1f986c729001c4fec944bf116640f
https://github.com/vojto/active_harmony/blob/03e5c67ea7a1f986c729001c4fec944bf116640f/lib/active_harmony/queue.rb#L8-L14
train
vojto/active_harmony
lib/active_harmony/queue.rb
ActiveHarmony.Queue.queue_pull
def queue_pull(object_class, remote_id) queue_item = QueueItem.new( :kind => "pull", :object_type => object_class.name, :object_remote_id => remote_id, :state => "new" ) queue_item.save end
ruby
def queue_pull(object_class, remote_id) queue_item = QueueItem.new( :kind => "pull", :object_type => object_class.name, :object_remote_id => remote_id, :state => "new" ) queue_item.save end
[ "def", "queue_pull", "(", "object_class", ",", "remote_id", ")", "queue_item", "=", "QueueItem", ".", "new", "(", ":kind", "=>", "\"pull\"", ",", ":object_type", "=>", "object_class", ".", "name", ",", ":object_remote_id", "=>", "remote_id", ",", ":state", "=>", "\"new\"", ")", "queue_item", ".", "save", "end" ]
Queues object for pull @param [Class] Class of object @param [String] Remote ID for object
[ "Queues", "object", "for", "pull" ]
03e5c67ea7a1f986c729001c4fec944bf116640f
https://github.com/vojto/active_harmony/blob/03e5c67ea7a1f986c729001c4fec944bf116640f/lib/active_harmony/queue.rb#L20-L26
train
xufeisofly/organismo
lib/organismo/element_collection.rb
Organismo.ElementCollection.elements_by_source
def elements_by_source source_items.map.with_index do |source_item, index| Organismo::Element.new(source_item, index).create end end
ruby
def elements_by_source source_items.map.with_index do |source_item, index| Organismo::Element.new(source_item, index).create end end
[ "def", "elements_by_source", "source_items", ".", "map", ".", "with_index", "do", "|", "source_item", ",", "index", "|", "Organismo", "::", "Element", ".", "new", "(", "source_item", ",", "index", ")", ".", "create", "end", "end" ]
initialize elements items
[ "initialize", "elements", "items" ]
cc133fc1c6206cb0efbff28daa7c9309481cd03e
https://github.com/xufeisofly/organismo/blob/cc133fc1c6206cb0efbff28daa7c9309481cd03e/lib/organismo/element_collection.rb#L16-L20
train
mntnorv/puttext
lib/puttext/po_entry.rb
PutText.POEntry.to_s
def to_s str = String.new('') # Add comments str = add_comment(str, ':', @references.join(' ')) if references? str = add_comment(str, ',', @flags.join("\n")) if flags? # Add id and context str = add_string(str, 'msgctxt', @msgctxt) if @msgctxt str = add_string(str, 'msgid', @msgid) str = add_string(str, 'msgid_plural', @msgid_plural) if plural? str = add_translations(str) str end
ruby
def to_s str = String.new('') # Add comments str = add_comment(str, ':', @references.join(' ')) if references? str = add_comment(str, ',', @flags.join("\n")) if flags? # Add id and context str = add_string(str, 'msgctxt', @msgctxt) if @msgctxt str = add_string(str, 'msgid', @msgid) str = add_string(str, 'msgid_plural', @msgid_plural) if plural? str = add_translations(str) str end
[ "def", "to_s", "str", "=", "String", ".", "new", "(", "''", ")", "str", "=", "add_comment", "(", "str", ",", "':'", ",", "@references", ".", "join", "(", "' '", ")", ")", "if", "references?", "str", "=", "add_comment", "(", "str", ",", "','", ",", "@flags", ".", "join", "(", "\"\\n\"", ")", ")", "if", "flags?", "str", "=", "add_string", "(", "str", ",", "'msgctxt'", ",", "@msgctxt", ")", "if", "@msgctxt", "str", "=", "add_string", "(", "str", ",", "'msgid'", ",", "@msgid", ")", "str", "=", "add_string", "(", "str", ",", "'msgid_plural'", ",", "@msgid_plural", ")", "if", "plural?", "str", "=", "add_translations", "(", "str", ")", "str", "end" ]
Create a new POEntry @param [Hash] attrs @option attrs [String] :msgid the id of the string (the string that needs to be translated). Can include a context, separated from the id by {NS_SEPARATOR} or by the specified :separator. @option attrs [String] :msgid_plural the pluralized id of the string (the pluralized string that needs to be translated). @option attrs [String] :msgctxt the context of the string. @option attrs [Array<String>] :msgstr the translated strings. @option attrs [Array<String>] :references a list of files with line numbers, pointing to where the string was found. @option attrs [Array<String>] :flags a list of flags for this entry. @option attrs [String] :separator the separator of context from id in :msgid. Convert the entry to a string representation, to be written to a .po file @return [String] a string representation of the entry.
[ "Create", "a", "new", "POEntry" ]
c5c210dff4e11f714418b6b426dc9e2739fe9876
https://github.com/mntnorv/puttext/blob/c5c210dff4e11f714418b6b426dc9e2739fe9876/lib/puttext/po_entry.rb#L52-L66
train
justinkim/tf2r
lib/tf2r/raffle.rb
TF2R.Raffle.info
def info @info ||= {link_snippet: @link_snippet, title: title, description: description, start_time: start_time, end_time: end_time, win_chance: win_chance, current_entries: current_entries, max_entries: max_entries, is_done: is_done} end
ruby
def info @info ||= {link_snippet: @link_snippet, title: title, description: description, start_time: start_time, end_time: end_time, win_chance: win_chance, current_entries: current_entries, max_entries: max_entries, is_done: is_done} end
[ "def", "info", "@info", "||=", "{", "link_snippet", ":", "@link_snippet", ",", "title", ":", "title", ",", "description", ":", "description", ",", "start_time", ":", "start_time", ",", "end_time", ":", "end_time", ",", "win_chance", ":", "win_chance", ",", "current_entries", ":", "current_entries", ",", "max_entries", ":", "max_entries", ",", "is_done", ":", "is_done", "}", "end" ]
Gives information about the raffle. @example r = Raffle.new('kstzcbd') r.info #=> {: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, :win_chance=>0.1, :current_entries=>10, :max_entries=>10, :is_done=>true} @param page [Mechanize::Page] the raffle page. @return [Hash] a 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. * :win_chance (+Float+) — a participant's chance to win the raffle. Rounded to 5 digits. * :current_entries (+Fixnum+) — the current number of participants. * :max_entries (+Fixnum+) — the maximum number of particpants allowed. * :is_done (+Boolean+) — whether new users can enter the raffle.
[ "Gives", "information", "about", "the", "raffle", "." ]
20d9648fe1048d9b2a34064821d8c95aaff505da
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/raffle.rb#L46-L52
train
justinkim/tf2r
lib/tf2r/raffle.rb
TF2R.Raffle.populate_raffle_info
def populate_raffle_info threads = [] threads << Thread.new do @api_info = API.raffle_info(@link_snippet) end threads << Thread.new do page = @scraper.fetch(raffle_link(@link_snippet)) @scraper_info = @scraper.scrape_raffle(page) end threads.each { |t| t.join } end
ruby
def populate_raffle_info threads = [] threads << Thread.new do @api_info = API.raffle_info(@link_snippet) end threads << Thread.new do page = @scraper.fetch(raffle_link(@link_snippet)) @scraper_info = @scraper.scrape_raffle(page) end threads.each { |t| t.join } end
[ "def", "populate_raffle_info", "threads", "=", "[", "]", "threads", "<<", "Thread", ".", "new", "do", "@api_info", "=", "API", ".", "raffle_info", "(", "@link_snippet", ")", "end", "threads", "<<", "Thread", ".", "new", "do", "page", "=", "@scraper", ".", "fetch", "(", "raffle_link", "(", "@link_snippet", ")", ")", "@scraper_info", "=", "@scraper", ".", "scrape_raffle", "(", "page", ")", "end", "threads", ".", "each", "{", "|", "t", "|", "t", ".", "join", "}", "end" ]
Asynchronously makes network connections to TF2R to query its API and scrape the raffle page.
[ "Asynchronously", "makes", "network", "connections", "to", "TF2R", "to", "query", "its", "API", "and", "scrape", "the", "raffle", "page", "." ]
20d9648fe1048d9b2a34064821d8c95aaff505da
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/raffle.rb#L76-L87
train
justinkim/tf2r
lib/tf2r/raffle.rb
TF2R.Raffle.normalize_entries
def normalize_entries(entries) entries.map do |entry| entry[:steam_id] = extract_steam_id entry.delete('link') entry[:username] = entry.delete('name') entry[:color] = entry.delete('color').downcase.strip entry[:avatar_link] = entry.delete('avatar') end entries end
ruby
def normalize_entries(entries) entries.map do |entry| entry[:steam_id] = extract_steam_id entry.delete('link') entry[:username] = entry.delete('name') entry[:color] = entry.delete('color').downcase.strip entry[:avatar_link] = entry.delete('avatar') end entries end
[ "def", "normalize_entries", "(", "entries", ")", "entries", ".", "map", "do", "|", "entry", "|", "entry", "[", ":steam_id", "]", "=", "extract_steam_id", "entry", ".", "delete", "(", "'link'", ")", "entry", "[", ":username", "]", "=", "entry", ".", "delete", "(", "'name'", ")", "entry", "[", ":color", "]", "=", "entry", ".", "delete", "(", "'color'", ")", ".", "downcase", ".", "strip", "entry", "[", ":avatar_link", "]", "=", "entry", ".", "delete", "(", "'avatar'", ")", "end", "entries", "end" ]
Converts the representation of participants by TF2R's API into our own standard representation.
[ "Converts", "the", "representation", "of", "participants", "by", "TF2R", "s", "API", "into", "our", "own", "standard", "representation", "." ]
20d9648fe1048d9b2a34064821d8c95aaff505da
https://github.com/justinkim/tf2r/blob/20d9648fe1048d9b2a34064821d8c95aaff505da/lib/tf2r/raffle.rb#L96-L104
train
moviepilot/andromeda
lib/andromeda/spot.rb
Andromeda.Spot.post_to
def post_to(track, data, tags_in = {}) tags_in = (here.tags.identical_copy.update(tags_in) rescue tags_in) if here plan.post_data self, track, data, tags_in self end
ruby
def post_to(track, data, tags_in = {}) tags_in = (here.tags.identical_copy.update(tags_in) rescue tags_in) if here plan.post_data self, track, data, tags_in self end
[ "def", "post_to", "(", "track", ",", "data", ",", "tags_in", "=", "{", "}", ")", "tags_in", "=", "(", "here", ".", "tags", ".", "identical_copy", ".", "update", "(", "tags_in", ")", "rescue", "tags_in", ")", "if", "here", "plan", ".", "post_data", "self", ",", "track", ",", "data", ",", "tags_in", "self", "end" ]
Post data with the associated tags_in to this's spot's plan's method spot with name name and hint that the caller requested the spot activation to be executed on track tack @param [Track] track requested target track @param [Any] data any data event @param [Hash] tags to be passed along @return [self]
[ "Post", "data", "with", "the", "associated", "tags_in", "to", "this", "s", "spot", "s", "plan", "s", "method", "spot", "with", "name", "name", "and", "hint", "that", "the", "caller", "requested", "the", "spot", "activation", "to", "be", "executed", "on", "track", "tack" ]
68e6bac3cdb798046dbfa0e08314e7a40c938927
https://github.com/moviepilot/andromeda/blob/68e6bac3cdb798046dbfa0e08314e7a40c938927/lib/andromeda/spot.rb#L83-L87
train
fenton-project/fenton_shell
lib/fenton_shell/organization.rb
FentonShell.Organization.organization_create
def organization_create(global_options, options) result = Excon.post( "#{global_options[:fenton_server_url]}/organizations.json", body: organization_json(options), headers: { 'Content-Type' => 'application/json' } ) [result.status, JSON.parse(result.body)] end
ruby
def organization_create(global_options, options) result = Excon.post( "#{global_options[:fenton_server_url]}/organizations.json", body: organization_json(options), headers: { 'Content-Type' => 'application/json' } ) [result.status, JSON.parse(result.body)] end
[ "def", "organization_create", "(", "global_options", ",", "options", ")", "result", "=", "Excon", ".", "post", "(", "\"#{global_options[:fenton_server_url]}/organizations.json\"", ",", "body", ":", "organization_json", "(", "options", ")", ",", "headers", ":", "{", "'Content-Type'", "=>", "'application/json'", "}", ")", "[", "result", ".", "status", ",", "JSON", ".", "parse", "(", "result", ".", "body", ")", "]", "end" ]
Sends a post request with json from the command line organization @param global_options [Hash] global command line options @param options [Hash] json fields to send to fenton server @return [Fixnum] http status code @return [String] message back from fenton server
[ "Sends", "a", "post", "request", "with", "json", "from", "the", "command", "line", "organization" ]
6e1d76186fa7ee7a3be141afad9361e3a3e0ec91
https://github.com/fenton-project/fenton_shell/blob/6e1d76186fa7ee7a3be141afad9361e3a3e0ec91/lib/fenton_shell/organization.rb#L35-L43
train
futurechimp/drafter
lib/drafter/creation.rb
Drafter.Creation.save_draft
def save_draft(parent_draft=nil, parent_association_name=nil) if valid? do_create_draft(parent_draft, parent_association_name) create_subdrafts end return self.draft.reload if self.draft end
ruby
def save_draft(parent_draft=nil, parent_association_name=nil) if valid? do_create_draft(parent_draft, parent_association_name) create_subdrafts end return self.draft.reload if self.draft end
[ "def", "save_draft", "(", "parent_draft", "=", "nil", ",", "parent_association_name", "=", "nil", ")", "if", "valid?", "do_create_draft", "(", "parent_draft", ",", "parent_association_name", ")", "create_subdrafts", "end", "return", "self", ".", "draft", ".", "reload", "if", "self", ".", "draft", "end" ]
Build and save the draft when told to do so.
[ "Build", "and", "save", "the", "draft", "when", "told", "to", "do", "so", "." ]
8308b922148a6a44280023b0ef33d48a41f2e83e
https://github.com/futurechimp/drafter/blob/8308b922148a6a44280023b0ef33d48a41f2e83e/lib/drafter/creation.rb#L14-L20
train
futurechimp/drafter
lib/drafter/creation.rb
Drafter.Creation.build_draft_uploads
def build_draft_uploads self.attributes.keys.each do |key| if (self.respond_to?(key) && self.send(key).is_a?(CarrierWave::Uploader::Base) && self.send(key).file) self.draft.draft_uploads << build_draft_upload(key) end end end
ruby
def build_draft_uploads self.attributes.keys.each do |key| if (self.respond_to?(key) && self.send(key).is_a?(CarrierWave::Uploader::Base) && self.send(key).file) self.draft.draft_uploads << build_draft_upload(key) end end end
[ "def", "build_draft_uploads", "self", ".", "attributes", ".", "keys", ".", "each", "do", "|", "key", "|", "if", "(", "self", ".", "respond_to?", "(", "key", ")", "&&", "self", ".", "send", "(", "key", ")", ".", "is_a?", "(", "CarrierWave", "::", "Uploader", "::", "Base", ")", "&&", "self", ".", "send", "(", "key", ")", ".", "file", ")", "self", ".", "draft", ".", "draft_uploads", "<<", "build_draft_upload", "(", "key", ")", "end", "end", "end" ]
Loop through and create DraftUpload objects for any Carrierwave uploaders mounted on this draftable object. @param [Hash] attrs the attributes to loop through @return [Array<DraftUpload>] an array of unsaved DraftUpload objects.
[ "Loop", "through", "and", "create", "DraftUpload", "objects", "for", "any", "Carrierwave", "uploaders", "mounted", "on", "this", "draftable", "object", "." ]
8308b922148a6a44280023b0ef33d48a41f2e83e
https://github.com/futurechimp/drafter/blob/8308b922148a6a44280023b0ef33d48a41f2e83e/lib/drafter/creation.rb#L54-L62
train
futurechimp/drafter
lib/drafter/creation.rb
Drafter.Creation.build_draft_upload
def build_draft_upload(key) cw_uploader = self.send(key) file = File.new(cw_uploader.file.path) if cw_uploader.file existing_upload = self.draft.draft_uploads.where(:draftable_mount_column => key).first draft_upload = existing_upload.nil? ? DraftUpload.new : existing_upload draft_upload.file_data = file draft_upload.draftable_mount_column = key draft_upload end
ruby
def build_draft_upload(key) cw_uploader = self.send(key) file = File.new(cw_uploader.file.path) if cw_uploader.file existing_upload = self.draft.draft_uploads.where(:draftable_mount_column => key).first draft_upload = existing_upload.nil? ? DraftUpload.new : existing_upload draft_upload.file_data = file draft_upload.draftable_mount_column = key draft_upload end
[ "def", "build_draft_upload", "(", "key", ")", "cw_uploader", "=", "self", ".", "send", "(", "key", ")", "file", "=", "File", ".", "new", "(", "cw_uploader", ".", "file", ".", "path", ")", "if", "cw_uploader", ".", "file", "existing_upload", "=", "self", ".", "draft", ".", "draft_uploads", ".", "where", "(", ":draftable_mount_column", "=>", "key", ")", ".", "first", "draft_upload", "=", "existing_upload", ".", "nil?", "?", "DraftUpload", ".", "new", ":", "existing_upload", "draft_upload", ".", "file_data", "=", "file", "draft_upload", ".", "draftable_mount_column", "=", "key", "draft_upload", "end" ]
Get a reference to the CarrierWave uploader mounted on the current draftable object, grab the file in it, and shove that file into a new DraftUpload. @param [String] key the attribute where the CarrierWave uploader is mounted. @return [DraftUpload] containing the file in the uploader.
[ "Get", "a", "reference", "to", "the", "CarrierWave", "uploader", "mounted", "on", "the", "current", "draftable", "object", "grab", "the", "file", "in", "it", "and", "shove", "that", "file", "into", "a", "new", "DraftUpload", "." ]
8308b922148a6a44280023b0ef33d48a41f2e83e
https://github.com/futurechimp/drafter/blob/8308b922148a6a44280023b0ef33d48a41f2e83e/lib/drafter/creation.rb#L71-L79
train
jnicklas/eb_nested_set
lib/eb_nested_set.rb
EvenBetterNestedSet.NestedSet.root
def root(force_reload=nil) @root = nil if force_reload @root ||= transaction do reload_boundaries base_class.roots.find(:first, :conditions => ["#{nested_set_column(:left)} <= ? AND #{nested_set_column(:right)} >= ?", left, right]) end end
ruby
def root(force_reload=nil) @root = nil if force_reload @root ||= transaction do reload_boundaries base_class.roots.find(:first, :conditions => ["#{nested_set_column(:left)} <= ? AND #{nested_set_column(:right)} >= ?", left, right]) end end
[ "def", "root", "(", "force_reload", "=", "nil", ")", "@root", "=", "nil", "if", "force_reload", "@root", "||=", "transaction", "do", "reload_boundaries", "base_class", ".", "roots", ".", "find", "(", ":first", ",", ":conditions", "=>", "[", "\"#{nested_set_column(:left)} <= ? AND #{nested_set_column(:right)} >= ?\"", ",", "left", ",", "right", "]", ")", "end", "end" ]
Finds the root node that this node descends from @param [Boolean] force_reload forces the root node to be reloaded @return [ActiveRecord::Base] node the root node this descends from
[ "Finds", "the", "root", "node", "that", "this", "node", "descends", "from" ]
71b7b71030116097e79a7bef02e77daedf9d3eae
https://github.com/jnicklas/eb_nested_set/blob/71b7b71030116097e79a7bef02e77daedf9d3eae/lib/eb_nested_set.rb#L206-L212
train
jnicklas/eb_nested_set
lib/eb_nested_set.rb
EvenBetterNestedSet.NestedSet.family_ids
def family_ids(force_reload=false) return @family_ids unless @family_ids.nil? or force_reload transaction do reload_boundaries query = "SELECT id FROM #{self.class.quote_db_property(base_class.table_name)} " + "WHERE #{nested_set_column(:left)} >= #{left} AND #{nested_set_column(:right)} <= #{right} " + "ORDER BY #{nested_set_column(:left)}" @family_ids = base_class.connection.select_values(query).map(&:to_i) end end
ruby
def family_ids(force_reload=false) return @family_ids unless @family_ids.nil? or force_reload transaction do reload_boundaries query = "SELECT id FROM #{self.class.quote_db_property(base_class.table_name)} " + "WHERE #{nested_set_column(:left)} >= #{left} AND #{nested_set_column(:right)} <= #{right} " + "ORDER BY #{nested_set_column(:left)}" @family_ids = base_class.connection.select_values(query).map(&:to_i) end end
[ "def", "family_ids", "(", "force_reload", "=", "false", ")", "return", "@family_ids", "unless", "@family_ids", ".", "nil?", "or", "force_reload", "transaction", "do", "reload_boundaries", "query", "=", "\"SELECT id FROM #{self.class.quote_db_property(base_class.table_name)} \"", "+", "\"WHERE #{nested_set_column(:left)} >= #{left} AND #{nested_set_column(:right)} <= #{right} \"", "+", "\"ORDER BY #{nested_set_column(:left)}\"", "@family_ids", "=", "base_class", ".", "connection", ".", "select_values", "(", "query", ")", ".", "map", "(", "&", ":to_i", ")", "end", "end" ]
Returns the ids of the node and all nodes that descend from it. @return [Array[Integer]]
[ "Returns", "the", "ids", "of", "the", "node", "and", "all", "nodes", "that", "descend", "from", "it", "." ]
71b7b71030116097e79a7bef02e77daedf9d3eae
https://github.com/jnicklas/eb_nested_set/blob/71b7b71030116097e79a7bef02e77daedf9d3eae/lib/eb_nested_set.rb#L279-L289
train
jnicklas/eb_nested_set
lib/eb_nested_set.rb
EvenBetterNestedSet.NestedSet.recalculate_nested_set
def recalculate_nested_set(left) #:nodoc: child_left = left + 1 children.each do |child| child_left = child.recalculate_nested_set(child_left) end set_boundaries(left, child_left) save_without_validation! right + 1 end
ruby
def recalculate_nested_set(left) #:nodoc: child_left = left + 1 children.each do |child| child_left = child.recalculate_nested_set(child_left) end set_boundaries(left, child_left) save_without_validation! right + 1 end
[ "def", "recalculate_nested_set", "(", "left", ")", "child_left", "=", "left", "+", "1", "children", ".", "each", "do", "|", "child", "|", "child_left", "=", "child", ".", "recalculate_nested_set", "(", "child_left", ")", "end", "set_boundaries", "(", "left", ",", "child_left", ")", "save_without_validation!", "right", "+", "1", "end" ]
Rebuild this node's childrens boundaries
[ "Rebuild", "this", "node", "s", "childrens", "boundaries" ]
71b7b71030116097e79a7bef02e77daedf9d3eae
https://github.com/jnicklas/eb_nested_set/blob/71b7b71030116097e79a7bef02e77daedf9d3eae/lib/eb_nested_set.rb#L363-L372
train
mabarroso/lleidasms
lib/lleidasms/client.rb
Lleidasms.Client.send_waplink
def send_waplink number, url, message cmd_waplink number, url, message if wait wait_for last_label return false if @response_cmd.eql? 'NOOK' return "#{@response_args[0]}.#{@response_args[1]}".to_f end end
ruby
def send_waplink number, url, message cmd_waplink number, url, message if wait wait_for last_label return false if @response_cmd.eql? 'NOOK' return "#{@response_args[0]}.#{@response_args[1]}".to_f end end
[ "def", "send_waplink", "number", ",", "url", ",", "message", "cmd_waplink", "number", ",", "url", ",", "message", "if", "wait", "wait_for", "last_label", "return", "false", "if", "@response_cmd", ".", "eql?", "'NOOK'", "return", "\"#{@response_args[0]}.#{@response_args[1]}\"", ".", "to_f", "end", "end" ]
number The telephone number url The URL to content. Usually a image, tone or application message Information text before downloading content
[ "number", "The", "telephone", "number", "url", "The", "URL", "to", "content", ".", "Usually", "a", "image", "tone", "or", "application", "message", "Information", "text", "before", "downloading", "content" ]
419d37d9a25cc73548e5d9e8ac86bc24f35793ee
https://github.com/mabarroso/lleidasms/blob/419d37d9a25cc73548e5d9e8ac86bc24f35793ee/lib/lleidasms/client.rb#L100-L108
train
mabarroso/lleidasms
lib/lleidasms/client.rb
Lleidasms.Client.add_addressee
def add_addressee addressees, wait = true @addressees_accepted = false @addressees_rejected = false if addressees.kind_of?(Array) addressees = addressees.join ' ' end cmd_dst addressees while wait && !@addressees_accepted wait_for last_label return false if !add_addressee_results end end
ruby
def add_addressee addressees, wait = true @addressees_accepted = false @addressees_rejected = false if addressees.kind_of?(Array) addressees = addressees.join ' ' end cmd_dst addressees while wait && !@addressees_accepted wait_for last_label return false if !add_addressee_results end end
[ "def", "add_addressee", "addressees", ",", "wait", "=", "true", "@addressees_accepted", "=", "false", "@addressees_rejected", "=", "false", "if", "addressees", ".", "kind_of?", "(", "Array", ")", "addressees", "=", "addressees", ".", "join", "' '", "end", "cmd_dst", "addressees", "while", "wait", "&&", "!", "@addressees_accepted", "wait_for", "last_label", "return", "false", "if", "!", "add_addressee_results", "end", "end" ]
Add telephone numbers into the massive send list. It is recommended not to send more than 50 in each call Return TRUE if ok - see accepted in *last_addressees_accepted* - see rejected in *last_addressees_rejected*
[ "Add", "telephone", "numbers", "into", "the", "massive", "send", "list", ".", "It", "is", "recommended", "not", "to", "send", "more", "than", "50", "in", "each", "call" ]
419d37d9a25cc73548e5d9e8ac86bc24f35793ee
https://github.com/mabarroso/lleidasms/blob/419d37d9a25cc73548e5d9e8ac86bc24f35793ee/lib/lleidasms/client.rb#L116-L129
train
mabarroso/lleidasms
lib/lleidasms/client.rb
Lleidasms.Client.msg
def msg message, wait = true cmd_msg message return false unless wait_for(last_label) if wait return @response_args end
ruby
def msg message, wait = true cmd_msg message return false unless wait_for(last_label) if wait return @response_args end
[ "def", "msg", "message", ",", "wait", "=", "true", "cmd_msg", "message", "return", "false", "unless", "wait_for", "(", "last_label", ")", "if", "wait", "return", "@response_args", "end" ]
Set the message for the massive send list
[ "Set", "the", "message", "for", "the", "massive", "send", "list" ]
419d37d9a25cc73548e5d9e8ac86bc24f35793ee
https://github.com/mabarroso/lleidasms/blob/419d37d9a25cc73548e5d9e8ac86bc24f35793ee/lib/lleidasms/client.rb#L140-L144
train
astjohn/cornerstone
app/mailers/cornerstone/cornerstone_mailer.rb
Cornerstone.CornerstoneMailer.new_post
def new_post(name, email, post, discussion) @post = post @discussion = discussion @name = name mail :to => email, :subject => I18n.t('cornerstone.cornerstone_mailer.new_post.subject', :topic => @discussion.subject) end
ruby
def new_post(name, email, post, discussion) @post = post @discussion = discussion @name = name mail :to => email, :subject => I18n.t('cornerstone.cornerstone_mailer.new_post.subject', :topic => @discussion.subject) end
[ "def", "new_post", "(", "name", ",", "email", ",", "post", ",", "discussion", ")", "@post", "=", "post", "@discussion", "=", "discussion", "@name", "=", "name", "mail", ":to", "=>", "email", ",", ":subject", "=>", "I18n", ".", "t", "(", "'cornerstone.cornerstone_mailer.new_post.subject'", ",", ":topic", "=>", "@discussion", ".", "subject", ")", "end" ]
Email a single participant within a discussion - refer to post observer
[ "Email", "a", "single", "participant", "within", "a", "discussion", "-", "refer", "to", "post", "observer" ]
d7af7c06288477c961f3e328b8640df4be337301
https://github.com/astjohn/cornerstone/blob/d7af7c06288477c961f3e328b8640df4be337301/app/mailers/cornerstone/cornerstone_mailer.rb#L20-L28
train
gouravtiwari/beam
lib/beam/upload.rb
Beam.Upload.validate_record
def validate_record(errors_count, row_hash, index) record = new(row_hash) unless record.valid? errors_count += 1 [nil, errors_count, log_and_return_validation_error(record, row_hash, index)] else [record, errors_count, nil] end end
ruby
def validate_record(errors_count, row_hash, index) record = new(row_hash) unless record.valid? errors_count += 1 [nil, errors_count, log_and_return_validation_error(record, row_hash, index)] else [record, errors_count, nil] end end
[ "def", "validate_record", "(", "errors_count", ",", "row_hash", ",", "index", ")", "record", "=", "new", "(", "row_hash", ")", "unless", "record", ".", "valid?", "errors_count", "+=", "1", "[", "nil", ",", "errors_count", ",", "log_and_return_validation_error", "(", "record", ",", "row_hash", ",", "index", ")", "]", "else", "[", "record", ",", "errors_count", ",", "nil", "]", "end", "end" ]
Validates each record and returns error count if record is invalid
[ "Validates", "each", "record", "and", "returns", "error", "count", "if", "record", "is", "invalid" ]
074f0d515b84cde319e95b18bd55e456400c3ab6
https://github.com/gouravtiwari/beam/blob/074f0d515b84cde319e95b18bd55e456400c3ab6/lib/beam/upload.rb#L82-L90
train
webco/tuiter
lib/tuiter/utils.rb
Tuiter.Request.create_http_request
def create_http_request(http_method, path, *arguments) http_method = http_method.to_sym if [:post, :put].include?(http_method) data = arguments.shift end headers = arguments.first.is_a?(Hash) ? arguments.shift : {} case http_method when :post request = Net::HTTP::Post.new(path,headers) request["Content-Length"] = 0 # Default to 0 when :put request = Net::HTTP::Put.new(path,headers) request["Content-Length"] = 0 # Default to 0 when :get request = Net::HTTP::Get.new(path,headers) when :delete request = Net::HTTP::Delete.new(path,headers) else raise ArgumentError, "Don't know how to handle http_method: :#{http_method.to_s}" end # handling basic http auth request.basic_auth @config[:username], @config[:password] if data.is_a?(Hash) request.set_form_data(data) elsif data request.body = data.to_s request["Content-Length"] = request.body.length end request end
ruby
def create_http_request(http_method, path, *arguments) http_method = http_method.to_sym if [:post, :put].include?(http_method) data = arguments.shift end headers = arguments.first.is_a?(Hash) ? arguments.shift : {} case http_method when :post request = Net::HTTP::Post.new(path,headers) request["Content-Length"] = 0 # Default to 0 when :put request = Net::HTTP::Put.new(path,headers) request["Content-Length"] = 0 # Default to 0 when :get request = Net::HTTP::Get.new(path,headers) when :delete request = Net::HTTP::Delete.new(path,headers) else raise ArgumentError, "Don't know how to handle http_method: :#{http_method.to_s}" end # handling basic http auth request.basic_auth @config[:username], @config[:password] if data.is_a?(Hash) request.set_form_data(data) elsif data request.body = data.to_s request["Content-Length"] = request.body.length end request end
[ "def", "create_http_request", "(", "http_method", ",", "path", ",", "*", "arguments", ")", "http_method", "=", "http_method", ".", "to_sym", "if", "[", ":post", ",", ":put", "]", ".", "include?", "(", "http_method", ")", "data", "=", "arguments", ".", "shift", "end", "headers", "=", "arguments", ".", "first", ".", "is_a?", "(", "Hash", ")", "?", "arguments", ".", "shift", ":", "{", "}", "case", "http_method", "when", ":post", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "path", ",", "headers", ")", "request", "[", "\"Content-Length\"", "]", "=", "0", "when", ":put", "request", "=", "Net", "::", "HTTP", "::", "Put", ".", "new", "(", "path", ",", "headers", ")", "request", "[", "\"Content-Length\"", "]", "=", "0", "when", ":get", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "path", ",", "headers", ")", "when", ":delete", "request", "=", "Net", "::", "HTTP", "::", "Delete", ".", "new", "(", "path", ",", "headers", ")", "else", "raise", "ArgumentError", ",", "\"Don't know how to handle http_method: :#{http_method.to_s}\"", "end", "request", ".", "basic_auth", "@config", "[", ":username", "]", ",", "@config", "[", ":password", "]", "if", "data", ".", "is_a?", "(", "Hash", ")", "request", ".", "set_form_data", "(", "data", ")", "elsif", "data", "request", ".", "body", "=", "data", ".", "to_s", "request", "[", "\"Content-Length\"", "]", "=", "request", ".", "body", ".", "length", "end", "request", "end" ]
snippet based on oauth gem
[ "snippet", "based", "on", "oauth", "gem" ]
ace7b8f8fc973ec3dbb59e6f80cf98f9f705d777
https://github.com/webco/tuiter/blob/ace7b8f8fc973ec3dbb59e6f80cf98f9f705d777/lib/tuiter/utils.rb#L95-L130
train
fotonauts/activr
lib/activr/registry.rb
Activr.Registry.timeline_entries
def timeline_entries @timeline_entries ||= begin result = { } self.timelines.each do |(timeline_kind, timeline_class)| dir_name = Activr::Utils.kind_for_class(timeline_class) dir_path = File.join(Activr.timelines_path, dir_name) if !File.directory?(dir_path) dir_name = Activr::Utils.kind_for_class(timeline_class, 'timeline') dir_path = File.join(Activr.timelines_path, dir_name) end if File.directory?(dir_path) result[timeline_kind] = { } Dir["#{dir_path}/*.rb"].sort.inject(result[timeline_kind]) do |memo, file_path| base_name = File.basename(file_path, '.rb') # skip base class if (base_name != "base_timeline_entry") klass = "#{timeline_class.name}::#{base_name.camelize}".constantize route_kind = if (match_data = base_name.match(/(.+)_timeline_entry$/)) match_data[1] else base_name end route = timeline_class.routes.find do |timeline_route| timeline_route.kind == route_kind end raise "Timeline entry class found for an unspecified timeline route: #{file_path} / routes: #{timeline_class.routes.inspect}" unless route memo[route_kind] = klass end memo end end end result end end
ruby
def timeline_entries @timeline_entries ||= begin result = { } self.timelines.each do |(timeline_kind, timeline_class)| dir_name = Activr::Utils.kind_for_class(timeline_class) dir_path = File.join(Activr.timelines_path, dir_name) if !File.directory?(dir_path) dir_name = Activr::Utils.kind_for_class(timeline_class, 'timeline') dir_path = File.join(Activr.timelines_path, dir_name) end if File.directory?(dir_path) result[timeline_kind] = { } Dir["#{dir_path}/*.rb"].sort.inject(result[timeline_kind]) do |memo, file_path| base_name = File.basename(file_path, '.rb') # skip base class if (base_name != "base_timeline_entry") klass = "#{timeline_class.name}::#{base_name.camelize}".constantize route_kind = if (match_data = base_name.match(/(.+)_timeline_entry$/)) match_data[1] else base_name end route = timeline_class.routes.find do |timeline_route| timeline_route.kind == route_kind end raise "Timeline entry class found for an unspecified timeline route: #{file_path} / routes: #{timeline_class.routes.inspect}" unless route memo[route_kind] = klass end memo end end end result end end
[ "def", "timeline_entries", "@timeline_entries", "||=", "begin", "result", "=", "{", "}", "self", ".", "timelines", ".", "each", "do", "|", "(", "timeline_kind", ",", "timeline_class", ")", "|", "dir_name", "=", "Activr", "::", "Utils", ".", "kind_for_class", "(", "timeline_class", ")", "dir_path", "=", "File", ".", "join", "(", "Activr", ".", "timelines_path", ",", "dir_name", ")", "if", "!", "File", ".", "directory?", "(", "dir_path", ")", "dir_name", "=", "Activr", "::", "Utils", ".", "kind_for_class", "(", "timeline_class", ",", "'timeline'", ")", "dir_path", "=", "File", ".", "join", "(", "Activr", ".", "timelines_path", ",", "dir_name", ")", "end", "if", "File", ".", "directory?", "(", "dir_path", ")", "result", "[", "timeline_kind", "]", "=", "{", "}", "Dir", "[", "\"#{dir_path}/*.rb\"", "]", ".", "sort", ".", "inject", "(", "result", "[", "timeline_kind", "]", ")", "do", "|", "memo", ",", "file_path", "|", "base_name", "=", "File", ".", "basename", "(", "file_path", ",", "'.rb'", ")", "if", "(", "base_name", "!=", "\"base_timeline_entry\"", ")", "klass", "=", "\"#{timeline_class.name}::#{base_name.camelize}\"", ".", "constantize", "route_kind", "=", "if", "(", "match_data", "=", "base_name", ".", "match", "(", "/", "/", ")", ")", "match_data", "[", "1", "]", "else", "base_name", "end", "route", "=", "timeline_class", ".", "routes", ".", "find", "do", "|", "timeline_route", "|", "timeline_route", ".", "kind", "==", "route_kind", "end", "raise", "\"Timeline entry class found for an unspecified timeline route: #{file_path} / routes: #{timeline_class.routes.inspect}\"", "unless", "route", "memo", "[", "route_kind", "]", "=", "klass", "end", "memo", "end", "end", "end", "result", "end", "end" ]
Get all registered timeline entries @return [Hash{String=>Hash{String=>Class}}] A hash of `<timeline kind> => { <route kind> => <timeline entry class>, ... }`
[ "Get", "all", "registered", "timeline", "entries" ]
92c071ad18a76d4130661da3ce47c1f0fb8ae913
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/registry.rb#L70-L114
train
fotonauts/activr
lib/activr/registry.rb
Activr.Registry.class_for_timeline_entry
def class_for_timeline_entry(timeline_kind, route_kind) (self.timeline_entries[timeline_kind] && self.timeline_entries[timeline_kind][route_kind]) || Activr::Timeline::Entry end
ruby
def class_for_timeline_entry(timeline_kind, route_kind) (self.timeline_entries[timeline_kind] && self.timeline_entries[timeline_kind][route_kind]) || Activr::Timeline::Entry end
[ "def", "class_for_timeline_entry", "(", "timeline_kind", ",", "route_kind", ")", "(", "self", ".", "timeline_entries", "[", "timeline_kind", "]", "&&", "self", ".", "timeline_entries", "[", "timeline_kind", "]", "[", "route_kind", "]", ")", "||", "Activr", "::", "Timeline", "::", "Entry", "end" ]
Get class for timeline entry corresponding to given route in given timeline @param timeline_kind [String] Timeline kind @param route_kind [String] Route kind @return [Class] Timeline entry class
[ "Get", "class", "for", "timeline", "entry", "corresponding", "to", "given", "route", "in", "given", "timeline" ]
92c071ad18a76d4130661da3ce47c1f0fb8ae913
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/registry.rb#L121-L123
train
fotonauts/activr
lib/activr/registry.rb
Activr.Registry.add_entity
def add_entity(entity_name, entity_options, activity_klass) entity_name = entity_name.to_sym if @entity_classes[entity_name] && (@entity_classes[entity_name].name != entity_options[:class].name) # otherwise this would break timeline entries deletion mecanism raise "Entity name #{entity_name} already used with class #{@entity_classes[entity_name]}, can't redefine it with class #{entity_options[:class]}" end # class for entity @entity_classes[entity_name] = entity_options[:class] # entities for activity @activity_entities[activity_klass] ||= [ ] @activity_entities[activity_klass] << entity_name # entities @entities ||= { } @entities[entity_name] ||= { } if !@entities[entity_name][activity_klass].blank? raise "Entity name #{entity_name} already used for activity: #{activity_klass}" end @entities[entity_name][activity_klass] = entity_options end
ruby
def add_entity(entity_name, entity_options, activity_klass) entity_name = entity_name.to_sym if @entity_classes[entity_name] && (@entity_classes[entity_name].name != entity_options[:class].name) # otherwise this would break timeline entries deletion mecanism raise "Entity name #{entity_name} already used with class #{@entity_classes[entity_name]}, can't redefine it with class #{entity_options[:class]}" end # class for entity @entity_classes[entity_name] = entity_options[:class] # entities for activity @activity_entities[activity_klass] ||= [ ] @activity_entities[activity_klass] << entity_name # entities @entities ||= { } @entities[entity_name] ||= { } if !@entities[entity_name][activity_klass].blank? raise "Entity name #{entity_name} already used for activity: #{activity_klass}" end @entities[entity_name][activity_klass] = entity_options end
[ "def", "add_entity", "(", "entity_name", ",", "entity_options", ",", "activity_klass", ")", "entity_name", "=", "entity_name", ".", "to_sym", "if", "@entity_classes", "[", "entity_name", "]", "&&", "(", "@entity_classes", "[", "entity_name", "]", ".", "name", "!=", "entity_options", "[", ":class", "]", ".", "name", ")", "raise", "\"Entity name #{entity_name} already used with class #{@entity_classes[entity_name]}, can't redefine it with class #{entity_options[:class]}\"", "end", "@entity_classes", "[", "entity_name", "]", "=", "entity_options", "[", ":class", "]", "@activity_entities", "[", "activity_klass", "]", "||=", "[", "]", "@activity_entities", "[", "activity_klass", "]", "<<", "entity_name", "@entities", "||=", "{", "}", "@entities", "[", "entity_name", "]", "||=", "{", "}", "if", "!", "@entities", "[", "entity_name", "]", "[", "activity_klass", "]", ".", "blank?", "raise", "\"Entity name #{entity_name} already used for activity: #{activity_klass}\"", "end", "@entities", "[", "entity_name", "]", "[", "activity_klass", "]", "=", "entity_options", "end" ]
Register an entity @param entity_name [Symbol] Entity name @param entity_options [Hash] Entity options @param activity_klass [Class] Activity class that uses that entity
[ "Register", "an", "entity" ]
92c071ad18a76d4130661da3ce47c1f0fb8ae913
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/registry.rb#L164-L188
train
fotonauts/activr
lib/activr/registry.rb
Activr.Registry.activity_entities_for_model
def activity_entities_for_model(model_class) @activity_entities_for_model[model_class] ||= begin result = [ ] @entity_classes.each do |entity_name, entity_class| result << entity_name if (entity_class == model_class) end result end end
ruby
def activity_entities_for_model(model_class) @activity_entities_for_model[model_class] ||= begin result = [ ] @entity_classes.each do |entity_name, entity_class| result << entity_name if (entity_class == model_class) end result end end
[ "def", "activity_entities_for_model", "(", "model_class", ")", "@activity_entities_for_model", "[", "model_class", "]", "||=", "begin", "result", "=", "[", "]", "@entity_classes", ".", "each", "do", "|", "entity_name", ",", "entity_class", "|", "result", "<<", "entity_name", "if", "(", "entity_class", "==", "model_class", ")", "end", "result", "end", "end" ]
Get all entities names for given model class
[ "Get", "all", "entities", "names", "for", "given", "model", "class" ]
92c071ad18a76d4130661da3ce47c1f0fb8ae913
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/registry.rb#L209-L219
train
fotonauts/activr
lib/activr/registry.rb
Activr.Registry.timeline_entities_for_model
def timeline_entities_for_model(model_class) @timeline_entities_for_model[model_class] ||= begin result = { } self.timelines.each do |timeline_kind, timeline_class| result[timeline_class] = [ ] timeline_class.routes.each do |route| entities_ary = @activity_entities[route.activity_class] (entities_ary || [ ]).each do |entity_name| result[timeline_class] << entity_name if (@entity_classes[entity_name] == model_class) end end result[timeline_class].uniq! end result end end
ruby
def timeline_entities_for_model(model_class) @timeline_entities_for_model[model_class] ||= begin result = { } self.timelines.each do |timeline_kind, timeline_class| result[timeline_class] = [ ] timeline_class.routes.each do |route| entities_ary = @activity_entities[route.activity_class] (entities_ary || [ ]).each do |entity_name| result[timeline_class] << entity_name if (@entity_classes[entity_name] == model_class) end end result[timeline_class].uniq! end result end end
[ "def", "timeline_entities_for_model", "(", "model_class", ")", "@timeline_entities_for_model", "[", "model_class", "]", "||=", "begin", "result", "=", "{", "}", "self", ".", "timelines", ".", "each", "do", "|", "timeline_kind", ",", "timeline_class", "|", "result", "[", "timeline_class", "]", "=", "[", "]", "timeline_class", ".", "routes", ".", "each", "do", "|", "route", "|", "entities_ary", "=", "@activity_entities", "[", "route", ".", "activity_class", "]", "(", "entities_ary", "||", "[", "]", ")", ".", "each", "do", "|", "entity_name", "|", "result", "[", "timeline_class", "]", "<<", "entity_name", "if", "(", "@entity_classes", "[", "entity_name", "]", "==", "model_class", ")", "end", "end", "result", "[", "timeline_class", "]", ".", "uniq!", "end", "result", "end", "end" ]
Get all entities names by timelines that can have a reference to given model class @param model_class [Class] Model class @return [Hash{Class=>Array<Symbol>}] Lists of entities names indexed by timeline class
[ "Get", "all", "entities", "names", "by", "timelines", "that", "can", "have", "a", "reference", "to", "given", "model", "class" ]
92c071ad18a76d4130661da3ce47c1f0fb8ae913
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/registry.rb#L225-L244
train
fotonauts/activr
lib/activr/registry.rb
Activr.Registry.classes_from_path
def classes_from_path(dir_path) Dir["#{dir_path}/*.rb"].sort.inject({ }) do |memo, file_path| klass = File.basename(file_path, '.rb').camelize.constantize if !memo[klass.kind].nil? raise "Kind #{klass.kind} already used by class #{memo[klass.kind]} so can't use it for class #{klass}" end memo[klass.kind] = klass memo end end
ruby
def classes_from_path(dir_path) Dir["#{dir_path}/*.rb"].sort.inject({ }) do |memo, file_path| klass = File.basename(file_path, '.rb').camelize.constantize if !memo[klass.kind].nil? raise "Kind #{klass.kind} already used by class #{memo[klass.kind]} so can't use it for class #{klass}" end memo[klass.kind] = klass memo end end
[ "def", "classes_from_path", "(", "dir_path", ")", "Dir", "[", "\"#{dir_path}/*.rb\"", "]", ".", "sort", ".", "inject", "(", "{", "}", ")", "do", "|", "memo", ",", "file_path", "|", "klass", "=", "File", ".", "basename", "(", "file_path", ",", "'.rb'", ")", ".", "camelize", ".", "constantize", "if", "!", "memo", "[", "klass", ".", "kind", "]", ".", "nil?", "raise", "\"Kind #{klass.kind} already used by class #{memo[klass.kind]} so can't use it for class #{klass}\"", "end", "memo", "[", "klass", ".", "kind", "]", "=", "klass", "memo", "end", "end" ]
Find all classes in given directory @api private @param dir_path [String] Directory path @return [Hash{String=>Class}] Hash of `<kind> => <Class>`
[ "Find", "all", "classes", "in", "given", "directory" ]
92c071ad18a76d4130661da3ce47c1f0fb8ae913
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/registry.rb#L252-L264
train
sugaryourcoffee/syclink
lib/syclink/internet_explorer.rb
SycLink.InternetExplorer.read
def read files = Dir.glob(File.join(path, "**/*")) regex = Regexp.new("(?<=#{path}).*") files.map do |file| unless ((File.directory? file) || (File.extname(file).upcase != ".URL")) url = File.read(file).scan(/(?<=\nURL=)(.*)$/).flatten.first.chomp name = url_name(File.basename(file, ".*")) description = "" tag = extract_tags(File.dirname(file).scan(regex)) [url, name, description, tag] end end.compact end
ruby
def read files = Dir.glob(File.join(path, "**/*")) regex = Regexp.new("(?<=#{path}).*") files.map do |file| unless ((File.directory? file) || (File.extname(file).upcase != ".URL")) url = File.read(file).scan(/(?<=\nURL=)(.*)$/).flatten.first.chomp name = url_name(File.basename(file, ".*")) description = "" tag = extract_tags(File.dirname(file).scan(regex)) [url, name, description, tag] end end.compact end
[ "def", "read", "files", "=", "Dir", ".", "glob", "(", "File", ".", "join", "(", "path", ",", "\"**/*\"", ")", ")", "regex", "=", "Regexp", ".", "new", "(", "\"(?<=#{path}).*\"", ")", "files", ".", "map", "do", "|", "file", "|", "unless", "(", "(", "File", ".", "directory?", "file", ")", "||", "(", "File", ".", "extname", "(", "file", ")", ".", "upcase", "!=", "\".URL\"", ")", ")", "url", "=", "File", ".", "read", "(", "file", ")", ".", "scan", "(", "/", "\\n", "/", ")", ".", "flatten", ".", "first", ".", "chomp", "name", "=", "url_name", "(", "File", ".", "basename", "(", "file", ",", "\".*\"", ")", ")", "description", "=", "\"\"", "tag", "=", "extract_tags", "(", "File", ".", "dirname", "(", "file", ")", ".", "scan", "(", "regex", ")", ")", "[", "url", ",", "name", ",", "description", ",", "tag", "]", "end", "end", ".", "compact", "end" ]
Reads the links from the Internet Explorer's bookmarks directory
[ "Reads", "the", "links", "from", "the", "Internet", "Explorer", "s", "bookmarks", "directory" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/internet_explorer.rb#L10-L24
train
toshi0328/gmath3D
lib/ext.rb
GMath3D.::Matrix.multi_new
def multi_new(rhs) if(rhs.kind_of?(Vector3)) ans = self.multi_inner(rhs.to_column_vector) return Vector3.new(ans[0,0], ans[1,0], ans[2,0]) end multi_inner(rhs) end
ruby
def multi_new(rhs) if(rhs.kind_of?(Vector3)) ans = self.multi_inner(rhs.to_column_vector) return Vector3.new(ans[0,0], ans[1,0], ans[2,0]) end multi_inner(rhs) end
[ "def", "multi_new", "(", "rhs", ")", "if", "(", "rhs", ".", "kind_of?", "(", "Vector3", ")", ")", "ans", "=", "self", ".", "multi_inner", "(", "rhs", ".", "to_column_vector", ")", "return", "Vector3", ".", "new", "(", "ans", "[", "0", ",", "0", "]", ",", "ans", "[", "1", ",", "0", "]", ",", "ans", "[", "2", ",", "0", "]", ")", "end", "multi_inner", "(", "rhs", ")", "end" ]
hold original multiply processing
[ "hold", "original", "multiply", "processing" ]
a90fc3bfbc447af0585632e8d6a68aeae6f5bcc4
https://github.com/toshi0328/gmath3D/blob/a90fc3bfbc447af0585632e8d6a68aeae6f5bcc4/lib/ext.rb#L46-L52
train
ideonetwork/lato-blog
app/models/lato_blog/tag.rb
LatoBlog.Tag.check_meta_permalink
def check_meta_permalink candidate = (self.meta_permalink ? self.meta_permalink : self.title.parameterize) accepted = nil counter = 0 while accepted.nil? if LatoBlog::Tag.find_by(meta_permalink: candidate) counter += 1 candidate = "#{candidate}-#{counter}" else accepted = candidate end end self.meta_permalink = accepted end
ruby
def check_meta_permalink candidate = (self.meta_permalink ? self.meta_permalink : self.title.parameterize) accepted = nil counter = 0 while accepted.nil? if LatoBlog::Tag.find_by(meta_permalink: candidate) counter += 1 candidate = "#{candidate}-#{counter}" else accepted = candidate end end self.meta_permalink = accepted end
[ "def", "check_meta_permalink", "candidate", "=", "(", "self", ".", "meta_permalink", "?", "self", ".", "meta_permalink", ":", "self", ".", "title", ".", "parameterize", ")", "accepted", "=", "nil", "counter", "=", "0", "while", "accepted", ".", "nil?", "if", "LatoBlog", "::", "Tag", ".", "find_by", "(", "meta_permalink", ":", "candidate", ")", "counter", "+=", "1", "candidate", "=", "\"#{candidate}-#{counter}\"", "else", "accepted", "=", "candidate", "end", "end", "self", ".", "meta_permalink", "=", "accepted", "end" ]
This function check if current permalink is valid. If it is not valid it generate a new from the post title.
[ "This", "function", "check", "if", "current", "permalink", "is", "valid", ".", "If", "it", "is", "not", "valid", "it", "generate", "a", "new", "from", "the", "post", "title", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/tag.rb#L48-L63
train
ideonetwork/lato-blog
app/models/lato_blog/tag.rb
LatoBlog.Tag.check_lato_blog_tag_parent
def check_lato_blog_tag_parent tag_parent = LatoBlog::TagParent.find_by(id: lato_blog_tag_parent_id) if !tag_parent errors.add('Tag parent', 'not exist for the tag') throw :abort return end same_language_tag = tag_parent.tags.find_by(meta_language: meta_language) if same_language_tag && same_language_tag.id != id errors.add('Tag parent', 'has another tag for the same language') throw :abort return end end
ruby
def check_lato_blog_tag_parent tag_parent = LatoBlog::TagParent.find_by(id: lato_blog_tag_parent_id) if !tag_parent errors.add('Tag parent', 'not exist for the tag') throw :abort return end same_language_tag = tag_parent.tags.find_by(meta_language: meta_language) if same_language_tag && same_language_tag.id != id errors.add('Tag parent', 'has another tag for the same language') throw :abort return end end
[ "def", "check_lato_blog_tag_parent", "tag_parent", "=", "LatoBlog", "::", "TagParent", ".", "find_by", "(", "id", ":", "lato_blog_tag_parent_id", ")", "if", "!", "tag_parent", "errors", ".", "add", "(", "'Tag parent'", ",", "'not exist for the tag'", ")", "throw", ":abort", "return", "end", "same_language_tag", "=", "tag_parent", ".", "tags", ".", "find_by", "(", "meta_language", ":", "meta_language", ")", "if", "same_language_tag", "&&", "same_language_tag", ".", "id", "!=", "id", "errors", ".", "add", "(", "'Tag parent'", ",", "'has another tag for the same language'", ")", "throw", ":abort", "return", "end", "end" ]
This function check that the category parent exist and has not others tags for the same language.
[ "This", "function", "check", "that", "the", "category", "parent", "exist", "and", "has", "not", "others", "tags", "for", "the", "same", "language", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/tag.rb#L66-L80
train
ideasasylum/tinycert
lib/tinycert/request.rb
Tinycert.Request.prepare_params
def prepare_params p results = {} # Build a new hash with string keys p.each { |k, v| results[k.to_s] = v } # Sort nested structures results.sort.to_h end
ruby
def prepare_params p results = {} # Build a new hash with string keys p.each { |k, v| results[k.to_s] = v } # Sort nested structures results.sort.to_h end
[ "def", "prepare_params", "p", "results", "=", "{", "}", "p", ".", "each", "{", "|", "k", ",", "v", "|", "results", "[", "k", ".", "to_s", "]", "=", "v", "}", "results", ".", "sort", ".", "to_h", "end" ]
Sort the params consistently
[ "Sort", "the", "params", "consistently" ]
6176e740e7d14eb3e9468e442d6c3575fb5810dc
https://github.com/ideasasylum/tinycert/blob/6176e740e7d14eb3e9468e442d6c3575fb5810dc/lib/tinycert/request.rb#L22-L28
train
topbitdu/progne_tapera
lib/progne_tapera/enum_list.rb
ProgneTapera::EnumList.ClassMethods.enum_constants
def enum_constants constants.select { |constant| value = const_get constant value.is_a? ProgneTapera::EnumItem } end
ruby
def enum_constants constants.select { |constant| value = const_get constant value.is_a? ProgneTapera::EnumItem } end
[ "def", "enum_constants", "constants", ".", "select", "{", "|", "constant", "|", "value", "=", "const_get", "constant", "value", ".", "is_a?", "ProgneTapera", "::", "EnumItem", "}", "end" ]
Destroy or Update the Enum Items def clear_optional_items end Infrastructure for the Enumerable
[ "Destroy", "or", "Update", "the", "Enum", "Items", "def", "clear_optional_items" ]
7815a518e4c23acaeafb9dbf4a7c4eb08bcfdbcc
https://github.com/topbitdu/progne_tapera/blob/7815a518e4c23acaeafb9dbf4a7c4eb08bcfdbcc/lib/progne_tapera/enum_list.rb#L54-L59
train
ajeychronus/chronuscop_client
lib/chronuscop_client/configuration.rb
ChronuscopClient.Configuration.load_yaml_configuration
def load_yaml_configuration yaml_config = YAML.load_file("#{@rails_root_dir}/config/chronuscop.yml") @redis_db_number = yaml_config[@rails_environment]['redis_db_number'] @redis_server_port = yaml_config[@rails_environment]['redis_server_port'] @project_number = yaml_config[@rails_environment]['project_number'] @api_token = yaml_config[@rails_environment]['api_token'] @chronuscop_server_address = yaml_config[@rails_environment]['chronuscop_server_address'] @sync_time_interval = yaml_config[@rails_environment]['sync_time_interval'] end
ruby
def load_yaml_configuration yaml_config = YAML.load_file("#{@rails_root_dir}/config/chronuscop.yml") @redis_db_number = yaml_config[@rails_environment]['redis_db_number'] @redis_server_port = yaml_config[@rails_environment]['redis_server_port'] @project_number = yaml_config[@rails_environment]['project_number'] @api_token = yaml_config[@rails_environment]['api_token'] @chronuscop_server_address = yaml_config[@rails_environment]['chronuscop_server_address'] @sync_time_interval = yaml_config[@rails_environment]['sync_time_interval'] end
[ "def", "load_yaml_configuration", "yaml_config", "=", "YAML", ".", "load_file", "(", "\"#{@rails_root_dir}/config/chronuscop.yml\"", ")", "@redis_db_number", "=", "yaml_config", "[", "@rails_environment", "]", "[", "'redis_db_number'", "]", "@redis_server_port", "=", "yaml_config", "[", "@rails_environment", "]", "[", "'redis_server_port'", "]", "@project_number", "=", "yaml_config", "[", "@rails_environment", "]", "[", "'project_number'", "]", "@api_token", "=", "yaml_config", "[", "@rails_environment", "]", "[", "'api_token'", "]", "@chronuscop_server_address", "=", "yaml_config", "[", "@rails_environment", "]", "[", "'chronuscop_server_address'", "]", "@sync_time_interval", "=", "yaml_config", "[", "@rails_environment", "]", "[", "'sync_time_interval'", "]", "end" ]
rails root directory must be set before calling this.
[ "rails", "root", "directory", "must", "be", "set", "before", "calling", "this", "." ]
17834beba5215b122b399f145f8710da03ff7a0a
https://github.com/ajeychronus/chronuscop_client/blob/17834beba5215b122b399f145f8710da03ff7a0a/lib/chronuscop_client/configuration.rb#L41-L49
train
tbuehlmann/ponder
lib/ponder/user.rb
Ponder.User.whois
def whois connected do fiber = Fiber.current callbacks = {} # User is online. callbacks[311] = @thaum.on(311) do |event_data| nick = event_data[:params].split(' ')[1] if nick.downcase == @nick.downcase @online = true # TODO: Add properties. end end # User is not online. callbacks[401] = @thaum.on(401) do |event_data| nick = event_data[:params].split(' ')[1] if nick.downcase == @nick.downcase @online = false fiber.resume end end # End of WHOIS. callbacks[318] = @thaum.on(318) do |event_data| nick = event_data[:params].split(' ')[1] if nick.downcase == @nick.downcase fiber.resume end end raw "WHOIS #{@nick}" Fiber.yield callbacks.each do |type, callback| @thaum.callbacks[type].delete(callback) end end self end
ruby
def whois connected do fiber = Fiber.current callbacks = {} # User is online. callbacks[311] = @thaum.on(311) do |event_data| nick = event_data[:params].split(' ')[1] if nick.downcase == @nick.downcase @online = true # TODO: Add properties. end end # User is not online. callbacks[401] = @thaum.on(401) do |event_data| nick = event_data[:params].split(' ')[1] if nick.downcase == @nick.downcase @online = false fiber.resume end end # End of WHOIS. callbacks[318] = @thaum.on(318) do |event_data| nick = event_data[:params].split(' ')[1] if nick.downcase == @nick.downcase fiber.resume end end raw "WHOIS #{@nick}" Fiber.yield callbacks.each do |type, callback| @thaum.callbacks[type].delete(callback) end end self end
[ "def", "whois", "connected", "do", "fiber", "=", "Fiber", ".", "current", "callbacks", "=", "{", "}", "callbacks", "[", "311", "]", "=", "@thaum", ".", "on", "(", "311", ")", "do", "|", "event_data", "|", "nick", "=", "event_data", "[", ":params", "]", ".", "split", "(", "' '", ")", "[", "1", "]", "if", "nick", ".", "downcase", "==", "@nick", ".", "downcase", "@online", "=", "true", "end", "end", "callbacks", "[", "401", "]", "=", "@thaum", ".", "on", "(", "401", ")", "do", "|", "event_data", "|", "nick", "=", "event_data", "[", ":params", "]", ".", "split", "(", "' '", ")", "[", "1", "]", "if", "nick", ".", "downcase", "==", "@nick", ".", "downcase", "@online", "=", "false", "fiber", ".", "resume", "end", "end", "callbacks", "[", "318", "]", "=", "@thaum", ".", "on", "(", "318", ")", "do", "|", "event_data", "|", "nick", "=", "event_data", "[", ":params", "]", ".", "split", "(", "' '", ")", "[", "1", "]", "if", "nick", ".", "downcase", "==", "@nick", ".", "downcase", "fiber", ".", "resume", "end", "end", "raw", "\"WHOIS #{@nick}\"", "Fiber", ".", "yield", "callbacks", ".", "each", "do", "|", "type", ",", "callback", "|", "@thaum", ".", "callbacks", "[", "type", "]", ".", "delete", "(", "callback", ")", "end", "end", "self", "end" ]
Updates the properties of an user.
[ "Updates", "the", "properties", "of", "an", "user", "." ]
930912e1b78b41afa1359121aca46197e9edff9c
https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/user.rb#L11-L51
train
spaghetticode/lazymodel
lib/lazymodel/base.rb
Lazymodel.Base.attributes
def attributes _attributes.inject(HashWithIndifferentAccess.new) do |hash, attribute| hash.update attribute => send(attribute) end end
ruby
def attributes _attributes.inject(HashWithIndifferentAccess.new) do |hash, attribute| hash.update attribute => send(attribute) end end
[ "def", "attributes", "_attributes", ".", "inject", "(", "HashWithIndifferentAccess", ".", "new", ")", "do", "|", "hash", ",", "attribute", "|", "hash", ".", "update", "attribute", "=>", "send", "(", "attribute", ")", "end", "end" ]
don't override this method without calling super!
[ "don", "t", "override", "this", "method", "without", "calling", "super!" ]
de0b4567bf5c0731c7417f476d38fd74c5a2a3e2
https://github.com/spaghetticode/lazymodel/blob/de0b4567bf5c0731c7417f476d38fd74c5a2a3e2/lib/lazymodel/base.rb#L55-L59
train
rrn/acts_as_joinable
lib/joinable/permissions_attribute_wrapper.rb
Joinable.PermissionsAttributeWrapper.permission_attributes=
def permission_attributes=(permissions) self.permissions = [] # Reset permissions in anticipation for re-population permissions.each do |key, value| key, value = key.dup, value.dup # Component Permissions if key.ends_with? "_permissions" grant_permissions(value) # Singular Permission elsif key.chomp! "_permission" grant_permissions(key) if value.to_i != 0 end end end
ruby
def permission_attributes=(permissions) self.permissions = [] # Reset permissions in anticipation for re-population permissions.each do |key, value| key, value = key.dup, value.dup # Component Permissions if key.ends_with? "_permissions" grant_permissions(value) # Singular Permission elsif key.chomp! "_permission" grant_permissions(key) if value.to_i != 0 end end end
[ "def", "permission_attributes", "=", "(", "permissions", ")", "self", ".", "permissions", "=", "[", "]", "permissions", ".", "each", "do", "|", "key", ",", "value", "|", "key", ",", "value", "=", "key", ".", "dup", ",", "value", ".", "dup", "if", "key", ".", "ends_with?", "\"_permissions\"", "grant_permissions", "(", "value", ")", "elsif", "key", ".", "chomp!", "\"_permission\"", "grant_permissions", "(", "key", ")", "if", "value", ".", "to_i", "!=", "0", "end", "end", "end" ]
Used by advanced permission forms which group permissions by their associated component or using a single check box per permission.
[ "Used", "by", "advanced", "permission", "forms", "which", "group", "permissions", "by", "their", "associated", "component", "or", "using", "a", "single", "check", "box", "per", "permission", "." ]
33bfa5bfed84ec1644fd4ddfb75b661d24a2fb71
https://github.com/rrn/acts_as_joinable/blob/33bfa5bfed84ec1644fd4ddfb75b661d24a2fb71/lib/joinable/permissions_attribute_wrapper.rb#L33-L47
train
rrn/acts_as_joinable
lib/joinable/permissions_attribute_wrapper.rb
Joinable.PermissionsAttributeWrapper.has_permission?
def has_permission?(*levels) if levels.all? { |level| permissions.include? level.to_sym } return true else return false end end
ruby
def has_permission?(*levels) if levels.all? { |level| permissions.include? level.to_sym } return true else return false end end
[ "def", "has_permission?", "(", "*", "levels", ")", "if", "levels", ".", "all?", "{", "|", "level", "|", "permissions", ".", "include?", "level", ".", "to_sym", "}", "return", "true", "else", "return", "false", "end", "end" ]
Returns true if the object has all the permissions specified by +levels+
[ "Returns", "true", "if", "the", "object", "has", "all", "the", "permissions", "specified", "by", "+", "levels", "+" ]
33bfa5bfed84ec1644fd4ddfb75b661d24a2fb71
https://github.com/rrn/acts_as_joinable/blob/33bfa5bfed84ec1644fd4ddfb75b661d24a2fb71/lib/joinable/permissions_attribute_wrapper.rb#L59-L65
train
rrn/acts_as_joinable
lib/joinable/permissions_attribute_wrapper.rb
Joinable.PermissionsAttributeWrapper.method_missing
def method_missing(method_name, *args, &block) # NOTE: As of Rails 4, respond_to? must be checked inside the case statement otherwise it breaks regular AR attribute accessors case method_name.to_s when /.+_permissions/ return component_permissions_reader(method_name) if respond_to?(:joinable_type) && joinable_type.present? when /.+_permission/ return single_permission_reader(method_name) if respond_to?(:joinable_type) && joinable_type.present? end super end
ruby
def method_missing(method_name, *args, &block) # NOTE: As of Rails 4, respond_to? must be checked inside the case statement otherwise it breaks regular AR attribute accessors case method_name.to_s when /.+_permissions/ return component_permissions_reader(method_name) if respond_to?(:joinable_type) && joinable_type.present? when /.+_permission/ return single_permission_reader(method_name) if respond_to?(:joinable_type) && joinable_type.present? end super end
[ "def", "method_missing", "(", "method_name", ",", "*", "args", ",", "&", "block", ")", "case", "method_name", ".", "to_s", "when", "/", "/", "return", "component_permissions_reader", "(", "method_name", ")", "if", "respond_to?", "(", ":joinable_type", ")", "&&", "joinable_type", ".", "present?", "when", "/", "/", "return", "single_permission_reader", "(", "method_name", ")", "if", "respond_to?", "(", ":joinable_type", ")", "&&", "joinable_type", ".", "present?", "end", "super", "end" ]
Adds readers for component permission groups and single permissions Used by advanced permission forms to determine how which options to select in the various fields. (eg. which option of f.select :labels_permissions to choose)
[ "Adds", "readers", "for", "component", "permission", "groups", "and", "single", "permissions" ]
33bfa5bfed84ec1644fd4ddfb75b661d24a2fb71
https://github.com/rrn/acts_as_joinable/blob/33bfa5bfed84ec1644fd4ddfb75b661d24a2fb71/lib/joinable/permissions_attribute_wrapper.rb#L105-L115
train
rrn/acts_as_joinable
lib/joinable/permissions_attribute_wrapper.rb
Joinable.PermissionsAttributeWrapper.verify_and_sort_permissions
def verify_and_sort_permissions # DefaultPermissionSet is allowed to have blank permissions (private joinable), the other models need at least find and view self.permissions += [:find, :view] unless is_a?(DefaultPermissionSet) raise "Invalid permissions: #{(permissions - allowed_permissions).inspect}. Must be one of #{allowed_permissions.inspect}" unless permissions.all? {|permission| allowed_permissions.include? permission} self.permissions = permissions.uniq.sort_by { |permission| allowed_permissions.index(permission) } end
ruby
def verify_and_sort_permissions # DefaultPermissionSet is allowed to have blank permissions (private joinable), the other models need at least find and view self.permissions += [:find, :view] unless is_a?(DefaultPermissionSet) raise "Invalid permissions: #{(permissions - allowed_permissions).inspect}. Must be one of #{allowed_permissions.inspect}" unless permissions.all? {|permission| allowed_permissions.include? permission} self.permissions = permissions.uniq.sort_by { |permission| allowed_permissions.index(permission) } end
[ "def", "verify_and_sort_permissions", "self", ".", "permissions", "+=", "[", ":find", ",", ":view", "]", "unless", "is_a?", "(", "DefaultPermissionSet", ")", "raise", "\"Invalid permissions: #{(permissions - allowed_permissions).inspect}. Must be one of #{allowed_permissions.inspect}\"", "unless", "permissions", ".", "all?", "{", "|", "permission", "|", "allowed_permissions", ".", "include?", "permission", "}", "self", ".", "permissions", "=", "permissions", ".", "uniq", ".", "sort_by", "{", "|", "permission", "|", "allowed_permissions", ".", "index", "(", "permission", ")", "}", "end" ]
Verifies that all the access levels are valid for the attached permissible Makes sure no permissions are duplicated Enforces the order of access levels in the access attribute using the order of the permissions array
[ "Verifies", "that", "all", "the", "access", "levels", "are", "valid", "for", "the", "attached", "permissible", "Makes", "sure", "no", "permissions", "are", "duplicated", "Enforces", "the", "order", "of", "access", "levels", "in", "the", "access", "attribute", "using", "the", "order", "of", "the", "permissions", "array" ]
33bfa5bfed84ec1644fd4ddfb75b661d24a2fb71
https://github.com/rrn/acts_as_joinable/blob/33bfa5bfed84ec1644fd4ddfb75b661d24a2fb71/lib/joinable/permissions_attribute_wrapper.rb#L131-L138
train
jeremyruppel/git-approvals
lib/git/approvals/rspec.rb
RSpec.Approvals.verify
def verify( options={}, &block ) approval = Git::Approvals::Approval.new( approval_path, options ) approval.diff( block.call ) do |err| ::RSpec::Expectations.fail_with err end rescue Errno::ENOENT => e ::RSpec::Expectations.fail_with e.message EOS end
ruby
def verify( options={}, &block ) approval = Git::Approvals::Approval.new( approval_path, options ) approval.diff( block.call ) do |err| ::RSpec::Expectations.fail_with err end rescue Errno::ENOENT => e ::RSpec::Expectations.fail_with e.message EOS end
[ "def", "verify", "(", "options", "=", "{", "}", ",", "&", "block", ")", "approval", "=", "Git", "::", "Approvals", "::", "Approval", ".", "new", "(", "approval_path", ",", "options", ")", "approval", ".", "diff", "(", "block", ".", "call", ")", "do", "|", "err", "|", "::", "RSpec", "::", "Expectations", ".", "fail_with", "err", "end", "rescue", "Errno", "::", "ENOENT", "=>", "e", "::", "RSpec", "::", "Expectations", ".", "fail_with", "e", ".", "message", "EOS", "end" ]
Verifies that the result of the block is the same as the approved version.
[ "Verifies", "that", "the", "result", "of", "the", "block", "is", "the", "same", "as", "the", "approved", "version", "." ]
4d08f5cce9e0aa1d716dd9e14c86bc94d9499f96
https://github.com/jeremyruppel/git-approvals/blob/4d08f5cce9e0aa1d716dd9e14c86bc94d9499f96/lib/git/approvals/rspec.rb#L15-L23
train
jeremyruppel/git-approvals
lib/git/approvals/rspec.rb
RSpec.Approvals.approval_filename
def approval_filename parts = [ example, *example.example_group.parent_groups ].map do |ex| Git::Approvals::Utils.filenamify ex.description end File.join parts.to_a.reverse end
ruby
def approval_filename parts = [ example, *example.example_group.parent_groups ].map do |ex| Git::Approvals::Utils.filenamify ex.description end File.join parts.to_a.reverse end
[ "def", "approval_filename", "parts", "=", "[", "example", ",", "*", "example", ".", "example_group", ".", "parent_groups", "]", ".", "map", "do", "|", "ex", "|", "Git", "::", "Approvals", "::", "Utils", ".", "filenamify", "ex", ".", "description", "end", "File", ".", "join", "parts", ".", "to_a", ".", "reverse", "end" ]
The approval filename
[ "The", "approval", "filename" ]
4d08f5cce9e0aa1d716dd9e14c86bc94d9499f96
https://github.com/jeremyruppel/git-approvals/blob/4d08f5cce9e0aa1d716dd9e14c86bc94d9499f96/lib/git/approvals/rspec.rb#L33-L38
train
octoai/gem-octocore-cassandra
lib/octocore-cassandra/trends.rb
Octo.Trends.aggregate_and_create
def aggregate_and_create(oftype, ts = Time.now.floor) Octo::Enterprise.each do |enterprise| calculate(enterprise.id, oftype, ts) end end
ruby
def aggregate_and_create(oftype, ts = Time.now.floor) Octo::Enterprise.each do |enterprise| calculate(enterprise.id, oftype, ts) end end
[ "def", "aggregate_and_create", "(", "oftype", ",", "ts", "=", "Time", ".", "now", ".", "floor", ")", "Octo", "::", "Enterprise", ".", "each", "do", "|", "enterprise", "|", "calculate", "(", "enterprise", ".", "id", ",", "oftype", ",", "ts", ")", "end", "end" ]
Aggregates and creates trends for all the enterprises for a specific trend type at a specific timestamp @param [Fixnum] oftype The type of trend to be calculated @param [Time] ts The time at which trend needs to be calculated
[ "Aggregates", "and", "creates", "trends", "for", "all", "the", "enterprises", "for", "a", "specific", "trend", "type", "at", "a", "specific", "timestamp" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/trends.rb#L32-L36
train
octoai/gem-octocore-cassandra
lib/octocore-cassandra/trends.rb
Octo.Trends.aggregate!
def aggregate!(ts = Time.now.floor) aggregate_and_create(Octo::Counter::TYPE_MINUTE, ts) end
ruby
def aggregate!(ts = Time.now.floor) aggregate_and_create(Octo::Counter::TYPE_MINUTE, ts) end
[ "def", "aggregate!", "(", "ts", "=", "Time", ".", "now", ".", "floor", ")", "aggregate_and_create", "(", "Octo", "::", "Counter", "::", "TYPE_MINUTE", ",", "ts", ")", "end" ]
Override the aggregate! defined in counter class as the calculations for trending are a little different
[ "Override", "the", "aggregate!", "defined", "in", "counter", "class", "as", "the", "calculations", "for", "trending", "are", "a", "little", "different" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/trends.rb#L40-L42
train
octoai/gem-octocore-cassandra
lib/octocore-cassandra/trends.rb
Octo.Trends.calculate
def calculate(enterprise_id, trend_type, ts = Time.now.floor) args = { enterprise_id: enterprise_id, ts: ts, type: trend_type } klass = @trend_for.constantize hitsResult = klass.public_send(:where, args) trends = hitsResult.map { |h| counter2trend(h) } # group trends as per the time of their happening and rank them on their # score grouped_trends = trends.group_by { |x| x.ts } grouped_trends.each do |_ts, trendlist| sorted_trendlist = trendlist.sort_by { |x| x.score } sorted_trendlist.each_with_index do |trend, index| trend.rank = index trend.type = trend_type trend.save! end end end
ruby
def calculate(enterprise_id, trend_type, ts = Time.now.floor) args = { enterprise_id: enterprise_id, ts: ts, type: trend_type } klass = @trend_for.constantize hitsResult = klass.public_send(:where, args) trends = hitsResult.map { |h| counter2trend(h) } # group trends as per the time of their happening and rank them on their # score grouped_trends = trends.group_by { |x| x.ts } grouped_trends.each do |_ts, trendlist| sorted_trendlist = trendlist.sort_by { |x| x.score } sorted_trendlist.each_with_index do |trend, index| trend.rank = index trend.type = trend_type trend.save! end end end
[ "def", "calculate", "(", "enterprise_id", ",", "trend_type", ",", "ts", "=", "Time", ".", "now", ".", "floor", ")", "args", "=", "{", "enterprise_id", ":", "enterprise_id", ",", "ts", ":", "ts", ",", "type", ":", "trend_type", "}", "klass", "=", "@trend_for", ".", "constantize", "hitsResult", "=", "klass", ".", "public_send", "(", ":where", ",", "args", ")", "trends", "=", "hitsResult", ".", "map", "{", "|", "h", "|", "counter2trend", "(", "h", ")", "}", "grouped_trends", "=", "trends", ".", "group_by", "{", "|", "x", "|", "x", ".", "ts", "}", "grouped_trends", ".", "each", "do", "|", "_ts", ",", "trendlist", "|", "sorted_trendlist", "=", "trendlist", ".", "sort_by", "{", "|", "x", "|", "x", ".", "score", "}", "sorted_trendlist", ".", "each_with_index", "do", "|", "trend", ",", "index", "|", "trend", ".", "rank", "=", "index", "trend", ".", "type", "=", "trend_type", "trend", ".", "save!", "end", "end", "end" ]
Performs the actual trend calculation @param [String] enterprise_id The enterprise ID for whom trend needs to be found @param [Fixnum] trend_type The trend type to be calculates @param [Time] ts The Timestamp at which trend needs to be calculated.
[ "Performs", "the", "actual", "trend", "calculation" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/trends.rb#L48-L70
train
octoai/gem-octocore-cassandra
lib/octocore-cassandra/trends.rb
Octo.Trends.get_trending
def get_trending(enterprise_id, type, opts={}) ts = opts.fetch(:ts, Time.now.floor) args = { enterprise_id: enterprise_id, ts: opts.fetch(:ts, Time.now.floor), type: type } res = where(args).limit(opts.fetch(:limit, DEFAULT_COUNT)) enterprise = Octo::Enterprise.find_by_id(enterprise_id) if res.count == 0 and enterprise.fakedata? Octo.logger.info 'Beginning to fake data' res = [] if ts.class == Range ts_begin = ts.begin ts_end = ts.end ts_begin.to(ts_end, 1.day).each do |_ts| 3.times do |rank| items = @trend_class.constantize.send(:where, {enterprise_id: enterprise_id}).first(10) if items.count > 0 uid = items.shuffle.pop.unique_id _args = args.merge( ts: _ts, rank: rank, score: rank+1, uid: uid ) res << self.new(_args).save! end end end elsif ts.class == Time 3.times do |rank| uid = 0 items = @trend_class.constantize.send(:where, {enterprise_id: enterprise_id}).first(10) if items.count > 0 uid = items.shuffle.pop.unique_id _args = args.merge( rank: rank, score: rank+1, uid: uid ) res << self.new(_args).save! end end end end res.map do |r| clazz = @trend_class.constantize clazz.public_send(:recreate_from, r) end end
ruby
def get_trending(enterprise_id, type, opts={}) ts = opts.fetch(:ts, Time.now.floor) args = { enterprise_id: enterprise_id, ts: opts.fetch(:ts, Time.now.floor), type: type } res = where(args).limit(opts.fetch(:limit, DEFAULT_COUNT)) enterprise = Octo::Enterprise.find_by_id(enterprise_id) if res.count == 0 and enterprise.fakedata? Octo.logger.info 'Beginning to fake data' res = [] if ts.class == Range ts_begin = ts.begin ts_end = ts.end ts_begin.to(ts_end, 1.day).each do |_ts| 3.times do |rank| items = @trend_class.constantize.send(:where, {enterprise_id: enterprise_id}).first(10) if items.count > 0 uid = items.shuffle.pop.unique_id _args = args.merge( ts: _ts, rank: rank, score: rank+1, uid: uid ) res << self.new(_args).save! end end end elsif ts.class == Time 3.times do |rank| uid = 0 items = @trend_class.constantize.send(:where, {enterprise_id: enterprise_id}).first(10) if items.count > 0 uid = items.shuffle.pop.unique_id _args = args.merge( rank: rank, score: rank+1, uid: uid ) res << self.new(_args).save! end end end end res.map do |r| clazz = @trend_class.constantize clazz.public_send(:recreate_from, r) end end
[ "def", "get_trending", "(", "enterprise_id", ",", "type", ",", "opts", "=", "{", "}", ")", "ts", "=", "opts", ".", "fetch", "(", ":ts", ",", "Time", ".", "now", ".", "floor", ")", "args", "=", "{", "enterprise_id", ":", "enterprise_id", ",", "ts", ":", "opts", ".", "fetch", "(", ":ts", ",", "Time", ".", "now", ".", "floor", ")", ",", "type", ":", "type", "}", "res", "=", "where", "(", "args", ")", ".", "limit", "(", "opts", ".", "fetch", "(", ":limit", ",", "DEFAULT_COUNT", ")", ")", "enterprise", "=", "Octo", "::", "Enterprise", ".", "find_by_id", "(", "enterprise_id", ")", "if", "res", ".", "count", "==", "0", "and", "enterprise", ".", "fakedata?", "Octo", ".", "logger", ".", "info", "'Beginning to fake data'", "res", "=", "[", "]", "if", "ts", ".", "class", "==", "Range", "ts_begin", "=", "ts", ".", "begin", "ts_end", "=", "ts", ".", "end", "ts_begin", ".", "to", "(", "ts_end", ",", "1", ".", "day", ")", ".", "each", "do", "|", "_ts", "|", "3", ".", "times", "do", "|", "rank", "|", "items", "=", "@trend_class", ".", "constantize", ".", "send", "(", ":where", ",", "{", "enterprise_id", ":", "enterprise_id", "}", ")", ".", "first", "(", "10", ")", "if", "items", ".", "count", ">", "0", "uid", "=", "items", ".", "shuffle", ".", "pop", ".", "unique_id", "_args", "=", "args", ".", "merge", "(", "ts", ":", "_ts", ",", "rank", ":", "rank", ",", "score", ":", "rank", "+", "1", ",", "uid", ":", "uid", ")", "res", "<<", "self", ".", "new", "(", "_args", ")", ".", "save!", "end", "end", "end", "elsif", "ts", ".", "class", "==", "Time", "3", ".", "times", "do", "|", "rank", "|", "uid", "=", "0", "items", "=", "@trend_class", ".", "constantize", ".", "send", "(", ":where", ",", "{", "enterprise_id", ":", "enterprise_id", "}", ")", ".", "first", "(", "10", ")", "if", "items", ".", "count", ">", "0", "uid", "=", "items", ".", "shuffle", ".", "pop", ".", "unique_id", "_args", "=", "args", ".", "merge", "(", "rank", ":", "rank", ",", "score", ":", "rank", "+", "1", ",", "uid", ":", "uid", ")", "res", "<<", "self", ".", "new", "(", "_args", ")", ".", "save!", "end", "end", "end", "end", "res", ".", "map", "do", "|", "r", "|", "clazz", "=", "@trend_class", ".", "constantize", "clazz", ".", "public_send", "(", ":recreate_from", ",", "r", ")", "end", "end" ]
Gets the trend of a type at a time @param [String] enterprise_id The ID of enterprise for whom trend to fetch @param [Fixnum] type The type of trend to fetch @param [Hash] opts The options to be provided for finding trends
[ "Gets", "the", "trend", "of", "a", "type", "at", "a", "time" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/trends.rb#L90-L131
train
octoai/gem-octocore-cassandra
lib/octocore-cassandra/trends.rb
Octo.Trends.counter2trend
def counter2trend(counter) self.new({ enterprise: counter.enterprise, score: score(counter.divergence), uid: counter.uid, ts: counter.ts }) end
ruby
def counter2trend(counter) self.new({ enterprise: counter.enterprise, score: score(counter.divergence), uid: counter.uid, ts: counter.ts }) end
[ "def", "counter2trend", "(", "counter", ")", "self", ".", "new", "(", "{", "enterprise", ":", "counter", ".", "enterprise", ",", "score", ":", "score", "(", "counter", ".", "divergence", ")", ",", "uid", ":", "counter", ".", "uid", ",", "ts", ":", "counter", ".", "ts", "}", ")", "end" ]
Converts a couunter into a trend @param [Object] counter A counter object. This object must belong to one of the counter types defined in models. @return [Object] Returns a trend instance corresponding to the counter instance
[ "Converts", "a", "couunter", "into", "a", "trend" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/trends.rb#L140-L147
train
bernerdschaefer/uninhibited
lib/uninhibited/formatter.rb
Uninhibited.Formatter.example_pending
def example_pending(example) if example_group.metadata[:feature] && example.metadata[:skipped] @skipped_examples << pending_examples.delete(example) @skipped_count += 1 output.puts cyan("#{current_indentation}#{example.description}") else super end end
ruby
def example_pending(example) if example_group.metadata[:feature] && example.metadata[:skipped] @skipped_examples << pending_examples.delete(example) @skipped_count += 1 output.puts cyan("#{current_indentation}#{example.description}") else super end end
[ "def", "example_pending", "(", "example", ")", "if", "example_group", ".", "metadata", "[", ":feature", "]", "&&", "example", ".", "metadata", "[", ":skipped", "]", "@skipped_examples", "<<", "pending_examples", ".", "delete", "(", "example", ")", "@skipped_count", "+=", "1", "output", ".", "puts", "cyan", "(", "\"#{current_indentation}#{example.description}\"", ")", "else", "super", "end", "end" ]
Builds a new formatter for outputting Uninhibited features. @api rspec @param [IO] output the output stream Adds the pending example to skipped examples array if it was skipped, otherwise it delegates to super. @api rspec
[ "Builds", "a", "new", "formatter", "for", "outputting", "Uninhibited", "features", "." ]
a45297e127f529ee10719f0306b1ae6721450a33
https://github.com/bernerdschaefer/uninhibited/blob/a45297e127f529ee10719f0306b1ae6721450a33/lib/uninhibited/formatter.rb#L28-L36
train
bernerdschaefer/uninhibited
lib/uninhibited/formatter.rb
Uninhibited.Formatter.summary_line
def summary_line(example_count, failure_count, pending_count) pending_count -= skipped_count summary = pluralize(example_count, "example") summary << " (" summary << red(pluralize(failure_count, "failure")) summary << ", " << yellow("#{pending_count} pending") if pending_count > 0 summary << ", " << cyan("#{skipped_count} skipped") if skipped_count > 0 summary << ")" summary end
ruby
def summary_line(example_count, failure_count, pending_count) pending_count -= skipped_count summary = pluralize(example_count, "example") summary << " (" summary << red(pluralize(failure_count, "failure")) summary << ", " << yellow("#{pending_count} pending") if pending_count > 0 summary << ", " << cyan("#{skipped_count} skipped") if skipped_count > 0 summary << ")" summary end
[ "def", "summary_line", "(", "example_count", ",", "failure_count", ",", "pending_count", ")", "pending_count", "-=", "skipped_count", "summary", "=", "pluralize", "(", "example_count", ",", "\"example\"", ")", "summary", "<<", "\" (\"", "summary", "<<", "red", "(", "pluralize", "(", "failure_count", ",", "\"failure\"", ")", ")", "summary", "<<", "\", \"", "<<", "yellow", "(", "\"#{pending_count} pending\"", ")", "if", "pending_count", ">", "0", "summary", "<<", "\", \"", "<<", "cyan", "(", "\"#{skipped_count} skipped\"", ")", "if", "skipped_count", ">", "0", "summary", "<<", "\")\"", "summary", "end" ]
Generates a colorized summary line based on the supplied arguments. formatter.summary_line(1, 0, 0) # => 1 example (0 failures) formatter.summary_line(2, 1, 1) # => 2 examples (1 failure, 1 pending) formatter.skipped_count += 1 formatter.summary_line(2, 0, 0) # => 2 examples (1 failure, 1 skipped) @param [Integer] example_count the total examples run @param [Integer] failure_count the failed examples @param [Integer] pending_count the pending examples @return [String] the formatted summary line @api rspec
[ "Generates", "a", "colorized", "summary", "line", "based", "on", "the", "supplied", "arguments", "." ]
a45297e127f529ee10719f0306b1ae6721450a33
https://github.com/bernerdschaefer/uninhibited/blob/a45297e127f529ee10719f0306b1ae6721450a33/lib/uninhibited/formatter.rb#L67-L76
train
MakarovCode/EasyPayULatam
lib/easy_pay_u_latam/r_api/subscription_interceptor.rb
PayuLatam.SubscriptionInterceptor.run
def run PayuLatam::SubscriptionService.new(context.params, context.current_user).call rescue => exception fail!(exception.message) end
ruby
def run PayuLatam::SubscriptionService.new(context.params, context.current_user).call rescue => exception fail!(exception.message) end
[ "def", "run", "PayuLatam", "::", "SubscriptionService", ".", "new", "(", "context", ".", "params", ",", "context", ".", "current_user", ")", ".", "call", "rescue", "=>", "exception", "fail!", "(", "exception", ".", "message", ")", "end" ]
metodo principal de esta clase al estar en un 'rescue' evitamos que el proyecto saque error 500 cuando algo sale mal INTERCEPTAMOS el error y lo enviamos al controller para que trabaje con el de la variable @context, obtenemos los params y el current_user en los params se encuentran datos del plan , tarjeta de crédito seleccionada o datos de nueva tarjeta se ejecuta el metodo 'call' del SubscriptionService
[ "metodo", "principal", "de", "esta", "clase", "al", "estar", "en", "un", "rescue", "evitamos", "que", "el", "proyecto", "saque", "error", "500", "cuando", "algo", "sale", "mal", "INTERCEPTAMOS", "el", "error", "y", "lo", "enviamos", "al", "controller", "para", "que", "trabaje", "con", "el" ]
c412b36fc316eabc338ce9cd152b8fea7316983d
https://github.com/MakarovCode/EasyPayULatam/blob/c412b36fc316eabc338ce9cd152b8fea7316983d/lib/easy_pay_u_latam/r_api/subscription_interceptor.rb#L34-L38
train
redding/logsly
lib/logsly/logging182/stats.rb
Logsly::Logging182::Stats.Sampler.coalesce
def coalesce( other ) @sum += other.sum @sumsq += other.sumsq if other.num > 0 @min = other.min if @min > other.min @max = other.max if @max < other.max @last = other.last end @num += other.num end
ruby
def coalesce( other ) @sum += other.sum @sumsq += other.sumsq if other.num > 0 @min = other.min if @min > other.min @max = other.max if @max < other.max @last = other.last end @num += other.num end
[ "def", "coalesce", "(", "other", ")", "@sum", "+=", "other", ".", "sum", "@sumsq", "+=", "other", ".", "sumsq", "if", "other", ".", "num", ">", "0", "@min", "=", "other", ".", "min", "if", "@min", ">", "other", ".", "min", "@max", "=", "other", ".", "max", "if", "@max", "<", "other", ".", "max", "@last", "=", "other", ".", "last", "end", "@num", "+=", "other", ".", "num", "end" ]
Coalesce the statistics from the _other_ sampler into this one. The _other_ sampler is not modified by this method. Coalescing the same two samplers multiple times should only be done if one of the samplers is reset between calls to this method. Otherwise statistics will be counted multiple times.
[ "Coalesce", "the", "statistics", "from", "the", "_other_", "sampler", "into", "this", "one", ".", "The", "_other_", "sampler", "is", "not", "modified", "by", "this", "method", "." ]
a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf
https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/stats.rb#L47-L56
train
redding/logsly
lib/logsly/logging182/stats.rb
Logsly::Logging182::Stats.Sampler.sample
def sample( s ) @sum += s @sumsq += s * s if @num == 0 @min = @max = s else @min = s if @min > s @max = s if @max < s end @num += 1 @last = s end
ruby
def sample( s ) @sum += s @sumsq += s * s if @num == 0 @min = @max = s else @min = s if @min > s @max = s if @max < s end @num += 1 @last = s end
[ "def", "sample", "(", "s", ")", "@sum", "+=", "s", "@sumsq", "+=", "s", "*", "s", "if", "@num", "==", "0", "@min", "=", "@max", "=", "s", "else", "@min", "=", "s", "if", "@min", ">", "s", "@max", "=", "s", "if", "@max", "<", "s", "end", "@num", "+=", "1", "@last", "=", "s", "end" ]
Adds a sampling to the calculations.
[ "Adds", "a", "sampling", "to", "the", "calculations", "." ]
a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf
https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/stats.rb#L60-L71
train
redding/logsly
lib/logsly/logging182/stats.rb
Logsly::Logging182::Stats.Sampler.sd
def sd return 0.0 if num < 2 # (sqrt( ((s).sumsq - ( (s).sum * (s).sum / (s).num)) / ((s).num-1) )) begin return Math.sqrt( (sumsq - ( sum * sum / num)) / (num-1) ) rescue Errno::EDOM return 0.0 end end
ruby
def sd return 0.0 if num < 2 # (sqrt( ((s).sumsq - ( (s).sum * (s).sum / (s).num)) / ((s).num-1) )) begin return Math.sqrt( (sumsq - ( sum * sum / num)) / (num-1) ) rescue Errno::EDOM return 0.0 end end
[ "def", "sd", "return", "0.0", "if", "num", "<", "2", "begin", "return", "Math", ".", "sqrt", "(", "(", "sumsq", "-", "(", "sum", "*", "sum", "/", "num", ")", ")", "/", "(", "num", "-", "1", ")", ")", "rescue", "Errno", "::", "EDOM", "return", "0.0", "end", "end" ]
Calculates the standard deviation of the data so far.
[ "Calculates", "the", "standard", "deviation", "of", "the", "data", "so", "far", "." ]
a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf
https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/stats.rb#L106-L115
train
redding/logsly
lib/logsly/logging182/stats.rb
Logsly::Logging182::Stats.Tracker.coalesce
def coalesce( other ) sync { other.stats.each do |name,sampler| stats[name].coalesce(sampler) end } end
ruby
def coalesce( other ) sync { other.stats.each do |name,sampler| stats[name].coalesce(sampler) end } end
[ "def", "coalesce", "(", "other", ")", "sync", "{", "other", ".", "stats", ".", "each", "do", "|", "name", ",", "sampler", "|", "stats", "[", "name", "]", ".", "coalesce", "(", "sampler", ")", "end", "}", "end" ]
Create a new Tracker instance. An optional boolean can be passed in to change the "threadsafe" value of the tracker. By default all trackers are created to be threadsafe. Coalesce the samplers from the _other_ tracker into this one. The _other_ tracker is not modified by this method. Coalescing the same two trackers multiple times should only be done if one of the trackers is reset between calls to this method. Otherwise statistics will be counted multiple times. Only this tracker is locked when the coalescing is happening. It is left to the user to lock the other tracker if that is the desired behavior. This is a deliberate choice in order to prevent deadlock situations where two threads are contending on the same mutex.
[ "Create", "a", "new", "Tracker", "instance", ".", "An", "optional", "boolean", "can", "be", "passed", "in", "to", "change", "the", "threadsafe", "value", "of", "the", "tracker", ".", "By", "default", "all", "trackers", "are", "created", "to", "be", "threadsafe", "." ]
a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf
https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/stats.rb#L175-L181
train
redding/logsly
lib/logsly/logging182/stats.rb
Logsly::Logging182::Stats.Tracker.time
def time( event ) sync {stats[event].mark} yield ensure sync {stats[event].tick} end
ruby
def time( event ) sync {stats[event].mark} yield ensure sync {stats[event].tick} end
[ "def", "time", "(", "event", ")", "sync", "{", "stats", "[", "event", "]", ".", "mark", "}", "yield", "ensure", "sync", "{", "stats", "[", "event", "]", ".", "tick", "}", "end" ]
Time the execution of the given block and store the results in the named _event_ sampler. The sampler will be created if it does not exist.
[ "Time", "the", "execution", "of", "the", "given", "block", "and", "store", "the", "results", "in", "the", "named", "_event_", "sampler", ".", "The", "sampler", "will", "be", "created", "if", "it", "does", "not", "exist", "." ]
a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf
https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/stats.rb#L208-L213
train
redding/logsly
lib/logsly/logging182/stats.rb
Logsly::Logging182::Stats.Tracker.periodically_run
def periodically_run( period, &block ) raise ArgumentError, 'a runner already exists' unless @runner.nil? @runner = Thread.new do start = stop = Time.now.to_f loop do seconds = period - (stop-start) seconds = period if seconds <= 0 sleep seconds start = Time.now.to_f break if Thread.current[:stop] == true if @mutex then @mutex.synchronize(&block) else block.call end stop = Time.now.to_f end end end
ruby
def periodically_run( period, &block ) raise ArgumentError, 'a runner already exists' unless @runner.nil? @runner = Thread.new do start = stop = Time.now.to_f loop do seconds = period - (stop-start) seconds = period if seconds <= 0 sleep seconds start = Time.now.to_f break if Thread.current[:stop] == true if @mutex then @mutex.synchronize(&block) else block.call end stop = Time.now.to_f end end end
[ "def", "periodically_run", "(", "period", ",", "&", "block", ")", "raise", "ArgumentError", ",", "'a runner already exists'", "unless", "@runner", ".", "nil?", "@runner", "=", "Thread", ".", "new", "do", "start", "=", "stop", "=", "Time", ".", "now", ".", "to_f", "loop", "do", "seconds", "=", "period", "-", "(", "stop", "-", "start", ")", "seconds", "=", "period", "if", "seconds", "<=", "0", "sleep", "seconds", "start", "=", "Time", ".", "now", ".", "to_f", "break", "if", "Thread", ".", "current", "[", ":stop", "]", "==", "true", "if", "@mutex", "then", "@mutex", ".", "synchronize", "(", "&", "block", ")", "else", "block", ".", "call", "end", "stop", "=", "Time", ".", "now", ".", "to_f", "end", "end", "end" ]
Periodically execute the given _block_ at the given _period_. The tracker will be locked while the block is executing. This method is useful for logging statistics at given interval. Example periodically_run( 300 ) { logger = Logsly::Logging182::Logger['stats'] tracker.each {|sampler| logger << sampler.to_s} tracker.reset }
[ "Periodically", "execute", "the", "given", "_block_", "at", "the", "given", "_period_", ".", "The", "tracker", "will", "be", "locked", "while", "the", "block", "is", "executing", "." ]
a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf
https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/stats.rb#L235-L252
train
ossuarium/palimpsest
lib/palimpsest/assets.rb
Palimpsest.Assets.write
def write(target, gzip: options[:gzip], hash: options[:hash]) asset = assets[target] return if asset.nil? name = hash ? asset.digest_path : asset.logical_path.to_s name = File.join(options[:output], name) unless options[:output].nil? path = name path = File.join(directory, path) unless directory.nil? write(target, gzip: gzip, hash: false) if hash == :also_unhashed asset.write_to "#{path}.gz", compress: true if gzip asset.write_to path name end
ruby
def write(target, gzip: options[:gzip], hash: options[:hash]) asset = assets[target] return if asset.nil? name = hash ? asset.digest_path : asset.logical_path.to_s name = File.join(options[:output], name) unless options[:output].nil? path = name path = File.join(directory, path) unless directory.nil? write(target, gzip: gzip, hash: false) if hash == :also_unhashed asset.write_to "#{path}.gz", compress: true if gzip asset.write_to path name end
[ "def", "write", "(", "target", ",", "gzip", ":", "options", "[", ":gzip", "]", ",", "hash", ":", "options", "[", ":hash", "]", ")", "asset", "=", "assets", "[", "target", "]", "return", "if", "asset", ".", "nil?", "name", "=", "hash", "?", "asset", ".", "digest_path", ":", "asset", ".", "logical_path", ".", "to_s", "name", "=", "File", ".", "join", "(", "options", "[", ":output", "]", ",", "name", ")", "unless", "options", "[", ":output", "]", ".", "nil?", "path", "=", "name", "path", "=", "File", ".", "join", "(", "directory", ",", "path", ")", "unless", "directory", ".", "nil?", "write", "(", "target", ",", "gzip", ":", "gzip", ",", "hash", ":", "false", ")", "if", "hash", "==", ":also_unhashed", "asset", ".", "write_to", "\"#{path}.gz\"", ",", "compress", ":", "true", "if", "gzip", "asset", ".", "write_to", "path", "name", "end" ]
Write a target asset to file with a hashed name. @param target [String] logical path to asset @param gzip [Boolean] if the asset should be gzipped @param hash [Boolean] if the asset name should include the hash @return [String, nil] the relative path to the written asset or `nil` if no such asset
[ "Write", "a", "target", "asset", "to", "file", "with", "a", "hashed", "name", "." ]
7a1d45d33ec7ed878e2b761150ec163ce2125274
https://github.com/ossuarium/palimpsest/blob/7a1d45d33ec7ed878e2b761150ec163ce2125274/lib/palimpsest/assets.rb#L131-L147
train
medcat/breadcrumb_trail
lib/breadcrumb_trail/breadcrumb.rb
BreadcrumbTrail.Breadcrumb.computed_path
def computed_path(context) @_path ||= case @path when String, Hash @path when Symbol context.public_send(@path) # todo when Proc context.instance_exec(&@path) else raise ArgumentError, "Expected one of String, Symbol, or Proc, " \ "got #{@path.class}" end end
ruby
def computed_path(context) @_path ||= case @path when String, Hash @path when Symbol context.public_send(@path) # todo when Proc context.instance_exec(&@path) else raise ArgumentError, "Expected one of String, Symbol, or Proc, " \ "got #{@path.class}" end end
[ "def", "computed_path", "(", "context", ")", "@_path", "||=", "case", "@path", "when", "String", ",", "Hash", "@path", "when", "Symbol", "context", ".", "public_send", "(", "@path", ")", "when", "Proc", "context", ".", "instance_exec", "(", "&", "@path", ")", "else", "raise", "ArgumentError", ",", "\"Expected one of String, Symbol, or Proc, \"", "\"got #{@path.class}\"", "end", "end" ]
Computes the path of the breadcrumb under the given context. @return [String, Hash]
[ "Computes", "the", "path", "of", "the", "breadcrumb", "under", "the", "given", "context", "." ]
02803a8a3f2492bf6e23d97873b3b906ee95d0b9
https://github.com/medcat/breadcrumb_trail/blob/02803a8a3f2492bf6e23d97873b3b906ee95d0b9/lib/breadcrumb_trail/breadcrumb.rb#L59-L72
train
medcat/breadcrumb_trail
lib/breadcrumb_trail/breadcrumb.rb
BreadcrumbTrail.Breadcrumb.computed_name
def computed_name(context) @_name ||= case @name when String @name when Symbol I18n.translate(@name) when Proc context.instance_exec(&@name) when nil computed_path(context) else raise ArgumentError, "Expected one of String, Symbol, or Proc, " \ "got #{@name.class}" end end
ruby
def computed_name(context) @_name ||= case @name when String @name when Symbol I18n.translate(@name) when Proc context.instance_exec(&@name) when nil computed_path(context) else raise ArgumentError, "Expected one of String, Symbol, or Proc, " \ "got #{@name.class}" end end
[ "def", "computed_name", "(", "context", ")", "@_name", "||=", "case", "@name", "when", "String", "@name", "when", "Symbol", "I18n", ".", "translate", "(", "@name", ")", "when", "Proc", "context", ".", "instance_exec", "(", "&", "@name", ")", "when", "nil", "computed_path", "(", "context", ")", "else", "raise", "ArgumentError", ",", "\"Expected one of String, Symbol, or Proc, \"", "\"got #{@name.class}\"", "end", "end" ]
Computes the name of the breadcrumb under the given context. @return [String]
[ "Computes", "the", "name", "of", "the", "breadcrumb", "under", "the", "given", "context", "." ]
02803a8a3f2492bf6e23d97873b3b906ee95d0b9
https://github.com/medcat/breadcrumb_trail/blob/02803a8a3f2492bf6e23d97873b3b906ee95d0b9/lib/breadcrumb_trail/breadcrumb.rb#L77-L92
train
sugaryourcoffee/syclink
lib/syclink/firefox.rb
SycLink.Firefox.read
def read bookmark_file = Dir.glob(File.expand_path(path)).shift raise "Did not find file #{path}" unless bookmark_file db = SQLite3::Database.new(path) import = db.execute(QUERY_STRING) end
ruby
def read bookmark_file = Dir.glob(File.expand_path(path)).shift raise "Did not find file #{path}" unless bookmark_file db = SQLite3::Database.new(path) import = db.execute(QUERY_STRING) end
[ "def", "read", "bookmark_file", "=", "Dir", ".", "glob", "(", "File", ".", "expand_path", "(", "path", ")", ")", ".", "shift", "raise", "\"Did not find file #{path}\"", "unless", "bookmark_file", "db", "=", "SQLite3", "::", "Database", ".", "new", "(", "path", ")", "import", "=", "db", ".", "execute", "(", "QUERY_STRING", ")", "end" ]
Reads the links from the Firefox database places.sqlite
[ "Reads", "the", "links", "from", "the", "Firefox", "database", "places", ".", "sqlite" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/firefox.rb#L14-L21
train
sugaryourcoffee/syclink
lib/syclink/firefox.rb
SycLink.Firefox.rows
def rows read.map do |row| a = row[0]; b = row[1]; c = row[2]; d = row[3]; e = row[4]; f = row[5] [a, b || c, (d || '').gsub("\n", ' '), [e, f].join(',').gsub(/^,|,$/, '')] end end
ruby
def rows read.map do |row| a = row[0]; b = row[1]; c = row[2]; d = row[3]; e = row[4]; f = row[5] [a, b || c, (d || '').gsub("\n", ' '), [e, f].join(',').gsub(/^,|,$/, '')] end end
[ "def", "rows", "read", ".", "map", "do", "|", "row", "|", "a", "=", "row", "[", "0", "]", ";", "b", "=", "row", "[", "1", "]", ";", "c", "=", "row", "[", "2", "]", ";", "d", "=", "row", "[", "3", "]", ";", "e", "=", "row", "[", "4", "]", ";", "f", "=", "row", "[", "5", "]", "[", "a", ",", "b", "||", "c", ",", "(", "d", "||", "''", ")", ".", "gsub", "(", "\"\\n\"", ",", "' '", ")", ",", "[", "e", ",", "f", "]", ".", "join", "(", "','", ")", ".", "gsub", "(", "/", "/", ",", "''", ")", "]", "end", "end" ]
Returns row values in Arrays
[ "Returns", "row", "values", "in", "Arrays" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/firefox.rb#L24-L32
train
linrock/favicon_party
lib/favicon_party/image.rb
FaviconParty.Image.to_png
def to_png return @png_data if !@png_data.nil? image = minimagick_image image.resize '16x16!' image.format 'png' image.strip @png_data = image.to_blob raise FaviconParty::InvalidData.new("Empty png") if @png_data.empty? @png_data end
ruby
def to_png return @png_data if !@png_data.nil? image = minimagick_image image.resize '16x16!' image.format 'png' image.strip @png_data = image.to_blob raise FaviconParty::InvalidData.new("Empty png") if @png_data.empty? @png_data end
[ "def", "to_png", "return", "@png_data", "if", "!", "@png_data", ".", "nil?", "image", "=", "minimagick_image", "image", ".", "resize", "'16x16!'", "image", ".", "format", "'png'", "image", ".", "strip", "@png_data", "=", "image", ".", "to_blob", "raise", "FaviconParty", "::", "InvalidData", ".", "new", "(", "\"Empty png\"", ")", "if", "@png_data", ".", "empty?", "@png_data", "end" ]
Export source_data as a 16x16 png
[ "Export", "source_data", "as", "a", "16x16", "png" ]
645d3c6f4a7152bf705ac092976a74f405f83ca1
https://github.com/linrock/favicon_party/blob/645d3c6f4a7152bf705ac092976a74f405f83ca1/lib/favicon_party/image.rb#L106-L115
train
ossuarium/palimpsest
lib/palimpsest/repo.rb
Palimpsest.Repo.extract_repo
def extract_repo(path, destination, reference) fail 'Git not installed' unless Utils.command? 'git' Dir.chdir path do system "git archive #{reference} | tar -x -C #{destination}" end end
ruby
def extract_repo(path, destination, reference) fail 'Git not installed' unless Utils.command? 'git' Dir.chdir path do system "git archive #{reference} | tar -x -C #{destination}" end end
[ "def", "extract_repo", "(", "path", ",", "destination", ",", "reference", ")", "fail", "'Git not installed'", "unless", "Utils", ".", "command?", "'git'", "Dir", ".", "chdir", "path", "do", "system", "\"git archive #{reference} | tar -x -C #{destination}\"", "end", "end" ]
Extract repository files at a particular reference to directory.
[ "Extract", "repository", "files", "at", "a", "particular", "reference", "to", "directory", "." ]
7a1d45d33ec7ed878e2b761150ec163ce2125274
https://github.com/ossuarium/palimpsest/blob/7a1d45d33ec7ed878e2b761150ec163ce2125274/lib/palimpsest/repo.rb#L82-L87
train
medcat/breadcrumb_trail
lib/breadcrumb_trail/builder.rb
BreadcrumbTrail.BlockBuilder.call
def call buffer = ActiveSupport::SafeBuffer.new @breadcrumbs.each do |breadcrumb| buffer << @block.call(breadcrumb.computed(@context)) end buffer end
ruby
def call buffer = ActiveSupport::SafeBuffer.new @breadcrumbs.each do |breadcrumb| buffer << @block.call(breadcrumb.computed(@context)) end buffer end
[ "def", "call", "buffer", "=", "ActiveSupport", "::", "SafeBuffer", ".", "new", "@breadcrumbs", ".", "each", "do", "|", "breadcrumb", "|", "buffer", "<<", "@block", ".", "call", "(", "breadcrumb", ".", "computed", "(", "@context", ")", ")", "end", "buffer", "end" ]
Creates a buffer, and iterates over every breadcrumb, yielding the breadcrumb to the block given on initialization. @return [String]
[ "Creates", "a", "buffer", "and", "iterates", "over", "every", "breadcrumb", "yielding", "the", "breadcrumb", "to", "the", "block", "given", "on", "initialization", "." ]
02803a8a3f2492bf6e23d97873b3b906ee95d0b9
https://github.com/medcat/breadcrumb_trail/blob/02803a8a3f2492bf6e23d97873b3b906ee95d0b9/lib/breadcrumb_trail/builder.rb#L43-L50
train
medcat/breadcrumb_trail
lib/breadcrumb_trail/builder.rb
BreadcrumbTrail.HTMLBuilder.call
def call outer_tag = @options.fetch(:outer, "ol") inner_tag = @options.fetch(:inner, "li") outer = tag(outer_tag, @options.fetch(:outer_options, nil), true) if outer_tag inner = tag(inner_tag, @options.fetch(:inner_options, nil), true) if inner_tag buffer = ActiveSupport::SafeBuffer.new buffer.safe_concat(outer) if outer_tag @breadcrumbs.each do |breadcrumb| buffer.safe_concat(inner) if inner_tag buffer << link_to(breadcrumb.computed_name(@context), breadcrumb.computed_path(@context), breadcrumb.options) buffer.safe_concat("</#{inner_tag}>") if inner_tag end buffer.safe_concat("</#{outer_tag}>") if outer_tag buffer end
ruby
def call outer_tag = @options.fetch(:outer, "ol") inner_tag = @options.fetch(:inner, "li") outer = tag(outer_tag, @options.fetch(:outer_options, nil), true) if outer_tag inner = tag(inner_tag, @options.fetch(:inner_options, nil), true) if inner_tag buffer = ActiveSupport::SafeBuffer.new buffer.safe_concat(outer) if outer_tag @breadcrumbs.each do |breadcrumb| buffer.safe_concat(inner) if inner_tag buffer << link_to(breadcrumb.computed_name(@context), breadcrumb.computed_path(@context), breadcrumb.options) buffer.safe_concat("</#{inner_tag}>") if inner_tag end buffer.safe_concat("</#{outer_tag}>") if outer_tag buffer end
[ "def", "call", "outer_tag", "=", "@options", ".", "fetch", "(", ":outer", ",", "\"ol\"", ")", "inner_tag", "=", "@options", ".", "fetch", "(", ":inner", ",", "\"li\"", ")", "outer", "=", "tag", "(", "outer_tag", ",", "@options", ".", "fetch", "(", ":outer_options", ",", "nil", ")", ",", "true", ")", "if", "outer_tag", "inner", "=", "tag", "(", "inner_tag", ",", "@options", ".", "fetch", "(", ":inner_options", ",", "nil", ")", ",", "true", ")", "if", "inner_tag", "buffer", "=", "ActiveSupport", "::", "SafeBuffer", ".", "new", "buffer", ".", "safe_concat", "(", "outer", ")", "if", "outer_tag", "@breadcrumbs", ".", "each", "do", "|", "breadcrumb", "|", "buffer", ".", "safe_concat", "(", "inner", ")", "if", "inner_tag", "buffer", "<<", "link_to", "(", "breadcrumb", ".", "computed_name", "(", "@context", ")", ",", "breadcrumb", ".", "computed_path", "(", "@context", ")", ",", "breadcrumb", ".", "options", ")", "buffer", ".", "safe_concat", "(", "\"</#{inner_tag}>\"", ")", "if", "inner_tag", "end", "buffer", ".", "safe_concat", "(", "\"</#{outer_tag}>\"", ")", "if", "outer_tag", "buffer", "end" ]
Renders the breadcrumbs in HTML tags. If no options were provided on initialization, it uses defaults. @option @options [String] :outer ("ol") The outer tag element to use. @option @options [String] :inner ("li") The inner tag element to use. @option @options [Hash] :outer_options (nil) The outer tag element attributes to use. Things like `class="some-class"` are best placed here. @option @options [Hash] :inner_options (nil) The inner tag element attributes to use. Things like `class="some-class"` are best placed here. @return [String]
[ "Renders", "the", "breadcrumbs", "in", "HTML", "tags", ".", "If", "no", "options", "were", "provided", "on", "initialization", "it", "uses", "defaults", "." ]
02803a8a3f2492bf6e23d97873b3b906ee95d0b9
https://github.com/medcat/breadcrumb_trail/blob/02803a8a3f2492bf6e23d97873b3b906ee95d0b9/lib/breadcrumb_trail/builder.rb#L72-L95
train
shanna/swift
lib/swift/fiber_connection_pool.rb
Swift.FiberConnectionPool.acquire
def acquire id, fiber if conn = @available.pop @reserved[id] = conn else Fiber.yield @pending.push(fiber) acquire(id, fiber) end end
ruby
def acquire id, fiber if conn = @available.pop @reserved[id] = conn else Fiber.yield @pending.push(fiber) acquire(id, fiber) end end
[ "def", "acquire", "id", ",", "fiber", "if", "conn", "=", "@available", ".", "pop", "@reserved", "[", "id", "]", "=", "conn", "else", "Fiber", ".", "yield", "@pending", ".", "push", "(", "fiber", ")", "acquire", "(", "id", ",", "fiber", ")", "end", "end" ]
Acquire a lock on a connection and assign it to executing fiber - if connection is available, pass it back to the calling block - if pool is full, yield the current fiber until connection is available
[ "Acquire", "a", "lock", "on", "a", "connection", "and", "assign", "it", "to", "executing", "fiber", "-", "if", "connection", "is", "available", "pass", "it", "back", "to", "the", "calling", "block", "-", "if", "pool", "is", "full", "yield", "the", "current", "fiber", "until", "connection", "is", "available" ]
c9488d5594da546958ab9cf3602d69d0ca51b021
https://github.com/shanna/swift/blob/c9488d5594da546958ab9cf3602d69d0ca51b021/lib/swift/fiber_connection_pool.rb#L47-L54
train
shanna/swift
lib/swift/fiber_connection_pool.rb
Swift.FiberConnectionPool.method_missing
def method_missing method, *args, &blk __reserve__ do |conn| if @trace conn.trace(@trace) {conn.__send__(method, *args, &blk)} else conn.__send__(method, *args, &blk) end end end
ruby
def method_missing method, *args, &blk __reserve__ do |conn| if @trace conn.trace(@trace) {conn.__send__(method, *args, &blk)} else conn.__send__(method, *args, &blk) end end end
[ "def", "method_missing", "method", ",", "*", "args", ",", "&", "blk", "__reserve__", "do", "|", "conn", "|", "if", "@trace", "conn", ".", "trace", "(", "@trace", ")", "{", "conn", ".", "__send__", "(", "method", ",", "*", "args", ",", "&", "blk", ")", "}", "else", "conn", ".", "__send__", "(", "method", ",", "*", "args", ",", "&", "blk", ")", "end", "end", "end" ]
Allow the pool to behave as the underlying connection
[ "Allow", "the", "pool", "to", "behave", "as", "the", "underlying", "connection" ]
c9488d5594da546958ab9cf3602d69d0ca51b021
https://github.com/shanna/swift/blob/c9488d5594da546958ab9cf3602d69d0ca51b021/lib/swift/fiber_connection_pool.rb#L67-L75
train
docwhat/lego_nxt
lib/lego_nxt/low_level/usb_connection.rb
LegoNXT::LowLevel.UsbConnection.transmit!
def transmit! bits bytes_sent = @handle.bulk_transfer dataOut: bits, endpoint: USB_ENDPOINT_OUT bytes_sent == bits.length end
ruby
def transmit! bits bytes_sent = @handle.bulk_transfer dataOut: bits, endpoint: USB_ENDPOINT_OUT bytes_sent == bits.length end
[ "def", "transmit!", "bits", "bytes_sent", "=", "@handle", ".", "bulk_transfer", "dataOut", ":", "bits", ",", "endpoint", ":", "USB_ENDPOINT_OUT", "bytes_sent", "==", "bits", ".", "length", "end" ]
Creates a connection to the NXT brick. Sends a packed string of bits. Example: # Causes the brick to beep conn.transmit [0x80, 0x03, 0xf4, 0x01, 0xf4, 0x01].pack('C*')' @see The LEGO MINDSTORMS NXT Communications Protocol (Appendex 1 of the Bluetooth Development Kit) @param {String} bits This must be a binary string. Use `Array#pack('C*')` to generate the string. @return [Boolean] Returns true if all the data was sent and received by the NXT.
[ "Creates", "a", "connection", "to", "the", "NXT", "brick", "." ]
74f6ea3e019bce0be68fa974eaa0a41185b6c4a8
https://github.com/docwhat/lego_nxt/blob/74f6ea3e019bce0be68fa974eaa0a41185b6c4a8/lib/lego_nxt/low_level/usb_connection.rb#L54-L57
train
docwhat/lego_nxt
lib/lego_nxt/low_level/usb_connection.rb
LegoNXT::LowLevel.UsbConnection.transceive
def transceive bits raise ::LegoNXT::BadOpCodeError unless bytestring(DirectOps::REQUIRE_RESPONSE, SystemOps::REQUIRE_RESPONSE).include? bits[0] raise ::LegoNXT::TransmitError unless transmit! bits bytes_received = @handle.bulk_transfer dataIn: 64, endpoint: USB_ENDPOINT_IN return bytes_received end
ruby
def transceive bits raise ::LegoNXT::BadOpCodeError unless bytestring(DirectOps::REQUIRE_RESPONSE, SystemOps::REQUIRE_RESPONSE).include? bits[0] raise ::LegoNXT::TransmitError unless transmit! bits bytes_received = @handle.bulk_transfer dataIn: 64, endpoint: USB_ENDPOINT_IN return bytes_received end
[ "def", "transceive", "bits", "raise", "::", "LegoNXT", "::", "BadOpCodeError", "unless", "bytestring", "(", "DirectOps", "::", "REQUIRE_RESPONSE", ",", "SystemOps", "::", "REQUIRE_RESPONSE", ")", ".", "include?", "bits", "[", "0", "]", "raise", "::", "LegoNXT", "::", "TransmitError", "unless", "transmit!", "bits", "bytes_received", "=", "@handle", ".", "bulk_transfer", "dataIn", ":", "64", ",", "endpoint", ":", "USB_ENDPOINT_IN", "return", "bytes_received", "end" ]
Sends a packet string of bits and then receives a result. Example: # Causes the brick to beep conn.transceive [0x80, 0x03, 0xf4, 0x01, 0xf4, 0x01].pack('C*')' @see The LEGO MINDSTORMS NXT Communications Protocol (Appendex 1 of the Bluetooth Development Kit) @param {String} bits This must be a binary string. Use `Array#pack('C*')` to generate the string. @raise {LegoNXT::TransmitError} Raised if the {#transmit} fails. @return [String] A packed string of the response bits. Use `String#unpack('C*')`.
[ "Sends", "a", "packet", "string", "of", "bits", "and", "then", "receives", "a", "result", "." ]
74f6ea3e019bce0be68fa974eaa0a41185b6c4a8
https://github.com/docwhat/lego_nxt/blob/74f6ea3e019bce0be68fa974eaa0a41185b6c4a8/lib/lego_nxt/low_level/usb_connection.rb#L83-L88
train
docwhat/lego_nxt
lib/lego_nxt/low_level/usb_connection.rb
LegoNXT::LowLevel.UsbConnection.open
def open context = LIBUSB::Context.new device = context.devices(:idVendor => LEGO_VENDOR_ID, :idProduct => NXT_PRODUCT_ID).first raise ::LegoNXT::NoDeviceError.new("Please make sure the device is plugged in and powered on") if device.nil? @handle = device.open @handle.claim_interface(0) end
ruby
def open context = LIBUSB::Context.new device = context.devices(:idVendor => LEGO_VENDOR_ID, :idProduct => NXT_PRODUCT_ID).first raise ::LegoNXT::NoDeviceError.new("Please make sure the device is plugged in and powered on") if device.nil? @handle = device.open @handle.claim_interface(0) end
[ "def", "open", "context", "=", "LIBUSB", "::", "Context", ".", "new", "device", "=", "context", ".", "devices", "(", ":idVendor", "=>", "LEGO_VENDOR_ID", ",", ":idProduct", "=>", "NXT_PRODUCT_ID", ")", ".", "first", "raise", "::", "LegoNXT", "::", "NoDeviceError", ".", "new", "(", "\"Please make sure the device is plugged in and powered on\"", ")", "if", "device", ".", "nil?", "@handle", "=", "device", ".", "open", "@handle", ".", "claim_interface", "(", "0", ")", "end" ]
Opens the connection This is triggered automatically by intantiating the object. @return [nil]
[ "Opens", "the", "connection" ]
74f6ea3e019bce0be68fa974eaa0a41185b6c4a8
https://github.com/docwhat/lego_nxt/blob/74f6ea3e019bce0be68fa974eaa0a41185b6c4a8/lib/lego_nxt/low_level/usb_connection.rb#L107-L113
train
starpeak/gricer
app/controllers/gricer/requests_controller.rb
Gricer.RequestsController.handle_special_fields
def handle_special_fields if ['referer_host', 'referer_path', 'referer_params', 'search_engine', 'search_query'].include?(params[:field]) @items = @items.only_first_in_session end if ['search_engine', 'search_query'].include?(params[:field]) @items = @items.without_nil_in params[:field] end if params[:field] == 'entry_path' params[:field] = 'path' @items = @items.only_first_in_session end super end
ruby
def handle_special_fields if ['referer_host', 'referer_path', 'referer_params', 'search_engine', 'search_query'].include?(params[:field]) @items = @items.only_first_in_session end if ['search_engine', 'search_query'].include?(params[:field]) @items = @items.without_nil_in params[:field] end if params[:field] == 'entry_path' params[:field] = 'path' @items = @items.only_first_in_session end super end
[ "def", "handle_special_fields", "if", "[", "'referer_host'", ",", "'referer_path'", ",", "'referer_params'", ",", "'search_engine'", ",", "'search_query'", "]", ".", "include?", "(", "params", "[", ":field", "]", ")", "@items", "=", "@items", ".", "only_first_in_session", "end", "if", "[", "'search_engine'", ",", "'search_query'", "]", ".", "include?", "(", "params", "[", ":field", "]", ")", "@items", "=", "@items", ".", "without_nil_in", "params", "[", ":field", "]", "end", "if", "params", "[", ":field", "]", "==", "'entry_path'", "params", "[", ":field", "]", "=", "'path'", "@items", "=", "@items", ".", "only_first_in_session", "end", "super", "end" ]
Handle special fields
[ "Handle", "special", "fields" ]
46bb77bd4fc7074ce294d0310ad459fef068f507
https://github.com/starpeak/gricer/blob/46bb77bd4fc7074ce294d0310ad459fef068f507/app/controllers/gricer/requests_controller.rb#L12-L27
train
johnwunder/stix_schema_spy
lib/stix_schema_spy/models/node.rb
StixSchemaSpy.Node.referenced_element
def referenced_element ref = @xml.attributes['ref'].value @referenced_element ||= if ref =~ /:/ prefix, element = ref.split(':') schema.find_element(element) || schema.find_attribute("@#{element}") if schema = Schema.find(prefix) else self.schema.find_element(ref) || self.schema.find_attribute("@#{ref}") end end
ruby
def referenced_element ref = @xml.attributes['ref'].value @referenced_element ||= if ref =~ /:/ prefix, element = ref.split(':') schema.find_element(element) || schema.find_attribute("@#{element}") if schema = Schema.find(prefix) else self.schema.find_element(ref) || self.schema.find_attribute("@#{ref}") end end
[ "def", "referenced_element", "ref", "=", "@xml", ".", "attributes", "[", "'ref'", "]", ".", "value", "@referenced_element", "||=", "if", "ref", "=~", "/", "/", "prefix", ",", "element", "=", "ref", ".", "split", "(", "':'", ")", "schema", ".", "find_element", "(", "element", ")", "||", "schema", ".", "find_attribute", "(", "\"@#{element}\"", ")", "if", "schema", "=", "Schema", ".", "find", "(", "prefix", ")", "else", "self", ".", "schema", ".", "find_element", "(", "ref", ")", "||", "self", ".", "schema", ".", "find_attribute", "(", "\"@#{ref}\"", ")", "end", "end" ]
Only valid if this is a reference. Also works for attributes, this was a crappy name
[ "Only", "valid", "if", "this", "is", "a", "reference", ".", "Also", "works", "for", "attributes", "this", "was", "a", "crappy", "name" ]
2d551c6854d749eb330340e69f73baee1c4b52d3
https://github.com/johnwunder/stix_schema_spy/blob/2d551c6854d749eb330340e69f73baee1c4b52d3/lib/stix_schema_spy/models/node.rb#L58-L66
train
maxim/has_price
lib/has_price/price_builder.rb
HasPrice.PriceBuilder.item
def item(price, item_name) @current_nesting_level[item_name.to_s] = price.respond_to?(:to_hash) ? price.to_hash : price.to_i end
ruby
def item(price, item_name) @current_nesting_level[item_name.to_s] = price.respond_to?(:to_hash) ? price.to_hash : price.to_i end
[ "def", "item", "(", "price", ",", "item_name", ")", "@current_nesting_level", "[", "item_name", ".", "to_s", "]", "=", "price", ".", "respond_to?", "(", ":to_hash", ")", "?", "price", ".", "to_hash", ":", "price", ".", "to_i", "end" ]
Creates PriceBuilder on a target object. @param [Object] object the target object on which price is being built. Adds price item to the current nesting level of price definition. @param [#to_hash, #to_i] price an integer representing amount for this price item. Alternatively, anything that responds to #to_hash can be used, and will be treated as a group named with item_name. @param [#to_s] item_name name for the provided price item or group. @see #group
[ "Creates", "PriceBuilder", "on", "a", "target", "object", "." ]
671c5c7463b0e6540cbb8ac3114da08b99c697bd
https://github.com/maxim/has_price/blob/671c5c7463b0e6540cbb8ac3114da08b99c697bd/lib/has_price/price_builder.rb#L22-L24
train