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
jwoertink/tourets
lib/tourets/utilities.rb
TouRETS.Utilities.value_map
def value_map(value) v = case value.class when Array value.join(',') when Range "#{value.first}-#{value.last}" when Hash if value.has_key?(:or) "|#{value[:or].join(',')}" elsif value.has_key?(:not) "~#{value[:not].join(',')}" end when TrueClass "Y" # TODO: figure out if this should be Y or Yes when FalseClass "N" # TODO: figure out if this should be N or No else value end v end
ruby
def value_map(value) v = case value.class when Array value.join(',') when Range "#{value.first}-#{value.last}" when Hash if value.has_key?(:or) "|#{value[:or].join(',')}" elsif value.has_key?(:not) "~#{value[:not].join(',')}" end when TrueClass "Y" # TODO: figure out if this should be Y or Yes when FalseClass "N" # TODO: figure out if this should be N or No else value end v end
[ "def", "value_map", "(", "value", ")", "v", "=", "case", "value", ".", "class", "when", "Array", "value", ".", "join", "(", "','", ")", "when", "Range", "\"#{value.first}-#{value.last}\"", "when", "Hash", "if", "value", ".", "has_key?", "(", ":or", ")", "\"|#{value[:or].join(',')}\"", "elsif", "value", ".", "has_key?", "(", ":not", ")", "\"~#{value[:not].join(',')}\"", "end", "when", "TrueClass", "\"Y\"", "when", "FalseClass", "\"N\"", "else", "value", "end", "v", "end" ]
Take values like true and false, convert them to "Y" or "N". make collections into joint strings.
[ "Take", "values", "like", "true", "and", "false", "convert", "them", "to", "Y", "or", "N", ".", "make", "collections", "into", "joint", "strings", "." ]
1cf5b5b061702846d38a261ad256f1641d2553c1
https://github.com/jwoertink/tourets/blob/1cf5b5b061702846d38a261ad256f1641d2553c1/lib/tourets/utilities.rb#L193-L213
train
fuminori-ido/edgarj
lib/edgarj/enum_cache.rb
Edgarj.EnumCache.label
def label(rec, attr, enum = nil) if !enum enum = rec.class.const_get(attr.to_s.camelize) raise(NameError, "wrong constant name #{attr}") if !enum end if !@enum_map[enum] @enum_map[enum] = {} end value = rec.attributes[attr.to_s] if label = @enum_map[enum][value] @hit += 1 label else member = enum.constants.detect{|m| enum.const_get(m) == value } @enum_map[enum][value] = if member @out += 1 rec.class.human_const_name(enum, member) else @out_of_enum += 1 '??' end end end
ruby
def label(rec, attr, enum = nil) if !enum enum = rec.class.const_get(attr.to_s.camelize) raise(NameError, "wrong constant name #{attr}") if !enum end if !@enum_map[enum] @enum_map[enum] = {} end value = rec.attributes[attr.to_s] if label = @enum_map[enum][value] @hit += 1 label else member = enum.constants.detect{|m| enum.const_get(m) == value } @enum_map[enum][value] = if member @out += 1 rec.class.human_const_name(enum, member) else @out_of_enum += 1 '??' end end end
[ "def", "label", "(", "rec", ",", "attr", ",", "enum", "=", "nil", ")", "if", "!", "enum", "enum", "=", "rec", ".", "class", ".", "const_get", "(", "attr", ".", "to_s", ".", "camelize", ")", "raise", "(", "NameError", ",", "\"wrong constant name #{attr}\"", ")", "if", "!", "enum", "end", "if", "!", "@enum_map", "[", "enum", "]", "@enum_map", "[", "enum", "]", "=", "{", "}", "end", "value", "=", "rec", ".", "attributes", "[", "attr", ".", "to_s", "]", "if", "label", "=", "@enum_map", "[", "enum", "]", "[", "value", "]", "@hit", "+=", "1", "label", "else", "member", "=", "enum", ".", "constants", ".", "detect", "{", "|", "m", "|", "enum", ".", "const_get", "(", "m", ")", "==", "value", "}", "@enum_map", "[", "enum", "]", "[", "value", "]", "=", "if", "member", "@out", "+=", "1", "rec", ".", "class", ".", "human_const_name", "(", "enum", ",", "member", ")", "else", "@out_of_enum", "+=", "1", "'??'", "end", "end", "end" ]
return label of 'rec.attr', where attr is enum value.
[ "return", "label", "of", "rec", ".", "attr", "where", "attr", "is", "enum", "value", "." ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/lib/edgarj/enum_cache.rb#L14-L39
train
ndlib/rof
lib/rof/compare_rof.rb
ROF.CompareRof.rights_equal
def rights_equal(rights_attr) f_rights = Array.wrap(fedora.fetch('rights', {}).fetch(rights_attr, [])).sort b_rights = Array.wrap(bendo.fetch('rights', {}).fetch(rights_attr, [])).sort return 0 if f_rights == b_rights 1 end
ruby
def rights_equal(rights_attr) f_rights = Array.wrap(fedora.fetch('rights', {}).fetch(rights_attr, [])).sort b_rights = Array.wrap(bendo.fetch('rights', {}).fetch(rights_attr, [])).sort return 0 if f_rights == b_rights 1 end
[ "def", "rights_equal", "(", "rights_attr", ")", "f_rights", "=", "Array", ".", "wrap", "(", "fedora", ".", "fetch", "(", "'rights'", ",", "{", "}", ")", ".", "fetch", "(", "rights_attr", ",", "[", "]", ")", ")", ".", "sort", "b_rights", "=", "Array", ".", "wrap", "(", "bendo", ".", "fetch", "(", "'rights'", ",", "{", "}", ")", ".", "fetch", "(", "rights_attr", ",", "[", "]", ")", ")", ".", "sort", "return", "0", "if", "f_rights", "==", "b_rights", "1", "end" ]
compare array or element for equivalence
[ "compare", "array", "or", "element", "for", "equivalence" ]
18a8cc009540a868447952eed82de035451025e8
https://github.com/ndlib/rof/blob/18a8cc009540a868447952eed82de035451025e8/lib/rof/compare_rof.rb#L51-L57
train
ndlib/rof
lib/rof/compare_rof.rb
ROF.CompareRof.compare_everything_else
def compare_everything_else error_count =0 exclude_keys = ['rights', 'rels-ext', 'metadata', 'thumbnail-file'] all_keys_to_check = (bendo.keys + fedora.keys - exclude_keys).uniq all_keys_to_check.each do |key| bendo_value = bendo.fetch(key, nil) fedora_value = fedora.fetch(key, nil) # Treat an empty hash and an empty array as equal next if bendo_value.empty? && fedora_value.empty? next if normalize_value(bendo_value) == normalize_value(fedora_value) error_count += 1 break end error_count end
ruby
def compare_everything_else error_count =0 exclude_keys = ['rights', 'rels-ext', 'metadata', 'thumbnail-file'] all_keys_to_check = (bendo.keys + fedora.keys - exclude_keys).uniq all_keys_to_check.each do |key| bendo_value = bendo.fetch(key, nil) fedora_value = fedora.fetch(key, nil) # Treat an empty hash and an empty array as equal next if bendo_value.empty? && fedora_value.empty? next if normalize_value(bendo_value) == normalize_value(fedora_value) error_count += 1 break end error_count end
[ "def", "compare_everything_else", "error_count", "=", "0", "exclude_keys", "=", "[", "'rights'", ",", "'rels-ext'", ",", "'metadata'", ",", "'thumbnail-file'", "]", "all_keys_to_check", "=", "(", "bendo", ".", "keys", "+", "fedora", ".", "keys", "-", "exclude_keys", ")", ".", "uniq", "all_keys_to_check", ".", "each", "do", "|", "key", "|", "bendo_value", "=", "bendo", ".", "fetch", "(", "key", ",", "nil", ")", "fedora_value", "=", "fedora", ".", "fetch", "(", "key", ",", "nil", ")", "next", "if", "bendo_value", ".", "empty?", "&&", "fedora_value", ".", "empty?", "next", "if", "normalize_value", "(", "bendo_value", ")", "==", "normalize_value", "(", "fedora_value", ")", "error_count", "+=", "1", "break", "end", "error_count", "end" ]
compare what remains
[ "compare", "what", "remains" ]
18a8cc009540a868447952eed82de035451025e8
https://github.com/ndlib/rof/blob/18a8cc009540a868447952eed82de035451025e8/lib/rof/compare_rof.rb#L95-L109
train
ndlib/rof
lib/rof/compare_rof.rb
ROF.CompareRof.normalize_value
def normalize_value(values) Array.wrap(values).map do |value| value.is_a?(String) ? value.gsub("\n", "") : value end end
ruby
def normalize_value(values) Array.wrap(values).map do |value| value.is_a?(String) ? value.gsub("\n", "") : value end end
[ "def", "normalize_value", "(", "values", ")", "Array", ".", "wrap", "(", "values", ")", ".", "map", "do", "|", "value", "|", "value", ".", "is_a?", "(", "String", ")", "?", "value", ".", "gsub", "(", "\"\\n\"", ",", "\"\"", ")", ":", "value", "end", "end" ]
Because sometimes we have carriage returns and line breaks but we really don't care @todo Do we care about line breaks?
[ "Because", "sometimes", "we", "have", "carriage", "returns", "and", "line", "breaks", "but", "we", "really", "don", "t", "care" ]
18a8cc009540a868447952eed82de035451025e8
https://github.com/ndlib/rof/blob/18a8cc009540a868447952eed82de035451025e8/lib/rof/compare_rof.rb#L115-L119
train
fuminori-ido/edgarj
app/models/edgarj/search_popup.rb
Edgarj.SearchPopup.conditions
def conditions return ['1=0'] if !valid? if @val.blank? [] else # FIXME: assume type is just string op = '=?' val = @val if val =~ /\*$/ op = ' like ?' val = @val.gsub(/\*/, '%') end ["#{@col}#{op}", val] end end
ruby
def conditions return ['1=0'] if !valid? if @val.blank? [] else # FIXME: assume type is just string op = '=?' val = @val if val =~ /\*$/ op = ' like ?' val = @val.gsub(/\*/, '%') end ["#{@col}#{op}", val] end end
[ "def", "conditions", "return", "[", "'1=0'", "]", "if", "!", "valid?", "if", "@val", ".", "blank?", "[", "]", "else", "op", "=", "'=?'", "val", "=", "@val", "if", "val", "=~", "/", "\\*", "/", "op", "=", "' like ?'", "val", "=", "@val", ".", "gsub", "(", "/", "\\*", "/", ",", "'%'", ")", "end", "[", "\"#{@col}#{op}\"", ",", "val", "]", "end", "end" ]
implement to generate search-conditions
[ "implement", "to", "generate", "search", "-", "conditions" ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/models/edgarj/search_popup.rb#L16-L31
train
nu7hatch/react
lib/react/runner.rb
React.Runner.start
def start puts "== Connected to #{redis.client.id}" puts "== Waiting for commands from `#{options[:queue]}`" if options[:daemon] puts "== Daemonizing..." Daemons.daemonize end loop do begin cid = redis.blpop(options[:queue], 10)[1] if cmd = commands[cid.to_s] puts "\e[33m[#{Time.now}]\e[0m Reacting for `#{cid}` command" threads.add(Thread.new { system(cmd) }) end rescue Interrupt, SystemExit puts "\nCleaning up..." return 0 rescue => ex puts "ERROR: #{ex}" end end end
ruby
def start puts "== Connected to #{redis.client.id}" puts "== Waiting for commands from `#{options[:queue]}`" if options[:daemon] puts "== Daemonizing..." Daemons.daemonize end loop do begin cid = redis.blpop(options[:queue], 10)[1] if cmd = commands[cid.to_s] puts "\e[33m[#{Time.now}]\e[0m Reacting for `#{cid}` command" threads.add(Thread.new { system(cmd) }) end rescue Interrupt, SystemExit puts "\nCleaning up..." return 0 rescue => ex puts "ERROR: #{ex}" end end end
[ "def", "start", "puts", "\"== Connected to #{redis.client.id}\"", "puts", "\"== Waiting for commands from `#{options[:queue]}`\"", "if", "options", "[", ":daemon", "]", "puts", "\"== Daemonizing...\"", "Daemons", ".", "daemonize", "end", "loop", "do", "begin", "cid", "=", "redis", ".", "blpop", "(", "options", "[", ":queue", "]", ",", "10", ")", "[", "1", "]", "if", "cmd", "=", "commands", "[", "cid", ".", "to_s", "]", "puts", "\"\\e[33m[#{Time.now}]\\e[0m Reacting for `#{cid}` command\"", "threads", ".", "add", "(", "Thread", ".", "new", "{", "system", "(", "cmd", ")", "}", ")", "end", "rescue", "Interrupt", ",", "SystemExit", "puts", "\"\\nCleaning up...\"", "return", "0", "rescue", "=>", "ex", "puts", "\"ERROR: #{ex}\"", "end", "end", "end" ]
It starts the consumer loop.
[ "It", "starts", "the", "consumer", "loop", "." ]
74a8f7cb83df0e6c2d343172a68f9f30097678b1
https://github.com/nu7hatch/react/blob/74a8f7cb83df0e6c2d343172a68f9f30097678b1/lib/react/runner.rb#L17-L40
train
dvwright/svn_wc
lib/svn_wc.rb
SvnWc.RepoAccess.set_conf
def set_conf(conf) begin conf = load_conf(conf) @svn_user = conf['svn_user'] @svn_pass = conf['svn_pass'] @force_checkout = conf['force_checkout'] @svn_repo_master = conf['svn_repo_master'] @svn_repo_working_copy = conf['svn_repo_working_copy'] @svn_repo_config_path = conf['svn_repo_config_path'] Svn::Core::Config.ensure(@svn_repo_config_path) rescue Exception => e raise RepoAccessError, 'errors loading conf file' end end
ruby
def set_conf(conf) begin conf = load_conf(conf) @svn_user = conf['svn_user'] @svn_pass = conf['svn_pass'] @force_checkout = conf['force_checkout'] @svn_repo_master = conf['svn_repo_master'] @svn_repo_working_copy = conf['svn_repo_working_copy'] @svn_repo_config_path = conf['svn_repo_config_path'] Svn::Core::Config.ensure(@svn_repo_config_path) rescue Exception => e raise RepoAccessError, 'errors loading conf file' end end
[ "def", "set_conf", "(", "conf", ")", "begin", "conf", "=", "load_conf", "(", "conf", ")", "@svn_user", "=", "conf", "[", "'svn_user'", "]", "@svn_pass", "=", "conf", "[", "'svn_pass'", "]", "@force_checkout", "=", "conf", "[", "'force_checkout'", "]", "@svn_repo_master", "=", "conf", "[", "'svn_repo_master'", "]", "@svn_repo_working_copy", "=", "conf", "[", "'svn_repo_working_copy'", "]", "@svn_repo_config_path", "=", "conf", "[", "'svn_repo_config_path'", "]", "Svn", "::", "Core", "::", "Config", ".", "ensure", "(", "@svn_repo_config_path", ")", "rescue", "Exception", "=>", "e", "raise", "RepoAccessError", ",", "'errors loading conf file'", "end", "end" ]
set config file with abs path
[ "set", "config", "file", "with", "abs", "path" ]
f9cda1140d5d101239b104558680c638361c68a4
https://github.com/dvwright/svn_wc/blob/f9cda1140d5d101239b104558680c638361c68a4/lib/svn_wc.rb#L177-L190
train
dvwright/svn_wc
lib/svn_wc.rb
SvnWc.RepoAccess.add
def add(files=[], recurse=true, force=false, no_ignore=false) # TODO make sure args are what is expected for all methods raise ArgumentError, 'files is empty' unless files svn_session() do |svn| begin files.each do |ef| svn.add(ef, recurse, force, no_ignore) end #rescue Svn::Error::ENTRY_EXISTS, # Svn::Error::AuthnNoProvider, # #Svn::Error::WcNotDirectory, # Svn::Error::SvnError => e rescue Exception => excp raise RepoAccessError, "Add Failed: #{excp.message}" end end end
ruby
def add(files=[], recurse=true, force=false, no_ignore=false) # TODO make sure args are what is expected for all methods raise ArgumentError, 'files is empty' unless files svn_session() do |svn| begin files.each do |ef| svn.add(ef, recurse, force, no_ignore) end #rescue Svn::Error::ENTRY_EXISTS, # Svn::Error::AuthnNoProvider, # #Svn::Error::WcNotDirectory, # Svn::Error::SvnError => e rescue Exception => excp raise RepoAccessError, "Add Failed: #{excp.message}" end end end
[ "def", "add", "(", "files", "=", "[", "]", ",", "recurse", "=", "true", ",", "force", "=", "false", ",", "no_ignore", "=", "false", ")", "raise", "ArgumentError", ",", "'files is empty'", "unless", "files", "svn_session", "(", ")", "do", "|", "svn", "|", "begin", "files", ".", "each", "do", "|", "ef", "|", "svn", ".", "add", "(", "ef", ",", "recurse", ",", "force", ",", "no_ignore", ")", "end", "rescue", "Exception", "=>", "excp", "raise", "RepoAccessError", ",", "\"Add Failed: #{excp.message}\"", "end", "end", "end" ]
add entities to the repo pass a single entry or list of file(s) with fully qualified path, which must exist, raises RepoAccessError if something goes wrong -- "svn/client.rb" Svn::Client def add(path, recurse=true, force=false, no_ignore=false) Client.add3(path, recurse, force, no_ignore, self) end ++
[ "add", "entities", "to", "the", "repo" ]
f9cda1140d5d101239b104558680c638361c68a4
https://github.com/dvwright/svn_wc/blob/f9cda1140d5d101239b104558680c638361c68a4/lib/svn_wc.rb#L284-L302
train
dvwright/svn_wc
lib/svn_wc.rb
SvnWc.RepoAccess.delete
def delete(files=[], recurs=false) svn_session() do |svn| begin svn.delete(files) #rescue Svn::Error::AuthnNoProvider, # #Svn::Error::WcNotDirectory, # Svn::Error::ClientModified, # Svn::Error::SvnError => e rescue Exception => err raise RepoAccessError, "Delete Failed: #{err.message}" end end end
ruby
def delete(files=[], recurs=false) svn_session() do |svn| begin svn.delete(files) #rescue Svn::Error::AuthnNoProvider, # #Svn::Error::WcNotDirectory, # Svn::Error::ClientModified, # Svn::Error::SvnError => e rescue Exception => err raise RepoAccessError, "Delete Failed: #{err.message}" end end end
[ "def", "delete", "(", "files", "=", "[", "]", ",", "recurs", "=", "false", ")", "svn_session", "(", ")", "do", "|", "svn", "|", "begin", "svn", ".", "delete", "(", "files", ")", "rescue", "Exception", "=>", "err", "raise", "RepoAccessError", ",", "\"Delete Failed: #{err.message}\"", "end", "end", "end" ]
delete entities from the repository pass single entity or list of files with fully qualified path, which must exist, raises RepoAccessError if something goes wrong
[ "delete", "entities", "from", "the", "repository" ]
f9cda1140d5d101239b104558680c638361c68a4
https://github.com/dvwright/svn_wc/blob/f9cda1140d5d101239b104558680c638361c68a4/lib/svn_wc.rb#L313-L325
train
dvwright/svn_wc
lib/svn_wc.rb
SvnWc.RepoAccess.commit
def commit(files=[], msg='') if files and files.empty? or files.nil? then files = self.svn_repo_working_copy end rev = '' svn_session(msg) do |svn| begin rev = svn.commit(files).revision #rescue Svn::Error::AuthnNoProvider, # #Svn::Error::WcNotDirectory, # Svn::Error::IllegalTarget, # #Svn::Error::EntryNotFound => e # Exception => e rescue Exception => err raise RepoAccessError, "Commit Failed: #{err.message}" end end rev end
ruby
def commit(files=[], msg='') if files and files.empty? or files.nil? then files = self.svn_repo_working_copy end rev = '' svn_session(msg) do |svn| begin rev = svn.commit(files).revision #rescue Svn::Error::AuthnNoProvider, # #Svn::Error::WcNotDirectory, # Svn::Error::IllegalTarget, # #Svn::Error::EntryNotFound => e # Exception => e rescue Exception => err raise RepoAccessError, "Commit Failed: #{err.message}" end end rev end
[ "def", "commit", "(", "files", "=", "[", "]", ",", "msg", "=", "''", ")", "if", "files", "and", "files", ".", "empty?", "or", "files", ".", "nil?", "then", "files", "=", "self", ".", "svn_repo_working_copy", "end", "rev", "=", "''", "svn_session", "(", "msg", ")", "do", "|", "svn", "|", "begin", "rev", "=", "svn", ".", "commit", "(", "files", ")", ".", "revision", "rescue", "Exception", "=>", "err", "raise", "RepoAccessError", ",", "\"Commit Failed: #{err.message}\"", "end", "end", "rev", "end" ]
commit entities to the repository params single or list of files (full relative path (to repo root) needed) optional message raises RepoAccessError if something goes wrong returns the revision of the commmit
[ "commit", "entities", "to", "the", "repository" ]
f9cda1140d5d101239b104558680c638361c68a4
https://github.com/dvwright/svn_wc/blob/f9cda1140d5d101239b104558680c638361c68a4/lib/svn_wc.rb#L340-L357
train
dvwright/svn_wc
lib/svn_wc.rb
SvnWc.RepoAccess._pre_update_entries
def _pre_update_entries #:nodoc: @pre_up_entries = Array.new @modified_entries = Array.new list_entries.each do |ent| ##puts "#{ent[:status]} | #{ent[:repo_rev]} | #{ent[:entry_name]}" e_name = ent[:entry_name] stat = ent[:status] if @limit_to_dir_path # limit files returned to this (and subdir's of) dir fle = File.join(self.svn_repo_working_copy, e_name) next unless fle.include? @limit_to_dir_path end @pre_up_entries.push e_name ## how does it handle deletes? #if info()[:rev] != ent[:repo_rev] # puts "changed file: #{File.join(paths, ent[:entry_name])} | #{ent[:status]} " #end if stat == 'M' then @modified_entries.push "#{stat}\t#{e_name}" end end end
ruby
def _pre_update_entries #:nodoc: @pre_up_entries = Array.new @modified_entries = Array.new list_entries.each do |ent| ##puts "#{ent[:status]} | #{ent[:repo_rev]} | #{ent[:entry_name]}" e_name = ent[:entry_name] stat = ent[:status] if @limit_to_dir_path # limit files returned to this (and subdir's of) dir fle = File.join(self.svn_repo_working_copy, e_name) next unless fle.include? @limit_to_dir_path end @pre_up_entries.push e_name ## how does it handle deletes? #if info()[:rev] != ent[:repo_rev] # puts "changed file: #{File.join(paths, ent[:entry_name])} | #{ent[:status]} " #end if stat == 'M' then @modified_entries.push "#{stat}\t#{e_name}" end end end
[ "def", "_pre_update_entries", "@pre_up_entries", "=", "Array", ".", "new", "@modified_entries", "=", "Array", ".", "new", "list_entries", ".", "each", "do", "|", "ent", "|", "e_name", "=", "ent", "[", ":entry_name", "]", "stat", "=", "ent", "[", ":status", "]", "if", "@limit_to_dir_path", "fle", "=", "File", ".", "join", "(", "self", ".", "svn_repo_working_copy", ",", "e_name", ")", "next", "unless", "fle", ".", "include?", "@limit_to_dir_path", "end", "@pre_up_entries", ".", "push", "e_name", "if", "stat", "==", "'M'", "then", "@modified_entries", ".", "push", "\"#{stat}\\t#{e_name}\"", "end", "end", "end" ]
get list of entries before doing an update
[ "get", "list", "of", "entries", "before", "doing", "an", "update" ]
f9cda1140d5d101239b104558680c638361c68a4
https://github.com/dvwright/svn_wc/blob/f9cda1140d5d101239b104558680c638361c68a4/lib/svn_wc.rb#L413-L434
train
dvwright/svn_wc
lib/svn_wc.rb
SvnWc.RepoAccess._post_update_entries
def _post_update_entries #:nodoc: post_up_entries = Array.new list_entries.each { |ent| if @limit_to_dir_path # limit files returned to this (and subdir's of) dir fle = File.join(self.svn_repo_working_copy, ent[:entry_name]) next unless fle.include? @limit_to_dir_path end post_up_entries.push ent[:entry_name] } added = post_up_entries - @pre_up_entries removed = @pre_up_entries - post_up_entries #raise "#{post_up_entries}\n#{@pre_up_entries}" #raise "#{added} - #{removed}" if added.length > 0 added.each {|e_add| @modified_entries.push "A\t#{e_add}" } end if removed.length > 0 removed.each {|e_rm| @modified_entries.push "D\t#{e_rm}" } end end
ruby
def _post_update_entries #:nodoc: post_up_entries = Array.new list_entries.each { |ent| if @limit_to_dir_path # limit files returned to this (and subdir's of) dir fle = File.join(self.svn_repo_working_copy, ent[:entry_name]) next unless fle.include? @limit_to_dir_path end post_up_entries.push ent[:entry_name] } added = post_up_entries - @pre_up_entries removed = @pre_up_entries - post_up_entries #raise "#{post_up_entries}\n#{@pre_up_entries}" #raise "#{added} - #{removed}" if added.length > 0 added.each {|e_add| @modified_entries.push "A\t#{e_add}" } end if removed.length > 0 removed.each {|e_rm| @modified_entries.push "D\t#{e_rm}" } end end
[ "def", "_post_update_entries", "post_up_entries", "=", "Array", ".", "new", "list_entries", ".", "each", "{", "|", "ent", "|", "if", "@limit_to_dir_path", "fle", "=", "File", ".", "join", "(", "self", ".", "svn_repo_working_copy", ",", "ent", "[", ":entry_name", "]", ")", "next", "unless", "fle", ".", "include?", "@limit_to_dir_path", "end", "post_up_entries", ".", "push", "ent", "[", ":entry_name", "]", "}", "added", "=", "post_up_entries", "-", "@pre_up_entries", "removed", "=", "@pre_up_entries", "-", "post_up_entries", "if", "added", ".", "length", ">", "0", "added", ".", "each", "{", "|", "e_add", "|", "@modified_entries", ".", "push", "\"A\\t#{e_add}\"", "}", "end", "if", "removed", ".", "length", ">", "0", "removed", ".", "each", "{", "|", "e_rm", "|", "@modified_entries", ".", "push", "\"D\\t#{e_rm}\"", "}", "end", "end" ]
get list of entries after doing an update
[ "get", "list", "of", "entries", "after", "doing", "an", "update" ]
f9cda1140d5d101239b104558680c638361c68a4
https://github.com/dvwright/svn_wc/blob/f9cda1140d5d101239b104558680c638361c68a4/lib/svn_wc.rb#L440-L464
train
dvwright/svn_wc
lib/svn_wc.rb
SvnWc.RepoAccess.revert
def revert(file_path='') if file_path.empty? then file_path = self.svn_repo_working_copy end svn_session() { |svn| svn.revert(file_path) } end
ruby
def revert(file_path='') if file_path.empty? then file_path = self.svn_repo_working_copy end svn_session() { |svn| svn.revert(file_path) } end
[ "def", "revert", "(", "file_path", "=", "''", ")", "if", "file_path", ".", "empty?", "then", "file_path", "=", "self", ".", "svn_repo_working_copy", "end", "svn_session", "(", ")", "{", "|", "svn", "|", "svn", ".", "revert", "(", "file_path", ")", "}", "end" ]
discard working copy changes, get current repository entry
[ "discard", "working", "copy", "changes", "get", "current", "repository", "entry" ]
f9cda1140d5d101239b104558680c638361c68a4
https://github.com/dvwright/svn_wc/blob/f9cda1140d5d101239b104558680c638361c68a4/lib/svn_wc.rb#L821-L824
train
petebrowne/massimo
lib/massimo/resource.rb
Massimo.Resource.render
def render extensions.reverse.inject(content) do |output, ext| if template_type = Tilt[ext] template_options = Massimo.config.options_for(ext[1..-1]) template = template_type.new(source_path.to_s, @line, template_options) { output } template.render(template_scope, template_locals) else output end end end
ruby
def render extensions.reverse.inject(content) do |output, ext| if template_type = Tilt[ext] template_options = Massimo.config.options_for(ext[1..-1]) template = template_type.new(source_path.to_s, @line, template_options) { output } template.render(template_scope, template_locals) else output end end end
[ "def", "render", "extensions", ".", "reverse", ".", "inject", "(", "content", ")", "do", "|", "output", ",", "ext", "|", "if", "template_type", "=", "Tilt", "[", "ext", "]", "template_options", "=", "Massimo", ".", "config", ".", "options_for", "(", "ext", "[", "1", "..", "-", "1", "]", ")", "template", "=", "template_type", ".", "new", "(", "source_path", ".", "to_s", ",", "@line", ",", "template_options", ")", "{", "output", "}", "template", ".", "render", "(", "template_scope", ",", "template_locals", ")", "else", "output", "end", "end", "end" ]
Runs the content through any necessary filters, templates, etc.
[ "Runs", "the", "content", "through", "any", "necessary", "filters", "templates", "etc", "." ]
c450edc531ad358f011da0a47e5d0bc9a038d911
https://github.com/petebrowne/massimo/blob/c450edc531ad358f011da0a47e5d0bc9a038d911/lib/massimo/resource.rb#L94-L104
train
petebrowne/massimo
lib/massimo/resource.rb
Massimo.Resource.process
def process FileUtils.mkdir_p(output_path.dirname) output_path.open('w') do |f| f.write render end end
ruby
def process FileUtils.mkdir_p(output_path.dirname) output_path.open('w') do |f| f.write render end end
[ "def", "process", "FileUtils", ".", "mkdir_p", "(", "output_path", ".", "dirname", ")", "output_path", ".", "open", "(", "'w'", ")", "do", "|", "f", "|", "f", ".", "write", "render", "end", "end" ]
Writes the rendered content to the output file.
[ "Writes", "the", "rendered", "content", "to", "the", "output", "file", "." ]
c450edc531ad358f011da0a47e5d0bc9a038d911
https://github.com/petebrowne/massimo/blob/c450edc531ad358f011da0a47e5d0bc9a038d911/lib/massimo/resource.rb#L107-L112
train
galetahub/web_video
lib/web_video/transcoder.rb
WebVideo.Transcoder.convert
def convert(destination, options = {}, &block) options.symbolize_keys! process(destination, @source.convert_command, options, &block) end
ruby
def convert(destination, options = {}, &block) options.symbolize_keys! process(destination, @source.convert_command, options, &block) end
[ "def", "convert", "(", "destination", ",", "options", "=", "{", "}", ",", "&", "block", ")", "options", ".", "symbolize_keys!", "process", "(", "destination", ",", "@source", ".", "convert_command", ",", "options", ",", "&", "block", ")", "end" ]
Generate new video file transcoder = WebVideo::Transcoder.new("demo.avi") begin transcoder.convert("demo.flv", :resolution => "480x360") do |command| command << "-ar 22050" command << "-ab 128k" command << "-acodec libmp3lame" command << "-vcodec flv" command << "-r 25" command << "-y" end rescue WebVideo::CommandLineError => e WebVideo.logger.error("Unable to transcode video: #{e.class} - #{e.message}") end options: :resolution - video resolution
[ "Generate", "new", "video", "file" ]
a73c10501871ba136302cecad411b1c8f8dbaaf8
https://github.com/galetahub/web_video/blob/a73c10501871ba136302cecad411b1c8f8dbaaf8/lib/web_video/transcoder.rb#L81-L85
train
expectedbehavior/cheddargetter_client_ruby
lib/cheddar_getter/response.rb
CheddarGetter.Response.customer_outstanding_invoices
def customer_outstanding_invoices(code = nil) now = Time.now customer_invoices(code).reject do |i| i[:paidTransactionId] || i[:billingDatetime] > now end end
ruby
def customer_outstanding_invoices(code = nil) now = Time.now customer_invoices(code).reject do |i| i[:paidTransactionId] || i[:billingDatetime] > now end end
[ "def", "customer_outstanding_invoices", "(", "code", "=", "nil", ")", "now", "=", "Time", ".", "now", "customer_invoices", "(", "code", ")", ".", "reject", "do", "|", "i", "|", "i", "[", ":paidTransactionId", "]", "||", "i", "[", ":billingDatetime", "]", ">", "now", "end", "end" ]
Returns an array of any currently outstanding invoices for the given customer. code must be provided if this response contains more than one customer.
[ "Returns", "an", "array", "of", "any", "currently", "outstanding", "invoices", "for", "the", "given", "customer", "." ]
f3942d362f031e0c667892099c272737c152cbdf
https://github.com/expectedbehavior/cheddargetter_client_ruby/blob/f3942d362f031e0c667892099c272737c152cbdf/lib/cheddar_getter/response.rb#L180-L185
train
expectedbehavior/cheddargetter_client_ruby
lib/cheddar_getter/response.rb
CheddarGetter.Response.customer_item
def customer_item(item_code = nil, code = nil) sub_item = retrieve_item(customer_subscription(code), :items, item_code) plan_item = retrieve_item(customer_plan(code), :items, item_code) return nil unless sub_item && plan_item item = plan_item.dup item[:quantity] = sub_item[:quantity] item end
ruby
def customer_item(item_code = nil, code = nil) sub_item = retrieve_item(customer_subscription(code), :items, item_code) plan_item = retrieve_item(customer_plan(code), :items, item_code) return nil unless sub_item && plan_item item = plan_item.dup item[:quantity] = sub_item[:quantity] item end
[ "def", "customer_item", "(", "item_code", "=", "nil", ",", "code", "=", "nil", ")", "sub_item", "=", "retrieve_item", "(", "customer_subscription", "(", "code", ")", ",", ":items", ",", "item_code", ")", "plan_item", "=", "retrieve_item", "(", "customer_plan", "(", "code", ")", ",", ":items", ",", "item_code", ")", "return", "nil", "unless", "sub_item", "&&", "plan_item", "item", "=", "plan_item", ".", "dup", "item", "[", ":quantity", "]", "=", "sub_item", "[", ":quantity", "]", "item", "end" ]
Info about the given item for the given customer. Merges the plan item info with the subscription item info. item_code must be provided if the customer is on a plan with more than one item. code must be provided if this response contains more than one customer.
[ "Info", "about", "the", "given", "item", "for", "the", "given", "customer", ".", "Merges", "the", "plan", "item", "info", "with", "the", "subscription", "item", "info", "." ]
f3942d362f031e0c667892099c272737c152cbdf
https://github.com/expectedbehavior/cheddargetter_client_ruby/blob/f3942d362f031e0c667892099c272737c152cbdf/lib/cheddar_getter/response.rb#L193-L200
train
expectedbehavior/cheddargetter_client_ruby
lib/cheddar_getter/response.rb
CheddarGetter.Response.customer_item_quantity_remaining
def customer_item_quantity_remaining(item_code = nil, code = nil) item = customer_item(item_code, code) item ? item[:quantityIncluded] - item[:quantity] : 0 end
ruby
def customer_item_quantity_remaining(item_code = nil, code = nil) item = customer_item(item_code, code) item ? item[:quantityIncluded] - item[:quantity] : 0 end
[ "def", "customer_item_quantity_remaining", "(", "item_code", "=", "nil", ",", "code", "=", "nil", ")", "item", "=", "customer_item", "(", "item_code", ",", "code", ")", "item", "?", "item", "[", ":quantityIncluded", "]", "-", "item", "[", ":quantity", "]", ":", "0", "end" ]
The amount remaining for a given item for a given customer. item_code must be provided if the customer is on a plan with more than one item. code must be provided if this response contains more than one customer.
[ "The", "amount", "remaining", "for", "a", "given", "item", "for", "a", "given", "customer", "." ]
f3942d362f031e0c667892099c272737c152cbdf
https://github.com/expectedbehavior/cheddargetter_client_ruby/blob/f3942d362f031e0c667892099c272737c152cbdf/lib/cheddar_getter/response.rb#L207-L210
train
expectedbehavior/cheddargetter_client_ruby
lib/cheddar_getter/response.rb
CheddarGetter.Response.customer_item_quantity_overage
def customer_item_quantity_overage(item_code = nil, code = nil) over = -customer_item_quantity_remaining(item_code, code) over = 0 if over <= 0 over end
ruby
def customer_item_quantity_overage(item_code = nil, code = nil) over = -customer_item_quantity_remaining(item_code, code) over = 0 if over <= 0 over end
[ "def", "customer_item_quantity_overage", "(", "item_code", "=", "nil", ",", "code", "=", "nil", ")", "over", "=", "-", "customer_item_quantity_remaining", "(", "item_code", ",", "code", ")", "over", "=", "0", "if", "over", "<=", "0", "over", "end" ]
The overage amount for the given item for the given customer. 0 if they are still under their limit. item_code must be provided if the customer is on a plan with more than one item. code must be provided if this response contains more than one customer.
[ "The", "overage", "amount", "for", "the", "given", "item", "for", "the", "given", "customer", ".", "0", "if", "they", "are", "still", "under", "their", "limit", "." ]
f3942d362f031e0c667892099c272737c152cbdf
https://github.com/expectedbehavior/cheddargetter_client_ruby/blob/f3942d362f031e0c667892099c272737c152cbdf/lib/cheddar_getter/response.rb#L217-L221
train
expectedbehavior/cheddargetter_client_ruby
lib/cheddar_getter/response.rb
CheddarGetter.Response.customer_item_quantity_overage_cost
def customer_item_quantity_overage_cost(item_code = nil, code = nil) item = customer_item(item_code, code) return 0 unless item overage = customer_item_quantity_overage(item_code, code) item[:overageAmount] * overage end
ruby
def customer_item_quantity_overage_cost(item_code = nil, code = nil) item = customer_item(item_code, code) return 0 unless item overage = customer_item_quantity_overage(item_code, code) item[:overageAmount] * overage end
[ "def", "customer_item_quantity_overage_cost", "(", "item_code", "=", "nil", ",", "code", "=", "nil", ")", "item", "=", "customer_item", "(", "item_code", ",", "code", ")", "return", "0", "unless", "item", "overage", "=", "customer_item_quantity_overage", "(", "item_code", ",", "code", ")", "item", "[", ":overageAmount", "]", "*", "overage", "end" ]
The current overage cost for the given item for the given customer. item_code must be provided if the customer is on a plan with more than one item. code must be provided if this response contains more than one customer.
[ "The", "current", "overage", "cost", "for", "the", "given", "item", "for", "the", "given", "customer", "." ]
f3942d362f031e0c667892099c272737c152cbdf
https://github.com/expectedbehavior/cheddargetter_client_ruby/blob/f3942d362f031e0c667892099c272737c152cbdf/lib/cheddar_getter/response.rb#L228-L233
train
expectedbehavior/cheddargetter_client_ruby
lib/cheddar_getter/response.rb
CheddarGetter.Response.customer_active?
def customer_active?(code = nil) subscription = customer_subscription(code) if subscription[:canceledDatetime] && subscription[:canceledDatetime] <= Time.now false else true end end
ruby
def customer_active?(code = nil) subscription = customer_subscription(code) if subscription[:canceledDatetime] && subscription[:canceledDatetime] <= Time.now false else true end end
[ "def", "customer_active?", "(", "code", "=", "nil", ")", "subscription", "=", "customer_subscription", "(", "code", ")", "if", "subscription", "[", ":canceledDatetime", "]", "&&", "subscription", "[", ":canceledDatetime", "]", "<=", "Time", ".", "now", "false", "else", "true", "end", "end" ]
Get an array representation of a single customer's current subscription @throws CheddarGetter_Response_Exception if the response type is incompatible or if a $code is not provided and the response contains more than one customer @return array
[ "Get", "an", "array", "representation", "of", "a", "single", "customer", "s", "current", "subscription" ]
f3942d362f031e0c667892099c272737c152cbdf
https://github.com/expectedbehavior/cheddargetter_client_ruby/blob/f3942d362f031e0c667892099c272737c152cbdf/lib/cheddar_getter/response.rb#L247-L254
train
expectedbehavior/cheddargetter_client_ruby
lib/cheddar_getter/response.rb
CheddarGetter.Response.customer_waiting_for_paypal?
def customer_waiting_for_paypal?(code = nil) subscription = customer_subscription(code) if subscription[:canceledDatetime] && subscription[:canceledDatetime] <= Time.now && subscription[:cancelType] == 'paypal-wait' true else false end end
ruby
def customer_waiting_for_paypal?(code = nil) subscription = customer_subscription(code) if subscription[:canceledDatetime] && subscription[:canceledDatetime] <= Time.now && subscription[:cancelType] == 'paypal-wait' true else false end end
[ "def", "customer_waiting_for_paypal?", "(", "code", "=", "nil", ")", "subscription", "=", "customer_subscription", "(", "code", ")", "if", "subscription", "[", ":canceledDatetime", "]", "&&", "subscription", "[", ":canceledDatetime", "]", "<=", "Time", ".", "now", "&&", "subscription", "[", ":cancelType", "]", "==", "'paypal-wait'", "true", "else", "false", "end", "end" ]
Is this customer's account pending paypal preapproval confirmation?
[ "Is", "this", "customer", "s", "account", "pending", "paypal", "preapproval", "confirmation?" ]
f3942d362f031e0c667892099c272737c152cbdf
https://github.com/expectedbehavior/cheddargetter_client_ruby/blob/f3942d362f031e0c667892099c272737c152cbdf/lib/cheddar_getter/response.rb#L257-L264
train
kul1/jinda
lib/jinda/gemhelpers.rb
Jinda.GemHelpers.process_controllers
def process_controllers process_services modules= Jinda::Module.all modules.each do |m| next if controller_exists?(m.code) puts " Rails generate controller #{m.code}" end end
ruby
def process_controllers process_services modules= Jinda::Module.all modules.each do |m| next if controller_exists?(m.code) puts " Rails generate controller #{m.code}" end end
[ "def", "process_controllers", "process_services", "modules", "=", "Jinda", "::", "Module", ".", "all", "modules", ".", "each", "do", "|", "m", "|", "next", "if", "controller_exists?", "(", "m", ".", "code", ")", "puts", "\" Rails generate controller #{m.code}\"", "end", "end" ]
Mock generate controller for test Otherwise test will call rails g controller
[ "Mock", "generate", "controller", "for", "test", "Otherwise", "test", "will", "call", "rails", "g", "controller" ]
97cbf13fa5f9c8b6afdc50c61fc76a4d21f1d7f6
https://github.com/kul1/jinda/blob/97cbf13fa5f9c8b6afdc50c61fc76a4d21f1d7f6/lib/jinda/gemhelpers.rb#L19-L26
train
fuminori-ido/edgarj
app/controllers/edgarj/rescue_mixin.rb
Edgarj.RescueMixin.edgarj_rescue_sub
def edgarj_rescue_sub(ex, message) logger.info( "#{ex.class} #{ex.message} bactrace:\n " + ex.backtrace.join("\n ")) respond_to do |format| format.html { flash[:error] = message redirect_to top_path } format.js { flash.now[:error] = message render 'message_popup' } end end
ruby
def edgarj_rescue_sub(ex, message) logger.info( "#{ex.class} #{ex.message} bactrace:\n " + ex.backtrace.join("\n ")) respond_to do |format| format.html { flash[:error] = message redirect_to top_path } format.js { flash.now[:error] = message render 'message_popup' } end end
[ "def", "edgarj_rescue_sub", "(", "ex", ",", "message", ")", "logger", ".", "info", "(", "\"#{ex.class} #{ex.message} bactrace:\\n \"", "+", "ex", ".", "backtrace", ".", "join", "(", "\"\\n \"", ")", ")", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "flash", "[", ":error", "]", "=", "message", "redirect_to", "top_path", "}", "format", ".", "js", "{", "flash", ".", "now", "[", ":error", "]", "=", "message", "render", "'message_popup'", "}", "end", "end" ]
rescue callback sub method to show message by flush on normal http request or by popup-dialog on Ajax request.
[ "rescue", "callback", "sub", "method", "to", "show", "message", "by", "flush", "on", "normal", "http", "request", "or", "by", "popup", "-", "dialog", "on", "Ajax", "request", "." ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/controllers/edgarj/rescue_mixin.rb#L10-L25
train
mamantoha/freshdesk_api_client_rb
lib/freshdesk_api/actions.rb
FreshdeskAPI.Read.find!
def find!(client, options = {}) @client = client # so we can use client.logger in rescue raise ArgumentError, 'No :id given' unless options[:id] path = api_url(options) + "/#{options[:id]}" response = client.make_request!(path, :get) new(@client).tap do |resource| resource.attributes.merge!(options) resource.handle_response(response) end end
ruby
def find!(client, options = {}) @client = client # so we can use client.logger in rescue raise ArgumentError, 'No :id given' unless options[:id] path = api_url(options) + "/#{options[:id]}" response = client.make_request!(path, :get) new(@client).tap do |resource| resource.attributes.merge!(options) resource.handle_response(response) end end
[ "def", "find!", "(", "client", ",", "options", "=", "{", "}", ")", "@client", "=", "client", "raise", "ArgumentError", ",", "'No :id given'", "unless", "options", "[", ":id", "]", "path", "=", "api_url", "(", "options", ")", "+", "\"/#{options[:id]}\"", "response", "=", "client", ".", "make_request!", "(", "path", ",", ":get", ")", "new", "(", "@client", ")", ".", "tap", "do", "|", "resource", "|", "resource", ".", "attributes", ".", "merge!", "(", "options", ")", "resource", ".", "handle_response", "(", "response", ")", "end", "end" ]
Finds a resource by an id and any options passed in @param [Client] client The {Client} object to be used @param [Hash] option Any additional GET parameters to be added
[ "Finds", "a", "resource", "by", "an", "id", "and", "any", "options", "passed", "in" ]
74367fe0dd31bd269197b3f419412ef600031e62
https://github.com/mamantoha/freshdesk_api_client_rb/blob/74367fe0dd31bd269197b3f419412ef600031e62/lib/freshdesk_api/actions.rb#L20-L32
train
mamantoha/freshdesk_api_client_rb
lib/freshdesk_api/actions.rb
FreshdeskAPI.Read.find
def find(client, options = {}, &block) find!(client, options, &block) rescue FreshdeskAPI::Error::ClientError nil end
ruby
def find(client, options = {}, &block) find!(client, options, &block) rescue FreshdeskAPI::Error::ClientError nil end
[ "def", "find", "(", "client", ",", "options", "=", "{", "}", ",", "&", "block", ")", "find!", "(", "client", ",", "options", ",", "&", "block", ")", "rescue", "FreshdeskAPI", "::", "Error", "::", "ClientError", "nil", "end" ]
Finds, returning nil if it fails
[ "Finds", "returning", "nil", "if", "it", "fails" ]
74367fe0dd31bd269197b3f419412ef600031e62
https://github.com/mamantoha/freshdesk_api_client_rb/blob/74367fe0dd31bd269197b3f419412ef600031e62/lib/freshdesk_api/actions.rb#L35-L39
train
code-and-effect/effective_obfuscation
app/models/concerns/acts_as_obfuscated.rb
ActsAsObfuscated.ClassMethods.deobfuscate
def deobfuscate(original, rescue_with_original_id = true) if original.kind_of?(Array) return original.map { |value| deobfuscate(value, true) } # Always rescue with original ID elsif !(original.kind_of?(Integer) || original.kind_of?(String)) return original end # Remove any non-digit formatting characters, and only consider the first 10 digits obfuscated_id = original.to_s.delete('^0-9').first(10) # 2147483647 is PostgreSQL's Integer Max Value. If we return a value higher than this, we get weird DB errors revealed = [EffectiveObfuscation.show(obfuscated_id, acts_as_obfuscated_opts[:spin]).to_i, 2147483647].min if rescue_with_original_id && (revealed >= 2147483647 || revealed > deobfuscated_maximum_id) original else revealed end end
ruby
def deobfuscate(original, rescue_with_original_id = true) if original.kind_of?(Array) return original.map { |value| deobfuscate(value, true) } # Always rescue with original ID elsif !(original.kind_of?(Integer) || original.kind_of?(String)) return original end # Remove any non-digit formatting characters, and only consider the first 10 digits obfuscated_id = original.to_s.delete('^0-9').first(10) # 2147483647 is PostgreSQL's Integer Max Value. If we return a value higher than this, we get weird DB errors revealed = [EffectiveObfuscation.show(obfuscated_id, acts_as_obfuscated_opts[:spin]).to_i, 2147483647].min if rescue_with_original_id && (revealed >= 2147483647 || revealed > deobfuscated_maximum_id) original else revealed end end
[ "def", "deobfuscate", "(", "original", ",", "rescue_with_original_id", "=", "true", ")", "if", "original", ".", "kind_of?", "(", "Array", ")", "return", "original", ".", "map", "{", "|", "value", "|", "deobfuscate", "(", "value", ",", "true", ")", "}", "elsif", "!", "(", "original", ".", "kind_of?", "(", "Integer", ")", "||", "original", ".", "kind_of?", "(", "String", ")", ")", "return", "original", "end", "obfuscated_id", "=", "original", ".", "to_s", ".", "delete", "(", "'^0-9'", ")", ".", "first", "(", "10", ")", "revealed", "=", "[", "EffectiveObfuscation", ".", "show", "(", "obfuscated_id", ",", "acts_as_obfuscated_opts", "[", ":spin", "]", ")", ".", "to_i", ",", "2147483647", "]", ".", "min", "if", "rescue_with_original_id", "&&", "(", "revealed", ">=", "2147483647", "||", "revealed", ">", "deobfuscated_maximum_id", ")", "original", "else", "revealed", "end", "end" ]
If rescue_with_original_id is set to true the original ID will be returned when its Obfuscated Id is not found We use this as the default behaviour on everything except Class.find()
[ "If", "rescue_with_original_id", "is", "set", "to", "true", "the", "original", "ID", "will", "be", "returned", "when", "its", "Obfuscated", "Id", "is", "not", "found" ]
c6e5ec480401448f31c9fb71b496c85c4a7b4685
https://github.com/code-and-effect/effective_obfuscation/blob/c6e5ec480401448f31c9fb71b496c85c4a7b4685/app/models/concerns/acts_as_obfuscated.rb#L75-L93
train
lvxn0va/catarse_stripe
app/controllers/catarse_stripe/payment/stripe_controller.rb
CatarseStripe::Payment.StripeController.callback
def callback @stripe_user = current_user code = params[:code] @response = @client.auth_code.get_token(code, { :headers => {'Authorization' => "Bearer(::Configuration['stripe_secret_key'])"} #Platform Secret Key }) #Save PROJECT owner's new keys @stripe_user.stripe_access_token = @response.token @stripe_user.stripe_key = @response.params['stripe_publishable_key'] @stripe_user.stripe_userid = @response.params['stripe_user_id'] @stripe_user.save return redirect_to payment_stripe_auth_path(@stripe_user) rescue Stripe::AuthenticationError => e ::Airbrake.notify({ :error_class => "Stripe #Pay Error", :error_message => "Stripe #Pay Error: #{e.inspect}", :parameters => params}) rescue nil Rails.logger.info "-----> #{e.inspect}" flash[:error] = e.message return redirect_to main_app.user_path(@stripe_user) end
ruby
def callback @stripe_user = current_user code = params[:code] @response = @client.auth_code.get_token(code, { :headers => {'Authorization' => "Bearer(::Configuration['stripe_secret_key'])"} #Platform Secret Key }) #Save PROJECT owner's new keys @stripe_user.stripe_access_token = @response.token @stripe_user.stripe_key = @response.params['stripe_publishable_key'] @stripe_user.stripe_userid = @response.params['stripe_user_id'] @stripe_user.save return redirect_to payment_stripe_auth_path(@stripe_user) rescue Stripe::AuthenticationError => e ::Airbrake.notify({ :error_class => "Stripe #Pay Error", :error_message => "Stripe #Pay Error: #{e.inspect}", :parameters => params}) rescue nil Rails.logger.info "-----> #{e.inspect}" flash[:error] = e.message return redirect_to main_app.user_path(@stripe_user) end
[ "def", "callback", "@stripe_user", "=", "current_user", "code", "=", "params", "[", ":code", "]", "@response", "=", "@client", ".", "auth_code", ".", "get_token", "(", "code", ",", "{", ":headers", "=>", "{", "'Authorization'", "=>", "\"Bearer(::Configuration['stripe_secret_key'])\"", "}", "}", ")", "@stripe_user", ".", "stripe_access_token", "=", "@response", ".", "token", "@stripe_user", ".", "stripe_key", "=", "@response", ".", "params", "[", "'stripe_publishable_key'", "]", "@stripe_user", ".", "stripe_userid", "=", "@response", ".", "params", "[", "'stripe_user_id'", "]", "@stripe_user", ".", "save", "return", "redirect_to", "payment_stripe_auth_path", "(", "@stripe_user", ")", "rescue", "Stripe", "::", "AuthenticationError", "=>", "e", "::", "Airbrake", ".", "notify", "(", "{", ":error_class", "=>", "\"Stripe #Pay Error\"", ",", ":error_message", "=>", "\"Stripe #Pay Error: #{e.inspect}\"", ",", ":parameters", "=>", "params", "}", ")", "rescue", "nil", "Rails", ".", "logger", ".", "info", "\"---", "flash", "[", ":error", "]", "=", "e", ".", "message", "return", "redirect_to", "main_app", ".", "user_path", "(", "@stripe_user", ")", "end" ]
Brings back the authcode from Stripe and makes another call to Stripe to convert to a authtoken
[ "Brings", "back", "the", "authcode", "from", "Stripe", "and", "makes", "another", "call", "to", "Stripe", "to", "convert", "to", "a", "authtoken" ]
66b7b0b3e785d3b1c6fa4c0305d78cf99d10a412
https://github.com/lvxn0va/catarse_stripe/blob/66b7b0b3e785d3b1c6fa4c0305d78cf99d10a412/app/controllers/catarse_stripe/payment/stripe_controller.rb#L31-L52
train
datamapper/dm-adjust
lib/dm-adjust/collection.rb
DataMapper.Collection.adjust!
def adjust!(attributes = {}, reload = false) return true if attributes.empty? reload_conditions = if reload model_key = model.key(repository.name) Query.target_conditions(self, model_key, model_key) end adjust_attributes = adjust_attributes(attributes) repository.adjust(adjust_attributes, self) if reload_conditions @query.clear @query.update(:conditions => reload_conditions) self.reload end true end
ruby
def adjust!(attributes = {}, reload = false) return true if attributes.empty? reload_conditions = if reload model_key = model.key(repository.name) Query.target_conditions(self, model_key, model_key) end adjust_attributes = adjust_attributes(attributes) repository.adjust(adjust_attributes, self) if reload_conditions @query.clear @query.update(:conditions => reload_conditions) self.reload end true end
[ "def", "adjust!", "(", "attributes", "=", "{", "}", ",", "reload", "=", "false", ")", "return", "true", "if", "attributes", ".", "empty?", "reload_conditions", "=", "if", "reload", "model_key", "=", "model", ".", "key", "(", "repository", ".", "name", ")", "Query", ".", "target_conditions", "(", "self", ",", "model_key", ",", "model_key", ")", "end", "adjust_attributes", "=", "adjust_attributes", "(", "attributes", ")", "repository", ".", "adjust", "(", "adjust_attributes", ",", "self", ")", "if", "reload_conditions", "@query", ".", "clear", "@query", ".", "update", "(", ":conditions", "=>", "reload_conditions", ")", "self", ".", "reload", "end", "true", "end" ]
increment or decrement attributes on a collection @example [Usage] * People.all.adjust(:salary => +1000) * Children.all(:age.gte => 18).adjust(:allowance => -100) @param attributes <Hash> A hash of attributes to adjust, and their adjustment @param reload <FalseClass,TrueClass> If true, affected objects will be reloaded @api public
[ "increment", "or", "decrement", "attributes", "on", "a", "collection" ]
17d342755ba937a394af3a1a40fd13a253bc3c9c
https://github.com/datamapper/dm-adjust/blob/17d342755ba937a394af3a1a40fd13a253bc3c9c/lib/dm-adjust/collection.rb#L19-L37
train
Kuniri/kuniri
lib/kuniri/language/container_data/structured_and_oo/function_abstract.rb
Languages.FunctionAbstract.add_parameters
def add_parameters(pValue) unless ((pValue.respond_to?(:has_key?) && pValue.length == 1) || pValue.respond_to?(:to_str)) return nil end @parameters.push(pValue) end
ruby
def add_parameters(pValue) unless ((pValue.respond_to?(:has_key?) && pValue.length == 1) || pValue.respond_to?(:to_str)) return nil end @parameters.push(pValue) end
[ "def", "add_parameters", "(", "pValue", ")", "unless", "(", "(", "pValue", ".", "respond_to?", "(", ":has_key?", ")", "&&", "pValue", ".", "length", "==", "1", ")", "||", "pValue", ".", "respond_to?", "(", ":to_str", ")", ")", "return", "nil", "end", "@parameters", ".", "push", "(", "pValue", ")", "end" ]
Add parameters inside function. @param pValue Add a parameter inside function. @return if pValue is not String or Hash with more than one element. return nil.
[ "Add", "parameters", "inside", "function", "." ]
8b840ab307dc6bec48edd272c732b28c98f93f45
https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/language/container_data/structured_and_oo/function_abstract.rb#L42-L48
train
Kuniri/kuniri
lib/kuniri/language/container_data/structured_and_oo/function_abstract.rb
Languages.FunctionAbstract.add_conditional
def add_conditional(pConditional, pBehaviour = Languages::KEEP_LEVEL) return nil unless (pConditional.instance_of?Languages::ConditionalData) add_with_manager(pConditional, 'conditional', pBehaviour) end
ruby
def add_conditional(pConditional, pBehaviour = Languages::KEEP_LEVEL) return nil unless (pConditional.instance_of?Languages::ConditionalData) add_with_manager(pConditional, 'conditional', pBehaviour) end
[ "def", "add_conditional", "(", "pConditional", ",", "pBehaviour", "=", "Languages", "::", "KEEP_LEVEL", ")", "return", "nil", "unless", "(", "pConditional", ".", "instance_of?", "Languages", "::", "ConditionalData", ")", "add_with_manager", "(", "pConditional", ",", "'conditional'", ",", "pBehaviour", ")", "end" ]
Add conditional element inside function. @param pConditional An object of ConditionalData. @return If pConditional is not an instance of ConditionalData, return nil.
[ "Add", "conditional", "element", "inside", "function", "." ]
8b840ab307dc6bec48edd272c732b28c98f93f45
https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/language/container_data/structured_and_oo/function_abstract.rb#L54-L57
train
Kuniri/kuniri
lib/kuniri/language/container_data/structured_and_oo/function_abstract.rb
Languages.FunctionAbstract.add_repetition
def add_repetition(pRepetition, pBehaviour = Languages::KEEP_LEVEL) return nil unless (pRepetition.instance_of?Languages::RepetitionData) add_with_manager(pRepetition, 'repetition', pBehaviour) end
ruby
def add_repetition(pRepetition, pBehaviour = Languages::KEEP_LEVEL) return nil unless (pRepetition.instance_of?Languages::RepetitionData) add_with_manager(pRepetition, 'repetition', pBehaviour) end
[ "def", "add_repetition", "(", "pRepetition", ",", "pBehaviour", "=", "Languages", "::", "KEEP_LEVEL", ")", "return", "nil", "unless", "(", "pRepetition", ".", "instance_of?", "Languages", "::", "RepetitionData", ")", "add_with_manager", "(", "pRepetition", ",", "'repetition'", ",", "pBehaviour", ")", "end" ]
Add repetition element inside function. @param pRepetition An object of RepetitionData. @return If pRepetition is not RepetitionData instance return nil.
[ "Add", "repetition", "element", "inside", "function", "." ]
8b840ab307dc6bec48edd272c732b28c98f93f45
https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/language/container_data/structured_and_oo/function_abstract.rb#L62-L65
train
Kuniri/kuniri
lib/kuniri/language/container_data/structured_and_oo/function_abstract.rb
Languages.FunctionAbstract.add_block
def add_block(pBlock, pBehaviour = Languages::KEEP_LEVEL) return nil unless (pBlock.instance_of?Languages::BlockData) add_with_manager(pBlock, 'block', pBehaviour) end
ruby
def add_block(pBlock, pBehaviour = Languages::KEEP_LEVEL) return nil unless (pBlock.instance_of?Languages::BlockData) add_with_manager(pBlock, 'block', pBehaviour) end
[ "def", "add_block", "(", "pBlock", ",", "pBehaviour", "=", "Languages", "::", "KEEP_LEVEL", ")", "return", "nil", "unless", "(", "pBlock", ".", "instance_of?", "Languages", "::", "BlockData", ")", "add_with_manager", "(", "pBlock", ",", "'block'", ",", "pBehaviour", ")", "end" ]
Add block element inside function. @param pBlock An object of BlockData. @return If pBlock is not pBlockData instance return nil.
[ "Add", "block", "element", "inside", "function", "." ]
8b840ab307dc6bec48edd272c732b28c98f93f45
https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/language/container_data/structured_and_oo/function_abstract.rb#L70-L73
train
Kuniri/kuniri
lib/kuniri/language/container_data/structured_and_oo/function_abstract.rb
Languages.FunctionAbstract.<<
def <<(fromTo) return nil unless fromTo.is_a?(Languages::FunctionAbstract) @name = fromTo.name @parameters = fromTo.parameters @managerCondLoopAndBlock = fromTo.managerCondLoopAndBlock @visibility = fromTo.visibility @comments = fromTo.comments @type = @type end
ruby
def <<(fromTo) return nil unless fromTo.is_a?(Languages::FunctionAbstract) @name = fromTo.name @parameters = fromTo.parameters @managerCondLoopAndBlock = fromTo.managerCondLoopAndBlock @visibility = fromTo.visibility @comments = fromTo.comments @type = @type end
[ "def", "<<", "(", "fromTo", ")", "return", "nil", "unless", "fromTo", ".", "is_a?", "(", "Languages", "::", "FunctionAbstract", ")", "@name", "=", "fromTo", ".", "name", "@parameters", "=", "fromTo", ".", "parameters", "@managerCondLoopAndBlock", "=", "fromTo", ".", "managerCondLoopAndBlock", "@visibility", "=", "fromTo", ".", "visibility", "@comments", "=", "fromTo", ".", "comments", "@type", "=", "@type", "end" ]
Copy elements from an object of FunctionAbstract to specific element @param fromTo Reference from FunctionAbstract
[ "Copy", "elements", "from", "an", "object", "of", "FunctionAbstract", "to", "specific", "element" ]
8b840ab307dc6bec48edd272c732b28c98f93f45
https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/language/container_data/structured_and_oo/function_abstract.rb#L77-L85
train
Kuniri/kuniri
lib/kuniri/language/container_data/structured_and_oo/function_abstract.rb
Languages.FunctionAbstract.add_with_manager
def add_with_manager(pElementToAdd, pMetaData, pBehaviour) case pBehaviour when Languages::KEEP_LEVEL @managerCondLoopAndBlock.send("add_#{pMetaData}", pElementToAdd) when Languages::UP_LEVEL @managerCondLoopAndBlock.decrease_deep_level @managerCondLoopAndBlock.send("add_#{pMetaData}", pElementToAdd) when Languages::DOWN_LEVEL @managerCondLoopAndBlock.increase_deep_level @managerCondLoopAndBlock.send("add_#{pMetaData}", pElementToAdd) end end
ruby
def add_with_manager(pElementToAdd, pMetaData, pBehaviour) case pBehaviour when Languages::KEEP_LEVEL @managerCondLoopAndBlock.send("add_#{pMetaData}", pElementToAdd) when Languages::UP_LEVEL @managerCondLoopAndBlock.decrease_deep_level @managerCondLoopAndBlock.send("add_#{pMetaData}", pElementToAdd) when Languages::DOWN_LEVEL @managerCondLoopAndBlock.increase_deep_level @managerCondLoopAndBlock.send("add_#{pMetaData}", pElementToAdd) end end
[ "def", "add_with_manager", "(", "pElementToAdd", ",", "pMetaData", ",", "pBehaviour", ")", "case", "pBehaviour", "when", "Languages", "::", "KEEP_LEVEL", "@managerCondLoopAndBlock", ".", "send", "(", "\"add_#{pMetaData}\"", ",", "pElementToAdd", ")", "when", "Languages", "::", "UP_LEVEL", "@managerCondLoopAndBlock", ".", "decrease_deep_level", "@managerCondLoopAndBlock", ".", "send", "(", "\"add_#{pMetaData}\"", ",", "pElementToAdd", ")", "when", "Languages", "::", "DOWN_LEVEL", "@managerCondLoopAndBlock", ".", "increase_deep_level", "@managerCondLoopAndBlock", ".", "send", "(", "\"add_#{pMetaData}\"", ",", "pElementToAdd", ")", "end", "end" ]
Add to a manager conditional or repetition. @param pElementToAdd Element wish we want to add. @param pMetaData String with name for of element we want to add. @param pBehaviour Flag with behaviour.
[ "Add", "to", "a", "manager", "conditional", "or", "repetition", "." ]
8b840ab307dc6bec48edd272c732b28c98f93f45
https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/language/container_data/structured_and_oo/function_abstract.rb#L93-L104
train
news-scraper/news_scraper
lib/news_scraper/extractors_helpers.rb
NewsScraper.ExtractorsHelpers.http_request
def http_request(url) url = URIParser.new(url).with_scheme CLI.put_header(url) CLI.log "Beginning HTTP request for #{url}" response = HTTParty.get(url, headers: { "User-Agent" => "news-scraper-#{NewsScraper::VERSION}" }) raise ResponseError.new( error_code: response.code, message: response.message, url: url ) unless response.code == 200 CLI.log "#{response.code} - #{response.message}. Request successful for #{url}" CLI.put_footer if block_given? yield response else response end end
ruby
def http_request(url) url = URIParser.new(url).with_scheme CLI.put_header(url) CLI.log "Beginning HTTP request for #{url}" response = HTTParty.get(url, headers: { "User-Agent" => "news-scraper-#{NewsScraper::VERSION}" }) raise ResponseError.new( error_code: response.code, message: response.message, url: url ) unless response.code == 200 CLI.log "#{response.code} - #{response.message}. Request successful for #{url}" CLI.put_footer if block_given? yield response else response end end
[ "def", "http_request", "(", "url", ")", "url", "=", "URIParser", ".", "new", "(", "url", ")", ".", "with_scheme", "CLI", ".", "put_header", "(", "url", ")", "CLI", ".", "log", "\"Beginning HTTP request for #{url}\"", "response", "=", "HTTParty", ".", "get", "(", "url", ",", "headers", ":", "{", "\"User-Agent\"", "=>", "\"news-scraper-#{NewsScraper::VERSION}\"", "}", ")", "raise", "ResponseError", ".", "new", "(", "error_code", ":", "response", ".", "code", ",", "message", ":", "response", ".", "message", ",", "url", ":", "url", ")", "unless", "response", ".", "code", "==", "200", "CLI", ".", "log", "\"#{response.code} - #{response.message}. Request successful for #{url}\"", "CLI", ".", "put_footer", "if", "block_given?", "yield", "response", "else", "response", "end", "end" ]
Perform an HTTP request with a standardized response *Params* - <code>url</code>: the url on which to perform a get request
[ "Perform", "an", "HTTP", "request", "with", "a", "standardized", "response" ]
3ee2ea9590d081ffb8e98120b2e1344dec88a15e
https://github.com/news-scraper/news_scraper/blob/3ee2ea9590d081ffb8e98120b2e1344dec88a15e/lib/news_scraper/extractors_helpers.rb#L8-L29
train
PerfectMemory/translator-text
lib/translator_text/client.rb
TranslatorText.Client.detect
def detect(sentences) results = post( '/detect', body: build_sentences(sentences).to_json ) results.map { |r| Types::DetectionResult.new(r) } end
ruby
def detect(sentences) results = post( '/detect', body: build_sentences(sentences).to_json ) results.map { |r| Types::DetectionResult.new(r) } end
[ "def", "detect", "(", "sentences", ")", "results", "=", "post", "(", "'/detect'", ",", "body", ":", "build_sentences", "(", "sentences", ")", ".", "to_json", ")", "results", ".", "map", "{", "|", "r", "|", "Types", "::", "DetectionResult", ".", "new", "(", "r", ")", "}", "end" ]
Identifies the language of a piece of text. The following limitations apply: * The array _sentences_ can have at most 100 elements. * The text value of an array element cannot exceed 10,000 characters including spaces. * The entire text included in the request cannot exceed 50,000 characters including spaces. @see https://docs.microsoft.com/en-us/azure/cognitive-services/translator/reference/v3-0-detect @param sentences [Array<String, TranslatorText::Types::Sentence>] the sentences to process @return [Array<TranslatorText::Types::DetectionResult>] the detection results
[ "Identifies", "the", "language", "of", "a", "piece", "of", "text", "." ]
17518d3b0cbda23d2beef1d88c95ba38e21db33e
https://github.com/PerfectMemory/translator-text/blob/17518d3b0cbda23d2beef1d88c95ba38e21db33e/lib/translator_text/client.rb#L52-L59
train
jm/literati
lib/literati.rb
Literati.MarkdownRenderer.determine_markdown_renderer
def determine_markdown_renderer @markdown = if installed?('github/markdown') GitHubWrapper.new(@content) elsif installed?('redcarpet/compat') Markdown.new(@content, :fenced_code, :safelink, :autolink) elsif installed?('redcarpet') RedcarpetCompat.new(@content) elsif installed?('rdiscount') RDiscount.new(@content) elsif installed?('maruku') Maruku.new(@content) elsif installed?('kramdown') Kramdown::Document.new(@content) elsif installed?('bluecloth') BlueCloth.new(@content) end end
ruby
def determine_markdown_renderer @markdown = if installed?('github/markdown') GitHubWrapper.new(@content) elsif installed?('redcarpet/compat') Markdown.new(@content, :fenced_code, :safelink, :autolink) elsif installed?('redcarpet') RedcarpetCompat.new(@content) elsif installed?('rdiscount') RDiscount.new(@content) elsif installed?('maruku') Maruku.new(@content) elsif installed?('kramdown') Kramdown::Document.new(@content) elsif installed?('bluecloth') BlueCloth.new(@content) end end
[ "def", "determine_markdown_renderer", "@markdown", "=", "if", "installed?", "(", "'github/markdown'", ")", "GitHubWrapper", ".", "new", "(", "@content", ")", "elsif", "installed?", "(", "'redcarpet/compat'", ")", "Markdown", ".", "new", "(", "@content", ",", ":fenced_code", ",", ":safelink", ",", ":autolink", ")", "elsif", "installed?", "(", "'redcarpet'", ")", "RedcarpetCompat", ".", "new", "(", "@content", ")", "elsif", "installed?", "(", "'rdiscount'", ")", "RDiscount", ".", "new", "(", "@content", ")", "elsif", "installed?", "(", "'maruku'", ")", "Maruku", ".", "new", "(", "@content", ")", "elsif", "installed?", "(", "'kramdown'", ")", "Kramdown", "::", "Document", ".", "new", "(", "@content", ")", "elsif", "installed?", "(", "'bluecloth'", ")", "BlueCloth", ".", "new", "(", "@content", ")", "end", "end" ]
Create a new compatibility instance. content - The Markdown content to render.
[ "Create", "a", "new", "compatibility", "instance", "." ]
ee2c949ccd015cbc037921213516bae96832716a
https://github.com/jm/literati/blob/ee2c949ccd015cbc037921213516bae96832716a/lib/literati.rb#L32-L48
train
jm/literati
lib/literati.rb
Literati.Renderer.to_markdown
def to_markdown lines = @bare_content.split("\n") markdown = "" # Using `while` here so we can alter the collection at will while current_line = lines.shift # If we got us some of them bird tracks... if current_line =~ BIRD_TRACKS_REGEX # Remove the bird tracks from this line current_line = remove_bird_tracks(current_line) # Grab the remaining code block current_line << slurp_remaining_bird_tracks(lines) # Fence it and add it to the output markdown << "```haskell\n#{current_line}\n```\n" else # No tracks? Just stick it back in the pile. markdown << current_line + "\n" end end markdown end
ruby
def to_markdown lines = @bare_content.split("\n") markdown = "" # Using `while` here so we can alter the collection at will while current_line = lines.shift # If we got us some of them bird tracks... if current_line =~ BIRD_TRACKS_REGEX # Remove the bird tracks from this line current_line = remove_bird_tracks(current_line) # Grab the remaining code block current_line << slurp_remaining_bird_tracks(lines) # Fence it and add it to the output markdown << "```haskell\n#{current_line}\n```\n" else # No tracks? Just stick it back in the pile. markdown << current_line + "\n" end end markdown end
[ "def", "to_markdown", "lines", "=", "@bare_content", ".", "split", "(", "\"\\n\"", ")", "markdown", "=", "\"\"", "while", "current_line", "=", "lines", ".", "shift", "if", "current_line", "=~", "BIRD_TRACKS_REGEX", "current_line", "=", "remove_bird_tracks", "(", "current_line", ")", "current_line", "<<", "slurp_remaining_bird_tracks", "(", "lines", ")", "markdown", "<<", "\"```haskell\\n#{current_line}\\n```\\n\"", "else", "markdown", "<<", "current_line", "+", "\"\\n\"", "end", "end", "markdown", "end" ]
Initialize a new literate Haskell renderer. content - The literate Haskell code string markdowner - The class we'll use to render the HTML (defaults to our RedCarpet wrapper). Render the given literate Haskell to a Markdown string. Returns a Markdown string we can render to HTML.
[ "Initialize", "a", "new", "literate", "Haskell", "renderer", "." ]
ee2c949ccd015cbc037921213516bae96832716a
https://github.com/jm/literati/blob/ee2c949ccd015cbc037921213516bae96832716a/lib/literati.rb#L90-L112
train
jm/literati
lib/literati.rb
Literati.Renderer.remove_bird_tracks
def remove_bird_tracks(line) tracks = line.scan(BIRD_TRACKS_REGEX)[0] (tracks.first == " ") ? tracks[1] : tracks.join end
ruby
def remove_bird_tracks(line) tracks = line.scan(BIRD_TRACKS_REGEX)[0] (tracks.first == " ") ? tracks[1] : tracks.join end
[ "def", "remove_bird_tracks", "(", "line", ")", "tracks", "=", "line", ".", "scan", "(", "BIRD_TRACKS_REGEX", ")", "[", "0", "]", "(", "tracks", ".", "first", "==", "\" \"", ")", "?", "tracks", "[", "1", "]", ":", "tracks", ".", "join", "end" ]
Remove Bird-style comment markers from a line of text. comment = "> Haskell codes" remove_bird_tracks(comment) # => "Haskell codes" Returns the given line of text sans bird tracks.
[ "Remove", "Bird", "-", "style", "comment", "markers", "from", "a", "line", "of", "text", "." ]
ee2c949ccd015cbc037921213516bae96832716a
https://github.com/jm/literati/blob/ee2c949ccd015cbc037921213516bae96832716a/lib/literati.rb#L121-L124
train
jm/literati
lib/literati.rb
Literati.Renderer.slurp_remaining_bird_tracks
def slurp_remaining_bird_tracks(lines) tracked_lines = [] while lines.first =~ BIRD_TRACKS_REGEX tracked_lines << remove_bird_tracks(lines.shift) end if tracked_lines.empty? "" else "\n" + tracked_lines.join("\n") end end
ruby
def slurp_remaining_bird_tracks(lines) tracked_lines = [] while lines.first =~ BIRD_TRACKS_REGEX tracked_lines << remove_bird_tracks(lines.shift) end if tracked_lines.empty? "" else "\n" + tracked_lines.join("\n") end end
[ "def", "slurp_remaining_bird_tracks", "(", "lines", ")", "tracked_lines", "=", "[", "]", "while", "lines", ".", "first", "=~", "BIRD_TRACKS_REGEX", "tracked_lines", "<<", "remove_bird_tracks", "(", "lines", ".", "shift", ")", "end", "if", "tracked_lines", ".", "empty?", "\"\"", "else", "\"\\n\"", "+", "tracked_lines", ".", "join", "(", "\"\\n\"", ")", "end", "end" ]
Given an Array of lines, pulls from the front of the Array until the next line doesn't match our bird tracks regex. lines = ["> code", "> code", "", "not code"] slurp_remaining_bird_tracks(lines) # => "code\ncode" Returns the lines mashed into a string separated by a newline.
[ "Given", "an", "Array", "of", "lines", "pulls", "from", "the", "front", "of", "the", "Array", "until", "the", "next", "line", "doesn", "t", "match", "our", "bird", "tracks", "regex", "." ]
ee2c949ccd015cbc037921213516bae96832716a
https://github.com/jm/literati/blob/ee2c949ccd015cbc037921213516bae96832716a/lib/literati.rb#L134-L146
train
flori/cpu
lib/cpu/usage_sampler.rb
CPU.UsageSampler.sample
def sample total, @usages = nil, {} timestamp = Time.now File.foreach('/proc/stat') do |line| case line when /^cpu[^\d]/ next when CPU times = $~.captures processor_id = times[0] = times[0].to_i (1...times.size).each { |i| times[i] = times[i].to_f / USER_HZ } times << timestamp << timestamp @usages[processor_id] = Usage.new(self, *times) else break end end if @usages.empty? raise NoSampleDataError, "could not sample measurement data" end self end
ruby
def sample total, @usages = nil, {} timestamp = Time.now File.foreach('/proc/stat') do |line| case line when /^cpu[^\d]/ next when CPU times = $~.captures processor_id = times[0] = times[0].to_i (1...times.size).each { |i| times[i] = times[i].to_f / USER_HZ } times << timestamp << timestamp @usages[processor_id] = Usage.new(self, *times) else break end end if @usages.empty? raise NoSampleDataError, "could not sample measurement data" end self end
[ "def", "sample", "total", ",", "@usages", "=", "nil", ",", "{", "}", "timestamp", "=", "Time", ".", "now", "File", ".", "foreach", "(", "'/proc/stat'", ")", "do", "|", "line", "|", "case", "line", "when", "/", "\\d", "/", "next", "when", "CPU", "times", "=", "$~", ".", "captures", "processor_id", "=", "times", "[", "0", "]", "=", "times", "[", "0", "]", ".", "to_i", "(", "1", "...", "times", ".", "size", ")", ".", "each", "{", "|", "i", "|", "times", "[", "i", "]", "=", "times", "[", "i", "]", ".", "to_f", "/", "USER_HZ", "}", "times", "<<", "timestamp", "<<", "timestamp", "@usages", "[", "processor_id", "]", "=", "Usage", ".", "new", "(", "self", ",", "*", "times", ")", "else", "break", "end", "end", "if", "@usages", ".", "empty?", "raise", "NoSampleDataError", ",", "\"could not sample measurement data\"", "end", "self", "end" ]
Take one sample of CPU usage data for every processor in this computer and store them in the +usages+ attribute.
[ "Take", "one", "sample", "of", "CPU", "usage", "data", "for", "every", "processor", "in", "this", "computer", "and", "store", "them", "in", "the", "+", "usages", "+", "attribute", "." ]
b1e320c83a6653758b266b02141fc57e5379d1e6
https://github.com/flori/cpu/blob/b1e320c83a6653758b266b02141fc57e5379d1e6/lib/cpu/usage_sampler.rb#L26-L47
train
adamcooke/datey
lib/datey/formatter.rb
Datey.Formatter.include_year_in_dates?
def include_year_in_dates? if @time.year != Date.today.year # If the year was in the past, always include the year return true end if @time.year == Date.today.year && @time.month < (Date.today.month - 4) # If the year is this year, include if it happened more than 6 months # ago. return true end end
ruby
def include_year_in_dates? if @time.year != Date.today.year # If the year was in the past, always include the year return true end if @time.year == Date.today.year && @time.month < (Date.today.month - 4) # If the year is this year, include if it happened more than 6 months # ago. return true end end
[ "def", "include_year_in_dates?", "if", "@time", ".", "year", "!=", "Date", ".", "today", ".", "year", "return", "true", "end", "if", "@time", ".", "year", "==", "Date", ".", "today", ".", "year", "&&", "@time", ".", "month", "<", "(", "Date", ".", "today", ".", "month", "-", "4", ")", "return", "true", "end", "end" ]
Should years be included in dates?
[ "Should", "years", "be", "included", "in", "dates?" ]
6bf55aa533f7e17df66b8a188ed6d6e6d17cf06f
https://github.com/adamcooke/datey/blob/6bf55aa533f7e17df66b8a188ed6d6e6d17cf06f/lib/datey/formatter.rb#L103-L114
train
payneteasy/ruby-library-payneteasy-api
lib/paynet_easy/paynet_easy_api/transport/gateway_client.rb
PaynetEasy::PaynetEasyApi::Transport.GatewayClient.parse_response
def parse_response(response) unless response.body raise ResponseError, 'PaynetEasy response is empty' end # Change hash format from {'key' => ['value']} to {'key' => 'value'} in map block response_fields = Hash[CGI.parse(response.body).map {|key, value| [key, value.first]}] Response.new response_fields end
ruby
def parse_response(response) unless response.body raise ResponseError, 'PaynetEasy response is empty' end # Change hash format from {'key' => ['value']} to {'key' => 'value'} in map block response_fields = Hash[CGI.parse(response.body).map {|key, value| [key, value.first]}] Response.new response_fields end
[ "def", "parse_response", "(", "response", ")", "unless", "response", ".", "body", "raise", "ResponseError", ",", "'PaynetEasy response is empty'", "end", "response_fields", "=", "Hash", "[", "CGI", ".", "parse", "(", "response", ".", "body", ")", ".", "map", "{", "|", "key", ",", "value", "|", "[", "key", ",", "value", ".", "first", "]", "}", "]", "Response", ".", "new", "response_fields", "end" ]
Parse PaynetEasy response from string to Response object @param response [HTTPResponse] PaynetEasy response as HTTPResponse @return [Response] PaynetEasy response as Response
[ "Parse", "PaynetEasy", "response", "from", "string", "to", "Response", "object" ]
3200a447829b62e241fdc329f80fddb5f8d68cc0
https://github.com/payneteasy/ruby-library-payneteasy-api/blob/3200a447829b62e241fdc329f80fddb5f8d68cc0/lib/paynet_easy/paynet_easy_api/transport/gateway_client.rb#L61-L70
train
donaldpiret/github-pivotal-flow
lib/github_pivotal_flow/finish.rb
GithubPivotalFlow.Finish.run!
def run! raise_error_if_development_or_master story = @configuration.story fail("Could not find story associated with branch") unless story story.can_merge? commit_message = options[:commit_message] if story.release? story.merge_release!(commit_message, @options) else story.merge_to_roots!(commit_message, @options) end return 0 end
ruby
def run! raise_error_if_development_or_master story = @configuration.story fail("Could not find story associated with branch") unless story story.can_merge? commit_message = options[:commit_message] if story.release? story.merge_release!(commit_message, @options) else story.merge_to_roots!(commit_message, @options) end return 0 end
[ "def", "run!", "raise_error_if_development_or_master", "story", "=", "@configuration", ".", "story", "fail", "(", "\"Could not find story associated with branch\"", ")", "unless", "story", "story", ".", "can_merge?", "commit_message", "=", "options", "[", ":commit_message", "]", "if", "story", ".", "release?", "story", ".", "merge_release!", "(", "commit_message", ",", "@options", ")", "else", "story", ".", "merge_to_roots!", "(", "commit_message", ",", "@options", ")", "end", "return", "0", "end" ]
Finishes a Pivotal Tracker story
[ "Finishes", "a", "Pivotal", "Tracker", "story" ]
676436950b691f57ad793a9023a4765ab9420dd0
https://github.com/donaldpiret/github-pivotal-flow/blob/676436950b691f57ad793a9023a4765ab9420dd0/lib/github_pivotal_flow/finish.rb#L6-L18
train
jage/elk
lib/elk/sms.rb
Elk.SMS.reload
def reload response = @client.get("/SMS/#{self.message_id}") self.set_parameters(Elk::Util.parse_json(response.body)) response.code == 200 end
ruby
def reload response = @client.get("/SMS/#{self.message_id}") self.set_parameters(Elk::Util.parse_json(response.body)) response.code == 200 end
[ "def", "reload", "response", "=", "@client", ".", "get", "(", "\"/SMS/#{self.message_id}\"", ")", "self", ".", "set_parameters", "(", "Elk", "::", "Util", ".", "parse_json", "(", "response", ".", "body", ")", ")", "response", ".", "code", "==", "200", "end" ]
Reloads a SMS from server
[ "Reloads", "a", "SMS", "from", "server" ]
9e28155d1c270d7a21f5c009a4cdff9a0fff0808
https://github.com/jage/elk/blob/9e28155d1c270d7a21f5c009a4cdff9a0fff0808/lib/elk/sms.rb#L26-L30
train
cul/cul_omniauth
app/models/concerns/cul/omniauth/users.rb
Cul::Omniauth::Users.ClassMethods.find_for_provider
def find_for_provider(token, provider) return nil unless token['uid'] props = {:uid => token['uid'].downcase, provider: provider.downcase} user = where(props).first # create new user if necessary unless user user = create!(whitelist(props)) # can we add groups or roles here? end user end
ruby
def find_for_provider(token, provider) return nil unless token['uid'] props = {:uid => token['uid'].downcase, provider: provider.downcase} user = where(props).first # create new user if necessary unless user user = create!(whitelist(props)) # can we add groups or roles here? end user end
[ "def", "find_for_provider", "(", "token", ",", "provider", ")", "return", "nil", "unless", "token", "[", "'uid'", "]", "props", "=", "{", ":uid", "=>", "token", "[", "'uid'", "]", ".", "downcase", ",", "provider", ":", "provider", ".", "downcase", "}", "user", "=", "where", "(", "props", ")", ".", "first", "unless", "user", "user", "=", "create!", "(", "whitelist", "(", "props", ")", ")", "end", "user", "end" ]
token is an omniauth hash
[ "token", "is", "an", "omniauth", "hash" ]
bf40dfe86e246dffbac70e0551b57f7638959a3b
https://github.com/cul/cul_omniauth/blob/bf40dfe86e246dffbac70e0551b57f7638959a3b/app/models/concerns/cul/omniauth/users.rb#L33-L43
train
mooreryan/parse_fasta
lib/parse_fasta/record.rb
ParseFasta.Record.to_fastq
def to_fastq opts = {} if fastq? "@#{@header}\n#{@seq}\n+#{@desc}\n#{qual}" else qual = opts.fetch :qual, "I" check_qual qual desc = opts.fetch :desc, "" qual_str = make_qual_str qual "@#{@header}\n#{@seq}\n+#{desc}\n#{qual_str}" end end
ruby
def to_fastq opts = {} if fastq? "@#{@header}\n#{@seq}\n+#{@desc}\n#{qual}" else qual = opts.fetch :qual, "I" check_qual qual desc = opts.fetch :desc, "" qual_str = make_qual_str qual "@#{@header}\n#{@seq}\n+#{desc}\n#{qual_str}" end end
[ "def", "to_fastq", "opts", "=", "{", "}", "if", "fastq?", "\"@#{@header}\\n#{@seq}\\n+#{@desc}\\n#{qual}\"", "else", "qual", "=", "opts", ".", "fetch", ":qual", ",", "\"I\"", "check_qual", "qual", "desc", "=", "opts", ".", "fetch", ":desc", ",", "\"\"", "qual_str", "=", "make_qual_str", "qual", "\"@#{@header}\\n#{@seq}\\n+#{desc}\\n#{qual_str}\"", "end", "end" ]
Returns a fastA record ready to print. If the record is fastA like, the desc and qual can be specified. @return [String] a printable fastQ sequence record @example When the record is fastA like, no args rec = Record.new header: "Apple", seq: "ACTG" rec.to_fastq #=> "@Apple\nACTG\n+\nIIII" @example When the record is fastA like, desc and qual specified rec = Record.new header: "Apple", seq: "ACTG" rec.to_fastq decs: "Hi", qual: "A" #=> "@Apple\nACTG\n+Hi\nAAAA" @example When the record is fastA like, can specify fancy qual strings rec = Record.new header: "Apple", seq: "ACTGACTG" rec.to_fastq decs: "Hi", qual: "!a2" #=> "@Apple\nACTG\n+Hi\n!a2!a2!a" @example When the record is fastQ like rec = Record.new header: "Apple", seq: "ACTG", desc: "Hi", qual: "IIII" rec.to_fastq #=> ">Apple\nACTG" @raise [ParseFasta::Error::ArgumentError] if qual is ""
[ "Returns", "a", "fastA", "record", "ready", "to", "print", "." ]
016272371be668addb29d3c92ec6a5d2e07332ad
https://github.com/mooreryan/parse_fasta/blob/016272371be668addb29d3c92ec6a5d2e07332ad/lib/parse_fasta/record.rb#L137-L150
train
MattRyder/tableau
lib/tableau/moduleparser.rb
Tableau.ModuleParser.module_info
def module_info mod, types = parse, Set.new mod.classes.each { |c| types.add?(c.type) } return { name: mod.name, code: mod.module_id, types: types } end
ruby
def module_info mod, types = parse, Set.new mod.classes.each { |c| types.add?(c.type) } return { name: mod.name, code: mod.module_id, types: types } end
[ "def", "module_info", "mod", ",", "types", "=", "parse", ",", "Set", ".", "new", "mod", ".", "classes", ".", "each", "{", "|", "c", "|", "types", ".", "add?", "(", "c", ".", "type", ")", "}", "return", "{", "name", ":", "mod", ".", "name", ",", "code", ":", "mod", ".", "module_id", ",", "types", ":", "types", "}", "end" ]
Create a new ModuleParser, with an optional module code
[ "Create", "a", "new", "ModuleParser", "with", "an", "optional", "module", "code" ]
a313fa88bf165ca66cb564c14abd3e526d6c1494
https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/moduleparser.rb#L21-L26
train
fuminori-ido/edgarj
app/controllers/edgarj/edgarj_controller.rb
Edgarj.EdgarjController.create
def create upsert do # NOTE: create!() is not used because assign to @record to draw form. # Otherwise, @record would be in nil so failure at edgarj/_form rendering. # # NOTE2: valid? after create() calls validate_on_update. This is not # an expected behavior. So, new, valid?, then save. @record = model.new(permitted_params(:create)) @record_saved = @record # copy for possible later use on_upsert #upsert_files raise ActiveRecord::RecordNotSaved if [email protected]? @record.save # clear @record values for next data-entry @record = model.new end end
ruby
def create upsert do # NOTE: create!() is not used because assign to @record to draw form. # Otherwise, @record would be in nil so failure at edgarj/_form rendering. # # NOTE2: valid? after create() calls validate_on_update. This is not # an expected behavior. So, new, valid?, then save. @record = model.new(permitted_params(:create)) @record_saved = @record # copy for possible later use on_upsert #upsert_files raise ActiveRecord::RecordNotSaved if [email protected]? @record.save # clear @record values for next data-entry @record = model.new end end
[ "def", "create", "upsert", "do", "@record", "=", "model", ".", "new", "(", "permitted_params", "(", ":create", ")", ")", "@record_saved", "=", "@record", "on_upsert", "raise", "ActiveRecord", "::", "RecordNotSaved", "if", "!", "@record", ".", "valid?", "@record", ".", "save", "@record", "=", "model", ".", "new", "end", "end" ]
save new record === Permission ModelPermission::CREATE on this controller is required.
[ "save", "new", "record" ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/controllers/edgarj/edgarj_controller.rb#L134-L151
train
fuminori-ido/edgarj
app/controllers/edgarj/edgarj_controller.rb
Edgarj.EdgarjController.show
def show @record = user_scoped.find(params[:id]) #add_topic_path respond_to do |format| format.html { prepare_list @search = page_info.record render :action=>'index' } format.js end end
ruby
def show @record = user_scoped.find(params[:id]) #add_topic_path respond_to do |format| format.html { prepare_list @search = page_info.record render :action=>'index' } format.js end end
[ "def", "show", "@record", "=", "user_scoped", ".", "find", "(", "params", "[", ":id", "]", ")", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "prepare_list", "@search", "=", "page_info", ".", "record", "render", ":action", "=>", "'index'", "}", "format", ".", "js", "end", "end" ]
Show detail of one record. Format of html & js should be supported. === Permission ModelPermission::READ on this controller is required.
[ "Show", "detail", "of", "one", "record", ".", "Format", "of", "html", "&", "js", "should", "be", "supported", "." ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/controllers/edgarj/edgarj_controller.rb#L158-L169
train
fuminori-ido/edgarj
app/controllers/edgarj/edgarj_controller.rb
Edgarj.EdgarjController.update
def update upsert do # NOTE: # 1. update ++then++ valid to set new values in @record to draw form. # 1. user_scoped may have joins so that record could be # ActiveRecord::ReadOnlyRecord so that's why access again from # model. @record = model.find(user_scoped.find(params[:id]).id) #upsert_files if [email protected]_attributes(permitted_params(:update)) raise ActiveRecord::RecordInvalid.new(@record) end end end
ruby
def update upsert do # NOTE: # 1. update ++then++ valid to set new values in @record to draw form. # 1. user_scoped may have joins so that record could be # ActiveRecord::ReadOnlyRecord so that's why access again from # model. @record = model.find(user_scoped.find(params[:id]).id) #upsert_files if [email protected]_attributes(permitted_params(:update)) raise ActiveRecord::RecordInvalid.new(@record) end end end
[ "def", "update", "upsert", "do", "@record", "=", "model", ".", "find", "(", "user_scoped", ".", "find", "(", "params", "[", ":id", "]", ")", ".", "id", ")", "if", "!", "@record", ".", "update_attributes", "(", "permitted_params", "(", ":update", ")", ")", "raise", "ActiveRecord", "::", "RecordInvalid", ".", "new", "(", "@record", ")", "end", "end", "end" ]
save existence modified record === Permission ModelPermission::UPDATE on this controller is required.
[ "save", "existence", "modified", "record" ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/controllers/edgarj/edgarj_controller.rb#L176-L189
train
fuminori-ido/edgarj
app/controllers/edgarj/edgarj_controller.rb
Edgarj.EdgarjController.search_save
def search_save SavedVcontext.save(current_user, nil, params[:saved_page_info_name], page_info) render :update do |page| page << "Edgarj.SearchSavePopup.close();" page.replace 'edgarj_load_condition_menu', :partial=>'edgarj/load_condition_menu' end rescue ActiveRecord::ActiveRecordError app_rescue render :update do |page| page.replace_html 'search_save_popup_flash_error', :text=>t('save_fail') end end
ruby
def search_save SavedVcontext.save(current_user, nil, params[:saved_page_info_name], page_info) render :update do |page| page << "Edgarj.SearchSavePopup.close();" page.replace 'edgarj_load_condition_menu', :partial=>'edgarj/load_condition_menu' end rescue ActiveRecord::ActiveRecordError app_rescue render :update do |page| page.replace_html 'search_save_popup_flash_error', :text=>t('save_fail') end end
[ "def", "search_save", "SavedVcontext", ".", "save", "(", "current_user", ",", "nil", ",", "params", "[", ":saved_page_info_name", "]", ",", "page_info", ")", "render", ":update", "do", "|", "page", "|", "page", "<<", "\"Edgarj.SearchSavePopup.close();\"", "page", ".", "replace", "'edgarj_load_condition_menu'", ",", ":partial", "=>", "'edgarj/load_condition_menu'", "end", "rescue", "ActiveRecord", "::", "ActiveRecordError", "app_rescue", "render", ":update", "do", "|", "page", "|", "page", ".", "replace_html", "'search_save_popup_flash_error'", ",", ":text", "=>", "t", "(", "'save_fail'", ")", "end", "end" ]
Ajax method to save search conditions === call flow Edgarj.SearchSavePopup.open() (javascript) (show $('search_save_popup')) Edgarj.SearchSavePopup.submit() (javascript) (copy entered name into $('saved_page_info_name') in form) call :action=>'search_save' ==== TRICKY PART There are two requirements: 1. use modal-dialog to enter name to decrese busy in search form. 1. send Search Form with name to server. To comply these, Edgarj.SearchSavePopup copies the entered name to 'saved_page_info_name' hidden field and then sends the form which includes the copied name. === Permission ModelPermission::READ on this controller is required.
[ "Ajax", "method", "to", "save", "search", "conditions" ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/controllers/edgarj/edgarj_controller.rb#L260-L274
train
fuminori-ido/edgarj
app/controllers/edgarj/edgarj_controller.rb
Edgarj.EdgarjController.csv_download
def csv_download filename = sprintf("%s-%s.csv", model_name, Time.now.strftime("%Y%m%d-%H%M%S")) file = Tempfile.new(filename, Settings.edgarj.csv_dir) csv_visitor = EdgarjHelper::CsvVisitor.new(view_context) file.write CSV.generate_line(model.columns.map{|c| c.name}) for rec in user_scoped.where(page_info.record.conditions). order( page_info.order_by.blank? ? nil : page_info.order_by + ' ' + page_info.dir) do array = [] for col in model.columns do array << csv_visitor.visit_column(rec, col) end file.write CSV.generate_line(array) end file.close File.chmod(Settings.edgarj.csv_permission, file.path) send_file(file.path, { type: 'text/csv', filename: filename}) #file.close(true) end
ruby
def csv_download filename = sprintf("%s-%s.csv", model_name, Time.now.strftime("%Y%m%d-%H%M%S")) file = Tempfile.new(filename, Settings.edgarj.csv_dir) csv_visitor = EdgarjHelper::CsvVisitor.new(view_context) file.write CSV.generate_line(model.columns.map{|c| c.name}) for rec in user_scoped.where(page_info.record.conditions). order( page_info.order_by.blank? ? nil : page_info.order_by + ' ' + page_info.dir) do array = [] for col in model.columns do array << csv_visitor.visit_column(rec, col) end file.write CSV.generate_line(array) end file.close File.chmod(Settings.edgarj.csv_permission, file.path) send_file(file.path, { type: 'text/csv', filename: filename}) #file.close(true) end
[ "def", "csv_download", "filename", "=", "sprintf", "(", "\"%s-%s.csv\"", ",", "model_name", ",", "Time", ".", "now", ".", "strftime", "(", "\"%Y%m%d-%H%M%S\"", ")", ")", "file", "=", "Tempfile", ".", "new", "(", "filename", ",", "Settings", ".", "edgarj", ".", "csv_dir", ")", "csv_visitor", "=", "EdgarjHelper", "::", "CsvVisitor", ".", "new", "(", "view_context", ")", "file", ".", "write", "CSV", ".", "generate_line", "(", "model", ".", "columns", ".", "map", "{", "|", "c", "|", "c", ".", "name", "}", ")", "for", "rec", "in", "user_scoped", ".", "where", "(", "page_info", ".", "record", ".", "conditions", ")", ".", "order", "(", "page_info", ".", "order_by", ".", "blank?", "?", "nil", ":", "page_info", ".", "order_by", "+", "' '", "+", "page_info", ".", "dir", ")", "do", "array", "=", "[", "]", "for", "col", "in", "model", ".", "columns", "do", "array", "<<", "csv_visitor", ".", "visit_column", "(", "rec", ",", "col", ")", "end", "file", ".", "write", "CSV", ".", "generate_line", "(", "array", ")", "end", "file", ".", "close", "File", ".", "chmod", "(", "Settings", ".", "edgarj", ".", "csv_permission", ",", "file", ".", "path", ")", "send_file", "(", "file", ".", "path", ",", "{", "type", ":", "'text/csv'", ",", "filename", ":", "filename", "}", ")", "end" ]
zip -> address completion === INPUTS params[:zip]:: key to find address info. hyphen is supported. params[:adrs_prefix]:: address fields DOM id prefix. e.g. 'org_adrs_0_' === call flow ==== on drawing EdgarjHelper.draw_adrs() app/helpers/edgarj_helper.rb app/views/edgarj/_address.html.erb Example: : <input type=text name='org[adrs_0_zip]'> : ==== on clicking zip->address button Edgarj.zip_complete() public/javascripts/edgarj.js Ajax.Request() EdgarjController.zip_complete app/controllers/edgarj_controller.rb inline RJS to fill address info =begin def zip_complete zip = params[:zip].gsub(/\D/, '') @address = ZipAddress.find_by_zip(zip) || ZipAddress.new( :prefecture => '?', :city => '', :other => '') # sanitize @adrs_prefix = params[:adrs_prefix].gsub(/[^a-zA-Z_0-9]/, '') end =end download model under current condition <tt>respond_to...format.csv</tt> approach was not used since \@list is different as follows: * csv returns all of records under the conditions * HTML returns *just* in specified 'page'. === Permission ModelPermission::READ on this controller is required. FIXME: file.close(true) deletes files *BEFORE* actually send file so that comment it out. Need to clean these work files.
[ "zip", "-", ">", "address", "completion" ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/controllers/edgarj/edgarj_controller.rb#L329-L353
train
fuminori-ido/edgarj
app/controllers/edgarj/edgarj_controller.rb
Edgarj.EdgarjController.drawer_class
def drawer_class @_drawer_cache ||= if self.class == Edgarj::EdgarjController Edgarj::Drawer::Normal else (self.class.name.gsub(/Controller$/, '').singularize + 'Drawer').constantize end end
ruby
def drawer_class @_drawer_cache ||= if self.class == Edgarj::EdgarjController Edgarj::Drawer::Normal else (self.class.name.gsub(/Controller$/, '').singularize + 'Drawer').constantize end end
[ "def", "drawer_class", "@_drawer_cache", "||=", "if", "self", ".", "class", "==", "Edgarj", "::", "EdgarjController", "Edgarj", "::", "Drawer", "::", "Normal", "else", "(", "self", ".", "class", ".", "name", ".", "gsub", "(", "/", "/", ",", "''", ")", ".", "singularize", "+", "'Drawer'", ")", ".", "constantize", "end", "end" ]
derive drawer class from this controller. If controller cannot guess drawer class, overwrite this. === Examples: * AuthorsController -> AuthorDrawer * UsersController -> UserDrawer
[ "derive", "drawer", "class", "from", "this", "controller", "." ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/controllers/edgarj/edgarj_controller.rb#L440-L448
train
fuminori-ido/edgarj
app/models/edgarj/search.rb
Edgarj.Search.column_type
def column_type(col_name) cache = Cache.instance cache.klass_hash[@_klass_str] ||= {} if v = cache.klass_hash[@_klass_str][col_name.to_s] cache.hit += 1 v else cache.miss += 1 col = @_klass_str.constantize.columns.find{|c| c.name == col_name.to_s } if col cache.klass_hash[@_klass_str][col_name.to_s] = col.type end end end
ruby
def column_type(col_name) cache = Cache.instance cache.klass_hash[@_klass_str] ||= {} if v = cache.klass_hash[@_klass_str][col_name.to_s] cache.hit += 1 v else cache.miss += 1 col = @_klass_str.constantize.columns.find{|c| c.name == col_name.to_s } if col cache.klass_hash[@_klass_str][col_name.to_s] = col.type end end end
[ "def", "column_type", "(", "col_name", ")", "cache", "=", "Cache", ".", "instance", "cache", ".", "klass_hash", "[", "@_klass_str", "]", "||=", "{", "}", "if", "v", "=", "cache", ".", "klass_hash", "[", "@_klass_str", "]", "[", "col_name", ".", "to_s", "]", "cache", ".", "hit", "+=", "1", "v", "else", "cache", ".", "miss", "+=", "1", "col", "=", "@_klass_str", ".", "constantize", ".", "columns", ".", "find", "{", "|", "c", "|", "c", ".", "name", "==", "col_name", ".", "to_s", "}", "if", "col", "cache", ".", "klass_hash", "[", "@_klass_str", "]", "[", "col_name", ".", "to_s", "]", "=", "col", ".", "type", "end", "end", "end" ]
cache column type
[ "cache", "column", "type" ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/models/edgarj/search.rb#L64-L79
train
efreesen/active_repository
lib/active_repository/writers.rb
ActiveRepository.Writers.create
def create(attributes={}) attributes = attributes.symbolize_keys if attributes.respond_to?(:symbolize_keys) object = self.new(attributes) if object.present? && object.valid? if persistence_class == self object.id = nil unless exists?(object.id) object.save else object = PersistenceAdapter.create(self, object.attributes) end end new_object = serialize!(object.reload.attributes) new_object.valid? new_object end
ruby
def create(attributes={}) attributes = attributes.symbolize_keys if attributes.respond_to?(:symbolize_keys) object = self.new(attributes) if object.present? && object.valid? if persistence_class == self object.id = nil unless exists?(object.id) object.save else object = PersistenceAdapter.create(self, object.attributes) end end new_object = serialize!(object.reload.attributes) new_object.valid? new_object end
[ "def", "create", "(", "attributes", "=", "{", "}", ")", "attributes", "=", "attributes", ".", "symbolize_keys", "if", "attributes", ".", "respond_to?", "(", ":symbolize_keys", ")", "object", "=", "self", ".", "new", "(", "attributes", ")", "if", "object", ".", "present?", "&&", "object", ".", "valid?", "if", "persistence_class", "==", "self", "object", ".", "id", "=", "nil", "unless", "exists?", "(", "object", ".", "id", ")", "object", ".", "save", "else", "object", "=", "PersistenceAdapter", ".", "create", "(", "self", ",", "object", ".", "attributes", ")", "end", "end", "new_object", "=", "serialize!", "(", "object", ".", "reload", ".", "attributes", ")", "new_object", ".", "valid?", "new_object", "end" ]
Creates an object and persists it.
[ "Creates", "an", "object", "and", "persists", "it", "." ]
e134b0e02959ac7e745319a2d74398101dfc5900
https://github.com/efreesen/active_repository/blob/e134b0e02959ac7e745319a2d74398101dfc5900/lib/active_repository/writers.rb#L5-L24
train
MattRyder/tableau
lib/tableau/tablebuilder.rb
Tableau.TableBuilder.to_html
def to_html time_header, rows = '<th></th>', Array.new end_time = Time.new(2013, 1, 1, 21, 0, 0) # make the time row @time = Time.new(2013, 1, 1, 9, 0, 0) while @time < end_time time_header += "<th>#{@time.strftime("%-k:%M")}</th>" @time += 900 end #make each day row (0..4).each do |day| classes = @timetable.classes_for_day(day) rows << day_row(day, classes) end rows_str, id_str = '', "id=\"#{@timetable.name}\"" rows.each{ |r| rows_str += "<tr class=\"day\">\n#{r}\n</tr>\n" } %Q{ <!DOCTYPE html> <html> <head> <title>#{@timetable.name || 'Timetable' } - Timetablr.co</title> <style>#{build_css}</style> </head> <body> <h3>#{@timetable.name}</h3> <table #{id_str if @timetable.name}> <tr id="time">#{time_header}</tr> #{rows_str} </table> </body> </html> } end
ruby
def to_html time_header, rows = '<th></th>', Array.new end_time = Time.new(2013, 1, 1, 21, 0, 0) # make the time row @time = Time.new(2013, 1, 1, 9, 0, 0) while @time < end_time time_header += "<th>#{@time.strftime("%-k:%M")}</th>" @time += 900 end #make each day row (0..4).each do |day| classes = @timetable.classes_for_day(day) rows << day_row(day, classes) end rows_str, id_str = '', "id=\"#{@timetable.name}\"" rows.each{ |r| rows_str += "<tr class=\"day\">\n#{r}\n</tr>\n" } %Q{ <!DOCTYPE html> <html> <head> <title>#{@timetable.name || 'Timetable' } - Timetablr.co</title> <style>#{build_css}</style> </head> <body> <h3>#{@timetable.name}</h3> <table #{id_str if @timetable.name}> <tr id="time">#{time_header}</tr> #{rows_str} </table> </body> </html> } end
[ "def", "to_html", "time_header", ",", "rows", "=", "'<th></th>'", ",", "Array", ".", "new", "end_time", "=", "Time", ".", "new", "(", "2013", ",", "1", ",", "1", ",", "21", ",", "0", ",", "0", ")", "@time", "=", "Time", ".", "new", "(", "2013", ",", "1", ",", "1", ",", "9", ",", "0", ",", "0", ")", "while", "@time", "<", "end_time", "time_header", "+=", "\"<th>#{@time.strftime(\"%-k:%M\")}</th>\"", "@time", "+=", "900", "end", "(", "0", "..", "4", ")", ".", "each", "do", "|", "day", "|", "classes", "=", "@timetable", ".", "classes_for_day", "(", "day", ")", "rows", "<<", "day_row", "(", "day", ",", "classes", ")", "end", "rows_str", ",", "id_str", "=", "''", ",", "\"id=\\\"#{@timetable.name}\\\"\"", "rows", ".", "each", "{", "|", "r", "|", "rows_str", "+=", "\"<tr class=\\\"day\\\">\\n#{r}\\n</tr>\\n\"", "}", "%Q{ <!DOCTYPE html> <html> <head> <title>#{@timetable.name || 'Timetable' } - Timetablr.co</title> <style>#{build_css}</style> </head> <body> <h3>#{@timetable.name}</h3> <table #{id_str if @timetable.name}> <tr id=\"time\">#{time_header}</tr> #{rows_str} </table> </body> </html> }", "end" ]
HTML5 representation of the timetable
[ "HTML5", "representation", "of", "the", "timetable" ]
a313fa88bf165ca66cb564c14abd3e526d6c1494
https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/tablebuilder.rb#L95-L131
train
Kuniri/kuniri
lib/kuniri/core/setting.rb
Kuniri.Setting.read_configuration_file
def read_configuration_file(pPath = '.kuniri.yml') if !(File.exist?(pPath)) set_default_configuration else safeInfo = SafeYAML.load(File.read(pPath)) # SafeYAML add collon (':') in the begin of each key. We handle it here @configurationInfo = safeInfo.map do |key, value| [key.tr(':', '').to_sym, value] end.to_h verify_syntax end return @configurationInfo end
ruby
def read_configuration_file(pPath = '.kuniri.yml') if !(File.exist?(pPath)) set_default_configuration else safeInfo = SafeYAML.load(File.read(pPath)) # SafeYAML add collon (':') in the begin of each key. We handle it here @configurationInfo = safeInfo.map do |key, value| [key.tr(':', '').to_sym, value] end.to_h verify_syntax end return @configurationInfo end
[ "def", "read_configuration_file", "(", "pPath", "=", "'.kuniri.yml'", ")", "if", "!", "(", "File", ".", "exist?", "(", "pPath", ")", ")", "set_default_configuration", "else", "safeInfo", "=", "SafeYAML", ".", "load", "(", "File", ".", "read", "(", "pPath", ")", ")", "@configurationInfo", "=", "safeInfo", ".", "map", "do", "|", "key", ",", "value", "|", "[", "key", ".", "tr", "(", "':'", ",", "''", ")", ".", "to_sym", ",", "value", "]", "end", ".", "to_h", "verify_syntax", "end", "return", "@configurationInfo", "end" ]
In this method it is checked the configuration file syntax. @param pPath [String] Path to ".kuniri" file, it means, the configurations. @return [Hash] Return a Hash with the configurations read in ".kuniri", otherwise, raise an exception.
[ "In", "this", "method", "it", "is", "checked", "the", "configuration", "file", "syntax", "." ]
8b840ab307dc6bec48edd272c732b28c98f93f45
https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/core/setting.rb#L39-L52
train
godfat/pagify
lib/pagify/pager/basic.rb
Pagify.BasicPager.page
def page page if page_exists?(page) return BasicPage.new(self, normalize_page(page)) else if null_page return null_page_instance else return nil end end end
ruby
def page page if page_exists?(page) return BasicPage.new(self, normalize_page(page)) else if null_page return null_page_instance else return nil end end end
[ "def", "page", "page", "if", "page_exists?", "(", "page", ")", "return", "BasicPage", ".", "new", "(", "self", ",", "normalize_page", "(", "page", ")", ")", "else", "if", "null_page", "return", "null_page_instance", "else", "return", "nil", "end", "end", "end" ]
create page instance by page number. if page number you specified was not existed, nil would be returned. note, page start at 1, not zero.
[ "create", "page", "instance", "by", "page", "number", ".", "if", "page", "number", "you", "specified", "was", "not", "existed", "nil", "would", "be", "returned", ".", "note", "page", "start", "at", "1", "not", "zero", "." ]
178fafc959335050e89e9d5a1d1a347145ee61db
https://github.com/godfat/pagify/blob/178fafc959335050e89e9d5a1d1a347145ee61db/lib/pagify/pager/basic.rb#L70-L83
train
news-scraper/news_scraper
lib/news_scraper/scraper.rb
NewsScraper.Scraper.scrape
def scrape article_urls = Extractors::GoogleNewsRss.new(query: @query).extract transformed_articles = [] article_urls.each do |article_url| payload = Extractors::Article.new(url: article_url).extract article_transformer = Transformers::Article.new(url: article_url, payload: payload) begin transformed_article = article_transformer.transform transformed_articles << transformed_article yield transformed_article if block_given? rescue Transformers::ScrapePatternNotDefined => e raise e unless block_given? yield e end end transformed_articles end
ruby
def scrape article_urls = Extractors::GoogleNewsRss.new(query: @query).extract transformed_articles = [] article_urls.each do |article_url| payload = Extractors::Article.new(url: article_url).extract article_transformer = Transformers::Article.new(url: article_url, payload: payload) begin transformed_article = article_transformer.transform transformed_articles << transformed_article yield transformed_article if block_given? rescue Transformers::ScrapePatternNotDefined => e raise e unless block_given? yield e end end transformed_articles end
[ "def", "scrape", "article_urls", "=", "Extractors", "::", "GoogleNewsRss", ".", "new", "(", "query", ":", "@query", ")", ".", "extract", "transformed_articles", "=", "[", "]", "article_urls", ".", "each", "do", "|", "article_url", "|", "payload", "=", "Extractors", "::", "Article", ".", "new", "(", "url", ":", "article_url", ")", ".", "extract", "article_transformer", "=", "Transformers", "::", "Article", ".", "new", "(", "url", ":", "article_url", ",", "payload", ":", "payload", ")", "begin", "transformed_article", "=", "article_transformer", ".", "transform", "transformed_articles", "<<", "transformed_article", "yield", "transformed_article", "if", "block_given?", "rescue", "Transformers", "::", "ScrapePatternNotDefined", "=>", "e", "raise", "e", "unless", "block_given?", "yield", "e", "end", "end", "transformed_articles", "end" ]
Initialize a Scraper object *Params* - <code>query</code>: a keyword arugment specifying the query to scrape Fetches articles from Extraction sources and scrapes the results *Yields* - Will yield individually extracted articles *Raises* - Will raise a <code>Transformers::ScrapePatternNotDefined</code> if an article is not in the root domains - Will <code>yield</code> the error if a block is given - Root domains are specified by the <code>article_scrape_patterns.yml</code> file - This root domain will need to be trained, it would be helpful to have a PR created to train the domain - You can train the domain by running <code>NewsScraper::Trainer::UrlTrainer.new(URL_TO_TRAIN).train</code> *Returns* - <code>transformed_articles</code>: The transformed articles fetched from the extracted sources
[ "Initialize", "a", "Scraper", "object" ]
3ee2ea9590d081ffb8e98120b2e1344dec88a15e
https://github.com/news-scraper/news_scraper/blob/3ee2ea9590d081ffb8e98120b2e1344dec88a15e/lib/news_scraper/scraper.rb#L27-L47
train
news-scraper/news_scraper
lib/news_scraper/trainer.rb
NewsScraper.Trainer.train
def train(query: '') article_urls = Extractors::GoogleNewsRss.new(query: query).extract article_urls.each do |url| Trainer::UrlTrainer.new(url).train end end
ruby
def train(query: '') article_urls = Extractors::GoogleNewsRss.new(query: query).extract article_urls.each do |url| Trainer::UrlTrainer.new(url).train end end
[ "def", "train", "(", "query", ":", "''", ")", "article_urls", "=", "Extractors", "::", "GoogleNewsRss", ".", "new", "(", "query", ":", "query", ")", ".", "extract", "article_urls", ".", "each", "do", "|", "url", "|", "Trainer", "::", "UrlTrainer", ".", "new", "(", "url", ")", ".", "train", "end", "end" ]
Fetches articles from Extraction sources and trains on the results *Training* is a process where we take an untrained url (root domain is not in <code>article_scrape_patterns.yml</code>) and determine patterns and methods to match the data_types listed in <code>article_scrape_patterns.yml</code>, then record them to the <code>article_scrape_patterns.yml</code> file *Params* - <code>query</code>: a keyword arugment specifying the query to train on
[ "Fetches", "articles", "from", "Extraction", "sources", "and", "trains", "on", "the", "results" ]
3ee2ea9590d081ffb8e98120b2e1344dec88a15e
https://github.com/news-scraper/news_scraper/blob/3ee2ea9590d081ffb8e98120b2e1344dec88a15e/lib/news_scraper/trainer.rb#L18-L23
train
bdurand/json_record
lib/json_record/schema.rb
JsonRecord.Schema.key
def key (name, *args) options = args.extract_options! name = name.to_s json_type = args.first || String raise ArgumentError.new("too many arguments (must be 1 or 2 plus an options hash)") if args.length > 1 field = FieldDefinition.new(name, :type => json_type, :default => options[:default]) fields[name] = field add_json_validations(field, options) define_json_accessor(field, json_field_name) end
ruby
def key (name, *args) options = args.extract_options! name = name.to_s json_type = args.first || String raise ArgumentError.new("too many arguments (must be 1 or 2 plus an options hash)") if args.length > 1 field = FieldDefinition.new(name, :type => json_type, :default => options[:default]) fields[name] = field add_json_validations(field, options) define_json_accessor(field, json_field_name) end
[ "def", "key", "(", "name", ",", "*", "args", ")", "options", "=", "args", ".", "extract_options!", "name", "=", "name", ".", "to_s", "json_type", "=", "args", ".", "first", "||", "String", "raise", "ArgumentError", ".", "new", "(", "\"too many arguments (must be 1 or 2 plus an options hash)\"", ")", "if", "args", ".", "length", ">", "1", "field", "=", "FieldDefinition", ".", "new", "(", "name", ",", ":type", "=>", "json_type", ",", ":default", "=>", "options", "[", ":default", "]", ")", "fields", "[", "name", "]", "=", "field", "add_json_validations", "(", "field", ",", "options", ")", "define_json_accessor", "(", "field", ",", "json_field_name", ")", "end" ]
Create a schema on the class for a particular field. Define a single valued field in the schema. The first argument is the field name. This must be unique for the class accross all attributes. The optional second argument can be used to specify the class of the field values. It will default to String if not specified. Valid types are String, Integer, Float, Date, Time, DateTime, Boolean, Array, Hash, or any class that inherits from EmbeddedDocument. The last argument can be a hash with any of these keys: * :default - * :required - * :length - * :format - * :in -
[ "Create", "a", "schema", "on", "the", "class", "for", "a", "particular", "field", ".", "Define", "a", "single", "valued", "field", "in", "the", "schema", ".", "The", "first", "argument", "is", "the", "field", "name", ".", "This", "must", "be", "unique", "for", "the", "class", "accross", "all", "attributes", "." ]
463f4719d9618f6d2406c0aab6028e0156f7c775
https://github.com/bdurand/json_record/blob/463f4719d9618f6d2406c0aab6028e0156f7c775/lib/json_record/schema.rb#L27-L38
train
bdurand/json_record
lib/json_record/schema.rb
JsonRecord.Schema.many
def many (name, *args) name = name.to_s options = args.extract_options! type = args.first || name.singularize.classify.constantize field = FieldDefinition.new(name, :type => type, :multivalued => true) fields[name] = field add_json_validations(field, options) define_many_json_accessor(field, json_field_name) end
ruby
def many (name, *args) name = name.to_s options = args.extract_options! type = args.first || name.singularize.classify.constantize field = FieldDefinition.new(name, :type => type, :multivalued => true) fields[name] = field add_json_validations(field, options) define_many_json_accessor(field, json_field_name) end
[ "def", "many", "(", "name", ",", "*", "args", ")", "name", "=", "name", ".", "to_s", "options", "=", "args", ".", "extract_options!", "type", "=", "args", ".", "first", "||", "name", ".", "singularize", ".", "classify", ".", "constantize", "field", "=", "FieldDefinition", ".", "new", "(", "name", ",", ":type", "=>", "type", ",", ":multivalued", "=>", "true", ")", "fields", "[", "name", "]", "=", "field", "add_json_validations", "(", "field", ",", "options", ")", "define_many_json_accessor", "(", "field", ",", "json_field_name", ")", "end" ]
Define a multi valued field in the schema. The first argument is the field name. This must be unique for the class accross all attributes. The optional second argument should be the class of field values. This class must include EmbeddedDocument. If it is not specified, the class name will be guessed from the field name. The last argument can be :unique => field_name which is used to indicate that the values in the field must have unique values in the indicated field name. The value of the field will always be an EmbeddedDocumentArray and adding and removing values is as simple as appending them to the array. You can also call the build method on the array to keep the syntax the same as when dealing with ActiveRecord has_many associations.
[ "Define", "a", "multi", "valued", "field", "in", "the", "schema", ".", "The", "first", "argument", "is", "the", "field", "name", ".", "This", "must", "be", "unique", "for", "the", "class", "accross", "all", "attributes", "." ]
463f4719d9618f6d2406c0aab6028e0156f7c775
https://github.com/bdurand/json_record/blob/463f4719d9618f6d2406c0aab6028e0156f7c775/lib/json_record/schema.rb#L52-L60
train
MattRyder/tableau
lib/tableau/classarray.rb
Tableau.ClassArray.classes_for_day
def classes_for_day(day) days_classes = ClassArray.new self.each { |c| days_classes << c if c.day == day } days_classes.count > 0 ? days_classes : nil end
ruby
def classes_for_day(day) days_classes = ClassArray.new self.each { |c| days_classes << c if c.day == day } days_classes.count > 0 ? days_classes : nil end
[ "def", "classes_for_day", "(", "day", ")", "days_classes", "=", "ClassArray", ".", "new", "self", ".", "each", "{", "|", "c", "|", "days_classes", "<<", "c", "if", "c", ".", "day", "==", "day", "}", "days_classes", ".", "count", ">", "0", "?", "days_classes", ":", "nil", "end" ]
Returns an array of all the classes for the day
[ "Returns", "an", "array", "of", "all", "the", "classes", "for", "the", "day" ]
a313fa88bf165ca66cb564c14abd3e526d6c1494
https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/classarray.rb#L9-L13
train
MattRyder/tableau
lib/tableau/classarray.rb
Tableau.ClassArray.earliest_class
def earliest_class earliest = self.first self.each { |c| earliest = c if c.time < earliest.time } earliest end
ruby
def earliest_class earliest = self.first self.each { |c| earliest = c if c.time < earliest.time } earliest end
[ "def", "earliest_class", "earliest", "=", "self", ".", "first", "self", ".", "each", "{", "|", "c", "|", "earliest", "=", "c", "if", "c", ".", "time", "<", "earliest", ".", "time", "}", "earliest", "end" ]
Returns the earliest class in the module
[ "Returns", "the", "earliest", "class", "in", "the", "module" ]
a313fa88bf165ca66cb564c14abd3e526d6c1494
https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/classarray.rb#L16-L20
train
namelessjon/todoist
lib/todoist/task.rb
Todoist.Task.save
def save opts = {} opts['priority'] = priority if priority opts['date_string'] = date if date # if we don't have an id, then we can assume this is a new task. unless (task_details.has_key?('id')) result = self.class.create(self.content, self.project_id, opts) else result = self.class.update(self.content, self.id, opts) end self.content = result.content self.project_id = result.project_id self.task_details = result.task_details self end
ruby
def save opts = {} opts['priority'] = priority if priority opts['date_string'] = date if date # if we don't have an id, then we can assume this is a new task. unless (task_details.has_key?('id')) result = self.class.create(self.content, self.project_id, opts) else result = self.class.update(self.content, self.id, opts) end self.content = result.content self.project_id = result.project_id self.task_details = result.task_details self end
[ "def", "save", "opts", "=", "{", "}", "opts", "[", "'priority'", "]", "=", "priority", "if", "priority", "opts", "[", "'date_string'", "]", "=", "date", "if", "date", "unless", "(", "task_details", ".", "has_key?", "(", "'id'", ")", ")", "result", "=", "self", ".", "class", ".", "create", "(", "self", ".", "content", ",", "self", ".", "project_id", ",", "opts", ")", "else", "result", "=", "self", ".", "class", ".", "update", "(", "self", ".", "content", ",", "self", ".", "id", ",", "opts", ")", "end", "self", ".", "content", "=", "result", ".", "content", "self", ".", "project_id", "=", "result", ".", "project_id", "self", ".", "task_details", "=", "result", ".", "task_details", "self", "end" ]
Saves the task Save the task, either creating a new task on the todoist service, or updating a previously retrieved task with new content, priority etc.
[ "Saves", "the", "task" ]
65f049436f639fcb7dc3c8f5b5737ba0f81be9d5
https://github.com/namelessjon/todoist/blob/65f049436f639fcb7dc3c8f5b5737ba0f81be9d5/lib/todoist/task.rb#L188-L203
train
tpope/ldaptic
lib/ldaptic/attribute_set.rb
Ldaptic.AttributeSet.replace
def replace(*attributes) attributes = safe_array(attributes) user_modification_guard seen = {} filtered = [] attributes.each do |value| matchable = matchable(value) unless seen[matchable] filtered << value seen[matchable] = true end end @target.replace(filtered) self end
ruby
def replace(*attributes) attributes = safe_array(attributes) user_modification_guard seen = {} filtered = [] attributes.each do |value| matchable = matchable(value) unless seen[matchable] filtered << value seen[matchable] = true end end @target.replace(filtered) self end
[ "def", "replace", "(", "*", "attributes", ")", "attributes", "=", "safe_array", "(", "attributes", ")", "user_modification_guard", "seen", "=", "{", "}", "filtered", "=", "[", "]", "attributes", ".", "each", "do", "|", "value", "|", "matchable", "=", "matchable", "(", "value", ")", "unless", "seen", "[", "matchable", "]", "filtered", "<<", "value", "seen", "[", "matchable", "]", "=", "true", "end", "end", "@target", ".", "replace", "(", "filtered", ")", "self", "end" ]
Does a complete replacement of the attributes. Multiple attributes can be given as either multiple arguments or as an array.
[ "Does", "a", "complete", "replacement", "of", "the", "attributes", ".", "Multiple", "attributes", "can", "be", "given", "as", "either", "multiple", "arguments", "or", "as", "an", "array", "." ]
159a39464e9f5a05c0145db2b21cb256ef859612
https://github.com/tpope/ldaptic/blob/159a39464e9f5a05c0145db2b21cb256ef859612/lib/ldaptic/attribute_set.rb#L124-L138
train
fuminori-ido/edgarj
app/models/edgarj/search_form.rb
Edgarj.SearchForm.method_missing
def method_missing(method_name, *args) if method_name.to_s =~ /^(.*)=$/ @attrs[$1.to_sym] = args[0] else val = @attrs[method_name.to_sym] case column_type(method_name) when :integer if val =~ /^\d+$/ val.to_i else val end else val end end end
ruby
def method_missing(method_name, *args) if method_name.to_s =~ /^(.*)=$/ @attrs[$1.to_sym] = args[0] else val = @attrs[method_name.to_sym] case column_type(method_name) when :integer if val =~ /^\d+$/ val.to_i else val end else val end end end
[ "def", "method_missing", "(", "method_name", ",", "*", "args", ")", "if", "method_name", ".", "to_s", "=~", "/", "/", "@attrs", "[", "$1", ".", "to_sym", "]", "=", "args", "[", "0", "]", "else", "val", "=", "@attrs", "[", "method_name", ".", "to_sym", "]", "case", "column_type", "(", "method_name", ")", "when", ":integer", "if", "val", "=~", "/", "\\d", "/", "val", ".", "to_i", "else", "val", "end", "else", "val", "end", "end", "end" ]
Build SearchForm object from ActiveRecord 'klass' and attrs. === INPUTS klass:: ActiveRecord attrs:: hash of key=>value pair map attribute name to hash entry. This mechanism is required to be used in 'form_for' helper. When column type is integer and has digits value, return integer. This is required for selection helper. Even it is integer but has no value, keeps blank. When attribute name ends '=', assignment to hash works. === EXAMPLE s = Searchform.new(Product, :name=>'a') s.name s.conditions # ["name=?", "a"] s.name = 'b' # method_missing('name=', 'b') is called s.conditions # ["name=?", "b"]
[ "Build", "SearchForm", "object", "from", "ActiveRecord", "klass", "and", "attrs", "." ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/models/edgarj/search_form.rb#L127-L143
train
imanel/libwebsocket
lib/libwebsocket/url.rb
LibWebSocket.URL.parse
def parse(string) return nil unless string.is_a?(String) uri = Addressable::URI.parse(string) scheme = uri.scheme return nil unless scheme self.secure = true if scheme.match(/ss\Z/m) host = uri.host host = '/' unless host && host != '' self.host = host self.port = uri.port.to_s if uri.port request_uri = uri.path request_uri = '/' unless request_uri && request_uri != '' request_uri += "?" + uri.query if uri.query self.resource_name = request_uri return self end
ruby
def parse(string) return nil unless string.is_a?(String) uri = Addressable::URI.parse(string) scheme = uri.scheme return nil unless scheme self.secure = true if scheme.match(/ss\Z/m) host = uri.host host = '/' unless host && host != '' self.host = host self.port = uri.port.to_s if uri.port request_uri = uri.path request_uri = '/' unless request_uri && request_uri != '' request_uri += "?" + uri.query if uri.query self.resource_name = request_uri return self end
[ "def", "parse", "(", "string", ")", "return", "nil", "unless", "string", ".", "is_a?", "(", "String", ")", "uri", "=", "Addressable", "::", "URI", ".", "parse", "(", "string", ")", "scheme", "=", "uri", ".", "scheme", "return", "nil", "unless", "scheme", "self", ".", "secure", "=", "true", "if", "scheme", ".", "match", "(", "/", "\\Z", "/m", ")", "host", "=", "uri", ".", "host", "host", "=", "'/'", "unless", "host", "&&", "host", "!=", "''", "self", ".", "host", "=", "host", "self", ".", "port", "=", "uri", ".", "port", ".", "to_s", "if", "uri", ".", "port", "request_uri", "=", "uri", ".", "path", "request_uri", "=", "'/'", "unless", "request_uri", "&&", "request_uri", "!=", "''", "request_uri", "+=", "\"?\"", "+", "uri", ".", "query", "if", "uri", ".", "query", "self", ".", "resource_name", "=", "request_uri", "return", "self", "end" ]
Parse a WebSocket URL. @example Parse url = LibWebSocket::URL.new url.parse('wss://example.com:3000') url.host # => example.com url.port # => 3000 url.secure # => true
[ "Parse", "a", "WebSocket", "URL", "." ]
3e071439246f5a2c306e16fefc772d2f6f716f6b
https://github.com/imanel/libwebsocket/blob/3e071439246f5a2c306e16fefc772d2f6f716f6b/lib/libwebsocket/url.rb#L24-L45
train
imanel/libwebsocket
lib/libwebsocket/url.rb
LibWebSocket.URL.to_s
def to_s string = '' string += 'ws' string += 's' if self.secure string += '://' string += self.host string += ':' + self.port.to_s if self.port string += self.resource_name || '/' return string end
ruby
def to_s string = '' string += 'ws' string += 's' if self.secure string += '://' string += self.host string += ':' + self.port.to_s if self.port string += self.resource_name || '/' return string end
[ "def", "to_s", "string", "=", "''", "string", "+=", "'ws'", "string", "+=", "'s'", "if", "self", ".", "secure", "string", "+=", "'://'", "string", "+=", "self", ".", "host", "string", "+=", "':'", "+", "self", ".", "port", ".", "to_s", "if", "self", ".", "port", "string", "+=", "self", ".", "resource_name", "||", "'/'", "return", "string", "end" ]
Construct a WebSocket URL. @example Construct url = LibWebSocket::URL.new url.host = 'example.com' url.port = '3000' url.secure = true url.to_s # => 'wss://example.com:3000'
[ "Construct", "a", "WebSocket", "URL", "." ]
3e071439246f5a2c306e16fefc772d2f6f716f6b
https://github.com/imanel/libwebsocket/blob/3e071439246f5a2c306e16fefc772d2f6f716f6b/lib/libwebsocket/url.rb#L54-L65
train
at-point/loggr
lib/loggr/adapter.rb
Loggr.Adapter.logger
def logger(name, options = {}, &block) use_adapter = options.key?(:adapter) ? get_adapter(options.delete(:adapter)) : self.adapter use_adapter.logger(name, options).tap do |logger| yield(logger) if block_given? end end
ruby
def logger(name, options = {}, &block) use_adapter = options.key?(:adapter) ? get_adapter(options.delete(:adapter)) : self.adapter use_adapter.logger(name, options).tap do |logger| yield(logger) if block_given? end end
[ "def", "logger", "(", "name", ",", "options", "=", "{", "}", ",", "&", "block", ")", "use_adapter", "=", "options", ".", "key?", "(", ":adapter", ")", "?", "get_adapter", "(", "options", ".", "delete", "(", ":adapter", ")", ")", ":", "self", ".", "adapter", "use_adapter", ".", "logger", "(", "name", ",", "options", ")", ".", "tap", "do", "|", "logger", "|", "yield", "(", "logger", ")", "if", "block_given?", "end", "end" ]
Get a new logger instance for supplied named logger or class name. All adapters must ensure that they provide the same API for creating new loggers. Each logger has a name, further possible options are: - `:to`, filename or IO, where to write the output to - `:level`, Fixnum, starting log level, @see `Loggr::Severity` - `:marker`, String, name of the category/marker If an adapter does not support setting a specific option, just ignore it.
[ "Get", "a", "new", "logger", "instance", "for", "supplied", "named", "logger", "or", "class", "name", "." ]
d87f2d7bf4566fc5a2038fb6c559786d23aade75
https://github.com/at-point/loggr/blob/d87f2d7bf4566fc5a2038fb6c559786d23aade75/lib/loggr/adapter.rb#L56-L61
train
at-point/loggr
lib/loggr/adapter.rb
Loggr.Adapter.get_adapter
def get_adapter(adp) # okay, this is only because we can't camelize it :) adp = Loggr::Adapter::NOP if !adp # Code adapter from ActiveSupport::Inflector#camelize # https://github.com/rails/rails/blob/v3.0.9/activesupport/lib/active_support/inflector/methods.rb#L30 adp = adp.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } if adp.is_a?(Symbol) clazz = adp if adp.respond_to?(:to_str) const = begin Loggr::Adapter.const_get(adp.to_s) rescue begin Loggr::Adapter.const_get(adp.to_s.upcase) rescue nil end end unless const # code adapter from ActiveSupport::Inflector#constantize # https://github.com/rails/rails/blob/v3.0.9/activesupport/lib/active_support/inflector/methods.rb#L107 names = adp.to_s.split('::') names.shift if names.empty? || names.first.empty? const = ::Object names.each { |n| const = const.const_get(n) } end clazz = const end raise "#{clazz}: an adapter must implement #logger and #mdc" unless clazz.respond_to?(:logger) && clazz.respond_to?(:mdc) clazz end
ruby
def get_adapter(adp) # okay, this is only because we can't camelize it :) adp = Loggr::Adapter::NOP if !adp # Code adapter from ActiveSupport::Inflector#camelize # https://github.com/rails/rails/blob/v3.0.9/activesupport/lib/active_support/inflector/methods.rb#L30 adp = adp.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } if adp.is_a?(Symbol) clazz = adp if adp.respond_to?(:to_str) const = begin Loggr::Adapter.const_get(adp.to_s) rescue begin Loggr::Adapter.const_get(adp.to_s.upcase) rescue nil end end unless const # code adapter from ActiveSupport::Inflector#constantize # https://github.com/rails/rails/blob/v3.0.9/activesupport/lib/active_support/inflector/methods.rb#L107 names = adp.to_s.split('::') names.shift if names.empty? || names.first.empty? const = ::Object names.each { |n| const = const.const_get(n) } end clazz = const end raise "#{clazz}: an adapter must implement #logger and #mdc" unless clazz.respond_to?(:logger) && clazz.respond_to?(:mdc) clazz end
[ "def", "get_adapter", "(", "adp", ")", "adp", "=", "Loggr", "::", "Adapter", "::", "NOP", "if", "!", "adp", "adp", "=", "adp", ".", "to_s", ".", "gsub", "(", "/", "\\/", "/", ")", "{", "\"::#{$1.upcase}\"", "}", ".", "gsub", "(", "/", "/", ")", "{", "$1", ".", "upcase", "}", "if", "adp", ".", "is_a?", "(", "Symbol", ")", "clazz", "=", "adp", "if", "adp", ".", "respond_to?", "(", ":to_str", ")", "const", "=", "begin", "Loggr", "::", "Adapter", ".", "const_get", "(", "adp", ".", "to_s", ")", "rescue", "begin", "Loggr", "::", "Adapter", ".", "const_get", "(", "adp", ".", "to_s", ".", "upcase", ")", "rescue", "nil", "end", "end", "unless", "const", "names", "=", "adp", ".", "to_s", ".", "split", "(", "'::'", ")", "names", ".", "shift", "if", "names", ".", "empty?", "||", "names", ".", "first", ".", "empty?", "const", "=", "::", "Object", "names", ".", "each", "{", "|", "n", "|", "const", "=", "const", ".", "const_get", "(", "n", ")", "}", "end", "clazz", "=", "const", "end", "raise", "\"#{clazz}: an adapter must implement #logger and #mdc\"", "unless", "clazz", ".", "respond_to?", "(", ":logger", ")", "&&", "clazz", ".", "respond_to?", "(", ":mdc", ")", "clazz", "end" ]
Try to get adapter class from Symbol, String or use Object as-is.
[ "Try", "to", "get", "adapter", "class", "from", "Symbol", "String", "or", "use", "Object", "as", "-", "is", "." ]
d87f2d7bf4566fc5a2038fb6c559786d23aade75
https://github.com/at-point/loggr/blob/d87f2d7bf4566fc5a2038fb6c559786d23aade75/lib/loggr/adapter.rb#L87-L113
train
CITguy/xml-fu
lib/xml-fu/node.rb
XmlFu.Node.name_parse_special_characters
def name_parse_special_characters(val) use_this = val.dup # Ensure that we don't have special characters at end of name while ["!","/","*"].include?(use_this.to_s[-1,1]) do # Will this node contain escaped XML? if use_this.to_s[-1,1] == '!' @escape_xml = false use_this.chop! end # Will this be a self closing node? if use_this.to_s[-1,1] == '/' @self_closing = true use_this.chop! end # Will this node contain a collection of sibling nodes? if use_this.to_s[-1,1] == '*' @content_type = "collection" use_this.chop! end end return use_this end
ruby
def name_parse_special_characters(val) use_this = val.dup # Ensure that we don't have special characters at end of name while ["!","/","*"].include?(use_this.to_s[-1,1]) do # Will this node contain escaped XML? if use_this.to_s[-1,1] == '!' @escape_xml = false use_this.chop! end # Will this be a self closing node? if use_this.to_s[-1,1] == '/' @self_closing = true use_this.chop! end # Will this node contain a collection of sibling nodes? if use_this.to_s[-1,1] == '*' @content_type = "collection" use_this.chop! end end return use_this end
[ "def", "name_parse_special_characters", "(", "val", ")", "use_this", "=", "val", ".", "dup", "while", "[", "\"!\"", ",", "\"/\"", ",", "\"*\"", "]", ".", "include?", "(", "use_this", ".", "to_s", "[", "-", "1", ",", "1", "]", ")", "do", "if", "use_this", ".", "to_s", "[", "-", "1", ",", "1", "]", "==", "'!'", "@escape_xml", "=", "false", "use_this", ".", "chop!", "end", "if", "use_this", ".", "to_s", "[", "-", "1", ",", "1", "]", "==", "'/'", "@self_closing", "=", "true", "use_this", ".", "chop!", "end", "if", "use_this", ".", "to_s", "[", "-", "1", ",", "1", "]", "==", "'*'", "@content_type", "=", "\"collection\"", "use_this", ".", "chop!", "end", "end", "return", "use_this", "end" ]
name= Converts name into proper XML node name @param [String, Symbol] val Raw name
[ "name", "=", "Converts", "name", "into", "proper", "XML", "node", "name" ]
2499571130ba2cac2e62f6e9d27d953a2f1e6ad7
https://github.com/CITguy/xml-fu/blob/2499571130ba2cac2e62f6e9d27d953a2f1e6ad7/lib/xml-fu/node.rb#L66-L91
train
CITguy/xml-fu
lib/xml-fu/node.rb
XmlFu.Node.value=
def value=(val) case val when ::String then @value = val.to_s when ::Hash then @value = val when ::Array then @value = val when ::OpenStruct then @value = val when ::DateTime then @value = val.strftime XS_DATETIME_FORMAT when ::Time then @value = val.strftime XS_DATETIME_FORMAT when ::Date then @value = val.strftime XS_DATETIME_FORMAT else if val.respond_to?(:to_datetime) @value = val.to_datetime elsif val.respond_to?(:call) @value = val.call elsif val.nil? @value = nil else @value = val.to_s end end rescue => e @value = val.to_s end
ruby
def value=(val) case val when ::String then @value = val.to_s when ::Hash then @value = val when ::Array then @value = val when ::OpenStruct then @value = val when ::DateTime then @value = val.strftime XS_DATETIME_FORMAT when ::Time then @value = val.strftime XS_DATETIME_FORMAT when ::Date then @value = val.strftime XS_DATETIME_FORMAT else if val.respond_to?(:to_datetime) @value = val.to_datetime elsif val.respond_to?(:call) @value = val.call elsif val.nil? @value = nil else @value = val.to_s end end rescue => e @value = val.to_s end
[ "def", "value", "=", "(", "val", ")", "case", "val", "when", "::", "String", "then", "@value", "=", "val", ".", "to_s", "when", "::", "Hash", "then", "@value", "=", "val", "when", "::", "Array", "then", "@value", "=", "val", "when", "::", "OpenStruct", "then", "@value", "=", "val", "when", "::", "DateTime", "then", "@value", "=", "val", ".", "strftime", "XS_DATETIME_FORMAT", "when", "::", "Time", "then", "@value", "=", "val", ".", "strftime", "XS_DATETIME_FORMAT", "when", "::", "Date", "then", "@value", "=", "val", ".", "strftime", "XS_DATETIME_FORMAT", "else", "if", "val", ".", "respond_to?", "(", ":to_datetime", ")", "@value", "=", "val", ".", "to_datetime", "elsif", "val", ".", "respond_to?", "(", ":call", ")", "@value", "=", "val", ".", "call", "elsif", "val", ".", "nil?", "@value", "=", "nil", "else", "@value", "=", "val", ".", "to_s", "end", "end", "rescue", "=>", "e", "@value", "=", "val", ".", "to_s", "end" ]
name_parse_special_characters Custom Setter for @value instance method
[ "name_parse_special_characters", "Custom", "Setter", "for" ]
2499571130ba2cac2e62f6e9d27d953a2f1e6ad7
https://github.com/CITguy/xml-fu/blob/2499571130ba2cac2e62f6e9d27d953a2f1e6ad7/lib/xml-fu/node.rb#L95-L117
train
Kuniri/kuniri
lib/kuniri/language/ruby/ruby_syntax.rb
Languages.RubySyntax.handle_semicolon
def handle_semicolon(pLine) commentLine = [] if pLine =~ /^=begin(.*?)/ @flagMultipleLineComment = true elsif pLine =~ /^=end/ @flagMultipleLineComment = false end unless @flagMultipleLineComment == true || pLine =~ /#(.*)/ return pLine.split(/;/) end commentLine << pLine end
ruby
def handle_semicolon(pLine) commentLine = [] if pLine =~ /^=begin(.*?)/ @flagMultipleLineComment = true elsif pLine =~ /^=end/ @flagMultipleLineComment = false end unless @flagMultipleLineComment == true || pLine =~ /#(.*)/ return pLine.split(/;/) end commentLine << pLine end
[ "def", "handle_semicolon", "(", "pLine", ")", "commentLine", "=", "[", "]", "if", "pLine", "=~", "/", "/", "@flagMultipleLineComment", "=", "true", "elsif", "pLine", "=~", "/", "/", "@flagMultipleLineComment", "=", "false", "end", "unless", "@flagMultipleLineComment", "==", "true", "||", "pLine", "=~", "/", "/", "return", "pLine", ".", "split", "(", "/", "/", ")", "end", "commentLine", "<<", "pLine", "end" ]
Puts every statement in a single line @param pLine Line of the file to be analysed.
[ "Puts", "every", "statement", "in", "a", "single", "line" ]
8b840ab307dc6bec48edd272c732b28c98f93f45
https://github.com/Kuniri/kuniri/blob/8b840ab307dc6bec48edd272c732b28c98f93f45/lib/kuniri/language/ruby/ruby_syntax.rb#L58-L71
train
tpope/ldaptic
lib/ldaptic/dn.rb
Ldaptic.DN.find
def find(source = @source) scope = 0 filter = "(objectClass=*)" if source.respond_to?(:search2_ext) source.search2( to_s, scope, filter ) elsif source.respond_to?(:search) Array(source.search( :base => to_s, :scope => scope, :filter => filter, :limit => 1 )) else raise RuntimeError, "missing or invalid source for LDAP search", caller end.first end
ruby
def find(source = @source) scope = 0 filter = "(objectClass=*)" if source.respond_to?(:search2_ext) source.search2( to_s, scope, filter ) elsif source.respond_to?(:search) Array(source.search( :base => to_s, :scope => scope, :filter => filter, :limit => 1 )) else raise RuntimeError, "missing or invalid source for LDAP search", caller end.first end
[ "def", "find", "(", "source", "=", "@source", ")", "scope", "=", "0", "filter", "=", "\"(objectClass=*)\"", "if", "source", ".", "respond_to?", "(", ":search2_ext", ")", "source", ".", "search2", "(", "to_s", ",", "scope", ",", "filter", ")", "elsif", "source", ".", "respond_to?", "(", ":search", ")", "Array", "(", "source", ".", "search", "(", ":base", "=>", "to_s", ",", ":scope", "=>", "scope", ",", ":filter", "=>", "filter", ",", ":limit", "=>", "1", ")", ")", "else", "raise", "RuntimeError", ",", "\"missing or invalid source for LDAP search\"", ",", "caller", "end", ".", "first", "end" ]
If a source object was given, it is used to search for the DN. Otherwise, an exception is raised.
[ "If", "a", "source", "object", "was", "given", "it", "is", "used", "to", "search", "for", "the", "DN", ".", "Otherwise", "an", "exception", "is", "raised", "." ]
159a39464e9f5a05c0145db2b21cb256ef859612
https://github.com/tpope/ldaptic/blob/159a39464e9f5a05c0145db2b21cb256ef859612/lib/ldaptic/dn.rb#L73-L92
train
tpope/ldaptic
lib/ldaptic/dn.rb
Ldaptic.DN.domain
def domain components = rdns.map {|rdn| rdn[:dc]}.compact components.join('.') unless components.empty? end
ruby
def domain components = rdns.map {|rdn| rdn[:dc]}.compact components.join('.') unless components.empty? end
[ "def", "domain", "components", "=", "rdns", ".", "map", "{", "|", "rdn", "|", "rdn", "[", ":dc", "]", "}", ".", "compact", "components", ".", "join", "(", "'.'", ")", "unless", "components", ".", "empty?", "end" ]
Join all DC elements with periods.
[ "Join", "all", "DC", "elements", "with", "periods", "." ]
159a39464e9f5a05c0145db2b21cb256ef859612
https://github.com/tpope/ldaptic/blob/159a39464e9f5a05c0145db2b21cb256ef859612/lib/ldaptic/dn.rb#L117-L120
train
stepheneb/jnlp
lib/jnlp/jnlp.rb
Jnlp.Jnlp.generate_local_jnlp
def generate_local_jnlp(options={}) # # get a copy of the existing jnlp # (it should be easier than this) # @local_jnlp = Nokogiri::XML(@jnlp.to_s) # # we'll be working with the Hpricot root element # jnlp_elem = (@local_jnlp/"jnlp").first # # set the new codebase # jnlp_elem[:codebase] = "file:#{@local_cache_dir}" # # set the new href # jnlp_elem[:href] = @local_jnlp_href # # for each jar and nativelib remove the version # attribute and point the href to the local cache # @jars.each do |jar| j = @local_jnlp.at("//jar[@href=#{jar.href}]") j.remove_attribute(:version) if options[:include_pack_gz] j[:href] = jar.relative_local_path_pack_gz else j[:href] = jar.relative_local_path end end @nativelibs.each do |nativelib| nl = @local_jnlp.at("//nativelib[@href=#{nativelib.href}]") nl.remove_attribute(:version) if options[:include_pack_gz] nl[:href] = nativelib.relative_local_path_pack_gz else nl[:href] = nativelib.relative_local_path end end end
ruby
def generate_local_jnlp(options={}) # # get a copy of the existing jnlp # (it should be easier than this) # @local_jnlp = Nokogiri::XML(@jnlp.to_s) # # we'll be working with the Hpricot root element # jnlp_elem = (@local_jnlp/"jnlp").first # # set the new codebase # jnlp_elem[:codebase] = "file:#{@local_cache_dir}" # # set the new href # jnlp_elem[:href] = @local_jnlp_href # # for each jar and nativelib remove the version # attribute and point the href to the local cache # @jars.each do |jar| j = @local_jnlp.at("//jar[@href=#{jar.href}]") j.remove_attribute(:version) if options[:include_pack_gz] j[:href] = jar.relative_local_path_pack_gz else j[:href] = jar.relative_local_path end end @nativelibs.each do |nativelib| nl = @local_jnlp.at("//nativelib[@href=#{nativelib.href}]") nl.remove_attribute(:version) if options[:include_pack_gz] nl[:href] = nativelib.relative_local_path_pack_gz else nl[:href] = nativelib.relative_local_path end end end
[ "def", "generate_local_jnlp", "(", "options", "=", "{", "}", ")", "@local_jnlp", "=", "Nokogiri", "::", "XML", "(", "@jnlp", ".", "to_s", ")", "jnlp_elem", "=", "(", "@local_jnlp", "/", "\"jnlp\"", ")", ".", "first", "jnlp_elem", "[", ":codebase", "]", "=", "\"file:#{@local_cache_dir}\"", "jnlp_elem", "[", ":href", "]", "=", "@local_jnlp_href", "@jars", ".", "each", "do", "|", "jar", "|", "j", "=", "@local_jnlp", ".", "at", "(", "\"//jar[@href=#{jar.href}]\"", ")", "j", ".", "remove_attribute", "(", ":version", ")", "if", "options", "[", ":include_pack_gz", "]", "j", "[", ":href", "]", "=", "jar", ".", "relative_local_path_pack_gz", "else", "j", "[", ":href", "]", "=", "jar", ".", "relative_local_path", "end", "end", "@nativelibs", ".", "each", "do", "|", "nativelib", "|", "nl", "=", "@local_jnlp", ".", "at", "(", "\"//nativelib[@href=#{nativelib.href}]\"", ")", "nl", ".", "remove_attribute", "(", ":version", ")", "if", "options", "[", ":include_pack_gz", "]", "nl", "[", ":href", "]", "=", "nativelib", ".", "relative_local_path_pack_gz", "else", "nl", "[", ":href", "]", "=", "nativelib", ".", "relative_local_path", "end", "end", "end" ]
Copies the original Hpricot jnlp into @local_jnlp and modifies it to reference resources in the local cache.
[ "Copies", "the", "original", "Hpricot", "jnlp", "into" ]
9d78fe8b0ebf5bcc68105513d35ce43199607ac4
https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/jnlp.rb#L485-L525
train
stepheneb/jnlp
lib/jnlp/jnlp.rb
Jnlp.Jnlp.resource_paths
def resource_paths(options={}) if options[:include_pack_gs] cp_jars = @jars.empty? ? [] : @jars.collect {|j| j.local_path_pack_gz} cp_nativelibs = @nativelibs.empty? ? [] : @nativelibs.collect {|n| n.local_path_pack_gz} resources = cp_jars + cp_nativelibs else cp_jars = @jars.empty? ? [] : @jars.collect {|j| j.local_path} cp_nativelibs = @nativelibs.empty? ? [] : @nativelibs.collect {|n| n.local_path} resources = cp_jars + cp_nativelibs end # # FIXME: this should probably be more discriminatory # if options[:remove_jruby] resources = resources.reject {|r| r =~ /\/jruby\//} end resources end
ruby
def resource_paths(options={}) if options[:include_pack_gs] cp_jars = @jars.empty? ? [] : @jars.collect {|j| j.local_path_pack_gz} cp_nativelibs = @nativelibs.empty? ? [] : @nativelibs.collect {|n| n.local_path_pack_gz} resources = cp_jars + cp_nativelibs else cp_jars = @jars.empty? ? [] : @jars.collect {|j| j.local_path} cp_nativelibs = @nativelibs.empty? ? [] : @nativelibs.collect {|n| n.local_path} resources = cp_jars + cp_nativelibs end # # FIXME: this should probably be more discriminatory # if options[:remove_jruby] resources = resources.reject {|r| r =~ /\/jruby\//} end resources end
[ "def", "resource_paths", "(", "options", "=", "{", "}", ")", "if", "options", "[", ":include_pack_gs", "]", "cp_jars", "=", "@jars", ".", "empty?", "?", "[", "]", ":", "@jars", ".", "collect", "{", "|", "j", "|", "j", ".", "local_path_pack_gz", "}", "cp_nativelibs", "=", "@nativelibs", ".", "empty?", "?", "[", "]", ":", "@nativelibs", ".", "collect", "{", "|", "n", "|", "n", ".", "local_path_pack_gz", "}", "resources", "=", "cp_jars", "+", "cp_nativelibs", "else", "cp_jars", "=", "@jars", ".", "empty?", "?", "[", "]", ":", "@jars", ".", "collect", "{", "|", "j", "|", "j", ".", "local_path", "}", "cp_nativelibs", "=", "@nativelibs", ".", "empty?", "?", "[", "]", ":", "@nativelibs", ".", "collect", "{", "|", "n", "|", "n", ".", "local_path", "}", "resources", "=", "cp_jars", "+", "cp_nativelibs", "end", "if", "options", "[", ":remove_jruby", "]", "resources", "=", "resources", ".", "reject", "{", "|", "r", "|", "r", "=~", "/", "\\/", "\\/", "/", "}", "end", "resources", "end" ]
Returns an array containing all the local paths for this jnlp's resources. Pass in the options hash: (:remove_jruby => true) and the first resource that contains the string /jruby/ will be removed from the returned array. Example: resource_paths(:remove_jruby => true) This is useful when the jruby-complete jar has been included in the jnlp and you don't want to require that jruby into this specific instance which is already running jruby. Here's an example of a jruby resource reference: "org/jruby/jruby/jruby__V1.0RC2.jar" Pass in the options hash: (:include_pack_gz => true) and the resources returned with be pack.gz jars instead of regular jars
[ "Returns", "an", "array", "containing", "all", "the", "local", "paths", "for", "this", "jnlp", "s", "resources", "." ]
9d78fe8b0ebf5bcc68105513d35ce43199607ac4
https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/jnlp.rb#L548-L565
train
stepheneb/jnlp
lib/jnlp/jnlp.rb
Jnlp.Jnlp.write_local_classpath_shell_script
def write_local_classpath_shell_script(filename="#{@name[/[A-Za-z0-9_-]*/]}_classpath.sh", options={}) script = "export CLASSPATH=$CLASSPATH#{local_classpath(options)}" File.open(filename, 'w'){|f| f.write script} end
ruby
def write_local_classpath_shell_script(filename="#{@name[/[A-Za-z0-9_-]*/]}_classpath.sh", options={}) script = "export CLASSPATH=$CLASSPATH#{local_classpath(options)}" File.open(filename, 'w'){|f| f.write script} end
[ "def", "write_local_classpath_shell_script", "(", "filename", "=", "\"#{@name[/[A-Za-z0-9_-]*/]}_classpath.sh\"", ",", "options", "=", "{", "}", ")", "script", "=", "\"export CLASSPATH=$CLASSPATH#{local_classpath(options)}\"", "File", ".", "open", "(", "filename", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "script", "}", "end" ]
Writes a shell script to the local filesystem that will export a modified CLASSPATH environmental variable with the paths to the resources used by this jnlp. Writes a jnlp to current working directory using name of original jnlp. Pass in the optional hash: (:remove_jruby => true) and the first resource that contains the string /jruby/ will be removed from the classapath shell script. Example: write_local_classpath_shell_scrip(:remove_jruby => true)
[ "Writes", "a", "shell", "script", "to", "the", "local", "filesystem", "that", "will", "export", "a", "modified", "CLASSPATH", "environmental", "variable", "with", "the", "paths", "to", "the", "resources", "used", "by", "this", "jnlp", "." ]
9d78fe8b0ebf5bcc68105513d35ce43199607ac4
https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/jnlp.rb#L599-L602
train
stepheneb/jnlp
lib/jnlp/jnlp.rb
Jnlp.Jnlp.write_jnlp
def write_jnlp(options={}) dir = options[:dir] || '.' path = options[:path] || @path.gsub(/^\//, '') Dir.chdir(dir) do FileUtils.mkdir_p(File.dirname(path)) File.open(path, 'w') {|f| f.write to_jnlp(options[:jnlp]) } if options[:snapshot] snapshot_path = "#{File.dirname(path)}/#{@family}.jnlp" File.open(snapshot_path, 'w') {|f| f.write to_jnlp(options[:jnlp]) } current_version_path = "#{File.dirname(path)}/#{@family}-CURRENT_VERSION.txt" File.open(current_version_path, 'w') {|f| f.write @version_str } end end end
ruby
def write_jnlp(options={}) dir = options[:dir] || '.' path = options[:path] || @path.gsub(/^\//, '') Dir.chdir(dir) do FileUtils.mkdir_p(File.dirname(path)) File.open(path, 'w') {|f| f.write to_jnlp(options[:jnlp]) } if options[:snapshot] snapshot_path = "#{File.dirname(path)}/#{@family}.jnlp" File.open(snapshot_path, 'w') {|f| f.write to_jnlp(options[:jnlp]) } current_version_path = "#{File.dirname(path)}/#{@family}-CURRENT_VERSION.txt" File.open(current_version_path, 'w') {|f| f.write @version_str } end end end
[ "def", "write_jnlp", "(", "options", "=", "{", "}", ")", "dir", "=", "options", "[", ":dir", "]", "||", "'.'", "path", "=", "options", "[", ":path", "]", "||", "@path", ".", "gsub", "(", "/", "\\/", "/", ",", "''", ")", "Dir", ".", "chdir", "(", "dir", ")", "do", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "path", ")", ")", "File", ".", "open", "(", "path", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "to_jnlp", "(", "options", "[", ":jnlp", "]", ")", "}", "if", "options", "[", ":snapshot", "]", "snapshot_path", "=", "\"#{File.dirname(path)}/#{@family}.jnlp\"", "File", ".", "open", "(", "snapshot_path", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "to_jnlp", "(", "options", "[", ":jnlp", "]", ")", "}", "current_version_path", "=", "\"#{File.dirname(path)}/#{@family}-CURRENT_VERSION.txt\"", "File", ".", "open", "(", "current_version_path", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "@version_str", "}", "end", "end", "end" ]
Writes a local copy of the original jnlp . Writes jnlp to path of original jnlp into current working directory. A number of options can be passed modify the result. Example: server = 'http://localhost:4321' jnlp_cache = 'jnlp' new_href = "#{server}#{jnlp.path}" jnlp.write_jnlp( { :dir => jnlp_cache, :jnlp => { :codebase => server, :href => new_href }, :snapshot => true } ) Writes a duplicate of the remote jnlp to a local path rooted at 'jnlp/'. With the codebase and href re-written referencing: 'http://localhost:4321' In addition a duplicate of the versioned jnlp is written without the version string as a snapshot jnlp and the version string is written to this file: jnlp-name-CURRENT_VERSION.txt
[ "Writes", "a", "local", "copy", "of", "the", "original", "jnlp", "." ]
9d78fe8b0ebf5bcc68105513d35ce43199607ac4
https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/jnlp.rb#L642-L655
train
stepheneb/jnlp
lib/jnlp/jnlp.rb
Jnlp.Jnlp.write_local_jnlp
def write_local_jnlp(filename=@local_jnlp_name) destination = File.expand_path(filename) unless @local_jnlp_href == destination @local_jnlp_href = destination @local_jnlp_name = File.basename(destination) self.generate_local_jnlp end File.open(filename, 'w') {|f| f.write to_local_jnlp } end
ruby
def write_local_jnlp(filename=@local_jnlp_name) destination = File.expand_path(filename) unless @local_jnlp_href == destination @local_jnlp_href = destination @local_jnlp_name = File.basename(destination) self.generate_local_jnlp end File.open(filename, 'w') {|f| f.write to_local_jnlp } end
[ "def", "write_local_jnlp", "(", "filename", "=", "@local_jnlp_name", ")", "destination", "=", "File", ".", "expand_path", "(", "filename", ")", "unless", "@local_jnlp_href", "==", "destination", "@local_jnlp_href", "=", "destination", "@local_jnlp_name", "=", "File", ".", "basename", "(", "destination", ")", "self", ".", "generate_local_jnlp", "end", "File", ".", "open", "(", "filename", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "to_local_jnlp", "}", "end" ]
Writes a local file-based jnlp. Will write jnlp to current working directory using name of original jnlp with "local-" prefix.
[ "Writes", "a", "local", "file", "-", "based", "jnlp", "." ]
9d78fe8b0ebf5bcc68105513d35ce43199607ac4
https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/jnlp.rb#L662-L670
train
stepheneb/jnlp
lib/jnlp/jnlp.rb
Jnlp.Jnlp.require_resources
def require_resources if RUBY_PLATFORM =~ /java/ resource_paths(:remove_jruby => true).each {|res| require res} true else false end end
ruby
def require_resources if RUBY_PLATFORM =~ /java/ resource_paths(:remove_jruby => true).each {|res| require res} true else false end end
[ "def", "require_resources", "if", "RUBY_PLATFORM", "=~", "/", "/", "resource_paths", "(", ":remove_jruby", "=>", "true", ")", ".", "each", "{", "|", "res", "|", "require", "res", "}", "true", "else", "false", "end", "end" ]
This will add all the jars for this jnlp to the effective classpath for this Java process. *If* you are already running in JRuby *AND* the jnlp references a JRuby resource the JRuby resource will not be required.
[ "This", "will", "add", "all", "the", "jars", "for", "this", "jnlp", "to", "the", "effective", "classpath", "for", "this", "Java", "process", "." ]
9d78fe8b0ebf5bcc68105513d35ce43199607ac4
https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/jnlp.rb#L678-L685
train
brianjlandau/unobtrusive_date_picker
lib/unobtrusive_date_picker.rb
UnobtrusiveDatePicker.UnobtrusiveDatePickerHelper.unobtrusive_date_text_picker_tag
def unobtrusive_date_text_picker_tag(name, date = Date.current, options = {}, html_options = {}) date ||= Date.current options = merge_defaults_for_text_picker(options) DateTimePickerSelector.new(date, options, html_options).text_date_picker(name) end
ruby
def unobtrusive_date_text_picker_tag(name, date = Date.current, options = {}, html_options = {}) date ||= Date.current options = merge_defaults_for_text_picker(options) DateTimePickerSelector.new(date, options, html_options).text_date_picker(name) end
[ "def", "unobtrusive_date_text_picker_tag", "(", "name", ",", "date", "=", "Date", ".", "current", ",", "options", "=", "{", "}", ",", "html_options", "=", "{", "}", ")", "date", "||=", "Date", ".", "current", "options", "=", "merge_defaults_for_text_picker", "(", "options", ")", "DateTimePickerSelector", ".", "new", "(", "date", ",", "options", ",", "html_options", ")", ".", "text_date_picker", "(", "name", ")", "end" ]
Creates the text field based date picker with the calendar widget without a model object.
[ "Creates", "the", "text", "field", "based", "date", "picker", "with", "the", "calendar", "widget", "without", "a", "model", "object", "." ]
fd15b829a92951c4a7550c0644502587040fdedc
https://github.com/brianjlandau/unobtrusive_date_picker/blob/fd15b829a92951c4a7550c0644502587040fdedc/lib/unobtrusive_date_picker.rb#L67-L71
train
stepheneb/jnlp
lib/jnlp/resource.rb
Jnlp.Resource.update_cache
def update_cache(source=@url, destination=@local_path, options={}) unless destination raise ArgumentError, "Must specify destination directory when updatng resource", caller end file_exists = File.exists?(destination) if file_exists && @signature_verified == nil verify_signature end unless file_exists && @signature_verified FileUtils.mkdir_p(File.dirname(destination)) puts "reading: #{source}" if options[:verbose] tried_to_read = 0 begin jarfile = open(source) rescue OpenURI::HTTPError => e puts e if tried_to_read < 1 tried_to_read += 1 retry end end if jarfile.class == Tempfile FileUtils.cp(jarfile.path, destination) puts "copying to: #{destination}" if options[:verbose] else File.open(destination, 'w') {|f| f.write jarfile.read } puts "writing to: #{destination}" if options[:verbose] end puts "#{jarfile.size} bytes written" if options[:verbose] verify_signature ? jarfile.size : false else File.size(destination) end end
ruby
def update_cache(source=@url, destination=@local_path, options={}) unless destination raise ArgumentError, "Must specify destination directory when updatng resource", caller end file_exists = File.exists?(destination) if file_exists && @signature_verified == nil verify_signature end unless file_exists && @signature_verified FileUtils.mkdir_p(File.dirname(destination)) puts "reading: #{source}" if options[:verbose] tried_to_read = 0 begin jarfile = open(source) rescue OpenURI::HTTPError => e puts e if tried_to_read < 1 tried_to_read += 1 retry end end if jarfile.class == Tempfile FileUtils.cp(jarfile.path, destination) puts "copying to: #{destination}" if options[:verbose] else File.open(destination, 'w') {|f| f.write jarfile.read } puts "writing to: #{destination}" if options[:verbose] end puts "#{jarfile.size} bytes written" if options[:verbose] verify_signature ? jarfile.size : false else File.size(destination) end end
[ "def", "update_cache", "(", "source", "=", "@url", ",", "destination", "=", "@local_path", ",", "options", "=", "{", "}", ")", "unless", "destination", "raise", "ArgumentError", ",", "\"Must specify destination directory when updatng resource\"", ",", "caller", "end", "file_exists", "=", "File", ".", "exists?", "(", "destination", ")", "if", "file_exists", "&&", "@signature_verified", "==", "nil", "verify_signature", "end", "unless", "file_exists", "&&", "@signature_verified", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "destination", ")", ")", "puts", "\"reading: #{source}\"", "if", "options", "[", ":verbose", "]", "tried_to_read", "=", "0", "begin", "jarfile", "=", "open", "(", "source", ")", "rescue", "OpenURI", "::", "HTTPError", "=>", "e", "puts", "e", "if", "tried_to_read", "<", "1", "tried_to_read", "+=", "1", "retry", "end", "end", "if", "jarfile", ".", "class", "==", "Tempfile", "FileUtils", ".", "cp", "(", "jarfile", ".", "path", ",", "destination", ")", "puts", "\"copying to: #{destination}\"", "if", "options", "[", ":verbose", "]", "else", "File", ".", "open", "(", "destination", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "jarfile", ".", "read", "}", "puts", "\"writing to: #{destination}\"", "if", "options", "[", ":verbose", "]", "end", "puts", "\"#{jarfile.size} bytes written\"", "if", "options", "[", ":verbose", "]", "verify_signature", "?", "jarfile", ".", "size", ":", "false", "else", "File", ".", "size", "(", "destination", ")", "end", "end" ]
Copies the file referenced in _source_ to _destination_ _source_ can be a url or local file path _destination_ must be a local path Will copy file if the file does not exists OR if the the file exists but the signature has not been successfully verified. Returns file size if cached succesfully, false otherwise.
[ "Copies", "the", "file", "referenced", "in", "_source_", "to", "_destination_", "_source_", "can", "be", "a", "url", "or", "local", "file", "path", "_destination_", "must", "be", "a", "local", "path" ]
9d78fe8b0ebf5bcc68105513d35ce43199607ac4
https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/resource.rb#L334-L367
train
stepheneb/jnlp
lib/jnlp/resource.rb
Jnlp.Resource.verify_signature
def verify_signature if @local_path if RUBY_PLATFORM =~ /java/ begin jarfile = java.util.jar.JarInputStream.new(FileInputStream.new(@local_path), true) @signature_verified = true rescue NativeException @signature_verified = false end else # Use IO.popen instead of system() to absorb # jarsigners messages to $stdout response = IO.popen("jarsigner -verify #{@local_path}"){|io| io.gets} @signature_verified = ($?.exitstatus == 0) end else nil end end
ruby
def verify_signature if @local_path if RUBY_PLATFORM =~ /java/ begin jarfile = java.util.jar.JarInputStream.new(FileInputStream.new(@local_path), true) @signature_verified = true rescue NativeException @signature_verified = false end else # Use IO.popen instead of system() to absorb # jarsigners messages to $stdout response = IO.popen("jarsigner -verify #{@local_path}"){|io| io.gets} @signature_verified = ($?.exitstatus == 0) end else nil end end
[ "def", "verify_signature", "if", "@local_path", "if", "RUBY_PLATFORM", "=~", "/", "/", "begin", "jarfile", "=", "java", ".", "util", ".", "jar", ".", "JarInputStream", ".", "new", "(", "FileInputStream", ".", "new", "(", "@local_path", ")", ",", "true", ")", "@signature_verified", "=", "true", "rescue", "NativeException", "@signature_verified", "=", "false", "end", "else", "response", "=", "IO", ".", "popen", "(", "\"jarsigner -verify #{@local_path}\"", ")", "{", "|", "io", "|", "io", ".", "gets", "}", "@signature_verified", "=", "(", "$?", ".", "exitstatus", "==", "0", ")", "end", "else", "nil", "end", "end" ]
Verifies signature of locallly cached resource Returns boolean value indicating whether the signature of the cached local copy of the resource verified successfully The value return is nil if no local cache has been created. Example: true || false || nil
[ "Verifies", "signature", "of", "locallly", "cached", "resource" ]
9d78fe8b0ebf5bcc68105513d35ce43199607ac4
https://github.com/stepheneb/jnlp/blob/9d78fe8b0ebf5bcc68105513d35ce43199607ac4/lib/jnlp/resource.rb#L380-L398
train
fuminori-ido/edgarj
app/helpers/edgarj/assoc_helper.rb
Edgarj.AssocHelper.draw_belongs_to_clear_link
def draw_belongs_to_clear_link(f, col_name, popup_field, parent_name, default_label) if Settings.edgarj.belongs_to.disable_clear_link f.hidden_field(col_name) else ('&nbsp;&nbsp;' + link_to("[#{I18n.t('edgarj.default.clear')}]", '#', onClick: "Edgarj.Popup.clear('#{j(popup_field.id_target)}','#{j(default_label)}'); return false;", id: popup_field.clear_link, style: 'display:' + (parent_name.blank? ? 'none' : '')) + f.hidden_field(col_name)).html_safe end end
ruby
def draw_belongs_to_clear_link(f, col_name, popup_field, parent_name, default_label) if Settings.edgarj.belongs_to.disable_clear_link f.hidden_field(col_name) else ('&nbsp;&nbsp;' + link_to("[#{I18n.t('edgarj.default.clear')}]", '#', onClick: "Edgarj.Popup.clear('#{j(popup_field.id_target)}','#{j(default_label)}'); return false;", id: popup_field.clear_link, style: 'display:' + (parent_name.blank? ? 'none' : '')) + f.hidden_field(col_name)).html_safe end end
[ "def", "draw_belongs_to_clear_link", "(", "f", ",", "col_name", ",", "popup_field", ",", "parent_name", ",", "default_label", ")", "if", "Settings", ".", "edgarj", ".", "belongs_to", ".", "disable_clear_link", "f", ".", "hidden_field", "(", "col_name", ")", "else", "(", "'&nbsp;&nbsp;'", "+", "link_to", "(", "\"[#{I18n.t('edgarj.default.clear')}]\"", ",", "'#'", ",", "onClick", ":", "\"Edgarj.Popup.clear('#{j(popup_field.id_target)}','#{j(default_label)}'); return false;\"", ",", "id", ":", "popup_field", ".", "clear_link", ",", "style", ":", "'display:'", "+", "(", "parent_name", ".", "blank?", "?", "'none'", ":", "''", ")", ")", "+", "f", ".", "hidden_field", "(", "col_name", ")", ")", ".", "html_safe", "end", "end" ]
draw 'clear' link for 'belongs_to' popup data-entry field === INPUTS f:: FormBuilder object col_name:: 'belongs_to' column name popup_field:: Edgarj::PopupHelper::PopupField object parent_name:: initial parent name
[ "draw", "clear", "link", "for", "belongs_to", "popup", "data", "-", "entry", "field" ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L179-L190
train
fuminori-ido/edgarj
app/helpers/edgarj/assoc_helper.rb
Edgarj.AssocHelper.draw_belongs_to_field
def draw_belongs_to_field(f, popup_path, col_name, model = f.object.class) col = model.columns.detect{|c| c.name == col_name.to_s} return "no column found" if !col parent_model = model.belongs_to_AR(col) return "parent_model is nil" if !parent_model parent_obj = f.object.belongs_to_AR(col) popup_field = Edgarj::PopupHelper::PopupField.new_builder( f.object_name, col_name) default_label = '[' + draw_belongs_to_label_sub(model, col.name, parent_model) + ']' label = content_tag(:span, parent_obj ? parent_obj.name : default_label.html_safe, id: popup_field.label_target) link_tag = Settings.edgarj.belongs_to.link_tag.html_safe if parent_obj if Settings.edgarj.belongs_to.popup_on == 'field' link_to( label + link_tag, popup_path, remote: true) else link_to(label, # TODO: Hardcoded 'master' prefix should be fixed controller: url_prefix + parent_obj.class.name.underscore.pluralize, action: 'show', id: parent_obj, topic_path: 'add') end else if Settings.edgarj.belongs_to.popup_on == 'field' link_to( label + link_tag, popup_path, remote: true) else label end end + draw_belongs_to_clear_link(f, col.name, popup_field, parent_obj && parent_obj.name, default_label) end
ruby
def draw_belongs_to_field(f, popup_path, col_name, model = f.object.class) col = model.columns.detect{|c| c.name == col_name.to_s} return "no column found" if !col parent_model = model.belongs_to_AR(col) return "parent_model is nil" if !parent_model parent_obj = f.object.belongs_to_AR(col) popup_field = Edgarj::PopupHelper::PopupField.new_builder( f.object_name, col_name) default_label = '[' + draw_belongs_to_label_sub(model, col.name, parent_model) + ']' label = content_tag(:span, parent_obj ? parent_obj.name : default_label.html_safe, id: popup_field.label_target) link_tag = Settings.edgarj.belongs_to.link_tag.html_safe if parent_obj if Settings.edgarj.belongs_to.popup_on == 'field' link_to( label + link_tag, popup_path, remote: true) else link_to(label, # TODO: Hardcoded 'master' prefix should be fixed controller: url_prefix + parent_obj.class.name.underscore.pluralize, action: 'show', id: parent_obj, topic_path: 'add') end else if Settings.edgarj.belongs_to.popup_on == 'field' link_to( label + link_tag, popup_path, remote: true) else label end end + draw_belongs_to_clear_link(f, col.name, popup_field, parent_obj && parent_obj.name, default_label) end
[ "def", "draw_belongs_to_field", "(", "f", ",", "popup_path", ",", "col_name", ",", "model", "=", "f", ".", "object", ".", "class", ")", "col", "=", "model", ".", "columns", ".", "detect", "{", "|", "c", "|", "c", ".", "name", "==", "col_name", ".", "to_s", "}", "return", "\"no column found\"", "if", "!", "col", "parent_model", "=", "model", ".", "belongs_to_AR", "(", "col", ")", "return", "\"parent_model is nil\"", "if", "!", "parent_model", "parent_obj", "=", "f", ".", "object", ".", "belongs_to_AR", "(", "col", ")", "popup_field", "=", "Edgarj", "::", "PopupHelper", "::", "PopupField", ".", "new_builder", "(", "f", ".", "object_name", ",", "col_name", ")", "default_label", "=", "'['", "+", "draw_belongs_to_label_sub", "(", "model", ",", "col", ".", "name", ",", "parent_model", ")", "+", "']'", "label", "=", "content_tag", "(", ":span", ",", "parent_obj", "?", "parent_obj", ".", "name", ":", "default_label", ".", "html_safe", ",", "id", ":", "popup_field", ".", "label_target", ")", "link_tag", "=", "Settings", ".", "edgarj", ".", "belongs_to", ".", "link_tag", ".", "html_safe", "if", "parent_obj", "if", "Settings", ".", "edgarj", ".", "belongs_to", ".", "popup_on", "==", "'field'", "link_to", "(", "label", "+", "link_tag", ",", "popup_path", ",", "remote", ":", "true", ")", "else", "link_to", "(", "label", ",", "controller", ":", "url_prefix", "+", "parent_obj", ".", "class", ".", "name", ".", "underscore", ".", "pluralize", ",", "action", ":", "'show'", ",", "id", ":", "parent_obj", ",", "topic_path", ":", "'add'", ")", "end", "else", "if", "Settings", ".", "edgarj", ".", "belongs_to", ".", "popup_on", "==", "'field'", "link_to", "(", "label", "+", "link_tag", ",", "popup_path", ",", "remote", ":", "true", ")", "else", "label", "end", "end", "+", "draw_belongs_to_clear_link", "(", "f", ",", "col", ".", "name", ",", "popup_field", ",", "parent_obj", "&&", "parent_obj", ".", "name", ",", "default_label", ")", "end" ]
draw 'belongs_to' popup data-entry field This is usually used with draw_belongs_to_label(). @param f [FormBuilder] FormBuilder object @param popup_path [String] popup path(url) @param col_name [String] 'belongs_to' column name @param model [AR] data model class
[ "draw", "belongs_to", "popup", "data", "-", "entry", "field" ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L200-L242
train
fuminori-ido/edgarj
app/helpers/edgarj/assoc_helper.rb
Edgarj.AssocHelper.flag_on?
def flag_on?(column_value, bitset, flag) val = column_value || 0 (val & bitset.const_get(flag)) != 0 end
ruby
def flag_on?(column_value, bitset, flag) val = column_value || 0 (val & bitset.const_get(flag)) != 0 end
[ "def", "flag_on?", "(", "column_value", ",", "bitset", ",", "flag", ")", "val", "=", "column_value", "||", "0", "(", "val", "&", "bitset", ".", "const_get", "(", "flag", ")", ")", "!=", "0", "end" ]
Is flag in column_value on?
[ "Is", "flag", "in", "column_value", "on?" ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L245-L248
train
fuminori-ido/edgarj
app/helpers/edgarj/assoc_helper.rb
Edgarj.AssocHelper.get_bitset
def get_bitset(model, col) bitset_name = col.name.camelize + 'Bitset' if model.const_defined?(bitset_name, false) _module = model.const_get(bitset_name) _module.is_a?(Module) ? _module : nil else nil end end
ruby
def get_bitset(model, col) bitset_name = col.name.camelize + 'Bitset' if model.const_defined?(bitset_name, false) _module = model.const_get(bitset_name) _module.is_a?(Module) ? _module : nil else nil end end
[ "def", "get_bitset", "(", "model", ",", "col", ")", "bitset_name", "=", "col", ".", "name", ".", "camelize", "+", "'Bitset'", "if", "model", ".", "const_defined?", "(", "bitset_name", ",", "false", ")", "_module", "=", "model", ".", "const_get", "(", "bitset_name", ")", "_module", ".", "is_a?", "(", "Module", ")", "?", "_module", ":", "nil", "else", "nil", "end", "end" ]
get bitset Module. When ColBitset(camelized argument col name + 'Bitset') module exists, the ColBitset is assumed enum definition.
[ "get", "bitset", "Module", "." ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L254-L262
train
fuminori-ido/edgarj
app/helpers/edgarj/assoc_helper.rb
Edgarj.AssocHelper.draw_column_bitset
def draw_column_bitset(rec, col_or_sym, bitset) turn_on_flags = [] value = rec.send(get_column_name(col_or_sym)) for flag in bitset.constants do turn_on_flags << flag if flag_on?(value, bitset, flag) end turn_on_flags.map{|f| rec.class.human_const_name(bitset, f) }.join(' ') end
ruby
def draw_column_bitset(rec, col_or_sym, bitset) turn_on_flags = [] value = rec.send(get_column_name(col_or_sym)) for flag in bitset.constants do turn_on_flags << flag if flag_on?(value, bitset, flag) end turn_on_flags.map{|f| rec.class.human_const_name(bitset, f) }.join(' ') end
[ "def", "draw_column_bitset", "(", "rec", ",", "col_or_sym", ",", "bitset", ")", "turn_on_flags", "=", "[", "]", "value", "=", "rec", ".", "send", "(", "get_column_name", "(", "col_or_sym", ")", ")", "for", "flag", "in", "bitset", ".", "constants", "do", "turn_on_flags", "<<", "flag", "if", "flag_on?", "(", "value", ",", "bitset", ",", "flag", ")", "end", "turn_on_flags", ".", "map", "{", "|", "f", "|", "rec", ".", "class", ".", "human_const_name", "(", "bitset", ",", "f", ")", "}", ".", "join", "(", "' '", ")", "end" ]
draw bitset column in list. === INPUTS rec:: AR object col_or_sym:: column object returned by rec.class.columns bitset:: Module which contains bitset constants === SEE ALSO get_bitset():: get bitset definition draw_bitset():: draw bitste checkboxes field draw_column_enum():: draw bitset column in list
[ "draw", "bitset", "column", "in", "list", "." ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L275-L282
train
fuminori-ido/edgarj
app/helpers/edgarj/assoc_helper.rb
Edgarj.AssocHelper.draw_column_enum
def draw_column_enum(rec, col_or_sym, enum) Edgarj::EnumCache.instance.label(rec, get_column_name(col_or_sym), enum) end
ruby
def draw_column_enum(rec, col_or_sym, enum) Edgarj::EnumCache.instance.label(rec, get_column_name(col_or_sym), enum) end
[ "def", "draw_column_enum", "(", "rec", ",", "col_or_sym", ",", "enum", ")", "Edgarj", "::", "EnumCache", ".", "instance", ".", "label", "(", "rec", ",", "get_column_name", "(", "col_or_sym", ")", ",", "enum", ")", "end" ]
draw enum column in list. When enum for col is defined, constant string (rather than rec.col value) is drawn. See get_enum() for more detail of enum for the col. === EXAMPLE Question has status attribute and Question::Status enum. When question.status == 300, draw_column_enum(question, status_col, Question::Status) returns I18n.t('WORKING'). Where: * question is Question AR object. * status_col is one of Question.columns object for status column. === INPUTS rec:: AR object col_or_sym:: column object returned by rec.class.columns enum:: Module which contains constants === SEE ALSO get_enum():: get enum definition draw_enum():: draw enum selection field draw_column_bitset():: draw bitset column in list
[ "draw", "enum", "column", "in", "list", "." ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L309-L311
train
fuminori-ido/edgarj
app/helpers/edgarj/assoc_helper.rb
Edgarj.AssocHelper.adrs_str_sub
def adrs_str_sub(model, prefix, element) e = model.send(prefix + element) e.blank? ? '' : e end
ruby
def adrs_str_sub(model, prefix, element) e = model.send(prefix + element) e.blank? ? '' : e end
[ "def", "adrs_str_sub", "(", "model", ",", "prefix", ",", "element", ")", "e", "=", "model", ".", "send", "(", "prefix", "+", "element", ")", "e", ".", "blank?", "?", "''", ":", "e", "end" ]
return address element string or ''
[ "return", "address", "element", "string", "or" ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L314-L317
train
fuminori-ido/edgarj
app/helpers/edgarj/assoc_helper.rb
Edgarj.AssocHelper.adrs_str
def adrs_str(model, adrs_prefix) result = '' for adrs_element in ['prefecture', 'city', 'other', 'bldg'] do result << adrs_str_sub(model, adrs_prefix, adrs_element) end result end
ruby
def adrs_str(model, adrs_prefix) result = '' for adrs_element in ['prefecture', 'city', 'other', 'bldg'] do result << adrs_str_sub(model, adrs_prefix, adrs_element) end result end
[ "def", "adrs_str", "(", "model", ",", "adrs_prefix", ")", "result", "=", "''", "for", "adrs_element", "in", "[", "'prefecture'", ",", "'city'", ",", "'other'", ",", "'bldg'", "]", "do", "result", "<<", "adrs_str_sub", "(", "model", ",", "adrs_prefix", ",", "adrs_element", ")", "end", "result", "end" ]
model & adrs_prefix -> address string
[ "model", "&", "adrs_prefix", "-", ">", "address", "string" ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L320-L326
train
fuminori-ido/edgarj
app/helpers/edgarj/assoc_helper.rb
Edgarj.AssocHelper.permitted?
def permitted?(requested_flags = 0) current_user_roles.any?{|ug| ug.admin?} || current_model_permissions.any?{|cp| cp.permitted?(requested_flags)} end
ruby
def permitted?(requested_flags = 0) current_user_roles.any?{|ug| ug.admin?} || current_model_permissions.any?{|cp| cp.permitted?(requested_flags)} end
[ "def", "permitted?", "(", "requested_flags", "=", "0", ")", "current_user_roles", ".", "any?", "{", "|", "ug", "|", "ug", ".", "admin?", "}", "||", "current_model_permissions", ".", "any?", "{", "|", "cp", "|", "cp", ".", "permitted?", "(", "requested_flags", ")", "}", "end" ]
return true if login user has enough permission on current controller.
[ "return", "true", "if", "login", "user", "has", "enough", "permission", "on", "current", "controller", "." ]
1648ab180f1f4adaeea03d54b645f58f3702a2bf
https://github.com/fuminori-ido/edgarj/blob/1648ab180f1f4adaeea03d54b645f58f3702a2bf/app/helpers/edgarj/assoc_helper.rb#L329-L332
train
ksylvest/serializer
lib/serializer.rb
Serializer.ClassMethods.has_serialized
def has_serialized(name, &block) serialize name, Hash initializer = Serializer::Initializer.new block.call(initializer) initializer.each do |method, options| define_method "#{method}" do hash = send(name) result = hash[method.to_sym] if hash if hash.nil? or result.nil? send("#{name}=", {}) unless send(name) hash = send(name) result = options[:default] result = result.clone if result.duplicable? hash[method.to_sym] = result end return result end define_method "#{method}?" do hash = send(name) result = hash[method.to_sym] if hash if hash.nil? or result.nil? send("#{name}=", {}) unless send(name) hash = send(name) result = options[:default] result = result.clone if result.duplicable? hash[method.to_sym] = result end return result end define_method "#{method}=" do |value| original = send(name) || {} if options[:type] and value case options[:type].to_sym when :float then value = value.to_f if value.respond_to? :to_f when :integer then value = value.to_i if value.respond_to? :to_i when :string then value = value.to_str if value.respond_to? :to_str when :symbol then value = value.to_sym if value.respond_to? :to_sym when :boolean then value = true if value.eql? "true" value = false if value.eql? "false" value = !value.to_i.zero? if value.respond_to? :to_i end end modified = original.clone modified[method.to_sym] = value send("#{name}_will_change!") unless modified.eql?(original) send("#{name}=", modified) end end end
ruby
def has_serialized(name, &block) serialize name, Hash initializer = Serializer::Initializer.new block.call(initializer) initializer.each do |method, options| define_method "#{method}" do hash = send(name) result = hash[method.to_sym] if hash if hash.nil? or result.nil? send("#{name}=", {}) unless send(name) hash = send(name) result = options[:default] result = result.clone if result.duplicable? hash[method.to_sym] = result end return result end define_method "#{method}?" do hash = send(name) result = hash[method.to_sym] if hash if hash.nil? or result.nil? send("#{name}=", {}) unless send(name) hash = send(name) result = options[:default] result = result.clone if result.duplicable? hash[method.to_sym] = result end return result end define_method "#{method}=" do |value| original = send(name) || {} if options[:type] and value case options[:type].to_sym when :float then value = value.to_f if value.respond_to? :to_f when :integer then value = value.to_i if value.respond_to? :to_i when :string then value = value.to_str if value.respond_to? :to_str when :symbol then value = value.to_sym if value.respond_to? :to_sym when :boolean then value = true if value.eql? "true" value = false if value.eql? "false" value = !value.to_i.zero? if value.respond_to? :to_i end end modified = original.clone modified[method.to_sym] = value send("#{name}_will_change!") unless modified.eql?(original) send("#{name}=", modified) end end end
[ "def", "has_serialized", "(", "name", ",", "&", "block", ")", "serialize", "name", ",", "Hash", "initializer", "=", "Serializer", "::", "Initializer", ".", "new", "block", ".", "call", "(", "initializer", ")", "initializer", ".", "each", "do", "|", "method", ",", "options", "|", "define_method", "\"#{method}\"", "do", "hash", "=", "send", "(", "name", ")", "result", "=", "hash", "[", "method", ".", "to_sym", "]", "if", "hash", "if", "hash", ".", "nil?", "or", "result", ".", "nil?", "send", "(", "\"#{name}=\"", ",", "{", "}", ")", "unless", "send", "(", "name", ")", "hash", "=", "send", "(", "name", ")", "result", "=", "options", "[", ":default", "]", "result", "=", "result", ".", "clone", "if", "result", ".", "duplicable?", "hash", "[", "method", ".", "to_sym", "]", "=", "result", "end", "return", "result", "end", "define_method", "\"#{method}?\"", "do", "hash", "=", "send", "(", "name", ")", "result", "=", "hash", "[", "method", ".", "to_sym", "]", "if", "hash", "if", "hash", ".", "nil?", "or", "result", ".", "nil?", "send", "(", "\"#{name}=\"", ",", "{", "}", ")", "unless", "send", "(", "name", ")", "hash", "=", "send", "(", "name", ")", "result", "=", "options", "[", ":default", "]", "result", "=", "result", ".", "clone", "if", "result", ".", "duplicable?", "hash", "[", "method", ".", "to_sym", "]", "=", "result", "end", "return", "result", "end", "define_method", "\"#{method}=\"", "do", "|", "value", "|", "original", "=", "send", "(", "name", ")", "||", "{", "}", "if", "options", "[", ":type", "]", "and", "value", "case", "options", "[", ":type", "]", ".", "to_sym", "when", ":float", "then", "value", "=", "value", ".", "to_f", "if", "value", ".", "respond_to?", ":to_f", "when", ":integer", "then", "value", "=", "value", ".", "to_i", "if", "value", ".", "respond_to?", ":to_i", "when", ":string", "then", "value", "=", "value", ".", "to_str", "if", "value", ".", "respond_to?", ":to_str", "when", ":symbol", "then", "value", "=", "value", ".", "to_sym", "if", "value", ".", "respond_to?", ":to_sym", "when", ":boolean", "then", "value", "=", "true", "if", "value", ".", "eql?", "\"true\"", "value", "=", "false", "if", "value", ".", "eql?", "\"false\"", "value", "=", "!", "value", ".", "to_i", ".", "zero?", "if", "value", ".", "respond_to?", ":to_i", "end", "end", "modified", "=", "original", ".", "clone", "modified", "[", "method", ".", "to_sym", "]", "=", "value", "send", "(", "\"#{name}_will_change!\"", ")", "unless", "modified", ".", "eql?", "(", "original", ")", "send", "(", "\"#{name}=\"", ",", "modified", ")", "end", "end", "end" ]
Add serializer to a class. Usage: has_serialized :settings do |settings| settings.define :tw_share, default: true, type: :boolean settings.define :fb_share, default: true, type: :boolean end
[ "Add", "serializer", "to", "a", "class", "." ]
cb018a5bf73a88eb7ec59fd996702337ddb81439
https://github.com/ksylvest/serializer/blob/cb018a5bf73a88eb7ec59fd996702337ddb81439/lib/serializer.rb#L22-L88
train
MattRyder/tableau
lib/tableau/baseparser.rb
Tableau.BaseParser.parse_table
def parse_table(table_rows) classes = Tableau::ClassArray.new @day = 0 # delete the time header row table_rows.delete(table_rows.first) table_rows.each do |row| @time = Time.new(2013, 1, 1, 9, 0, 0) # drop the 'Day' cell from the row row_items = row.xpath('td') row_items.delete(row_items.first) row_items.each do |cell| if cell.attribute('colspan') intervals = cell.attribute('colspan').value classes << create_class(cell) else intervals = 1 end inc_time(intervals) end @day += 1 end classes end
ruby
def parse_table(table_rows) classes = Tableau::ClassArray.new @day = 0 # delete the time header row table_rows.delete(table_rows.first) table_rows.each do |row| @time = Time.new(2013, 1, 1, 9, 0, 0) # drop the 'Day' cell from the row row_items = row.xpath('td') row_items.delete(row_items.first) row_items.each do |cell| if cell.attribute('colspan') intervals = cell.attribute('colspan').value classes << create_class(cell) else intervals = 1 end inc_time(intervals) end @day += 1 end classes end
[ "def", "parse_table", "(", "table_rows", ")", "classes", "=", "Tableau", "::", "ClassArray", ".", "new", "@day", "=", "0", "table_rows", ".", "delete", "(", "table_rows", ".", "first", ")", "table_rows", ".", "each", "do", "|", "row", "|", "@time", "=", "Time", ".", "new", "(", "2013", ",", "1", ",", "1", ",", "9", ",", "0", ",", "0", ")", "row_items", "=", "row", ".", "xpath", "(", "'td'", ")", "row_items", ".", "delete", "(", "row_items", ".", "first", ")", "row_items", ".", "each", "do", "|", "cell", "|", "if", "cell", ".", "attribute", "(", "'colspan'", ")", "intervals", "=", "cell", ".", "attribute", "(", "'colspan'", ")", ".", "value", "classes", "<<", "create_class", "(", "cell", ")", "else", "intervals", "=", "1", "end", "inc_time", "(", "intervals", ")", "end", "@day", "+=", "1", "end", "classes", "end" ]
Parse the module table for any classes
[ "Parse", "the", "module", "table", "for", "any", "classes" ]
a313fa88bf165ca66cb564c14abd3e526d6c1494
https://github.com/MattRyder/tableau/blob/a313fa88bf165ca66cb564c14abd3e526d6c1494/lib/tableau/baseparser.rb#L20-L48
train