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 |
---|---|---|---|---|---|---|---|---|---|---|---|
yaauie/implements | lib/implements/interface.rb | Implements.Interface.implementation | def implementation(*selectors)
selectors << :auto if selectors.empty?
Implementation::Registry::Finder.new(@implementations, selectors)
end | ruby | def implementation(*selectors)
selectors << :auto if selectors.empty?
Implementation::Registry::Finder.new(@implementations, selectors)
end | [
"def",
"implementation",
"(",
"*",
"selectors",
")",
"selectors",
"<<",
":auto",
"if",
"selectors",
".",
"empty?",
"Implementation",
"::",
"Registry",
"::",
"Finder",
".",
"new",
"(",
"@implementations",
",",
"selectors",
")",
"end"
] | Used to find a suitable implementation
@api public
@param [*selectors] zero or more selectors to use for finding an
implementation of this interface. If none is given, :auto is assumed.
@return [Implementation::Registry::Finder] | [
"Used",
"to",
"find",
"a",
"suitable",
"implementation"
] | 27c698d283dbf71d04721b4cf4929d53b4a99cb7 | https://github.com/yaauie/implements/blob/27c698d283dbf71d04721b4cf4929d53b4a99cb7/lib/implements/interface.rb#L11-L14 | train |
malmostad/siteseeker_normalizer | lib/siteseeker_normalizer/parse.rb | SiteseekerNormalizer.Parse.clean_up | def clean_up
@doc.css(".ess-separator").remove
@doc.css("@title").remove
@doc.css("@onclick").remove
@doc.css("@tabindex").remove
@doc.css(".ess-label-hits").remove
@doc.css(".ess-clear").remove
end | ruby | def clean_up
@doc.css(".ess-separator").remove
@doc.css("@title").remove
@doc.css("@onclick").remove
@doc.css("@tabindex").remove
@doc.css(".ess-label-hits").remove
@doc.css(".ess-clear").remove
end | [
"def",
"clean_up",
"@doc",
".",
"css",
"(",
"\".ess-separator\"",
")",
".",
"remove",
"@doc",
".",
"css",
"(",
"\"@title\"",
")",
".",
"remove",
"@doc",
".",
"css",
"(",
"\"@onclick\"",
")",
".",
"remove",
"@doc",
".",
"css",
"(",
"\"@tabindex\"",
")",
".",
"remove",
"@doc",
".",
"css",
"(",
"\".ess-label-hits\"",
")",
".",
"remove",
"@doc",
".",
"css",
"(",
"\".ess-clear\"",
")",
".",
"remove",
"end"
] | Cleanup some crap | [
"Cleanup",
"some",
"crap"
] | c5ed3a1edec7fb6c19e3ae87fc5960dd0ee9ef3d | https://github.com/malmostad/siteseeker_normalizer/blob/c5ed3a1edec7fb6c19e3ae87fc5960dd0ee9ef3d/lib/siteseeker_normalizer/parse.rb#L80-L87 | train |
mediasp/confuse | lib/confuse/key_splitter.rb | Confuse.KeySplitter.possible_namespaces | def possible_namespaces
namespaces = []
key = @key.to_s
while (index = key.rindex('_'))
key = key[0, index]
namespaces << key.to_sym
end
namespaces
end | ruby | def possible_namespaces
namespaces = []
key = @key.to_s
while (index = key.rindex('_'))
key = key[0, index]
namespaces << key.to_sym
end
namespaces
end | [
"def",
"possible_namespaces",
"namespaces",
"=",
"[",
"]",
"key",
"=",
"@key",
".",
"to_s",
"while",
"(",
"index",
"=",
"key",
".",
"rindex",
"(",
"'_'",
")",
")",
"key",
"=",
"key",
"[",
"0",
",",
"index",
"]",
"namespaces",
"<<",
"key",
".",
"to_sym",
"end",
"namespaces",
"end"
] | Returns an array of possible namespaces based on splitting the key at
every underscore. | [
"Returns",
"an",
"array",
"of",
"possible",
"namespaces",
"based",
"on",
"splitting",
"the",
"key",
"at",
"every",
"underscore",
"."
] | 7e0e976d9461cd794b222305a24fa44946d6a9d3 | https://github.com/mediasp/confuse/blob/7e0e976d9461cd794b222305a24fa44946d6a9d3/lib/confuse/key_splitter.rb#L20-L28 | train |
mediasp/confuse | lib/confuse/key_splitter.rb | Confuse.KeySplitter.rest_of_key | def rest_of_key(namespace)
return nil if @key == namespace
key = @key.to_s
index = key.index(namespace.to_s) && (namespace.to_s.length + 1)
key[index, key.length].to_sym if index
end | ruby | def rest_of_key(namespace)
return nil if @key == namespace
key = @key.to_s
index = key.index(namespace.to_s) && (namespace.to_s.length + 1)
key[index, key.length].to_sym if index
end | [
"def",
"rest_of_key",
"(",
"namespace",
")",
"return",
"nil",
"if",
"@key",
"==",
"namespace",
"key",
"=",
"@key",
".",
"to_s",
"index",
"=",
"key",
".",
"index",
"(",
"namespace",
".",
"to_s",
")",
"&&",
"(",
"namespace",
".",
"to_s",
".",
"length",
"+",
"1",
")",
"key",
"[",
"index",
",",
"key",
".",
"length",
"]",
".",
"to_sym",
"if",
"index",
"end"
] | Returns the rest of the key for a given namespace | [
"Returns",
"the",
"rest",
"of",
"the",
"key",
"for",
"a",
"given",
"namespace"
] | 7e0e976d9461cd794b222305a24fa44946d6a9d3 | https://github.com/mediasp/confuse/blob/7e0e976d9461cd794b222305a24fa44946d6a9d3/lib/confuse/key_splitter.rb#L31-L38 | train |
medcat/mixture | lib/mixture/attribute.rb | Mixture.Attribute.update | def update(value)
@list.callbacks[:update].inject(value) { |a, e| e.call(self, a) }
end | ruby | def update(value)
@list.callbacks[:update].inject(value) { |a, e| e.call(self, a) }
end | [
"def",
"update",
"(",
"value",
")",
"@list",
".",
"callbacks",
"[",
":update",
"]",
".",
"inject",
"(",
"value",
")",
"{",
"|",
"a",
",",
"e",
"|",
"e",
".",
"call",
"(",
"self",
",",
"a",
")",
"}",
"end"
] | Initialize the attribute.
@param name [Symbol] The name of the attribute.
@param list [AttributeList] The attribute list this attribute is
a part of.
@param options [Hash] The optiosn for the attribute.
Update the attribute with the given value. It runs the value
through the callbacks, and returns a new value given by the
callbacks.
@param value [Object] The new value.
@return [Object] The new new value. | [
"Initialize",
"the",
"attribute",
"."
] | 8c59a57e07d495f678a0adefba7bcfc088195614 | https://github.com/medcat/mixture/blob/8c59a57e07d495f678a0adefba7bcfc088195614/lib/mixture/attribute.rb#L36-L38 | train |
postmodern/ripl-shell_commands | lib/ripl/shell_commands.rb | Ripl.ShellCommands.loop_eval | def loop_eval(input)
if (@buffer.nil? && input =~ PATTERN)
command = input[1..-1]
name, arguments = ShellCommands.parse(command)
unless BLACKLIST.include?(name)
if BUILTIN.include?(name)
arguments ||= []
return ShellCommands.send(name,*arguments)
elsif EXECUTABLES[name]
return ShellCommands.exec(name,*arguments)
end
end
end
super(input)
end | ruby | def loop_eval(input)
if (@buffer.nil? && input =~ PATTERN)
command = input[1..-1]
name, arguments = ShellCommands.parse(command)
unless BLACKLIST.include?(name)
if BUILTIN.include?(name)
arguments ||= []
return ShellCommands.send(name,*arguments)
elsif EXECUTABLES[name]
return ShellCommands.exec(name,*arguments)
end
end
end
super(input)
end | [
"def",
"loop_eval",
"(",
"input",
")",
"if",
"(",
"@buffer",
".",
"nil?",
"&&",
"input",
"=~",
"PATTERN",
")",
"command",
"=",
"input",
"[",
"1",
"..",
"-",
"1",
"]",
"name",
",",
"arguments",
"=",
"ShellCommands",
".",
"parse",
"(",
"command",
")",
"unless",
"BLACKLIST",
".",
"include?",
"(",
"name",
")",
"if",
"BUILTIN",
".",
"include?",
"(",
"name",
")",
"arguments",
"||=",
"[",
"]",
"return",
"ShellCommands",
".",
"send",
"(",
"name",
",",
"*",
"arguments",
")",
"elsif",
"EXECUTABLES",
"[",
"name",
"]",
"return",
"ShellCommands",
".",
"exec",
"(",
"name",
",",
"*",
"arguments",
")",
"end",
"end",
"end",
"super",
"(",
"input",
")",
"end"
] | Dynamically execute shell commands, instead of Ruby.
@param [String] input
The input from the console. | [
"Dynamically",
"execute",
"shell",
"commands",
"instead",
"of",
"Ruby",
"."
] | 56bdca61921229af02f4699fa67fb84a78252099 | https://github.com/postmodern/ripl-shell_commands/blob/56bdca61921229af02f4699fa67fb84a78252099/lib/ripl/shell_commands.rb#L40-L57 | train |
iv-mexx/git-releaselog | lib/git-releaselog/changelog.rb | Releaselog.Changelog.section | def section(section_changes, header, entry_style, header_style = nil)
return "" unless section_changes.size > 0
str = ""
unless header.empty?
if header_style
str << header_style.call(header)
else
str << header
end
end
section_changes.each_with_index do |e, i|
str << entry_style.call(e, i)
end
str
end | ruby | def section(section_changes, header, entry_style, header_style = nil)
return "" unless section_changes.size > 0
str = ""
unless header.empty?
if header_style
str << header_style.call(header)
else
str << header
end
end
section_changes.each_with_index do |e, i|
str << entry_style.call(e, i)
end
str
end | [
"def",
"section",
"(",
"section_changes",
",",
"header",
",",
"entry_style",
",",
"header_style",
"=",
"nil",
")",
"return",
"\"\"",
"unless",
"section_changes",
".",
"size",
">",
"0",
"str",
"=",
"\"\"",
"unless",
"header",
".",
"empty?",
"if",
"header_style",
"str",
"<<",
"header_style",
".",
"call",
"(",
"header",
")",
"else",
"str",
"<<",
"header",
"end",
"end",
"section_changes",
".",
"each_with_index",
"do",
"|",
"e",
",",
"i",
"|",
"str",
"<<",
"entry_style",
".",
"call",
"(",
"e",
",",
"i",
")",
"end",
"str",
"end"
] | Format a specific section.
section_changes ... changes in the format of { section_1: [changes...], section_2: [changes...]}
header ... header of the section
entry_style ... is called for styling each item of a section
header_style ... optional, since styled header can be passed directly; is called for styling the header of the section | [
"Format",
"a",
"specific",
"section",
"."
] | 393d5d9b12f9dd808ccb2d13ab0ada12d72d2849 | https://github.com/iv-mexx/git-releaselog/blob/393d5d9b12f9dd808ccb2d13ab0ada12d72d2849/lib/git-releaselog/changelog.rb#L70-L86 | train |
iv-mexx/git-releaselog | lib/git-releaselog/changelog.rb | Releaselog.Changelog.to_slack | def to_slack
str = ""
str << tag_info { |t| t }
str << commit_info { |ci| ci.empty? ? "" : "(_#{ci}_)\n" }
str << sections(
changes,
-> (header) { "*#{header.capitalize}*\n" },
-> (field, _index) { "\t- #{field}\n" }
)
str
end | ruby | def to_slack
str = ""
str << tag_info { |t| t }
str << commit_info { |ci| ci.empty? ? "" : "(_#{ci}_)\n" }
str << sections(
changes,
-> (header) { "*#{header.capitalize}*\n" },
-> (field, _index) { "\t- #{field}\n" }
)
str
end | [
"def",
"to_slack",
"str",
"=",
"\"\"",
"str",
"<<",
"tag_info",
"{",
"|",
"t",
"|",
"t",
"}",
"str",
"<<",
"commit_info",
"{",
"|",
"ci",
"|",
"ci",
".",
"empty?",
"?",
"\"\"",
":",
"\"(_#{ci}_)\\n\"",
"}",
"str",
"<<",
"sections",
"(",
"changes",
",",
"->",
"(",
"header",
")",
"{",
"\"*#{header.capitalize}*\\n\"",
"}",
",",
"->",
"(",
"field",
",",
"_index",
")",
"{",
"\"\\t- #{field}\\n\"",
"}",
")",
"str",
"end"
] | Render the Changelog with Slack Formatting | [
"Render",
"the",
"Changelog",
"with",
"Slack",
"Formatting"
] | 393d5d9b12f9dd808ccb2d13ab0ada12d72d2849 | https://github.com/iv-mexx/git-releaselog/blob/393d5d9b12f9dd808ccb2d13ab0ada12d72d2849/lib/git-releaselog/changelog.rb#L89-L101 | train |
chetan/bixby-common | lib/bixby-common/util/thread_pool.rb | Bixby.ThreadPool.grow | def grow
@lock.synchronize do
prune
logger.debug { "jobs: #{num_jobs}; busy: #{num_working}; idle: #{num_idle}" }
if @size == 0 || (@size < @max_size && num_jobs > 0 && num_jobs > num_idle) then
space = @max_size-@size
jobs = num_jobs-num_idle
needed = space < jobs ? space : jobs
needed = 1 if needed <= 0
expand(needed)
else
logger.debug "NOT growing the pool!"
end
end
nil
end | ruby | def grow
@lock.synchronize do
prune
logger.debug { "jobs: #{num_jobs}; busy: #{num_working}; idle: #{num_idle}" }
if @size == 0 || (@size < @max_size && num_jobs > 0 && num_jobs > num_idle) then
space = @max_size-@size
jobs = num_jobs-num_idle
needed = space < jobs ? space : jobs
needed = 1 if needed <= 0
expand(needed)
else
logger.debug "NOT growing the pool!"
end
end
nil
end | [
"def",
"grow",
"@lock",
".",
"synchronize",
"do",
"prune",
"logger",
".",
"debug",
"{",
"\"jobs: #{num_jobs}; busy: #{num_working}; idle: #{num_idle}\"",
"}",
"if",
"@size",
"==",
"0",
"||",
"(",
"@size",
"<",
"@max_size",
"&&",
"num_jobs",
">",
"0",
"&&",
"num_jobs",
">",
"num_idle",
")",
"then",
"space",
"=",
"@max_size",
"-",
"@size",
"jobs",
"=",
"num_jobs",
"-",
"num_idle",
"needed",
"=",
"space",
"<",
"jobs",
"?",
"space",
":",
"jobs",
"needed",
"=",
"1",
"if",
"needed",
"<=",
"0",
"expand",
"(",
"needed",
")",
"else",
"logger",
".",
"debug",
"\"NOT growing the pool!\"",
"end",
"end",
"nil",
"end"
] | Grow the pool by one if we have more jobs than idle workers | [
"Grow",
"the",
"pool",
"by",
"one",
"if",
"we",
"have",
"more",
"jobs",
"than",
"idle",
"workers"
] | 3fb8829987b115fc53ec820d97a20b4a8c49b4a2 | https://github.com/chetan/bixby-common/blob/3fb8829987b115fc53ec820d97a20b4a8c49b4a2/lib/bixby-common/util/thread_pool.rb#L181-L197 | train |
zpatten/ztk | lib/ztk/config.rb | ZTK.Config.method_missing | def method_missing(method_symbol, *method_args)
if method_args.length > 0
_set(method_symbol, method_args.first)
end
_get(method_symbol)
end | ruby | def method_missing(method_symbol, *method_args)
if method_args.length > 0
_set(method_symbol, method_args.first)
end
_get(method_symbol)
end | [
"def",
"method_missing",
"(",
"method_symbol",
",",
"*",
"method_args",
")",
"if",
"method_args",
".",
"length",
">",
"0",
"_set",
"(",
"method_symbol",
",",
"method_args",
".",
"first",
")",
"end",
"_get",
"(",
"method_symbol",
")",
"end"
] | Handles method calls for our configuration keys. | [
"Handles",
"method",
"calls",
"for",
"our",
"configuration",
"keys",
"."
] | 9b0f35bef36f38428e1a57b36f25a806c240b3fb | https://github.com/zpatten/ztk/blob/9b0f35bef36f38428e1a57b36f25a806c240b3fb/lib/ztk/config.rb#L127-L133 | train |
SpeciesFileGroup/taxonifi | lib/taxonifi/export/format/base.rb | Taxonifi::Export.Base.write_file | def write_file(filename = 'foo', string = nil)
raise ExportError, 'Nothing to export for #{filename}.' if string.nil? || string == ""
f = File.new( File.expand_path(File.join(export_path, filename)), 'w+')
f.puts string
f.close
end | ruby | def write_file(filename = 'foo', string = nil)
raise ExportError, 'Nothing to export for #{filename}.' if string.nil? || string == ""
f = File.new( File.expand_path(File.join(export_path, filename)), 'w+')
f.puts string
f.close
end | [
"def",
"write_file",
"(",
"filename",
"=",
"'foo'",
",",
"string",
"=",
"nil",
")",
"raise",
"ExportError",
",",
"'Nothing to export for #{filename}.'",
"if",
"string",
".",
"nil?",
"||",
"string",
"==",
"\"\"",
"f",
"=",
"File",
".",
"new",
"(",
"File",
".",
"expand_path",
"(",
"File",
".",
"join",
"(",
"export_path",
",",
"filename",
")",
")",
",",
"'w+'",
")",
"f",
".",
"puts",
"string",
"f",
".",
"close",
"end"
] | Write the string to a file in the export path. | [
"Write",
"the",
"string",
"to",
"a",
"file",
"in",
"the",
"export",
"path",
"."
] | 100dc94e7ffd378f6a81381c13768e35b2b65bf2 | https://github.com/SpeciesFileGroup/taxonifi/blob/100dc94e7ffd378f6a81381c13768e35b2b65bf2/lib/taxonifi/export/format/base.rb#L99-L104 | train |
ebfjunior/juno-report | lib/juno-report/pdf.rb | JunoReport.Pdf.new_page | def new_page
@pdf.start_new_page
set_pos_y
print_section :page unless @sections[:page].nil?
set_pos_y (@sections[:body][:settings][:posY] || 0)
@current_groups.each do |field, value|
print_section field.to_sym, @record, true
end
draw_columns
end | ruby | def new_page
@pdf.start_new_page
set_pos_y
print_section :page unless @sections[:page].nil?
set_pos_y (@sections[:body][:settings][:posY] || 0)
@current_groups.each do |field, value|
print_section field.to_sym, @record, true
end
draw_columns
end | [
"def",
"new_page",
"@pdf",
".",
"start_new_page",
"set_pos_y",
"print_section",
":page",
"unless",
"@sections",
"[",
":page",
"]",
".",
"nil?",
"set_pos_y",
"(",
"@sections",
"[",
":body",
"]",
"[",
":settings",
"]",
"[",
":posY",
"]",
"||",
"0",
")",
"@current_groups",
".",
"each",
"do",
"|",
"field",
",",
"value",
"|",
"print_section",
"field",
".",
"to_sym",
",",
"@record",
",",
"true",
"end",
"draw_columns",
"end"
] | Creates a new page, restarting the vertical position of the pointer.
Print the whole header for the current groups and the columns of the report. | [
"Creates",
"a",
"new",
"page",
"restarting",
"the",
"vertical",
"position",
"of",
"the",
"pointer",
".",
"Print",
"the",
"whole",
"header",
"for",
"the",
"current",
"groups",
"and",
"the",
"columns",
"of",
"the",
"report",
"."
] | 139f2a1733e0d7a68160b338cc1a4645f05d5953 | https://github.com/ebfjunior/juno-report/blob/139f2a1733e0d7a68160b338cc1a4645f05d5953/lib/juno-report/pdf.rb#L72-L81 | train |
ebfjunior/juno-report | lib/juno-report/pdf.rb | JunoReport.Pdf.symbolize! | def symbolize! hash
hash.symbolize_keys!
hash.values.select{|v| v.is_a? Hash}.each{|h| symbolize!(h)}
end | ruby | def symbolize! hash
hash.symbolize_keys!
hash.values.select{|v| v.is_a? Hash}.each{|h| symbolize!(h)}
end | [
"def",
"symbolize!",
"hash",
"hash",
".",
"symbolize_keys!",
"hash",
".",
"values",
".",
"select",
"{",
"|",
"v",
"|",
"v",
".",
"is_a?",
"Hash",
"}",
".",
"each",
"{",
"|",
"h",
"|",
"symbolize!",
"(",
"h",
")",
"}",
"end"
] | Convert to symbol all hash keys, recursively. | [
"Convert",
"to",
"symbol",
"all",
"hash",
"keys",
"recursively",
"."
] | 139f2a1733e0d7a68160b338cc1a4645f05d5953 | https://github.com/ebfjunior/juno-report/blob/139f2a1733e0d7a68160b338cc1a4645f05d5953/lib/juno-report/pdf.rb#L149-L152 | train |
ebfjunior/juno-report | lib/juno-report/pdf.rb | JunoReport.Pdf.get_sections | def get_sections
symbolize! @rules
raise "[body] section on YAML file is needed to generate the report." if @rules[:body].nil?
@sections = {:page => @rules[:page], :body => @rules[:body], :defaults => @rules[:defaults], :groups => {}}
@sections[:body][:settings][:groups].each { |group| @sections[:groups][group.to_sym] = @rules[group.to_sym] } if has_groups?
end | ruby | def get_sections
symbolize! @rules
raise "[body] section on YAML file is needed to generate the report." if @rules[:body].nil?
@sections = {:page => @rules[:page], :body => @rules[:body], :defaults => @rules[:defaults], :groups => {}}
@sections[:body][:settings][:groups].each { |group| @sections[:groups][group.to_sym] = @rules[group.to_sym] } if has_groups?
end | [
"def",
"get_sections",
"symbolize!",
"@rules",
"raise",
"\"[body] section on YAML file is needed to generate the report.\"",
"if",
"@rules",
"[",
":body",
"]",
".",
"nil?",
"@sections",
"=",
"{",
":page",
"=>",
"@rules",
"[",
":page",
"]",
",",
":body",
"=>",
"@rules",
"[",
":body",
"]",
",",
":defaults",
"=>",
"@rules",
"[",
":defaults",
"]",
",",
":groups",
"=>",
"{",
"}",
"}",
"@sections",
"[",
":body",
"]",
"[",
":settings",
"]",
"[",
":groups",
"]",
".",
"each",
"{",
"|",
"group",
"|",
"@sections",
"[",
":groups",
"]",
"[",
"group",
".",
"to_sym",
"]",
"=",
"@rules",
"[",
"group",
".",
"to_sym",
"]",
"}",
"if",
"has_groups?",
"end"
] | Convert the structure of the rules to facilitate the generating proccess. | [
"Convert",
"the",
"structure",
"of",
"the",
"rules",
"to",
"facilitate",
"the",
"generating",
"proccess",
"."
] | 139f2a1733e0d7a68160b338cc1a4645f05d5953 | https://github.com/ebfjunior/juno-report/blob/139f2a1733e0d7a68160b338cc1a4645f05d5953/lib/juno-report/pdf.rb#L155-L160 | train |
ebfjunior/juno-report | lib/juno-report/pdf.rb | JunoReport.Pdf.initialize_footer_values | def initialize_footer_values
@sections[:body][:settings][:groups].each do |group|
current_footer = {}
@sections[:groups][group.to_sym][:footer].each { |field, settings| current_footer[field] = nil } unless @sections[:groups][group.to_sym][:footer].nil?
@footers[group.to_sym] = current_footer unless current_footer.empty?
end if has_groups?
raise "The report must have at least a footer on body section" if @sections[:body][:footer].nil?
current_footer = {}
@sections[:body][:footer].each { |field, settings| current_footer[field] = nil }
@footers[:body] = current_footer unless current_footer.empty?
end | ruby | def initialize_footer_values
@sections[:body][:settings][:groups].each do |group|
current_footer = {}
@sections[:groups][group.to_sym][:footer].each { |field, settings| current_footer[field] = nil } unless @sections[:groups][group.to_sym][:footer].nil?
@footers[group.to_sym] = current_footer unless current_footer.empty?
end if has_groups?
raise "The report must have at least a footer on body section" if @sections[:body][:footer].nil?
current_footer = {}
@sections[:body][:footer].each { |field, settings| current_footer[field] = nil }
@footers[:body] = current_footer unless current_footer.empty?
end | [
"def",
"initialize_footer_values",
"@sections",
"[",
":body",
"]",
"[",
":settings",
"]",
"[",
":groups",
"]",
".",
"each",
"do",
"|",
"group",
"|",
"current_footer",
"=",
"{",
"}",
"@sections",
"[",
":groups",
"]",
"[",
"group",
".",
"to_sym",
"]",
"[",
":footer",
"]",
".",
"each",
"{",
"|",
"field",
",",
"settings",
"|",
"current_footer",
"[",
"field",
"]",
"=",
"nil",
"}",
"unless",
"@sections",
"[",
":groups",
"]",
"[",
"group",
".",
"to_sym",
"]",
"[",
":footer",
"]",
".",
"nil?",
"@footers",
"[",
"group",
".",
"to_sym",
"]",
"=",
"current_footer",
"unless",
"current_footer",
".",
"empty?",
"end",
"if",
"has_groups?",
"raise",
"\"The report must have at least a footer on body section\"",
"if",
"@sections",
"[",
":body",
"]",
"[",
":footer",
"]",
".",
"nil?",
"current_footer",
"=",
"{",
"}",
"@sections",
"[",
":body",
"]",
"[",
":footer",
"]",
".",
"each",
"{",
"|",
"field",
",",
"settings",
"|",
"current_footer",
"[",
"field",
"]",
"=",
"nil",
"}",
"@footers",
"[",
":body",
"]",
"=",
"current_footer",
"unless",
"current_footer",
".",
"empty?",
"end"
] | Create a structure to calculate the footer values for all groups. Appends the footer body to total values too. | [
"Create",
"a",
"structure",
"to",
"calculate",
"the",
"footer",
"values",
"for",
"all",
"groups",
".",
"Appends",
"the",
"footer",
"body",
"to",
"total",
"values",
"too",
"."
] | 139f2a1733e0d7a68160b338cc1a4645f05d5953 | https://github.com/ebfjunior/juno-report/blob/139f2a1733e0d7a68160b338cc1a4645f05d5953/lib/juno-report/pdf.rb#L197-L207 | train |
ebfjunior/juno-report | lib/juno-report/pdf.rb | JunoReport.Pdf.draw_footer | def draw_footer footers_to_print, source
footers_to_print.reverse_each do |group|
draw_line(@posY + @sections[:body][:settings][:height]/2)
source[group][:footer].each do |field, settings|
settings = [settings[0], @posY, (@defaults.merge (settings[1] || { }).symbolize_keys!)]
settings[2][:style] = settings[2][:style].to_sym
set_options settings[2]
draw_text @footers[group][field], settings
end
draw_line(@posY - @sections[:body][:settings][:height]/4)
set_pos_y @sections[:body][:settings][:height]
reset_footer group
end
end | ruby | def draw_footer footers_to_print, source
footers_to_print.reverse_each do |group|
draw_line(@posY + @sections[:body][:settings][:height]/2)
source[group][:footer].each do |field, settings|
settings = [settings[0], @posY, (@defaults.merge (settings[1] || { }).symbolize_keys!)]
settings[2][:style] = settings[2][:style].to_sym
set_options settings[2]
draw_text @footers[group][field], settings
end
draw_line(@posY - @sections[:body][:settings][:height]/4)
set_pos_y @sections[:body][:settings][:height]
reset_footer group
end
end | [
"def",
"draw_footer",
"footers_to_print",
",",
"source",
"footers_to_print",
".",
"reverse_each",
"do",
"|",
"group",
"|",
"draw_line",
"(",
"@posY",
"+",
"@sections",
"[",
":body",
"]",
"[",
":settings",
"]",
"[",
":height",
"]",
"/",
"2",
")",
"source",
"[",
"group",
"]",
"[",
":footer",
"]",
".",
"each",
"do",
"|",
"field",
",",
"settings",
"|",
"settings",
"=",
"[",
"settings",
"[",
"0",
"]",
",",
"@posY",
",",
"(",
"@defaults",
".",
"merge",
"(",
"settings",
"[",
"1",
"]",
"||",
"{",
"}",
")",
".",
"symbolize_keys!",
")",
"]",
"settings",
"[",
"2",
"]",
"[",
":style",
"]",
"=",
"settings",
"[",
"2",
"]",
"[",
":style",
"]",
".",
"to_sym",
"set_options",
"settings",
"[",
"2",
"]",
"draw_text",
"@footers",
"[",
"group",
"]",
"[",
"field",
"]",
",",
"settings",
"end",
"draw_line",
"(",
"@posY",
"-",
"@sections",
"[",
":body",
"]",
"[",
":settings",
"]",
"[",
":height",
"]",
"/",
"4",
")",
"set_pos_y",
"@sections",
"[",
":body",
"]",
"[",
":settings",
"]",
"[",
":height",
"]",
"reset_footer",
"group",
"end",
"end"
] | Print the footers according to the groups and source specified | [
"Print",
"the",
"footers",
"according",
"to",
"the",
"groups",
"and",
"source",
"specified"
] | 139f2a1733e0d7a68160b338cc1a4645f05d5953 | https://github.com/ebfjunior/juno-report/blob/139f2a1733e0d7a68160b338cc1a4645f05d5953/lib/juno-report/pdf.rb#L239-L253 | train |
jeremyz/edoors-ruby | lib/edoors/spin.rb | Edoors.Spin.release_p | def release_p p
# hope there is no circular loop
while p2=p.merged_shift
release_p p2
end
p.reset!
( @pool[p.class] ||= [] ) << p
end | ruby | def release_p p
# hope there is no circular loop
while p2=p.merged_shift
release_p p2
end
p.reset!
( @pool[p.class] ||= [] ) << p
end | [
"def",
"release_p",
"p",
"while",
"p2",
"=",
"p",
".",
"merged_shift",
"release_p",
"p2",
"end",
"p",
".",
"reset!",
"(",
"@pool",
"[",
"p",
".",
"class",
"]",
"||=",
"[",
"]",
")",
"<<",
"p",
"end"
] | releases the given Particle
@parama [Particle] p the Particle to be released
@note the Particle is stored into Hash @pool to be reused as soon as needed
@see Particle#reset! the Particle is reseted before beeing stored | [
"releases",
"the",
"given",
"Particle"
] | 4f065f63125907b3a4f72fbab8722c58ccab41c1 | https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/spin.rb#L150-L157 | train |
jeremyz/edoors-ruby | lib/edoors/spin.rb | Edoors.Spin.require_p | def require_p p_kls
l = @pool[p_kls]
return p_kls.new if l.nil?
p = l.pop
return p_kls.new if p.nil?
p
end | ruby | def require_p p_kls
l = @pool[p_kls]
return p_kls.new if l.nil?
p = l.pop
return p_kls.new if p.nil?
p
end | [
"def",
"require_p",
"p_kls",
"l",
"=",
"@pool",
"[",
"p_kls",
"]",
"return",
"p_kls",
".",
"new",
"if",
"l",
".",
"nil?",
"p",
"=",
"l",
".",
"pop",
"return",
"p_kls",
".",
"new",
"if",
"p",
".",
"nil?",
"p",
"end"
] | requires a Particle of the given Class
@param [Class] p_kls the desired Class of Particle
@note if there is no Particle of the given Class, one is created | [
"requires",
"a",
"Particle",
"of",
"the",
"given",
"Class"
] | 4f065f63125907b3a4f72fbab8722c58ccab41c1 | https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/spin.rb#L165-L171 | train |
jeremyz/edoors-ruby | lib/edoors/spin.rb | Edoors.Spin.process_sys_p | def process_sys_p p
if p.action==Edoors::SYS_ACT_HIBERNATE
stop!
hibernate! p[FIELD_HIBERNATE_PATH]
else
super p
end
end | ruby | def process_sys_p p
if p.action==Edoors::SYS_ACT_HIBERNATE
stop!
hibernate! p[FIELD_HIBERNATE_PATH]
else
super p
end
end | [
"def",
"process_sys_p",
"p",
"if",
"p",
".",
"action",
"==",
"Edoors",
"::",
"SYS_ACT_HIBERNATE",
"stop!",
"hibernate!",
"p",
"[",
"FIELD_HIBERNATE_PATH",
"]",
"else",
"super",
"p",
"end",
"end"
] | process the given particle
@param [Particle] p the Particle to be processed | [
"process",
"the",
"given",
"particle"
] | 4f065f63125907b3a4f72fbab8722c58ccab41c1 | https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/spin.rb#L193-L200 | train |
jeremyz/edoors-ruby | lib/edoors/spin.rb | Edoors.Spin.spin! | def spin!
start!
@run = true
@hibernation = false
while @run and (@sys_fifo.length>0 or @app_fifo.length>0)
while @run and @sys_fifo.length>0
p = @sys_fifo.shift
p.dst.process_sys_p p
end
while @run and @app_fifo.length>0
p = @app_fifo.shift
p.dst.process_p p
break
end
end
stop!
end | ruby | def spin!
start!
@run = true
@hibernation = false
while @run and (@sys_fifo.length>0 or @app_fifo.length>0)
while @run and @sys_fifo.length>0
p = @sys_fifo.shift
p.dst.process_sys_p p
end
while @run and @app_fifo.length>0
p = @app_fifo.shift
p.dst.process_p p
break
end
end
stop!
end | [
"def",
"spin!",
"start!",
"@run",
"=",
"true",
"@hibernation",
"=",
"false",
"while",
"@run",
"and",
"(",
"@sys_fifo",
".",
"length",
">",
"0",
"or",
"@app_fifo",
".",
"length",
">",
"0",
")",
"while",
"@run",
"and",
"@sys_fifo",
".",
"length",
">",
"0",
"p",
"=",
"@sys_fifo",
".",
"shift",
"p",
".",
"dst",
".",
"process_sys_p",
"p",
"end",
"while",
"@run",
"and",
"@app_fifo",
".",
"length",
">",
"0",
"p",
"=",
"@app_fifo",
".",
"shift",
"p",
".",
"dst",
".",
"process_p",
"p",
"break",
"end",
"end",
"stop!",
"end"
] | starts the system mainloop
first Iota#start! is called on each children unless the system is resuming from hibernation
then while there is Particle in the fifo, first process all system Particle then 1 application Particle
after all Iota#stop! is called on each children, unless the system is going into hibernation | [
"starts",
"the",
"system",
"mainloop"
] | 4f065f63125907b3a4f72fbab8722c58ccab41c1 | https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/spin.rb#L208-L224 | train |
jeremyz/edoors-ruby | lib/edoors/spin.rb | Edoors.Spin.hibernate! | def hibernate! path=nil
@hibernation = true
File.open(path||@hibernate_path,'w') do |f| f << JSON.pretty_generate(self) end
end | ruby | def hibernate! path=nil
@hibernation = true
File.open(path||@hibernate_path,'w') do |f| f << JSON.pretty_generate(self) end
end | [
"def",
"hibernate!",
"path",
"=",
"nil",
"@hibernation",
"=",
"true",
"File",
".",
"open",
"(",
"path",
"||",
"@hibernate_path",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"f",
"<<",
"JSON",
".",
"pretty_generate",
"(",
"self",
")",
"end",
"end"
] | sends the system into hibernation
@param [String] path the path to the hibernation file
the system is serialized into JSON data and flushed to disk | [
"sends",
"the",
"system",
"into",
"hibernation"
] | 4f065f63125907b3a4f72fbab8722c58ccab41c1 | https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/spin.rb#L238-L241 | train |
loveablelobster/DwCR | lib/dwca_content_analyzer/column.rb | DwCAContentAnalyzer.Column.collapse | def collapse(types)
return types.first if types.size == 1
return nil if types.empty?
return String if string?(types)
return Float if float?(types)
String
end | ruby | def collapse(types)
return types.first if types.size == 1
return nil if types.empty?
return String if string?(types)
return Float if float?(types)
String
end | [
"def",
"collapse",
"(",
"types",
")",
"return",
"types",
".",
"first",
"if",
"types",
".",
"size",
"==",
"1",
"return",
"nil",
"if",
"types",
".",
"empty?",
"return",
"String",
"if",
"string?",
"(",
"types",
")",
"return",
"Float",
"if",
"float?",
"(",
"types",
")",
"String",
"end"
] | collapses all types encountered in a file's column into a single type | [
"collapses",
"all",
"types",
"encountered",
"in",
"a",
"file",
"s",
"column",
"into",
"a",
"single",
"type"
] | 093e112337bfb664630a0f164c9d9d7552b1e54c | https://github.com/loveablelobster/DwCR/blob/093e112337bfb664630a0f164c9d9d7552b1e54c/lib/dwca_content_analyzer/column.rb#L29-L35 | train |
Mordorreal/SiteAnalyzer | lib/site_analyzer/page.rb | SiteAnalyzer.Page.remote_a | def remote_a
return unless @page_a_tags
remote_a = []
@page_a_tags.uniq.each do |link|
uri = URI(link[0].to_ascii)
if uri && @site_domain
remote_a << link[0] unless uri.host == @site_domain
end
end
remote_a
end | ruby | def remote_a
return unless @page_a_tags
remote_a = []
@page_a_tags.uniq.each do |link|
uri = URI(link[0].to_ascii)
if uri && @site_domain
remote_a << link[0] unless uri.host == @site_domain
end
end
remote_a
end | [
"def",
"remote_a",
"return",
"unless",
"@page_a_tags",
"remote_a",
"=",
"[",
"]",
"@page_a_tags",
".",
"uniq",
".",
"each",
"do",
"|",
"link",
"|",
"uri",
"=",
"URI",
"(",
"link",
"[",
"0",
"]",
".",
"to_ascii",
")",
"if",
"uri",
"&&",
"@site_domain",
"remote_a",
"<<",
"link",
"[",
"0",
"]",
"unless",
"uri",
".",
"host",
"==",
"@site_domain",
"end",
"end",
"remote_a",
"end"
] | get all remote link on page | [
"get",
"all",
"remote",
"link",
"on",
"page"
] | 7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb | https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/page.rb#L37-L47 | train |
Mordorreal/SiteAnalyzer | lib/site_analyzer/page.rb | SiteAnalyzer.Page.fill_data_field! | def fill_data_field!
@all_titles = titles
@meta_data = collect_metadates
@title_h1_h2 = all_titles_h1_h2
@page_text_size = text_size
@page_a_tags = all_a_tags
@meta_desc_content = all_meta_description_content
@h2_text = h2
@hlu = bad_url
@title_good = title_good?
@title_and_h1_good = title_and_h1_good?
@meta_description_good = metadescription_good?
@meta_keywords = keywords_good?
@code_less = code_less?
@meta_title_duplicates = metadates_good?
@have_h2 = h2?
end | ruby | def fill_data_field!
@all_titles = titles
@meta_data = collect_metadates
@title_h1_h2 = all_titles_h1_h2
@page_text_size = text_size
@page_a_tags = all_a_tags
@meta_desc_content = all_meta_description_content
@h2_text = h2
@hlu = bad_url
@title_good = title_good?
@title_and_h1_good = title_and_h1_good?
@meta_description_good = metadescription_good?
@meta_keywords = keywords_good?
@code_less = code_less?
@meta_title_duplicates = metadates_good?
@have_h2 = h2?
end | [
"def",
"fill_data_field!",
"@all_titles",
"=",
"titles",
"@meta_data",
"=",
"collect_metadates",
"@title_h1_h2",
"=",
"all_titles_h1_h2",
"@page_text_size",
"=",
"text_size",
"@page_a_tags",
"=",
"all_a_tags",
"@meta_desc_content",
"=",
"all_meta_description_content",
"@h2_text",
"=",
"h2",
"@hlu",
"=",
"bad_url",
"@title_good",
"=",
"title_good?",
"@title_and_h1_good",
"=",
"title_and_h1_good?",
"@meta_description_good",
"=",
"metadescription_good?",
"@meta_keywords",
"=",
"keywords_good?",
"@code_less",
"=",
"code_less?",
"@meta_title_duplicates",
"=",
"metadates_good?",
"@have_h2",
"=",
"h2?",
"end"
] | fill Page instant with data for report | [
"fill",
"Page",
"instant",
"with",
"data",
"for",
"report"
] | 7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb | https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/page.rb#L52-L68 | train |
Mordorreal/SiteAnalyzer | lib/site_analyzer/page.rb | SiteAnalyzer.Page.get_page | def get_page(url)
timeout(30) do
page = open(url)
@site_domain = page.base_uri.host
@page_path = page.base_uri.request_uri
@page = Nokogiri::HTML(page)
end
rescue Timeout::Error, EOFError, OpenURI::HTTPError, Errno::ENOENT, TypeError
return nil
end | ruby | def get_page(url)
timeout(30) do
page = open(url)
@site_domain = page.base_uri.host
@page_path = page.base_uri.request_uri
@page = Nokogiri::HTML(page)
end
rescue Timeout::Error, EOFError, OpenURI::HTTPError, Errno::ENOENT, TypeError
return nil
end | [
"def",
"get_page",
"(",
"url",
")",
"timeout",
"(",
"30",
")",
"do",
"page",
"=",
"open",
"(",
"url",
")",
"@site_domain",
"=",
"page",
".",
"base_uri",
".",
"host",
"@page_path",
"=",
"page",
".",
"base_uri",
".",
"request_uri",
"@page",
"=",
"Nokogiri",
"::",
"HTML",
"(",
"page",
")",
"end",
"rescue",
"Timeout",
"::",
"Error",
",",
"EOFError",
",",
"OpenURI",
"::",
"HTTPError",
",",
"Errno",
"::",
"ENOENT",
",",
"TypeError",
"return",
"nil",
"end"
] | get page with open-uri, then parse it with Nokogiri. Get site domain and path from URI | [
"get",
"page",
"with",
"open",
"-",
"uri",
"then",
"parse",
"it",
"with",
"Nokogiri",
".",
"Get",
"site",
"domain",
"and",
"path",
"from",
"URI"
] | 7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb | https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/page.rb#L70-L79 | train |
Mordorreal/SiteAnalyzer | lib/site_analyzer/page.rb | SiteAnalyzer.Page.title_and_h1_good? | def title_and_h1_good?
return unless @page
arr = []
@page.css('h1').each { |node| arr << node.text }
@page.css('title').size == 1 && arr.uniq.size == arr.size
end | ruby | def title_and_h1_good?
return unless @page
arr = []
@page.css('h1').each { |node| arr << node.text }
@page.css('title').size == 1 && arr.uniq.size == arr.size
end | [
"def",
"title_and_h1_good?",
"return",
"unless",
"@page",
"arr",
"=",
"[",
"]",
"@page",
".",
"css",
"(",
"'h1'",
")",
".",
"each",
"{",
"|",
"node",
"|",
"arr",
"<<",
"node",
".",
"text",
"}",
"@page",
".",
"css",
"(",
"'title'",
")",
".",
"size",
"==",
"1",
"&&",
"arr",
".",
"uniq",
".",
"size",
"==",
"arr",
".",
"size",
"end"
] | true if title and h1 have no duplicates | [
"true",
"if",
"title",
"and",
"h1",
"have",
"no",
"duplicates"
] | 7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb | https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/page.rb#L85-L90 | train |
Mordorreal/SiteAnalyzer | lib/site_analyzer/page.rb | SiteAnalyzer.Page.metadescription_good? | def metadescription_good?
return unless @page
tags = @page.css("meta[name='description']")
return false if tags.size == 0
tags.each do |t|
unless t['value'].nil?
return false if t['content'].size == 0 || t['content'].size > 200
end
end
true
end | ruby | def metadescription_good?
return unless @page
tags = @page.css("meta[name='description']")
return false if tags.size == 0
tags.each do |t|
unless t['value'].nil?
return false if t['content'].size == 0 || t['content'].size > 200
end
end
true
end | [
"def",
"metadescription_good?",
"return",
"unless",
"@page",
"tags",
"=",
"@page",
".",
"css",
"(",
"\"meta[name='description']\"",
")",
"return",
"false",
"if",
"tags",
".",
"size",
"==",
"0",
"tags",
".",
"each",
"do",
"|",
"t",
"|",
"unless",
"t",
"[",
"'value'",
"]",
".",
"nil?",
"return",
"false",
"if",
"t",
"[",
"'content'",
"]",
".",
"size",
"==",
"0",
"||",
"t",
"[",
"'content'",
"]",
".",
"size",
">",
"200",
"end",
"end",
"true",
"end"
] | true if metadescription less then 200 symbols | [
"true",
"if",
"metadescription",
"less",
"then",
"200",
"symbols"
] | 7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb | https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/page.rb#L92-L102 | train |
Mordorreal/SiteAnalyzer | lib/site_analyzer/page.rb | SiteAnalyzer.Page.code_less? | def code_less?
return unless @page
sum = 0
page_text = @page.text.size
@page.css('script').each do |tag|
sum += tag.text.size
end
sum < page_text / 2
end | ruby | def code_less?
return unless @page
sum = 0
page_text = @page.text.size
@page.css('script').each do |tag|
sum += tag.text.size
end
sum < page_text / 2
end | [
"def",
"code_less?",
"return",
"unless",
"@page",
"sum",
"=",
"0",
"page_text",
"=",
"@page",
".",
"text",
".",
"size",
"@page",
".",
"css",
"(",
"'script'",
")",
".",
"each",
"do",
"|",
"tag",
"|",
"sum",
"+=",
"tag",
".",
"text",
".",
"size",
"end",
"sum",
"<",
"page_text",
"/",
"2",
"end"
] | true if code of page less then text on it | [
"true",
"if",
"code",
"of",
"page",
"less",
"then",
"text",
"on",
"it"
] | 7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb | https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/page.rb#L116-L124 | train |
Mordorreal/SiteAnalyzer | lib/site_analyzer/page.rb | SiteAnalyzer.Page.metadates_good? | def metadates_good?
return unless @page
return false if @all_titles.size > 1 || @meta_data.empty?
node_names = []
@meta_data.each { |node| node_names << node['name'] }
node_names.compact!
node_names.uniq.size == node_names.size unless node_names.nil? || node_names.size < 1
end | ruby | def metadates_good?
return unless @page
return false if @all_titles.size > 1 || @meta_data.empty?
node_names = []
@meta_data.each { |node| node_names << node['name'] }
node_names.compact!
node_names.uniq.size == node_names.size unless node_names.nil? || node_names.size < 1
end | [
"def",
"metadates_good?",
"return",
"unless",
"@page",
"return",
"false",
"if",
"@all_titles",
".",
"size",
">",
"1",
"||",
"@meta_data",
".",
"empty?",
"node_names",
"=",
"[",
"]",
"@meta_data",
".",
"each",
"{",
"|",
"node",
"|",
"node_names",
"<<",
"node",
"[",
"'name'",
"]",
"}",
"node_names",
".",
"compact!",
"node_names",
".",
"uniq",
".",
"size",
"==",
"node_names",
".",
"size",
"unless",
"node_names",
".",
"nil?",
"||",
"node_names",
".",
"size",
"<",
"1",
"end"
] | check meta and title tags duplicates | [
"check",
"meta",
"and",
"title",
"tags",
"duplicates"
] | 7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb | https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/page.rb#L132-L139 | train |
Mordorreal/SiteAnalyzer | lib/site_analyzer/page.rb | SiteAnalyzer.Page.all_titles_h1_h2 | def all_titles_h1_h2
return unless @page
out = []
out << @page.css('title').text << { @page_url => @page.css('h1').text }
out << { @page_url => @page.css('h2').text }
out
end | ruby | def all_titles_h1_h2
return unless @page
out = []
out << @page.css('title').text << { @page_url => @page.css('h1').text }
out << { @page_url => @page.css('h2').text }
out
end | [
"def",
"all_titles_h1_h2",
"return",
"unless",
"@page",
"out",
"=",
"[",
"]",
"out",
"<<",
"@page",
".",
"css",
"(",
"'title'",
")",
".",
"text",
"<<",
"{",
"@page_url",
"=>",
"@page",
".",
"css",
"(",
"'h1'",
")",
".",
"text",
"}",
"out",
"<<",
"{",
"@page_url",
"=>",
"@page",
".",
"css",
"(",
"'h2'",
")",
".",
"text",
"}",
"out",
"end"
] | return hash with all titles, h1 and h2 | [
"return",
"hash",
"with",
"all",
"titles",
"h1",
"and",
"h2"
] | 7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb | https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/page.rb#L141-L147 | train |
Mordorreal/SiteAnalyzer | lib/site_analyzer/page.rb | SiteAnalyzer.Page.all_a_tags | def all_a_tags
return unless @page
tags = []
@page.css('a').each do |node|
tags << [node['href'], node['target'], node['rel']]
end
tags.compact
end | ruby | def all_a_tags
return unless @page
tags = []
@page.css('a').each do |node|
tags << [node['href'], node['target'], node['rel']]
end
tags.compact
end | [
"def",
"all_a_tags",
"return",
"unless",
"@page",
"tags",
"=",
"[",
"]",
"@page",
".",
"css",
"(",
"'a'",
")",
".",
"each",
"do",
"|",
"node",
"|",
"tags",
"<<",
"[",
"node",
"[",
"'href'",
"]",
",",
"node",
"[",
"'target'",
"]",
",",
"node",
"[",
"'rel'",
"]",
"]",
"end",
"tags",
".",
"compact",
"end"
] | get all a tags | [
"get",
"all",
"a",
"tags"
] | 7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb | https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/page.rb#L157-L164 | train |
cajun/smile | lib/smile/common.rb | Smile.Common.default_params | def default_params
@params ||= { :api_key => session.api_key }
@params.merge!( :session_id => session.id ) if( session.id )
@params = Smile::ParamConverter.clean_hash_keys( @params )
end | ruby | def default_params
@params ||= { :api_key => session.api_key }
@params.merge!( :session_id => session.id ) if( session.id )
@params = Smile::ParamConverter.clean_hash_keys( @params )
end | [
"def",
"default_params",
"@params",
"||=",
"{",
":api_key",
"=>",
"session",
".",
"api_key",
"}",
"@params",
".",
"merge!",
"(",
":session_id",
"=>",
"session",
".",
"id",
")",
"if",
"(",
"session",
".",
"id",
")",
"@params",
"=",
"Smile",
"::",
"ParamConverter",
".",
"clean_hash_keys",
"(",
"@params",
")",
"end"
] | This will be included in every request once you have logged in | [
"This",
"will",
"be",
"included",
"in",
"every",
"request",
"once",
"you",
"have",
"logged",
"in"
] | 5a9ffe3d9f46cddf0562d8fe68d892dd785c0bd6 | https://github.com/cajun/smile/blob/5a9ffe3d9f46cddf0562d8fe68d892dd785c0bd6/lib/smile/common.rb#L14-L18 | train |
cajun/smile | lib/smile/common.rb | Smile.Common.base_web_method_call | def base_web_method_call( web_options, options ={}, url )
options = Smile::ParamConverter.clean_hash_keys( options )
web_options = Smile::ParamConverter.clean_hash_keys( web_options )
params = default_params.merge( web_options )
params.merge!( options ) if( options )
logger.info( params.inspect )
json = RestClient.post( url, params ).body
upper_hash_to_lower_hash( Smile::Json.parse( json ) )
end | ruby | def base_web_method_call( web_options, options ={}, url )
options = Smile::ParamConverter.clean_hash_keys( options )
web_options = Smile::ParamConverter.clean_hash_keys( web_options )
params = default_params.merge( web_options )
params.merge!( options ) if( options )
logger.info( params.inspect )
json = RestClient.post( url, params ).body
upper_hash_to_lower_hash( Smile::Json.parse( json ) )
end | [
"def",
"base_web_method_call",
"(",
"web_options",
",",
"options",
"=",
"{",
"}",
",",
"url",
")",
"options",
"=",
"Smile",
"::",
"ParamConverter",
".",
"clean_hash_keys",
"(",
"options",
")",
"web_options",
"=",
"Smile",
"::",
"ParamConverter",
".",
"clean_hash_keys",
"(",
"web_options",
")",
"params",
"=",
"default_params",
".",
"merge",
"(",
"web_options",
")",
"params",
".",
"merge!",
"(",
"options",
")",
"if",
"(",
"options",
")",
"logger",
".",
"info",
"(",
"params",
".",
"inspect",
")",
"json",
"=",
"RestClient",
".",
"post",
"(",
"url",
",",
"params",
")",
".",
"body",
"upper_hash_to_lower_hash",
"(",
"Smile",
"::",
"Json",
".",
"parse",
"(",
"json",
")",
")",
"end"
] | Call either the secure or the base web url | [
"Call",
"either",
"the",
"secure",
"or",
"the",
"base",
"web",
"url"
] | 5a9ffe3d9f46cddf0562d8fe68d892dd785c0bd6 | https://github.com/cajun/smile/blob/5a9ffe3d9f46cddf0562d8fe68d892dd785c0bd6/lib/smile/common.rb#L35-L46 | train |
cajun/smile | lib/smile/common.rb | Smile.Common.upper_hash_to_lower_hash | def upper_hash_to_lower_hash( upper )
case upper
when Hash
upper.inject({}) do |lower,array|
key, value = array
lower[key.downcase] = upper_hash_to_lower_hash( value )
lower
end
else
upper
end
end | ruby | def upper_hash_to_lower_hash( upper )
case upper
when Hash
upper.inject({}) do |lower,array|
key, value = array
lower[key.downcase] = upper_hash_to_lower_hash( value )
lower
end
else
upper
end
end | [
"def",
"upper_hash_to_lower_hash",
"(",
"upper",
")",
"case",
"upper",
"when",
"Hash",
"upper",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"lower",
",",
"array",
"|",
"key",
",",
"value",
"=",
"array",
"lower",
"[",
"key",
".",
"downcase",
"]",
"=",
"upper_hash_to_lower_hash",
"(",
"value",
")",
"lower",
"end",
"else",
"upper",
"end",
"end"
] | This converts a hash that has mixed case
into all lower case | [
"This",
"converts",
"a",
"hash",
"that",
"has",
"mixed",
"case",
"into",
"all",
"lower",
"case"
] | 5a9ffe3d9f46cddf0562d8fe68d892dd785c0bd6 | https://github.com/cajun/smile/blob/5a9ffe3d9f46cddf0562d8fe68d892dd785c0bd6/lib/smile/common.rb#L50-L61 | train |
galetahub/cancan_namespace | lib/cancan_namespace/rule.rb | CanCanNamespace.Rule.relevant? | def relevant?(action, subject, context = nil)
subject = subject.values.first if subject.class == Hash
@match_all || (matches_action?(action) && matches_subject?(subject) && matches_context(context))
end | ruby | def relevant?(action, subject, context = nil)
subject = subject.values.first if subject.class == Hash
@match_all || (matches_action?(action) && matches_subject?(subject) && matches_context(context))
end | [
"def",
"relevant?",
"(",
"action",
",",
"subject",
",",
"context",
"=",
"nil",
")",
"subject",
"=",
"subject",
".",
"values",
".",
"first",
"if",
"subject",
".",
"class",
"==",
"Hash",
"@match_all",
"||",
"(",
"matches_action?",
"(",
"action",
")",
"&&",
"matches_subject?",
"(",
"subject",
")",
"&&",
"matches_context",
"(",
"context",
")",
")",
"end"
] | Matches both the subject and action, not necessarily the conditions | [
"Matches",
"both",
"the",
"subject",
"and",
"action",
"not",
"necessarily",
"the",
"conditions"
] | 87b5ef90e620d7b692414e3cc8ed1c822dfafe8b | https://github.com/galetahub/cancan_namespace/blob/87b5ef90e620d7b692414e3cc8ed1c822dfafe8b/lib/cancan_namespace/rule.rb#L26-L29 | train |
vadviktor/jenkins_junit_builder | lib/jenkins_junit_builder/suite.rb | JenkinsJunitBuilder.Suite.build_report | def build_report
# build cases
builder = Nokogiri::XML::Builder.new do |xml|
xml.testsuites {
testsuite = xml.testsuite {
@cases.each do |tc|
testcase = xml.testcase {
if tc.result_has_message?
result_type = xml.send(tc.result)
result_type[:message] = tc.message if tc.message.present?
end
if tc.system_out.size > 0
xml.send('system-out') { xml.text tc.system_out.to_s }
end
if tc.system_err.size > 0
xml.send('system-err') { xml.text tc.system_err.to_s }
end
}
testcase[:name] = tc.name if tc.name.present?
testcase[:time] = tc.time if tc.time.present?
testcase[:classname] = package if package.present?
if tc.classname.present?
if testcase[:classname].present?
testcase[:classname] = "#{testcase[:classname]}.#{tc.classname}"
else
testcase[:classname] = tc.classname
end
end
end
}
testsuite[:name] = name if name.present?
testsuite[:package] = package if package.present?
}
end
builder.parent.root.to_xml
end | ruby | def build_report
# build cases
builder = Nokogiri::XML::Builder.new do |xml|
xml.testsuites {
testsuite = xml.testsuite {
@cases.each do |tc|
testcase = xml.testcase {
if tc.result_has_message?
result_type = xml.send(tc.result)
result_type[:message] = tc.message if tc.message.present?
end
if tc.system_out.size > 0
xml.send('system-out') { xml.text tc.system_out.to_s }
end
if tc.system_err.size > 0
xml.send('system-err') { xml.text tc.system_err.to_s }
end
}
testcase[:name] = tc.name if tc.name.present?
testcase[:time] = tc.time if tc.time.present?
testcase[:classname] = package if package.present?
if tc.classname.present?
if testcase[:classname].present?
testcase[:classname] = "#{testcase[:classname]}.#{tc.classname}"
else
testcase[:classname] = tc.classname
end
end
end
}
testsuite[:name] = name if name.present?
testsuite[:package] = package if package.present?
}
end
builder.parent.root.to_xml
end | [
"def",
"build_report",
"builder",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Builder",
".",
"new",
"do",
"|",
"xml",
"|",
"xml",
".",
"testsuites",
"{",
"testsuite",
"=",
"xml",
".",
"testsuite",
"{",
"@cases",
".",
"each",
"do",
"|",
"tc",
"|",
"testcase",
"=",
"xml",
".",
"testcase",
"{",
"if",
"tc",
".",
"result_has_message?",
"result_type",
"=",
"xml",
".",
"send",
"(",
"tc",
".",
"result",
")",
"result_type",
"[",
":message",
"]",
"=",
"tc",
".",
"message",
"if",
"tc",
".",
"message",
".",
"present?",
"end",
"if",
"tc",
".",
"system_out",
".",
"size",
">",
"0",
"xml",
".",
"send",
"(",
"'system-out'",
")",
"{",
"xml",
".",
"text",
"tc",
".",
"system_out",
".",
"to_s",
"}",
"end",
"if",
"tc",
".",
"system_err",
".",
"size",
">",
"0",
"xml",
".",
"send",
"(",
"'system-err'",
")",
"{",
"xml",
".",
"text",
"tc",
".",
"system_err",
".",
"to_s",
"}",
"end",
"}",
"testcase",
"[",
":name",
"]",
"=",
"tc",
".",
"name",
"if",
"tc",
".",
"name",
".",
"present?",
"testcase",
"[",
":time",
"]",
"=",
"tc",
".",
"time",
"if",
"tc",
".",
"time",
".",
"present?",
"testcase",
"[",
":classname",
"]",
"=",
"package",
"if",
"package",
".",
"present?",
"if",
"tc",
".",
"classname",
".",
"present?",
"if",
"testcase",
"[",
":classname",
"]",
".",
"present?",
"testcase",
"[",
":classname",
"]",
"=",
"\"#{testcase[:classname]}.#{tc.classname}\"",
"else",
"testcase",
"[",
":classname",
"]",
"=",
"tc",
".",
"classname",
"end",
"end",
"end",
"}",
"testsuite",
"[",
":name",
"]",
"=",
"name",
"if",
"name",
".",
"present?",
"testsuite",
"[",
":package",
"]",
"=",
"package",
"if",
"package",
".",
"present?",
"}",
"end",
"builder",
".",
"parent",
".",
"root",
".",
"to_xml",
"end"
] | In short, this is the XML string that makes the report.
@return [String] XML report | [
"In",
"short",
"this",
"is",
"the",
"XML",
"string",
"that",
"makes",
"the",
"report",
"."
] | 92dae28e2d135bc06f912c92572827850b95a2f0 | https://github.com/vadviktor/jenkins_junit_builder/blob/92dae28e2d135bc06f912c92572827850b95a2f0/lib/jenkins_junit_builder/suite.rb#L23-L65 | train |
vadviktor/jenkins_junit_builder | lib/jenkins_junit_builder/suite.rb | JenkinsJunitBuilder.Suite.write_report_file | def write_report_file
raise FileNotFoundException.new 'There is no report file path specified' if report_path.blank?
report = build_report
if append_report.present? && File.exist?(report_path)
f = File.open(report_path)
existing_xml = Nokogiri::XML(f)
f.close
report = existing_xml.root << Nokogiri::XML(report).at('testsuite')
# formatting
report = format_xml report.to_xml
end
File.write report_path, report
report
end | ruby | def write_report_file
raise FileNotFoundException.new 'There is no report file path specified' if report_path.blank?
report = build_report
if append_report.present? && File.exist?(report_path)
f = File.open(report_path)
existing_xml = Nokogiri::XML(f)
f.close
report = existing_xml.root << Nokogiri::XML(report).at('testsuite')
# formatting
report = format_xml report.to_xml
end
File.write report_path, report
report
end | [
"def",
"write_report_file",
"raise",
"FileNotFoundException",
".",
"new",
"'There is no report file path specified'",
"if",
"report_path",
".",
"blank?",
"report",
"=",
"build_report",
"if",
"append_report",
".",
"present?",
"&&",
"File",
".",
"exist?",
"(",
"report_path",
")",
"f",
"=",
"File",
".",
"open",
"(",
"report_path",
")",
"existing_xml",
"=",
"Nokogiri",
"::",
"XML",
"(",
"f",
")",
"f",
".",
"close",
"report",
"=",
"existing_xml",
".",
"root",
"<<",
"Nokogiri",
"::",
"XML",
"(",
"report",
")",
".",
"at",
"(",
"'testsuite'",
")",
"report",
"=",
"format_xml",
"report",
".",
"to_xml",
"end",
"File",
".",
"write",
"report_path",
",",
"report",
"report",
"end"
] | Writes the report to the specified file
also returns the new XML report content
@return [String] final XML report content | [
"Writes",
"the",
"report",
"to",
"the",
"specified",
"file",
"also",
"returns",
"the",
"new",
"XML",
"report",
"content"
] | 92dae28e2d135bc06f912c92572827850b95a2f0 | https://github.com/vadviktor/jenkins_junit_builder/blob/92dae28e2d135bc06f912c92572827850b95a2f0/lib/jenkins_junit_builder/suite.rb#L71-L89 | train |
checkdin/checkdin-ruby | lib/checkdin/client.rb | Checkdin.Client.return_error_or_body | def return_error_or_body(response)
if response.status / 100 == 2
response.body
else
raise Checkdin::APIError.new(response.status, response.body)
end
end | ruby | def return_error_or_body(response)
if response.status / 100 == 2
response.body
else
raise Checkdin::APIError.new(response.status, response.body)
end
end | [
"def",
"return_error_or_body",
"(",
"response",
")",
"if",
"response",
".",
"status",
"/",
"100",
"==",
"2",
"response",
".",
"body",
"else",
"raise",
"Checkdin",
"::",
"APIError",
".",
"new",
"(",
"response",
".",
"status",
",",
"response",
".",
"body",
")",
"end",
"end"
] | Helper method to return errors or desired response data as appropriate.
Added just for convenience to avoid having to traverse farther down the response just to get to returned data. | [
"Helper",
"method",
"to",
"return",
"errors",
"or",
"desired",
"response",
"data",
"as",
"appropriate",
"."
] | c3c4b38b0f8c710e1f805100dcf3a70649215b48 | https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/client.rb#L69-L75 | train |
michaelmior/mipper | lib/mipper/cbc/model.rb | MIPPeR.CbcModel.set_variable_bounds | def set_variable_bounds(var_index, lb, ub, force = false)
# This is a bit of a hack so that we don't try to set
# the variable bounds before they get added to the model
return unless force
Cbc.Cbc_setColLower @ptr, var_index, lb
Cbc.Cbc_setColUpper @ptr, var_index, ub
end | ruby | def set_variable_bounds(var_index, lb, ub, force = false)
# This is a bit of a hack so that we don't try to set
# the variable bounds before they get added to the model
return unless force
Cbc.Cbc_setColLower @ptr, var_index, lb
Cbc.Cbc_setColUpper @ptr, var_index, ub
end | [
"def",
"set_variable_bounds",
"(",
"var_index",
",",
"lb",
",",
"ub",
",",
"force",
"=",
"false",
")",
"return",
"unless",
"force",
"Cbc",
".",
"Cbc_setColLower",
"@ptr",
",",
"var_index",
",",
"lb",
"Cbc",
".",
"Cbc_setColUpper",
"@ptr",
",",
"var_index",
",",
"ub",
"end"
] | Set the bounds of a variable in the model | [
"Set",
"the",
"bounds",
"of",
"a",
"variable",
"in",
"the",
"model"
] | 4ab7f8b32c27f33fc5121756554a0a28d2077e06 | https://github.com/michaelmior/mipper/blob/4ab7f8b32c27f33fc5121756554a0a28d2077e06/lib/mipper/cbc/model.rb#L67-L74 | train |
michaelmior/mipper | lib/mipper/cbc/model.rb | MIPPeR.CbcModel.new_model | def new_model
ptr = FFI::AutoPointer.new Cbc.Cbc_newModel,
Cbc.method(:Cbc_deleteModel)
# Older versions of COIN-OR do not support setting the log level via
# the C interface in which case setParameter will not be defined
Cbc.Cbc_setParameter ptr, 'logLevel', '0' \
if Cbc.respond_to?(:Cbc_setParameter)
ptr
end | ruby | def new_model
ptr = FFI::AutoPointer.new Cbc.Cbc_newModel,
Cbc.method(:Cbc_deleteModel)
# Older versions of COIN-OR do not support setting the log level via
# the C interface in which case setParameter will not be defined
Cbc.Cbc_setParameter ptr, 'logLevel', '0' \
if Cbc.respond_to?(:Cbc_setParameter)
ptr
end | [
"def",
"new_model",
"ptr",
"=",
"FFI",
"::",
"AutoPointer",
".",
"new",
"Cbc",
".",
"Cbc_newModel",
",",
"Cbc",
".",
"method",
"(",
":Cbc_deleteModel",
")",
"Cbc",
".",
"Cbc_setParameter",
"ptr",
",",
"'logLevel'",
",",
"'0'",
"if",
"Cbc",
".",
"respond_to?",
"(",
":Cbc_setParameter",
")",
"ptr",
"end"
] | Construct a new model object | [
"Construct",
"a",
"new",
"model",
"object"
] | 4ab7f8b32c27f33fc5121756554a0a28d2077e06 | https://github.com/michaelmior/mipper/blob/4ab7f8b32c27f33fc5121756554a0a28d2077e06/lib/mipper/cbc/model.rb#L106-L116 | train |
michaelmior/mipper | lib/mipper/cbc/model.rb | MIPPeR.CbcModel.build_constraint_matrix | def build_constraint_matrix(constrs)
store_constraint_indexes constrs
# Construct a matrix of non-zero values in CSC format
start = []
index = []
value = []
col_start = 0
@variables.each do |var|
# Mark the start of this column
start << col_start
var.constraints.each do |constr|
col_start += 1
index << constr.index
value << constr.expression.terms[var]
end
end
start << col_start
[start, index, value]
end | ruby | def build_constraint_matrix(constrs)
store_constraint_indexes constrs
# Construct a matrix of non-zero values in CSC format
start = []
index = []
value = []
col_start = 0
@variables.each do |var|
# Mark the start of this column
start << col_start
var.constraints.each do |constr|
col_start += 1
index << constr.index
value << constr.expression.terms[var]
end
end
start << col_start
[start, index, value]
end | [
"def",
"build_constraint_matrix",
"(",
"constrs",
")",
"store_constraint_indexes",
"constrs",
"start",
"=",
"[",
"]",
"index",
"=",
"[",
"]",
"value",
"=",
"[",
"]",
"col_start",
"=",
"0",
"@variables",
".",
"each",
"do",
"|",
"var",
"|",
"start",
"<<",
"col_start",
"var",
".",
"constraints",
".",
"each",
"do",
"|",
"constr",
"|",
"col_start",
"+=",
"1",
"index",
"<<",
"constr",
".",
"index",
"value",
"<<",
"constr",
".",
"expression",
".",
"terms",
"[",
"var",
"]",
"end",
"end",
"start",
"<<",
"col_start",
"[",
"start",
",",
"index",
",",
"value",
"]",
"end"
] | Build a constraint matrix for the currently existing variables | [
"Build",
"a",
"constraint",
"matrix",
"for",
"the",
"currently",
"existing",
"variables"
] | 4ab7f8b32c27f33fc5121756554a0a28d2077e06 | https://github.com/michaelmior/mipper/blob/4ab7f8b32c27f33fc5121756554a0a28d2077e06/lib/mipper/cbc/model.rb#L128-L149 | train |
michaelmior/mipper | lib/mipper/cbc/model.rb | MIPPeR.CbcModel.store_model | def store_model(constrs, vars)
# Store all constraints
constrs.each do |constr|
store_constraint constr
@constraints << constr
end
# We store variables now since they didn't exist earlier
vars.each_with_index do |var, i|
var.index = i
var.model = self
store_variable var
end
end | ruby | def store_model(constrs, vars)
# Store all constraints
constrs.each do |constr|
store_constraint constr
@constraints << constr
end
# We store variables now since they didn't exist earlier
vars.each_with_index do |var, i|
var.index = i
var.model = self
store_variable var
end
end | [
"def",
"store_model",
"(",
"constrs",
",",
"vars",
")",
"constrs",
".",
"each",
"do",
"|",
"constr",
"|",
"store_constraint",
"constr",
"@constraints",
"<<",
"constr",
"end",
"vars",
".",
"each_with_index",
"do",
"|",
"var",
",",
"i",
"|",
"var",
".",
"index",
"=",
"i",
"var",
".",
"model",
"=",
"self",
"store_variable",
"var",
"end",
"end"
] | Store all data for the model | [
"Store",
"all",
"data",
"for",
"the",
"model"
] | 4ab7f8b32c27f33fc5121756554a0a28d2077e06 | https://github.com/michaelmior/mipper/blob/4ab7f8b32c27f33fc5121756554a0a28d2077e06/lib/mipper/cbc/model.rb#L152-L165 | train |
michaelmior/mipper | lib/mipper/cbc/model.rb | MIPPeR.CbcModel.store_constraint_bounds | def store_constraint_bounds(index, sense, rhs)
case sense
when :==
lb = ub = rhs
when :>=
lb = rhs
ub = Float::INFINITY
when :<=
lb = -Float::INFINITY
ub = rhs
end
Cbc.Cbc_setRowLower @ptr, index, lb
Cbc.Cbc_setRowUpper @ptr, index, ub
end | ruby | def store_constraint_bounds(index, sense, rhs)
case sense
when :==
lb = ub = rhs
when :>=
lb = rhs
ub = Float::INFINITY
when :<=
lb = -Float::INFINITY
ub = rhs
end
Cbc.Cbc_setRowLower @ptr, index, lb
Cbc.Cbc_setRowUpper @ptr, index, ub
end | [
"def",
"store_constraint_bounds",
"(",
"index",
",",
"sense",
",",
"rhs",
")",
"case",
"sense",
"when",
":==",
"lb",
"=",
"ub",
"=",
"rhs",
"when",
":>=",
"lb",
"=",
"rhs",
"ub",
"=",
"Float",
"::",
"INFINITY",
"when",
":<=",
"lb",
"=",
"-",
"Float",
"::",
"INFINITY",
"ub",
"=",
"rhs",
"end",
"Cbc",
".",
"Cbc_setRowLower",
"@ptr",
",",
"index",
",",
"lb",
"Cbc",
".",
"Cbc_setRowUpper",
"@ptr",
",",
"index",
",",
"ub",
"end"
] | Store the bounds for a given constraint | [
"Store",
"the",
"bounds",
"for",
"a",
"given",
"constraint"
] | 4ab7f8b32c27f33fc5121756554a0a28d2077e06 | https://github.com/michaelmior/mipper/blob/4ab7f8b32c27f33fc5121756554a0a28d2077e06/lib/mipper/cbc/model.rb#L212-L226 | train |
michaelmior/mipper | lib/mipper/cbc/model.rb | MIPPeR.CbcModel.store_variable | def store_variable(var)
# Force the correct bounds since we can't explicitly specify binary
if var.type == :binary
var.instance_variable_set(:@lower_bound, 0)
var.instance_variable_set(:@upper_bound, 1)
end
set_variable_bounds var.index, var.lower_bound, var.upper_bound, true
Cbc.Cbc_setObjCoeff @ptr, var.index, var.coefficient
Cbc.Cbc_setColName(@ptr, var.index, var.name) unless var.name.nil?
set_variable_type var.index, var.type
end | ruby | def store_variable(var)
# Force the correct bounds since we can't explicitly specify binary
if var.type == :binary
var.instance_variable_set(:@lower_bound, 0)
var.instance_variable_set(:@upper_bound, 1)
end
set_variable_bounds var.index, var.lower_bound, var.upper_bound, true
Cbc.Cbc_setObjCoeff @ptr, var.index, var.coefficient
Cbc.Cbc_setColName(@ptr, var.index, var.name) unless var.name.nil?
set_variable_type var.index, var.type
end | [
"def",
"store_variable",
"(",
"var",
")",
"if",
"var",
".",
"type",
"==",
":binary",
"var",
".",
"instance_variable_set",
"(",
":@lower_bound",
",",
"0",
")",
"var",
".",
"instance_variable_set",
"(",
":@upper_bound",
",",
"1",
")",
"end",
"set_variable_bounds",
"var",
".",
"index",
",",
"var",
".",
"lower_bound",
",",
"var",
".",
"upper_bound",
",",
"true",
"Cbc",
".",
"Cbc_setObjCoeff",
"@ptr",
",",
"var",
".",
"index",
",",
"var",
".",
"coefficient",
"Cbc",
".",
"Cbc_setColName",
"(",
"@ptr",
",",
"var",
".",
"index",
",",
"var",
".",
"name",
")",
"unless",
"var",
".",
"name",
".",
"nil?",
"set_variable_type",
"var",
".",
"index",
",",
"var",
".",
"type",
"end"
] | Set the properties of a variable in the model | [
"Set",
"the",
"properties",
"of",
"a",
"variable",
"in",
"the",
"model"
] | 4ab7f8b32c27f33fc5121756554a0a28d2077e06 | https://github.com/michaelmior/mipper/blob/4ab7f8b32c27f33fc5121756554a0a28d2077e06/lib/mipper/cbc/model.rb#L229-L240 | train |
robotex82/ecm_calendar_helper | app/helpers/ecm/calendar_helper.rb | Ecm.CalendarHelper.month_calendar | def month_calendar(date = Time.zone.now.to_date, elements = [], options = {})
options.reverse_merge! :date_method => :start_at, :display_method => :to_s, :link_elements => true, :start_day => :sunday, start_date_method: nil, end_date_method: nil
display_method = options.delete(:display_method)
link_elements = options.delete(:link_elements)
start_date_method = options.delete(:start_date_method)
end_date_method = options.delete(:end_date_method)
# calculate beginning and end of month
beginning_of_month = date.beginning_of_month.to_date
end_of_month = date.end_of_month.to_date
# Get localized day names
localized_day_names = I18n.t('date.abbr_day_names').dup
# Shift day names to suite start day
english_day_names = [:sunday, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday]
# Raise an exception if the passed start day is not an english day name
raise ":start_day option for month_calendar must be in: #{english_day_names.join(', ')}, but you passed: #{options[:start_day].to_s} (class: #{options[:start_day].class.to_s})" unless english_day_names.include?(options[:start_day])
# Get the offset of start day
offset = english_day_names.index(options[:start_day])
last_day_of_week = Time.zone.now.end_of_week.wday
# Change calendar heading if offset is not 0 (offset 0 means sunday is the first day of the week)
offset.times do
localized_day_names.push(localized_day_names.shift)
end
days_by_week = {}
first_day = beginning_of_month.beginning_of_week
last_day = end_of_month.end_of_week
days = (first_day..last_day).each_with_object({}).with_index do |(day, memo), index|
memo[day.to_date] = elements.find_all do |e|
if start_date_method.present? && end_date_method.present?
day.to_date.between?(e.send(start_date_method), e.send(end_date_method))
else
e.send(options[:date_method]).to_date == day.to_date
end
end || {}
end
days_by_week = days.each_with_object({}) { |(k, v), m| (m[k.cweek] ||= {})[k] = v }
render partial: 'ecm/calendar_helper/month_calendar', locals: { localized_day_names: localized_day_names, days_by_week: days_by_week, display_method: display_method, link_elements: link_elements }
end | ruby | def month_calendar(date = Time.zone.now.to_date, elements = [], options = {})
options.reverse_merge! :date_method => :start_at, :display_method => :to_s, :link_elements => true, :start_day => :sunday, start_date_method: nil, end_date_method: nil
display_method = options.delete(:display_method)
link_elements = options.delete(:link_elements)
start_date_method = options.delete(:start_date_method)
end_date_method = options.delete(:end_date_method)
# calculate beginning and end of month
beginning_of_month = date.beginning_of_month.to_date
end_of_month = date.end_of_month.to_date
# Get localized day names
localized_day_names = I18n.t('date.abbr_day_names').dup
# Shift day names to suite start day
english_day_names = [:sunday, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday]
# Raise an exception if the passed start day is not an english day name
raise ":start_day option for month_calendar must be in: #{english_day_names.join(', ')}, but you passed: #{options[:start_day].to_s} (class: #{options[:start_day].class.to_s})" unless english_day_names.include?(options[:start_day])
# Get the offset of start day
offset = english_day_names.index(options[:start_day])
last_day_of_week = Time.zone.now.end_of_week.wday
# Change calendar heading if offset is not 0 (offset 0 means sunday is the first day of the week)
offset.times do
localized_day_names.push(localized_day_names.shift)
end
days_by_week = {}
first_day = beginning_of_month.beginning_of_week
last_day = end_of_month.end_of_week
days = (first_day..last_day).each_with_object({}).with_index do |(day, memo), index|
memo[day.to_date] = elements.find_all do |e|
if start_date_method.present? && end_date_method.present?
day.to_date.between?(e.send(start_date_method), e.send(end_date_method))
else
e.send(options[:date_method]).to_date == day.to_date
end
end || {}
end
days_by_week = days.each_with_object({}) { |(k, v), m| (m[k.cweek] ||= {})[k] = v }
render partial: 'ecm/calendar_helper/month_calendar', locals: { localized_day_names: localized_day_names, days_by_week: days_by_week, display_method: display_method, link_elements: link_elements }
end | [
"def",
"month_calendar",
"(",
"date",
"=",
"Time",
".",
"zone",
".",
"now",
".",
"to_date",
",",
"elements",
"=",
"[",
"]",
",",
"options",
"=",
"{",
"}",
")",
"options",
".",
"reverse_merge!",
":date_method",
"=>",
":start_at",
",",
":display_method",
"=>",
":to_s",
",",
":link_elements",
"=>",
"true",
",",
":start_day",
"=>",
":sunday",
",",
"start_date_method",
":",
"nil",
",",
"end_date_method",
":",
"nil",
"display_method",
"=",
"options",
".",
"delete",
"(",
":display_method",
")",
"link_elements",
"=",
"options",
".",
"delete",
"(",
":link_elements",
")",
"start_date_method",
"=",
"options",
".",
"delete",
"(",
":start_date_method",
")",
"end_date_method",
"=",
"options",
".",
"delete",
"(",
":end_date_method",
")",
"beginning_of_month",
"=",
"date",
".",
"beginning_of_month",
".",
"to_date",
"end_of_month",
"=",
"date",
".",
"end_of_month",
".",
"to_date",
"localized_day_names",
"=",
"I18n",
".",
"t",
"(",
"'date.abbr_day_names'",
")",
".",
"dup",
"english_day_names",
"=",
"[",
":sunday",
",",
":monday",
",",
":tuesday",
",",
":wednesday",
",",
":thursday",
",",
":friday",
",",
":saturday",
"]",
"raise",
"\":start_day option for month_calendar must be in: #{english_day_names.join(', ')}, but you passed: #{options[:start_day].to_s} (class: #{options[:start_day].class.to_s})\"",
"unless",
"english_day_names",
".",
"include?",
"(",
"options",
"[",
":start_day",
"]",
")",
"offset",
"=",
"english_day_names",
".",
"index",
"(",
"options",
"[",
":start_day",
"]",
")",
"last_day_of_week",
"=",
"Time",
".",
"zone",
".",
"now",
".",
"end_of_week",
".",
"wday",
"offset",
".",
"times",
"do",
"localized_day_names",
".",
"push",
"(",
"localized_day_names",
".",
"shift",
")",
"end",
"days_by_week",
"=",
"{",
"}",
"first_day",
"=",
"beginning_of_month",
".",
"beginning_of_week",
"last_day",
"=",
"end_of_month",
".",
"end_of_week",
"days",
"=",
"(",
"first_day",
"..",
"last_day",
")",
".",
"each_with_object",
"(",
"{",
"}",
")",
".",
"with_index",
"do",
"|",
"(",
"day",
",",
"memo",
")",
",",
"index",
"|",
"memo",
"[",
"day",
".",
"to_date",
"]",
"=",
"elements",
".",
"find_all",
"do",
"|",
"e",
"|",
"if",
"start_date_method",
".",
"present?",
"&&",
"end_date_method",
".",
"present?",
"day",
".",
"to_date",
".",
"between?",
"(",
"e",
".",
"send",
"(",
"start_date_method",
")",
",",
"e",
".",
"send",
"(",
"end_date_method",
")",
")",
"else",
"e",
".",
"send",
"(",
"options",
"[",
":date_method",
"]",
")",
".",
"to_date",
"==",
"day",
".",
"to_date",
"end",
"end",
"||",
"{",
"}",
"end",
"days_by_week",
"=",
"days",
".",
"each_with_object",
"(",
"{",
"}",
")",
"{",
"|",
"(",
"k",
",",
"v",
")",
",",
"m",
"|",
"(",
"m",
"[",
"k",
".",
"cweek",
"]",
"||=",
"{",
"}",
")",
"[",
"k",
"]",
"=",
"v",
"}",
"render",
"partial",
":",
"'ecm/calendar_helper/month_calendar'",
",",
"locals",
":",
"{",
"localized_day_names",
":",
"localized_day_names",
",",
"days_by_week",
":",
"days_by_week",
",",
"display_method",
":",
"display_method",
",",
"link_elements",
":",
"link_elements",
"}",
"end"
] | renders a calendar table
Example with elements that span more than 1 day:
= month_calendar @date, @reservations, start_date_method: :start_at, end_date_method: :end_at
Example of using a lamda as display method:
= month_calendar(display_method: ->(context, resource) { context.link_to(resource.booker.human, resource.booker) }) | [
"renders",
"a",
"calendar",
"table"
] | 2bf66f370d0de1162705aa3c1f77559ad9386cb0 | https://github.com/robotex82/ecm_calendar_helper/blob/2bf66f370d0de1162705aa3c1f77559ad9386cb0/app/helpers/ecm/calendar_helper.rb#L13-L62 | train |
dominikh/weechat-ruby | lib/weechat/buffer.rb | Weechat.Buffer.command | def command(*parts)
parts[0][0,0] = '/' unless parts[0][0..0] == '/'
line = parts.join(" ")
Weechat.exec(line, self)
line
end | ruby | def command(*parts)
parts[0][0,0] = '/' unless parts[0][0..0] == '/'
line = parts.join(" ")
Weechat.exec(line, self)
line
end | [
"def",
"command",
"(",
"*",
"parts",
")",
"parts",
"[",
"0",
"]",
"[",
"0",
",",
"0",
"]",
"=",
"'/'",
"unless",
"parts",
"[",
"0",
"]",
"[",
"0",
"..",
"0",
"]",
"==",
"'/'",
"line",
"=",
"parts",
".",
"join",
"(",
"\" \"",
")",
"Weechat",
".",
"exec",
"(",
"line",
",",
"self",
")",
"line",
"end"
] | Send a command to the current buffer.
Note: If the given command does not start with a slash, one will be added.
@param [Array<String>] *parts All parts of the command to send
@return [String] The whole command as sent to the buffer
@example
my_buffer.command("/whois", "dominikh") | [
"Send",
"a",
"command",
"to",
"the",
"current",
"buffer",
"."
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat/buffer.rb#L377-L382 | train |
dominikh/weechat-ruby | lib/weechat/buffer.rb | Weechat.Buffer.send | def send(*text)
text[0][0,0] = '/' if text[0][0..0] == '/'
line = text.join(" ")
Weechat.exec(line)
line
end | ruby | def send(*text)
text[0][0,0] = '/' if text[0][0..0] == '/'
line = text.join(" ")
Weechat.exec(line)
line
end | [
"def",
"send",
"(",
"*",
"text",
")",
"text",
"[",
"0",
"]",
"[",
"0",
",",
"0",
"]",
"=",
"'/'",
"if",
"text",
"[",
"0",
"]",
"[",
"0",
"..",
"0",
"]",
"==",
"'/'",
"line",
"=",
"text",
".",
"join",
"(",
"\" \"",
")",
"Weechat",
".",
"exec",
"(",
"line",
")",
"line",
"end"
] | Send a text to the buffer. If the buffer represents a channel, the text
will be send as a message to the channel.
Note: this method will automatically escape a leading slash, if present.
@param [Array<String>] *text All parts of the text to send
@return [String] The whole string as sent to the buffer | [
"Send",
"a",
"text",
"to",
"the",
"buffer",
".",
"If",
"the",
"buffer",
"represents",
"a",
"channel",
"the",
"text",
"will",
"be",
"send",
"as",
"a",
"message",
"to",
"the",
"channel",
"."
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat/buffer.rb#L394-L399 | train |
dominikh/weechat-ruby | lib/weechat/buffer.rb | Weechat.Buffer.lines | def lines(strip_colors = false)
lines = []
Weechat::Infolist.parse("buffer_lines", @ptr).each do |line|
line = Weechat::Line.from_hash(line)
if strip_colors
line.prefix.strip_colors!
line.message.strip_colors!
end
lines << line
end
lines
end | ruby | def lines(strip_colors = false)
lines = []
Weechat::Infolist.parse("buffer_lines", @ptr).each do |line|
line = Weechat::Line.from_hash(line)
if strip_colors
line.prefix.strip_colors!
line.message.strip_colors!
end
lines << line
end
lines
end | [
"def",
"lines",
"(",
"strip_colors",
"=",
"false",
")",
"lines",
"=",
"[",
"]",
"Weechat",
"::",
"Infolist",
".",
"parse",
"(",
"\"buffer_lines\"",
",",
"@ptr",
")",
".",
"each",
"do",
"|",
"line",
"|",
"line",
"=",
"Weechat",
"::",
"Line",
".",
"from_hash",
"(",
"line",
")",
"if",
"strip_colors",
"line",
".",
"prefix",
".",
"strip_colors!",
"line",
".",
"message",
".",
"strip_colors!",
"end",
"lines",
"<<",
"line",
"end",
"lines",
"end"
] | Returns an array with all lines of the buffer.
@param [Boolean] strip_colors Whether to strip out all color codes
@return [Array<Line>] The lines
@see #text | [
"Returns",
"an",
"array",
"with",
"all",
"lines",
"of",
"the",
"buffer",
"."
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat/buffer.rb#L470-L482 | train |
dominikh/weechat-ruby | lib/weechat/buffer.rb | Weechat.Buffer.bind_keys | def bind_keys(*args)
keys = args[0..-2]
command = args[-1]
keychain = keys.join("-")
if command.is_a? Command
command = command.command
end
set("key_bind_#{keychain}", command)
@keybinds[keys] = command
keychain
end | ruby | def bind_keys(*args)
keys = args[0..-2]
command = args[-1]
keychain = keys.join("-")
if command.is_a? Command
command = command.command
end
set("key_bind_#{keychain}", command)
@keybinds[keys] = command
keychain
end | [
"def",
"bind_keys",
"(",
"*",
"args",
")",
"keys",
"=",
"args",
"[",
"0",
"..",
"-",
"2",
"]",
"command",
"=",
"args",
"[",
"-",
"1",
"]",
"keychain",
"=",
"keys",
".",
"join",
"(",
"\"-\"",
")",
"if",
"command",
".",
"is_a?",
"Command",
"command",
"=",
"command",
".",
"command",
"end",
"set",
"(",
"\"key_bind_#{keychain}\"",
",",
"command",
")",
"@keybinds",
"[",
"keys",
"]",
"=",
"command",
"keychain",
"end"
] | Bind keys to a command.
@param [Array<String>] keys An array of keys which will be used to build a keychain
@param [String, Command] command The command to execute when the keys are being pressed
@return [String] The keychain
@see #unbind_keys | [
"Bind",
"keys",
"to",
"a",
"command",
"."
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat/buffer.rb#L510-L521 | train |
agrobbin/google-api | lib/google-api/api.rb | GoogleAPI.API.request | def request(method, url = nil, options = {})
options[:headers] = {'Content-Type' => 'application/json'}.merge(options[:headers] || {})
options[:body] = options[:body].to_json if options[:body].is_a?(Hash)
# Adopt Google's API erorr handling recommendation here:
# https://developers.google.com/drive/handle-errors#implementing_exponential_backoff
#
# In essence, we try 5 times to perform the request. With each subsequent request,
# we wait 2^n seconds plus a random number of milliseconds (no greater than 1 second)
# until either we receive a successful response, or we run out of attempts.
# If the Retry-After header is in the error response, we use whichever happens to be
# greater, our calculated wait time, or the value in the Retry-After header.
#
# If development_mode is set to true, we only run the request once. This speeds up
# development for those using this gem.
attempt = 0
max_attempts = GoogleAPI.development_mode ? 1 : 5
while attempt < max_attempts
response = access_token.send(method.to_sym, url, options)
seconds_to_wait = [((2 ** attempt) + rand), response.headers['Retry-After'].to_i].max
attempt += 1
break if response.status < 400 || attempt == max_attempts
GoogleAPI.logger.error "Request attempt ##{attempt} to #{url} failed for. Trying again in #{seconds_to_wait} seconds..."
sleep seconds_to_wait
end
response.parsed || response
end | ruby | def request(method, url = nil, options = {})
options[:headers] = {'Content-Type' => 'application/json'}.merge(options[:headers] || {})
options[:body] = options[:body].to_json if options[:body].is_a?(Hash)
# Adopt Google's API erorr handling recommendation here:
# https://developers.google.com/drive/handle-errors#implementing_exponential_backoff
#
# In essence, we try 5 times to perform the request. With each subsequent request,
# we wait 2^n seconds plus a random number of milliseconds (no greater than 1 second)
# until either we receive a successful response, or we run out of attempts.
# If the Retry-After header is in the error response, we use whichever happens to be
# greater, our calculated wait time, or the value in the Retry-After header.
#
# If development_mode is set to true, we only run the request once. This speeds up
# development for those using this gem.
attempt = 0
max_attempts = GoogleAPI.development_mode ? 1 : 5
while attempt < max_attempts
response = access_token.send(method.to_sym, url, options)
seconds_to_wait = [((2 ** attempt) + rand), response.headers['Retry-After'].to_i].max
attempt += 1
break if response.status < 400 || attempt == max_attempts
GoogleAPI.logger.error "Request attempt ##{attempt} to #{url} failed for. Trying again in #{seconds_to_wait} seconds..."
sleep seconds_to_wait
end
response.parsed || response
end | [
"def",
"request",
"(",
"method",
",",
"url",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":headers",
"]",
"=",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
".",
"merge",
"(",
"options",
"[",
":headers",
"]",
"||",
"{",
"}",
")",
"options",
"[",
":body",
"]",
"=",
"options",
"[",
":body",
"]",
".",
"to_json",
"if",
"options",
"[",
":body",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"attempt",
"=",
"0",
"max_attempts",
"=",
"GoogleAPI",
".",
"development_mode",
"?",
"1",
":",
"5",
"while",
"attempt",
"<",
"max_attempts",
"response",
"=",
"access_token",
".",
"send",
"(",
"method",
".",
"to_sym",
",",
"url",
",",
"options",
")",
"seconds_to_wait",
"=",
"[",
"(",
"(",
"2",
"**",
"attempt",
")",
"+",
"rand",
")",
",",
"response",
".",
"headers",
"[",
"'Retry-After'",
"]",
".",
"to_i",
"]",
".",
"max",
"attempt",
"+=",
"1",
"break",
"if",
"response",
".",
"status",
"<",
"400",
"||",
"attempt",
"==",
"max_attempts",
"GoogleAPI",
".",
"logger",
".",
"error",
"\"Request attempt ##{attempt} to #{url} failed for. Trying again in #{seconds_to_wait} seconds...\"",
"sleep",
"seconds_to_wait",
"end",
"response",
".",
"parsed",
"||",
"response",
"end"
] | A really important part of this class. The headers are injected here,
and the body is transformed into a JSON'd string when necessary.
We do exponential back-off for error responses, and return a parsed
response body if present, the full Response object if not. | [
"A",
"really",
"important",
"part",
"of",
"this",
"class",
".",
"The",
"headers",
"are",
"injected",
"here",
"and",
"the",
"body",
"is",
"transformed",
"into",
"a",
"JSON",
"d",
"string",
"when",
"necessary",
".",
"We",
"do",
"exponential",
"back",
"-",
"off",
"for",
"error",
"responses",
"and",
"return",
"a",
"parsed",
"response",
"body",
"if",
"present",
"the",
"full",
"Response",
"object",
"if",
"not",
"."
] | 8d9577a476b018c964c803ea0485ed3d221540be | https://github.com/agrobbin/google-api/blob/8d9577a476b018c964c803ea0485ed3d221540be/lib/google-api/api.rb#L49-L76 | train |
agrobbin/google-api | lib/google-api/api.rb | GoogleAPI.API.upload | def upload(api_method, url, options = {})
mime_type = ::MIME::Types.type_for(options[:media]).first.to_s
file = File.read(options.delete(:media))
options[:body][:mimeType] = mime_type
options[:headers] = (options[:headers] || {}).merge({'X-Upload-Content-Type' => mime_type})
response = request(api_method, url, options)
options[:body] = file
options[:headers].delete('X-Upload-Content-Type')
options[:headers].merge!({'Content-Type' => mime_type, 'Content-Length' => file.bytesize.to_s})
request(:put, response.headers['Location'], options)
end | ruby | def upload(api_method, url, options = {})
mime_type = ::MIME::Types.type_for(options[:media]).first.to_s
file = File.read(options.delete(:media))
options[:body][:mimeType] = mime_type
options[:headers] = (options[:headers] || {}).merge({'X-Upload-Content-Type' => mime_type})
response = request(api_method, url, options)
options[:body] = file
options[:headers].delete('X-Upload-Content-Type')
options[:headers].merge!({'Content-Type' => mime_type, 'Content-Length' => file.bytesize.to_s})
request(:put, response.headers['Location'], options)
end | [
"def",
"upload",
"(",
"api_method",
",",
"url",
",",
"options",
"=",
"{",
"}",
")",
"mime_type",
"=",
"::",
"MIME",
"::",
"Types",
".",
"type_for",
"(",
"options",
"[",
":media",
"]",
")",
".",
"first",
".",
"to_s",
"file",
"=",
"File",
".",
"read",
"(",
"options",
".",
"delete",
"(",
":media",
")",
")",
"options",
"[",
":body",
"]",
"[",
":mimeType",
"]",
"=",
"mime_type",
"options",
"[",
":headers",
"]",
"=",
"(",
"options",
"[",
":headers",
"]",
"||",
"{",
"}",
")",
".",
"merge",
"(",
"{",
"'X-Upload-Content-Type'",
"=>",
"mime_type",
"}",
")",
"response",
"=",
"request",
"(",
"api_method",
",",
"url",
",",
"options",
")",
"options",
"[",
":body",
"]",
"=",
"file",
"options",
"[",
":headers",
"]",
".",
"delete",
"(",
"'X-Upload-Content-Type'",
")",
"options",
"[",
":headers",
"]",
".",
"merge!",
"(",
"{",
"'Content-Type'",
"=>",
"mime_type",
",",
"'Content-Length'",
"=>",
"file",
".",
"bytesize",
".",
"to_s",
"}",
")",
"request",
"(",
":put",
",",
"response",
".",
"headers",
"[",
"'Location'",
"]",
",",
"options",
")",
"end"
] | Build a resumable upload request that then makes POST and PUT requests with the correct
headers for each request.
The initial POST request initiates the upload process, passing the metadata for the file.
The response from the API includes a Location header telling us where to actually send the
media we want uploaded. The subsequent PUT request sends the media itself to the API. | [
"Build",
"a",
"resumable",
"upload",
"request",
"that",
"then",
"makes",
"POST",
"and",
"PUT",
"requests",
"with",
"the",
"correct",
"headers",
"for",
"each",
"request",
"."
] | 8d9577a476b018c964c803ea0485ed3d221540be | https://github.com/agrobbin/google-api/blob/8d9577a476b018c964c803ea0485ed3d221540be/lib/google-api/api.rb#L84-L98 | train |
agrobbin/google-api | lib/google-api/api.rb | GoogleAPI.API.build_url | def build_url(api_method, options = {})
if api_method['mediaUpload'] && options[:media]
# we need to do [1..-1] to remove the prepended slash
url = GoogleAPI.discovered_apis[api]['rootUrl'] + api_method['mediaUpload']['protocols']['resumable']['path'][1..-1]
else
url = GoogleAPI.discovered_apis[api]['baseUrl'] + api_method['path']
query_params = []
api_method['parameters'].each_with_index do |(param, settings), index|
param = param.to_sym
case settings['location']
when 'path'
raise ArgumentError, ":#{param} was not passed" if settings['required'] && !options[param]
url.sub!("{#{param}}", options.delete(param).to_s)
when 'query'
query_params << "#{param}=#{options.delete(param)}" if options[param]
end
end if api_method['parameters']
url += "?#{query_params.join('&')}" if query_params.length > 0
end
[url, options]
end | ruby | def build_url(api_method, options = {})
if api_method['mediaUpload'] && options[:media]
# we need to do [1..-1] to remove the prepended slash
url = GoogleAPI.discovered_apis[api]['rootUrl'] + api_method['mediaUpload']['protocols']['resumable']['path'][1..-1]
else
url = GoogleAPI.discovered_apis[api]['baseUrl'] + api_method['path']
query_params = []
api_method['parameters'].each_with_index do |(param, settings), index|
param = param.to_sym
case settings['location']
when 'path'
raise ArgumentError, ":#{param} was not passed" if settings['required'] && !options[param]
url.sub!("{#{param}}", options.delete(param).to_s)
when 'query'
query_params << "#{param}=#{options.delete(param)}" if options[param]
end
end if api_method['parameters']
url += "?#{query_params.join('&')}" if query_params.length > 0
end
[url, options]
end | [
"def",
"build_url",
"(",
"api_method",
",",
"options",
"=",
"{",
"}",
")",
"if",
"api_method",
"[",
"'mediaUpload'",
"]",
"&&",
"options",
"[",
":media",
"]",
"url",
"=",
"GoogleAPI",
".",
"discovered_apis",
"[",
"api",
"]",
"[",
"'rootUrl'",
"]",
"+",
"api_method",
"[",
"'mediaUpload'",
"]",
"[",
"'protocols'",
"]",
"[",
"'resumable'",
"]",
"[",
"'path'",
"]",
"[",
"1",
"..",
"-",
"1",
"]",
"else",
"url",
"=",
"GoogleAPI",
".",
"discovered_apis",
"[",
"api",
"]",
"[",
"'baseUrl'",
"]",
"+",
"api_method",
"[",
"'path'",
"]",
"query_params",
"=",
"[",
"]",
"api_method",
"[",
"'parameters'",
"]",
".",
"each_with_index",
"do",
"|",
"(",
"param",
",",
"settings",
")",
",",
"index",
"|",
"param",
"=",
"param",
".",
"to_sym",
"case",
"settings",
"[",
"'location'",
"]",
"when",
"'path'",
"raise",
"ArgumentError",
",",
"\":#{param} was not passed\"",
"if",
"settings",
"[",
"'required'",
"]",
"&&",
"!",
"options",
"[",
"param",
"]",
"url",
".",
"sub!",
"(",
"\"{#{param}}\"",
",",
"options",
".",
"delete",
"(",
"param",
")",
".",
"to_s",
")",
"when",
"'query'",
"query_params",
"<<",
"\"#{param}=#{options.delete(param)}\"",
"if",
"options",
"[",
"param",
"]",
"end",
"end",
"if",
"api_method",
"[",
"'parameters'",
"]",
"url",
"+=",
"\"?#{query_params.join('&')}\"",
"if",
"query_params",
".",
"length",
">",
"0",
"end",
"[",
"url",
",",
"options",
"]",
"end"
] | Put together the full URL we will send a request to.
First we join the API's base URL with the current method's path, forming the main URL.
If the method is mediaUpload-enabled (like uploading a file to Google Drive), then we want
to take the path from the resumable upload protocol.
If not, then, we are going to iterate through each of the parameters for the current method.
When the parameter's location is within the path, we first check that we have had that
option passed, and if so, substitute it in the correct place.
When the parameter's location is a query, we add it to our query parameters hash, provided it is present.
Before returning the URL and remaining options, we have to build the query parameters hash
into a string and append it to the end of the URL. | [
"Put",
"together",
"the",
"full",
"URL",
"we",
"will",
"send",
"a",
"request",
"to",
".",
"First",
"we",
"join",
"the",
"API",
"s",
"base",
"URL",
"with",
"the",
"current",
"method",
"s",
"path",
"forming",
"the",
"main",
"URL",
"."
] | 8d9577a476b018c964c803ea0485ed3d221540be | https://github.com/agrobbin/google-api/blob/8d9577a476b018c964c803ea0485ed3d221540be/lib/google-api/api.rb#L112-L133 | train |
Sitata/i18n_language_select | lib/i18n_language_select/instance_tag.rb | I18nLanguageSelect.InstanceTag.language_code_select | def language_code_select(priority_languages, options, html_options)
selected = object.send(@method_name) if object.respond_to?(@method_name)
languages = ""
if options.present? and options[:include_blank]
option = options[:include_blank] == true ? "" : options[:include_blank]
languages += "<option>#{option}</option>\n"
end
if priority_languages
languages += options_for_select(priority_languages, selected)
languages += "<option value=\"\" disabled=\"disabled\">-------------</option>\n"
end
languages = languages + options_for_select(language_translations, selected)
html_options = html_options.stringify_keys
add_default_name_and_id(html_options)
content_tag(:select, languages.html_safe, html_options)
end | ruby | def language_code_select(priority_languages, options, html_options)
selected = object.send(@method_name) if object.respond_to?(@method_name)
languages = ""
if options.present? and options[:include_blank]
option = options[:include_blank] == true ? "" : options[:include_blank]
languages += "<option>#{option}</option>\n"
end
if priority_languages
languages += options_for_select(priority_languages, selected)
languages += "<option value=\"\" disabled=\"disabled\">-------------</option>\n"
end
languages = languages + options_for_select(language_translations, selected)
html_options = html_options.stringify_keys
add_default_name_and_id(html_options)
content_tag(:select, languages.html_safe, html_options)
end | [
"def",
"language_code_select",
"(",
"priority_languages",
",",
"options",
",",
"html_options",
")",
"selected",
"=",
"object",
".",
"send",
"(",
"@method_name",
")",
"if",
"object",
".",
"respond_to?",
"(",
"@method_name",
")",
"languages",
"=",
"\"\"",
"if",
"options",
".",
"present?",
"and",
"options",
"[",
":include_blank",
"]",
"option",
"=",
"options",
"[",
":include_blank",
"]",
"==",
"true",
"?",
"\"\"",
":",
"options",
"[",
":include_blank",
"]",
"languages",
"+=",
"\"<option>#{option}</option>\\n\"",
"end",
"if",
"priority_languages",
"languages",
"+=",
"options_for_select",
"(",
"priority_languages",
",",
"selected",
")",
"languages",
"+=",
"\"<option value=\\\"\\\" disabled=\\\"disabled\\\">-------------</option>\\n\"",
"end",
"languages",
"=",
"languages",
"+",
"options_for_select",
"(",
"language_translations",
",",
"selected",
")",
"html_options",
"=",
"html_options",
".",
"stringify_keys",
"add_default_name_and_id",
"(",
"html_options",
")",
"content_tag",
"(",
":select",
",",
"languages",
".",
"html_safe",
",",
"html_options",
")",
"end"
] | Adapted from Rails language_select. Just uses language codes instead of full names. | [
"Adapted",
"from",
"Rails",
"language_select",
".",
"Just",
"uses",
"language",
"codes",
"instead",
"of",
"full",
"names",
"."
] | 4e41d4e43c013af54c765fa8e2a189e0be94fbe5 | https://github.com/Sitata/i18n_language_select/blob/4e41d4e43c013af54c765fa8e2a189e0be94fbe5/lib/i18n_language_select/instance_tag.rb#L13-L34 | train |
pwnall/file_blobs_rails | lib/file_blobs_rails/action_controller_data_streaming_extensions.rb | FileBlobs.ActionControllerDataStreamingExtensions.send_file_blob | def send_file_blob(proxy, options = {})
if request.get_header(HTTP_IF_NONE_MATCH) == proxy.blob_id
head :not_modified
else
response.headers[ETAG] = proxy.blob_id
send_options = { type: proxy.mime_type, filename: proxy.original_name }
send_options.merge! options
send_data proxy.data, send_options
end
end | ruby | def send_file_blob(proxy, options = {})
if request.get_header(HTTP_IF_NONE_MATCH) == proxy.blob_id
head :not_modified
else
response.headers[ETAG] = proxy.blob_id
send_options = { type: proxy.mime_type, filename: proxy.original_name }
send_options.merge! options
send_data proxy.data, send_options
end
end | [
"def",
"send_file_blob",
"(",
"proxy",
",",
"options",
"=",
"{",
"}",
")",
"if",
"request",
".",
"get_header",
"(",
"HTTP_IF_NONE_MATCH",
")",
"==",
"proxy",
".",
"blob_id",
"head",
":not_modified",
"else",
"response",
".",
"headers",
"[",
"ETAG",
"]",
"=",
"proxy",
".",
"blob_id",
"send_options",
"=",
"{",
"type",
":",
"proxy",
".",
"mime_type",
",",
"filename",
":",
"proxy",
".",
"original_name",
"}",
"send_options",
".",
"merge!",
"options",
"send_data",
"proxy",
".",
"data",
",",
"send_options",
"end",
"end"
] | Sends a file blob to the browser.
This method uses HTTP's strong etag feature to facilitate serving the files
from a cache whenever possible.
@param [FileBlobs::FileBlobProxy] proxy a proxy for a collection of
attributes generated by has_file_blob
@param [Hash<Symbol, Object>] options tweaks the options passed to the
underlying send_data call; this method sets the :filename and :type
options, but their values can be overridden by the options hash
@see ActionController::DataStreaming#send_data | [
"Sends",
"a",
"file",
"blob",
"to",
"the",
"browser",
"."
] | 688d43ec8547856f3572b0e6716e6faeff56345b | https://github.com/pwnall/file_blobs_rails/blob/688d43ec8547856f3572b0e6716e6faeff56345b/lib/file_blobs_rails/action_controller_data_streaming_extensions.rb#L21-L30 | train |
richhollis/diversion | lib/diversion/configurable.rb | Diversion.Configurable.validate_configuration! | def validate_configuration!
unless @host.is_a?(String) && @host.length > 0
raise(Error::ConfigurationError, "Invalid host specified: Host must contain the host to redirect to.")
end
if @host.end_with?('/')
raise(Error::ConfigurationError, "Invalid host specified: #{@host} should not end with a trailing slash.")
end
unless @path.is_a?(String) && @path.length > 0
raise(Error::ConfigurationError, "Invalid path specified: Path must contain a path to redirect to.")
end
unless @path.end_with?('/')
raise(Error::ConfigurationError, "Invalid path specified: #{@path} should end with a trailing slash.")
end
unless @port.is_a?(Integer) && @port > 0
raise(Error::ConfigurationError, "Invalid port specified: #{@port} must be an integer and non-zero.")
end
if !@sign_key.nil? && !@sign_key.is_a?(String)
raise(Error::ConfigurationError, "Invalid sign_key specified: #{@sign_key} must be a String.")
end
unless @sign_length.is_a?(Integer) && @sign_length.between?(0, Signing::MAX_SIGN_LENGTH)
raise(Error::ConfigurationError, "Invalid sign_length specified: #{@sign_length} must be an integer between 0-#{Signing::MAX_SIGN_LENGTH}.")
end
unless @encode_uris.is_a?(Array) && @encode_uris.count > 0
raise(Error::ConfigurationError, "Invalid encode_uris specified: #{@encode_uris} must be an array with at least one URI scheme.")
end
unless @url_encoding.is_a?(Module) && Encode::ENCODERS.include?(@url_encoding)
raise(Error::ConfigurationError, "Invalid url_encoding specified: #{@url_encoding} must be a valid encoder module.")
end
unless @url_decoding.is_a?(Module) && Decode::DECODERS.include?(@url_decoding)
raise(Error::ConfigurationError, "Invalid url_decoding specified: #{@url_decoding} must be a valid decoder module.")
end
end | ruby | def validate_configuration!
unless @host.is_a?(String) && @host.length > 0
raise(Error::ConfigurationError, "Invalid host specified: Host must contain the host to redirect to.")
end
if @host.end_with?('/')
raise(Error::ConfigurationError, "Invalid host specified: #{@host} should not end with a trailing slash.")
end
unless @path.is_a?(String) && @path.length > 0
raise(Error::ConfigurationError, "Invalid path specified: Path must contain a path to redirect to.")
end
unless @path.end_with?('/')
raise(Error::ConfigurationError, "Invalid path specified: #{@path} should end with a trailing slash.")
end
unless @port.is_a?(Integer) && @port > 0
raise(Error::ConfigurationError, "Invalid port specified: #{@port} must be an integer and non-zero.")
end
if !@sign_key.nil? && !@sign_key.is_a?(String)
raise(Error::ConfigurationError, "Invalid sign_key specified: #{@sign_key} must be a String.")
end
unless @sign_length.is_a?(Integer) && @sign_length.between?(0, Signing::MAX_SIGN_LENGTH)
raise(Error::ConfigurationError, "Invalid sign_length specified: #{@sign_length} must be an integer between 0-#{Signing::MAX_SIGN_LENGTH}.")
end
unless @encode_uris.is_a?(Array) && @encode_uris.count > 0
raise(Error::ConfigurationError, "Invalid encode_uris specified: #{@encode_uris} must be an array with at least one URI scheme.")
end
unless @url_encoding.is_a?(Module) && Encode::ENCODERS.include?(@url_encoding)
raise(Error::ConfigurationError, "Invalid url_encoding specified: #{@url_encoding} must be a valid encoder module.")
end
unless @url_decoding.is_a?(Module) && Decode::DECODERS.include?(@url_decoding)
raise(Error::ConfigurationError, "Invalid url_decoding specified: #{@url_decoding} must be a valid decoder module.")
end
end | [
"def",
"validate_configuration!",
"unless",
"@host",
".",
"is_a?",
"(",
"String",
")",
"&&",
"@host",
".",
"length",
">",
"0",
"raise",
"(",
"Error",
"::",
"ConfigurationError",
",",
"\"Invalid host specified: Host must contain the host to redirect to.\"",
")",
"end",
"if",
"@host",
".",
"end_with?",
"(",
"'/'",
")",
"raise",
"(",
"Error",
"::",
"ConfigurationError",
",",
"\"Invalid host specified: #{@host} should not end with a trailing slash.\"",
")",
"end",
"unless",
"@path",
".",
"is_a?",
"(",
"String",
")",
"&&",
"@path",
".",
"length",
">",
"0",
"raise",
"(",
"Error",
"::",
"ConfigurationError",
",",
"\"Invalid path specified: Path must contain a path to redirect to.\"",
")",
"end",
"unless",
"@path",
".",
"end_with?",
"(",
"'/'",
")",
"raise",
"(",
"Error",
"::",
"ConfigurationError",
",",
"\"Invalid path specified: #{@path} should end with a trailing slash.\"",
")",
"end",
"unless",
"@port",
".",
"is_a?",
"(",
"Integer",
")",
"&&",
"@port",
">",
"0",
"raise",
"(",
"Error",
"::",
"ConfigurationError",
",",
"\"Invalid port specified: #{@port} must be an integer and non-zero.\"",
")",
"end",
"if",
"!",
"@sign_key",
".",
"nil?",
"&&",
"!",
"@sign_key",
".",
"is_a?",
"(",
"String",
")",
"raise",
"(",
"Error",
"::",
"ConfigurationError",
",",
"\"Invalid sign_key specified: #{@sign_key} must be a String.\"",
")",
"end",
"unless",
"@sign_length",
".",
"is_a?",
"(",
"Integer",
")",
"&&",
"@sign_length",
".",
"between?",
"(",
"0",
",",
"Signing",
"::",
"MAX_SIGN_LENGTH",
")",
"raise",
"(",
"Error",
"::",
"ConfigurationError",
",",
"\"Invalid sign_length specified: #{@sign_length} must be an integer between 0-#{Signing::MAX_SIGN_LENGTH}.\"",
")",
"end",
"unless",
"@encode_uris",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"@encode_uris",
".",
"count",
">",
"0",
"raise",
"(",
"Error",
"::",
"ConfigurationError",
",",
"\"Invalid encode_uris specified: #{@encode_uris} must be an array with at least one URI scheme.\"",
")",
"end",
"unless",
"@url_encoding",
".",
"is_a?",
"(",
"Module",
")",
"&&",
"Encode",
"::",
"ENCODERS",
".",
"include?",
"(",
"@url_encoding",
")",
"raise",
"(",
"Error",
"::",
"ConfigurationError",
",",
"\"Invalid url_encoding specified: #{@url_encoding} must be a valid encoder module.\"",
")",
"end",
"unless",
"@url_decoding",
".",
"is_a?",
"(",
"Module",
")",
"&&",
"Decode",
"::",
"DECODERS",
".",
"include?",
"(",
"@url_decoding",
")",
"raise",
"(",
"Error",
"::",
"ConfigurationError",
",",
"\"Invalid url_decoding specified: #{@url_decoding} must be a valid decoder module.\"",
")",
"end",
"end"
] | Ensures that all configuration parameters are of an expected type.
@raise [Diversion::Error::ConfigurationError] Error is raised when
supplied configuration is not of expected type | [
"Ensures",
"that",
"all",
"configuration",
"parameters",
"are",
"of",
"an",
"expected",
"type",
"."
] | 87d1845d6cecbb5e1cc3048df1c8a6f3c8773131 | https://github.com/richhollis/diversion/blob/87d1845d6cecbb5e1cc3048df1c8a6f3c8773131/lib/diversion/configurable.rb#L59-L97 | train |
airblade/brocade | lib/brocade/has_barcode.rb | Brocade.InstanceMethods.barcode | def barcode(opts = {})
data = format_for_subset_c_if_applicable send(barcodable)
if (subset = opts[:subset])
case subset
when 'A'; Barby::Code128A.new data
when 'B'; Barby::Code128B.new data
when 'C'; Barby::Code128C.new data
end
else
most_efficient_barcode_for data
end
end | ruby | def barcode(opts = {})
data = format_for_subset_c_if_applicable send(barcodable)
if (subset = opts[:subset])
case subset
when 'A'; Barby::Code128A.new data
when 'B'; Barby::Code128B.new data
when 'C'; Barby::Code128C.new data
end
else
most_efficient_barcode_for data
end
end | [
"def",
"barcode",
"(",
"opts",
"=",
"{",
"}",
")",
"data",
"=",
"format_for_subset_c_if_applicable",
"send",
"(",
"barcodable",
")",
"if",
"(",
"subset",
"=",
"opts",
"[",
":subset",
"]",
")",
"case",
"subset",
"when",
"'A'",
";",
"Barby",
"::",
"Code128A",
".",
"new",
"data",
"when",
"'B'",
";",
"Barby",
"::",
"Code128B",
".",
"new",
"data",
"when",
"'C'",
";",
"Barby",
"::",
"Code128C",
".",
"new",
"data",
"end",
"else",
"most_efficient_barcode_for",
"data",
"end",
"end"
] | Returns a Code128 barcode instance.
opts:
:subset - specify the Code128 subset to use ('A', 'B', or 'C'). | [
"Returns",
"a",
"Code128",
"barcode",
"instance",
"."
] | 1c4291a508d8b896003d5de3a4a22639c2b91839 | https://github.com/airblade/brocade/blob/1c4291a508d8b896003d5de3a4a22639c2b91839/lib/brocade/has_barcode.rb#L44-L55 | train |
airblade/brocade | lib/brocade/has_barcode.rb | Brocade.InstanceMethods.create_barcode | def create_barcode(opts = {})
path = barcode_path
FileUtils.mkdir_p File.dirname(path)
File.open(path, 'wb') do |f|
f.write barcode(opts).to_png(self.class.options.merge(opts))
end
FileUtils.chmod(0666 &~ File.umask, path)
end | ruby | def create_barcode(opts = {})
path = barcode_path
FileUtils.mkdir_p File.dirname(path)
File.open(path, 'wb') do |f|
f.write barcode(opts).to_png(self.class.options.merge(opts))
end
FileUtils.chmod(0666 &~ File.umask, path)
end | [
"def",
"create_barcode",
"(",
"opts",
"=",
"{",
"}",
")",
"path",
"=",
"barcode_path",
"FileUtils",
".",
"mkdir_p",
"File",
".",
"dirname",
"(",
"path",
")",
"File",
".",
"open",
"(",
"path",
",",
"'wb'",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"barcode",
"(",
"opts",
")",
".",
"to_png",
"(",
"self",
".",
"class",
".",
"options",
".",
"merge",
"(",
"opts",
")",
")",
"end",
"FileUtils",
".",
"chmod",
"(",
"0666",
"&",
"~",
"File",
".",
"umask",
",",
"path",
")",
"end"
] | Writes a barcode PNG image.
opts:
:subset - specify the Code128 subset to use ('A', 'B', or 'C').
remaining options passed through to PNGOutputter. | [
"Writes",
"a",
"barcode",
"PNG",
"image",
"."
] | 1c4291a508d8b896003d5de3a4a22639c2b91839 | https://github.com/airblade/brocade/blob/1c4291a508d8b896003d5de3a4a22639c2b91839/lib/brocade/has_barcode.rb#L62-L69 | train |
checkdin/checkdin-ruby | lib/checkdin/leaderboard.rb | Checkdin.Leaderboard.classification_leaderboard | def classification_leaderboard(campaign_id)
response = connection.get do |req|
req.url "campaigns/#{campaign_id}/classification_leaderboard"
end
return_error_or_body(response)
end | ruby | def classification_leaderboard(campaign_id)
response = connection.get do |req|
req.url "campaigns/#{campaign_id}/classification_leaderboard"
end
return_error_or_body(response)
end | [
"def",
"classification_leaderboard",
"(",
"campaign_id",
")",
"response",
"=",
"connection",
".",
"get",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"\"campaigns/#{campaign_id}/classification_leaderboard\"",
"end",
"return_error_or_body",
"(",
"response",
")",
"end"
] | Get the classification leaderboard for a given campaign
param [Integer] campaign_id The ID of the campaign to fetch the leaderboard for. | [
"Get",
"the",
"classification",
"leaderboard",
"for",
"a",
"given",
"campaign"
] | c3c4b38b0f8c710e1f805100dcf3a70649215b48 | https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/leaderboard.rb#L33-L38 | train |
mattherick/dummy_text | lib/dummy_text/base.rb | DummyText.Base.character | def character(count, template)
out_of_order("c", count, template)
raw Character.new.render(count, template)
end | ruby | def character(count, template)
out_of_order("c", count, template)
raw Character.new.render(count, template)
end | [
"def",
"character",
"(",
"count",
",",
"template",
")",
"out_of_order",
"(",
"\"c\"",
",",
"count",
",",
"template",
")",
"raw",
"Character",
".",
"new",
".",
"render",
"(",
"count",
",",
"template",
")",
"end"
] | select "count characters" | [
"select",
"count",
"characters"
] | 9167261a974413a885dfe2abef1bdd40529fb500 | https://github.com/mattherick/dummy_text/blob/9167261a974413a885dfe2abef1bdd40529fb500/lib/dummy_text/base.rb#L32-L35 | train |
mattherick/dummy_text | lib/dummy_text/base.rb | DummyText.Base.word | def word(count, template)
out_of_order("w", count, template)
raw Word.new.render(count, template)
end | ruby | def word(count, template)
out_of_order("w", count, template)
raw Word.new.render(count, template)
end | [
"def",
"word",
"(",
"count",
",",
"template",
")",
"out_of_order",
"(",
"\"w\"",
",",
"count",
",",
"template",
")",
"raw",
"Word",
".",
"new",
".",
"render",
"(",
"count",
",",
"template",
")",
"end"
] | select "count" words | [
"select",
"count",
"words"
] | 9167261a974413a885dfe2abef1bdd40529fb500 | https://github.com/mattherick/dummy_text/blob/9167261a974413a885dfe2abef1bdd40529fb500/lib/dummy_text/base.rb#L38-L41 | train |
mattherick/dummy_text | lib/dummy_text/base.rb | DummyText.Base.paragraph | def paragraph(count, template)
out_of_order("p", count, template)
i = 0
result = ""
data = Paragraph.new.render(template)
while i < count
result += "<p>#{data[i]}</p>"
i += 1
end
raw result
end | ruby | def paragraph(count, template)
out_of_order("p", count, template)
i = 0
result = ""
data = Paragraph.new.render(template)
while i < count
result += "<p>#{data[i]}</p>"
i += 1
end
raw result
end | [
"def",
"paragraph",
"(",
"count",
",",
"template",
")",
"out_of_order",
"(",
"\"p\"",
",",
"count",
",",
"template",
")",
"i",
"=",
"0",
"result",
"=",
"\"\"",
"data",
"=",
"Paragraph",
".",
"new",
".",
"render",
"(",
"template",
")",
"while",
"i",
"<",
"count",
"result",
"+=",
"\"<p>#{data[i]}</p>\"",
"i",
"+=",
"1",
"end",
"raw",
"result",
"end"
] | select "count" paragraphs, wrap in p-tags | [
"select",
"count",
"paragraphs",
"wrap",
"in",
"p",
"-",
"tags"
] | 9167261a974413a885dfe2abef1bdd40529fb500 | https://github.com/mattherick/dummy_text/blob/9167261a974413a885dfe2abef1bdd40529fb500/lib/dummy_text/base.rb#L50-L60 | train |
caruby/core | lib/caruby/database.rb | CaRuby.Database.open | def open(user=nil, password=nil)
raise ArgumentError.new("Database open requires an execution block") unless block_given?
raise DatabaseError.new("The caRuby application database is already in use.") if open?
# reset the execution timers
persistence_services.each { |svc| svc.timer.reset }
# Start the session.
start_session(user, password)
# Call the block and close when done.
yield(self) ensure close
end | ruby | def open(user=nil, password=nil)
raise ArgumentError.new("Database open requires an execution block") unless block_given?
raise DatabaseError.new("The caRuby application database is already in use.") if open?
# reset the execution timers
persistence_services.each { |svc| svc.timer.reset }
# Start the session.
start_session(user, password)
# Call the block and close when done.
yield(self) ensure close
end | [
"def",
"open",
"(",
"user",
"=",
"nil",
",",
"password",
"=",
"nil",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Database open requires an execution block\"",
")",
"unless",
"block_given?",
"raise",
"DatabaseError",
".",
"new",
"(",
"\"The caRuby application database is already in use.\"",
")",
"if",
"open?",
"persistence_services",
".",
"each",
"{",
"|",
"svc",
"|",
"svc",
".",
"timer",
".",
"reset",
"}",
"start_session",
"(",
"user",
",",
"password",
")",
"yield",
"(",
"self",
")",
"ensure",
"close",
"end"
] | Calls the block given to this method with this database as an argument, and closes the
database when done.
@param [String, nil] user the application login user
@param [String, nil] password the application login password
@yield [database] the operation to perform on the database
@yieldparam [Database] database self | [
"Calls",
"the",
"block",
"given",
"to",
"this",
"method",
"with",
"this",
"database",
"as",
"an",
"argument",
"and",
"closes",
"the",
"database",
"when",
"done",
"."
] | a682dc57c6fa31aef765cdd206ed3d4b4c289c60 | https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database.rb#L122-L131 | train |
caruby/core | lib/caruby/database.rb | CaRuby.Database.close | def close
return if @session.nil?
begin
@session.terminate_session
rescue Exception => e
logger.error("Session termination unsuccessful - #{e.message}")
end
# clear the cache
clear
logger.info("Disconnected from application server.")
@session = nil
end | ruby | def close
return if @session.nil?
begin
@session.terminate_session
rescue Exception => e
logger.error("Session termination unsuccessful - #{e.message}")
end
# clear the cache
clear
logger.info("Disconnected from application server.")
@session = nil
end | [
"def",
"close",
"return",
"if",
"@session",
".",
"nil?",
"begin",
"@session",
".",
"terminate_session",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"error",
"(",
"\"Session termination unsuccessful - #{e.message}\"",
")",
"end",
"clear",
"logger",
".",
"info",
"(",
"\"Disconnected from application server.\"",
")",
"@session",
"=",
"nil",
"end"
] | Releases database resources. This method should be called when database interaction
is completed. | [
"Releases",
"database",
"resources",
".",
"This",
"method",
"should",
"be",
"called",
"when",
"database",
"interaction",
"is",
"completed",
"."
] | a682dc57c6fa31aef765cdd206ed3d4b4c289c60 | https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database.rb#L181-L192 | train |
caruby/core | lib/caruby/database.rb | CaRuby.Database.perform | def perform(op, obj, opts=nil, &block)
op_s = op.to_s.capitalize_first
pa = Options.get(:attribute, opts)
attr_s = " #{pa}" if pa
ag_s = " autogenerated" if Options.get(:autogenerated, opts)
ctxt_s = " in context #{print_operations}" unless @operations.empty?
logger.info(">> #{op_s}#{ag_s} #{obj.pp_s(:single_line)}#{attr_s}#{ctxt_s}...")
# Clear the error flag.
@error = nil
# Push the operation on the nested operation stack.
@operations.push(Operation.new(op, obj, opts))
begin
# perform the operation
result = perform_operation(&block)
rescue Exception => e
# If the current operation is the immediate cause, then print the
# error to the log.
if @error.nil? then
msg = "Error performing #{op} on #{obj}:\n#{e.message}\n#{obj.dump}\n#{e.backtrace.qp}"
logger.error(msg)
@error = e
end
raise e
ensure
# the operation is done
@operations.pop
# If this is a top-level operation, then clear the transient set.
if @operations.empty? then @transients.clear end
end
logger.info("<< Completed #{obj.qp}#{attr_s} #{op}.")
result
end | ruby | def perform(op, obj, opts=nil, &block)
op_s = op.to_s.capitalize_first
pa = Options.get(:attribute, opts)
attr_s = " #{pa}" if pa
ag_s = " autogenerated" if Options.get(:autogenerated, opts)
ctxt_s = " in context #{print_operations}" unless @operations.empty?
logger.info(">> #{op_s}#{ag_s} #{obj.pp_s(:single_line)}#{attr_s}#{ctxt_s}...")
# Clear the error flag.
@error = nil
# Push the operation on the nested operation stack.
@operations.push(Operation.new(op, obj, opts))
begin
# perform the operation
result = perform_operation(&block)
rescue Exception => e
# If the current operation is the immediate cause, then print the
# error to the log.
if @error.nil? then
msg = "Error performing #{op} on #{obj}:\n#{e.message}\n#{obj.dump}\n#{e.backtrace.qp}"
logger.error(msg)
@error = e
end
raise e
ensure
# the operation is done
@operations.pop
# If this is a top-level operation, then clear the transient set.
if @operations.empty? then @transients.clear end
end
logger.info("<< Completed #{obj.qp}#{attr_s} #{op}.")
result
end | [
"def",
"perform",
"(",
"op",
",",
"obj",
",",
"opts",
"=",
"nil",
",",
"&",
"block",
")",
"op_s",
"=",
"op",
".",
"to_s",
".",
"capitalize_first",
"pa",
"=",
"Options",
".",
"get",
"(",
":attribute",
",",
"opts",
")",
"attr_s",
"=",
"\" #{pa}\"",
"if",
"pa",
"ag_s",
"=",
"\" autogenerated\"",
"if",
"Options",
".",
"get",
"(",
":autogenerated",
",",
"opts",
")",
"ctxt_s",
"=",
"\" in context #{print_operations}\"",
"unless",
"@operations",
".",
"empty?",
"logger",
".",
"info",
"(",
"\">> #{op_s}#{ag_s} #{obj.pp_s(:single_line)}#{attr_s}#{ctxt_s}...\"",
")",
"@error",
"=",
"nil",
"@operations",
".",
"push",
"(",
"Operation",
".",
"new",
"(",
"op",
",",
"obj",
",",
"opts",
")",
")",
"begin",
"result",
"=",
"perform_operation",
"(",
"&",
"block",
")",
"rescue",
"Exception",
"=>",
"e",
"if",
"@error",
".",
"nil?",
"then",
"msg",
"=",
"\"Error performing #{op} on #{obj}:\\n#{e.message}\\n#{obj.dump}\\n#{e.backtrace.qp}\"",
"logger",
".",
"error",
"(",
"msg",
")",
"@error",
"=",
"e",
"end",
"raise",
"e",
"ensure",
"@operations",
".",
"pop",
"if",
"@operations",
".",
"empty?",
"then",
"@transients",
".",
"clear",
"end",
"end",
"logger",
".",
"info",
"(",
"\"<< Completed #{obj.qp}#{attr_s} #{op}.\"",
")",
"result",
"end"
] | Performs the operation given by the given op symbol on obj by calling the block given to this method.
Lazy loading is suspended during the operation.
@param [:find, :query, :create, :update, :delete] op the database operation type
@param [Resource] obj the domain object on which the operation is performed
@param opts (#see Operation#initialize)
@yield the database operation block
@return the result of calling the operation block | [
"Performs",
"the",
"operation",
"given",
"by",
"the",
"given",
"op",
"symbol",
"on",
"obj",
"by",
"calling",
"the",
"block",
"given",
"to",
"this",
"method",
".",
"Lazy",
"loading",
"is",
"suspended",
"during",
"the",
"operation",
"."
] | a682dc57c6fa31aef765cdd206ed3d4b4c289c60 | https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database.rb#L228-L259 | train |
caruby/core | lib/caruby/database.rb | CaRuby.Database.start_session | def start_session(user=nil, password=nil)
user ||= @user
password ||= @password
if user.nil? then raise DatabaseError.new('The caRuby application is missing the login user') end
if password.nil? then raise DatabaseError.new('The caRuby application is missing the login password') end
@session = ClientSession.instance
connect(user, password)
end | ruby | def start_session(user=nil, password=nil)
user ||= @user
password ||= @password
if user.nil? then raise DatabaseError.new('The caRuby application is missing the login user') end
if password.nil? then raise DatabaseError.new('The caRuby application is missing the login password') end
@session = ClientSession.instance
connect(user, password)
end | [
"def",
"start_session",
"(",
"user",
"=",
"nil",
",",
"password",
"=",
"nil",
")",
"user",
"||=",
"@user",
"password",
"||=",
"@password",
"if",
"user",
".",
"nil?",
"then",
"raise",
"DatabaseError",
".",
"new",
"(",
"'The caRuby application is missing the login user'",
")",
"end",
"if",
"password",
".",
"nil?",
"then",
"raise",
"DatabaseError",
".",
"new",
"(",
"'The caRuby application is missing the login password'",
")",
"end",
"@session",
"=",
"ClientSession",
".",
"instance",
"connect",
"(",
"user",
",",
"password",
")",
"end"
] | Initializes the default application service. | [
"Initializes",
"the",
"default",
"application",
"service",
"."
] | a682dc57c6fa31aef765cdd206ed3d4b4c289c60 | https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database.rb#L279-L286 | train |
caruby/core | lib/caruby/database.rb | CaRuby.Database.print_operations | def print_operations
ops = @operations.reverse.map do |op|
attr_s = " #{op.attribute}" if op.attribute
"#{op.type.to_s.capitalize_first} #{op.subject.qp}#{attr_s}"
end
ops.qp
end | ruby | def print_operations
ops = @operations.reverse.map do |op|
attr_s = " #{op.attribute}" if op.attribute
"#{op.type.to_s.capitalize_first} #{op.subject.qp}#{attr_s}"
end
ops.qp
end | [
"def",
"print_operations",
"ops",
"=",
"@operations",
".",
"reverse",
".",
"map",
"do",
"|",
"op",
"|",
"attr_s",
"=",
"\" #{op.attribute}\"",
"if",
"op",
".",
"attribute",
"\"#{op.type.to_s.capitalize_first} #{op.subject.qp}#{attr_s}\"",
"end",
"ops",
".",
"qp",
"end"
] | Returns the current database operation stack as a String. | [
"Returns",
"the",
"current",
"database",
"operation",
"stack",
"as",
"a",
"String",
"."
] | a682dc57c6fa31aef765cdd206ed3d4b4c289c60 | https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database.rb#L289-L295 | train |
caruby/core | lib/caruby/database.rb | CaRuby.Database.connect | def connect(user, password)
logger.debug { "Connecting to application server with login id #{user}..." }
begin
@session.start_session(user, password)
rescue Exception => e
logger.error("Login of #{user} with password #{password} was unsuccessful - #{e.message}")
raise e
end
logger.info("Connected to application server.")
end | ruby | def connect(user, password)
logger.debug { "Connecting to application server with login id #{user}..." }
begin
@session.start_session(user, password)
rescue Exception => e
logger.error("Login of #{user} with password #{password} was unsuccessful - #{e.message}")
raise e
end
logger.info("Connected to application server.")
end | [
"def",
"connect",
"(",
"user",
",",
"password",
")",
"logger",
".",
"debug",
"{",
"\"Connecting to application server with login id #{user}...\"",
"}",
"begin",
"@session",
".",
"start_session",
"(",
"user",
",",
"password",
")",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"error",
"(",
"\"Login of #{user} with password #{password} was unsuccessful - #{e.message}\"",
")",
"raise",
"e",
"end",
"logger",
".",
"info",
"(",
"\"Connected to application server.\"",
")",
"end"
] | Connects to the database. | [
"Connects",
"to",
"the",
"database",
"."
] | a682dc57c6fa31aef765cdd206ed3d4b4c289c60 | https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database.rb#L298-L307 | train |
exploration/markov_words | lib/markov_words/file_store.rb | MarkovWords.FileStore.retrieve_data | def retrieve_data(key = '')
key = key.to_s unless key.is_a? String
data_array = @db.execute 'SELECT value FROM data WHERE key = ?', key
Marshal.load(data_array[0][0]) unless data_array[0].nil?
end | ruby | def retrieve_data(key = '')
key = key.to_s unless key.is_a? String
data_array = @db.execute 'SELECT value FROM data WHERE key = ?', key
Marshal.load(data_array[0][0]) unless data_array[0].nil?
end | [
"def",
"retrieve_data",
"(",
"key",
"=",
"''",
")",
"key",
"=",
"key",
".",
"to_s",
"unless",
"key",
".",
"is_a?",
"String",
"data_array",
"=",
"@db",
".",
"execute",
"'SELECT value FROM data WHERE key = ?'",
",",
"key",
"Marshal",
".",
"load",
"(",
"data_array",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"unless",
"data_array",
"[",
"0",
"]",
".",
"nil?",
"end"
] | Retrieve whatever data is stored in at `key`, and return it! | [
"Retrieve",
"whatever",
"data",
"is",
"stored",
"in",
"at",
"key",
"and",
"return",
"it!"
] | 0fa71955bed0d027633a6d4ed42b50179c17132e | https://github.com/exploration/markov_words/blob/0fa71955bed0d027633a6d4ed42b50179c17132e/lib/markov_words/file_store.rb#L34-L38 | train |
nellshamrell/git_org_file_scanner | lib/git_org_file_scanner.rb | GitOrgFileScanner.Scanner.setup_client | def setup_client(token)
client = Octokit::Client.new(access_token: token)
client.auto_paginate = true
client
end | ruby | def setup_client(token)
client = Octokit::Client.new(access_token: token)
client.auto_paginate = true
client
end | [
"def",
"setup_client",
"(",
"token",
")",
"client",
"=",
"Octokit",
"::",
"Client",
".",
"new",
"(",
"access_token",
":",
"token",
")",
"client",
".",
"auto_paginate",
"=",
"true",
"client",
"end"
] | setup an oktokit client with auto_pagination turned on so we get all the repos
returned even in large organizations
@param token [String] the github access token
@return [Octokit::Client] the oktokit client object | [
"setup",
"an",
"oktokit",
"client",
"with",
"auto_pagination",
"turned",
"on",
"so",
"we",
"get",
"all",
"the",
"repos",
"returned",
"even",
"in",
"large",
"organizations"
] | a5681e3e8b065ecf1978ccb57f5455455436b011 | https://github.com/nellshamrell/git_org_file_scanner/blob/a5681e3e8b065ecf1978ccb57f5455455436b011/lib/git_org_file_scanner.rb#L21-L25 | train |
bradfeehan/derelict | lib/derelict/parser/plugin_list.rb | Derelict.Parser::PluginList.plugins | def plugins
raise NeedsReinstall, output if needs_reinstall?
plugin_lines.map {|l| parse_line l.match(PARSE_PLUGIN) }.to_set
end | ruby | def plugins
raise NeedsReinstall, output if needs_reinstall?
plugin_lines.map {|l| parse_line l.match(PARSE_PLUGIN) }.to_set
end | [
"def",
"plugins",
"raise",
"NeedsReinstall",
",",
"output",
"if",
"needs_reinstall?",
"plugin_lines",
".",
"map",
"{",
"|",
"l",
"|",
"parse_line",
"l",
".",
"match",
"(",
"PARSE_PLUGIN",
")",
"}",
".",
"to_set",
"end"
] | Retrieves a Set containing all the plugins from the output | [
"Retrieves",
"a",
"Set",
"containing",
"all",
"the",
"plugins",
"from",
"the",
"output"
] | c9d70f04562280a34083dd060b0e4099e6f32d8d | https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/parser/plugin_list.rb#L33-L36 | train |
bradfeehan/derelict | lib/derelict/parser/plugin_list.rb | Derelict.Parser::PluginList.parse_line | def parse_line(match)
raise InvalidFormat.new "Couldn't parse plugin" if match.nil?
Derelict::Plugin.new *match.captures[0..1]
end | ruby | def parse_line(match)
raise InvalidFormat.new "Couldn't parse plugin" if match.nil?
Derelict::Plugin.new *match.captures[0..1]
end | [
"def",
"parse_line",
"(",
"match",
")",
"raise",
"InvalidFormat",
".",
"new",
"\"Couldn't parse plugin\"",
"if",
"match",
".",
"nil?",
"Derelict",
"::",
"Plugin",
".",
"new",
"*",
"match",
".",
"captures",
"[",
"0",
"..",
"1",
"]",
"end"
] | Parses a single line of the output into a Plugin object | [
"Parses",
"a",
"single",
"line",
"of",
"the",
"output",
"into",
"a",
"Plugin",
"object"
] | c9d70f04562280a34083dd060b0e4099e6f32d8d | https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/parser/plugin_list.rb#L58-L61 | train |
ranmocy/xiami_sauce | lib/xiami_sauce/track.rb | XiamiSauce.Track.sospa | def sospa(location)
string = location[1..-1]
col = location[0].to_i
row = (string.length.to_f / col).floor
remainder = string.length % col
address = [[nil]*col]*(row+1)
sizes = [row+1] * remainder + [row] * (col - remainder)
pos = 0
sizes.each_with_index { |size, i|
size.times { |index| address[col * index + i] = string[pos + index] }
pos += size
}
address = CGI::unescape(address.join).gsub('^', '0')
rescue
raise location
end | ruby | def sospa(location)
string = location[1..-1]
col = location[0].to_i
row = (string.length.to_f / col).floor
remainder = string.length % col
address = [[nil]*col]*(row+1)
sizes = [row+1] * remainder + [row] * (col - remainder)
pos = 0
sizes.each_with_index { |size, i|
size.times { |index| address[col * index + i] = string[pos + index] }
pos += size
}
address = CGI::unescape(address.join).gsub('^', '0')
rescue
raise location
end | [
"def",
"sospa",
"(",
"location",
")",
"string",
"=",
"location",
"[",
"1",
"..",
"-",
"1",
"]",
"col",
"=",
"location",
"[",
"0",
"]",
".",
"to_i",
"row",
"=",
"(",
"string",
".",
"length",
".",
"to_f",
"/",
"col",
")",
".",
"floor",
"remainder",
"=",
"string",
".",
"length",
"%",
"col",
"address",
"=",
"[",
"[",
"nil",
"]",
"*",
"col",
"]",
"*",
"(",
"row",
"+",
"1",
")",
"sizes",
"=",
"[",
"row",
"+",
"1",
"]",
"*",
"remainder",
"+",
"[",
"row",
"]",
"*",
"(",
"col",
"-",
"remainder",
")",
"pos",
"=",
"0",
"sizes",
".",
"each_with_index",
"{",
"|",
"size",
",",
"i",
"|",
"size",
".",
"times",
"{",
"|",
"index",
"|",
"address",
"[",
"col",
"*",
"index",
"+",
"i",
"]",
"=",
"string",
"[",
"pos",
"+",
"index",
"]",
"}",
"pos",
"+=",
"size",
"}",
"address",
"=",
"CGI",
"::",
"unescape",
"(",
"address",
".",
"join",
")",
".",
"gsub",
"(",
"'^'",
",",
"'0'",
")",
"rescue",
"raise",
"location",
"end"
] | Rewrite the algorithm, much much more better. | [
"Rewrite",
"the",
"algorithm",
"much",
"much",
"more",
"better",
"."
] | e261b073319e691d71463f86cc996347e389b2a8 | https://github.com/ranmocy/xiami_sauce/blob/e261b073319e691d71463f86cc996347e389b2a8/lib/xiami_sauce/track.rb#L54-L71 | train |
billdueber/simple_solr_client | lib/simple_solr_client/client.rb | SimpleSolrClient.Client._post_json | def _post_json(path, object_to_post)
resp = @rawclient.post(url(path), JSON.dump(object_to_post), {'Content-type' => 'application/json'})
JSON.parse(resp.content)
end | ruby | def _post_json(path, object_to_post)
resp = @rawclient.post(url(path), JSON.dump(object_to_post), {'Content-type' => 'application/json'})
JSON.parse(resp.content)
end | [
"def",
"_post_json",
"(",
"path",
",",
"object_to_post",
")",
"resp",
"=",
"@rawclient",
".",
"post",
"(",
"url",
"(",
"path",
")",
",",
"JSON",
".",
"dump",
"(",
"object_to_post",
")",
",",
"{",
"'Content-type'",
"=>",
"'application/json'",
"}",
")",
"JSON",
".",
"parse",
"(",
"resp",
".",
"content",
")",
"end"
] | post JSON data.
@param [String] path The parts of the URL that comes after the core
@param [Hash,Array] object_to_post The data to post as json
@return [Hash] the parsed-out response | [
"post",
"JSON",
"data",
"."
] | 51fab6319e7f295c081e77584b66996b73bc5355 | https://github.com/billdueber/simple_solr_client/blob/51fab6319e7f295c081e77584b66996b73bc5355/lib/simple_solr_client/client.rb#L109-L112 | train |
billdueber/simple_solr_client | lib/simple_solr_client/client.rb | SimpleSolrClient.Client.get | def get(path, args = {}, response_type = nil)
response_type = SimpleSolrClient::Response::GenericResponse if response_type.nil?
response_type.new(_get(path, args))
end | ruby | def get(path, args = {}, response_type = nil)
response_type = SimpleSolrClient::Response::GenericResponse if response_type.nil?
response_type.new(_get(path, args))
end | [
"def",
"get",
"(",
"path",
",",
"args",
"=",
"{",
"}",
",",
"response_type",
"=",
"nil",
")",
"response_type",
"=",
"SimpleSolrClient",
"::",
"Response",
"::",
"GenericResponse",
"if",
"response_type",
".",
"nil?",
"response_type",
".",
"new",
"(",
"_get",
"(",
"path",
",",
"args",
")",
")",
"end"
] | Get from solr, and return a Response object of some sort
@return [SimpleSolrClient::Response, response_type] | [
"Get",
"from",
"solr",
"and",
"return",
"a",
"Response",
"object",
"of",
"some",
"sort"
] | 51fab6319e7f295c081e77584b66996b73bc5355 | https://github.com/billdueber/simple_solr_client/blob/51fab6319e7f295c081e77584b66996b73bc5355/lib/simple_solr_client/client.rb#L116-L119 | train |
billdueber/simple_solr_client | lib/simple_solr_client/client.rb | SimpleSolrClient.Client.post_json | def post_json(path, object_to_post, response_type = nil)
response_type = SimpleSolrClient::Response::GenericResponse if response_type.nil?
response_type.new(_post_json(path, object_to_post))
end | ruby | def post_json(path, object_to_post, response_type = nil)
response_type = SimpleSolrClient::Response::GenericResponse if response_type.nil?
response_type.new(_post_json(path, object_to_post))
end | [
"def",
"post_json",
"(",
"path",
",",
"object_to_post",
",",
"response_type",
"=",
"nil",
")",
"response_type",
"=",
"SimpleSolrClient",
"::",
"Response",
"::",
"GenericResponse",
"if",
"response_type",
".",
"nil?",
"response_type",
".",
"new",
"(",
"_post_json",
"(",
"path",
",",
"object_to_post",
")",
")",
"end"
] | Post an object as JSON and return a Response object
@return [SimpleSolrClient::Response, response_type] | [
"Post",
"an",
"object",
"as",
"JSON",
"and",
"return",
"a",
"Response",
"object"
] | 51fab6319e7f295c081e77584b66996b73bc5355 | https://github.com/billdueber/simple_solr_client/blob/51fab6319e7f295c081e77584b66996b73bc5355/lib/simple_solr_client/client.rb#L123-L126 | train |
billdueber/simple_solr_client | lib/simple_solr_client/client.rb | SimpleSolrClient.Client.core | def core(corename)
raise "Core #{corename} not found" unless cores.include? corename.to_s
SimpleSolrClient::Core.new(@base_url, corename.to_s)
end | ruby | def core(corename)
raise "Core #{corename} not found" unless cores.include? corename.to_s
SimpleSolrClient::Core.new(@base_url, corename.to_s)
end | [
"def",
"core",
"(",
"corename",
")",
"raise",
"\"Core #{corename} not found\"",
"unless",
"cores",
".",
"include?",
"corename",
".",
"to_s",
"SimpleSolrClient",
"::",
"Core",
".",
"new",
"(",
"@base_url",
",",
"corename",
".",
"to_s",
")",
"end"
] | Get a client specific to the given core2
@param [String] corename The name of the core (which must already exist!)
@return [SimpleSolrClient::Core] | [
"Get",
"a",
"client",
"specific",
"to",
"the",
"given",
"core2"
] | 51fab6319e7f295c081e77584b66996b73bc5355 | https://github.com/billdueber/simple_solr_client/blob/51fab6319e7f295c081e77584b66996b73bc5355/lib/simple_solr_client/client.rb#L132-L135 | train |
billdueber/simple_solr_client | lib/simple_solr_client/client.rb | SimpleSolrClient.Client.new_core | def new_core(corename)
dir = temp_core_dir_setup(corename)
args = {
:wt => 'json',
:action => 'CREATE',
:name => corename,
:instanceDir => dir
}
get('admin/cores', args)
core(corename)
end | ruby | def new_core(corename)
dir = temp_core_dir_setup(corename)
args = {
:wt => 'json',
:action => 'CREATE',
:name => corename,
:instanceDir => dir
}
get('admin/cores', args)
core(corename)
end | [
"def",
"new_core",
"(",
"corename",
")",
"dir",
"=",
"temp_core_dir_setup",
"(",
"corename",
")",
"args",
"=",
"{",
":wt",
"=>",
"'json'",
",",
":action",
"=>",
"'CREATE'",
",",
":name",
"=>",
"corename",
",",
":instanceDir",
"=>",
"dir",
"}",
"get",
"(",
"'admin/cores'",
",",
"args",
")",
"core",
"(",
"corename",
")",
"end"
] | Create a new, temporary core
noinspection RubyWrongHash | [
"Create",
"a",
"new",
"temporary",
"core",
"noinspection",
"RubyWrongHash"
] | 51fab6319e7f295c081e77584b66996b73bc5355 | https://github.com/billdueber/simple_solr_client/blob/51fab6319e7f295c081e77584b66996b73bc5355/lib/simple_solr_client/client.rb#L146-L159 | train |
billdueber/simple_solr_client | lib/simple_solr_client/client.rb | SimpleSolrClient.Client.temp_core_dir_setup | def temp_core_dir_setup(corename)
dest = Dir.mktmpdir("simple_solr_#{corename}_#{SecureRandom.uuid}")
src = SAMPLE_CORE_DIR
FileUtils.cp_r File.join(src, '.'), dest
dest
end | ruby | def temp_core_dir_setup(corename)
dest = Dir.mktmpdir("simple_solr_#{corename}_#{SecureRandom.uuid}")
src = SAMPLE_CORE_DIR
FileUtils.cp_r File.join(src, '.'), dest
dest
end | [
"def",
"temp_core_dir_setup",
"(",
"corename",
")",
"dest",
"=",
"Dir",
".",
"mktmpdir",
"(",
"\"simple_solr_#{corename}_#{SecureRandom.uuid}\"",
")",
"src",
"=",
"SAMPLE_CORE_DIR",
"FileUtils",
".",
"cp_r",
"File",
".",
"join",
"(",
"src",
",",
"'.'",
")",
",",
"dest",
"dest",
"end"
] | Set up files for a temp core | [
"Set",
"up",
"files",
"for",
"a",
"temp",
"core"
] | 51fab6319e7f295c081e77584b66996b73bc5355 | https://github.com/billdueber/simple_solr_client/blob/51fab6319e7f295c081e77584b66996b73bc5355/lib/simple_solr_client/client.rb#L166-L171 | train |
Syncano/syncano-ruby | lib/syncano/jimson_client.rb | Jimson.ClientHelper.send_single_request | def send_single_request(method, args)
post_data = {
'jsonrpc' => JSON_RPC_VERSION,
'method' => method,
'params' => args,
'id' => self.class.make_id
}.to_json
resp = RestClient.post(@url, post_data, content_type: 'application/json', user_agent: "syncano-ruby-#{Syncano::VERSION}")
if resp.nil? || resp.body.nil? || resp.body.empty?
raise Jimson::ClientError::InvalidResponse.new
end
return resp.body
rescue Exception, StandardError
raise Jimson::ClientError::InternalError.new($!)
end | ruby | def send_single_request(method, args)
post_data = {
'jsonrpc' => JSON_RPC_VERSION,
'method' => method,
'params' => args,
'id' => self.class.make_id
}.to_json
resp = RestClient.post(@url, post_data, content_type: 'application/json', user_agent: "syncano-ruby-#{Syncano::VERSION}")
if resp.nil? || resp.body.nil? || resp.body.empty?
raise Jimson::ClientError::InvalidResponse.new
end
return resp.body
rescue Exception, StandardError
raise Jimson::ClientError::InternalError.new($!)
end | [
"def",
"send_single_request",
"(",
"method",
",",
"args",
")",
"post_data",
"=",
"{",
"'jsonrpc'",
"=>",
"JSON_RPC_VERSION",
",",
"'method'",
"=>",
"method",
",",
"'params'",
"=>",
"args",
",",
"'id'",
"=>",
"self",
".",
"class",
".",
"make_id",
"}",
".",
"to_json",
"resp",
"=",
"RestClient",
".",
"post",
"(",
"@url",
",",
"post_data",
",",
"content_type",
":",
"'application/json'",
",",
"user_agent",
":",
"\"syncano-ruby-#{Syncano::VERSION}\"",
")",
"if",
"resp",
".",
"nil?",
"||",
"resp",
".",
"body",
".",
"nil?",
"||",
"resp",
".",
"body",
".",
"empty?",
"raise",
"Jimson",
"::",
"ClientError",
"::",
"InvalidResponse",
".",
"new",
"end",
"return",
"resp",
".",
"body",
"rescue",
"Exception",
",",
"StandardError",
"raise",
"Jimson",
"::",
"ClientError",
"::",
"InternalError",
".",
"new",
"(",
"$!",
")",
"end"
] | Overwritten send_single_request method, so it now adds header with the user agent
@return [Array] collection of responses | [
"Overwritten",
"send_single_request",
"method",
"so",
"it",
"now",
"adds",
"header",
"with",
"the",
"user",
"agent"
] | 59155f8afd7a19dd1a168716c4409270a7edc0d3 | https://github.com/Syncano/syncano-ruby/blob/59155f8afd7a19dd1a168716c4409270a7edc0d3/lib/syncano/jimson_client.rb#L7-L23 | train |
Syncano/syncano-ruby | lib/syncano/jimson_client.rb | Jimson.ClientHelper.send_batch_request | def send_batch_request(batch)
post_data = batch.to_json
resp = RestClient.post(@url, post_data, content_type: 'application/json', user_agent: "syncano-ruby-#{Syncano::VERSION}")
if resp.nil? || resp.body.nil? || resp.body.empty?
raise Jimson::ClientError::InvalidResponse.new
end
return resp.body
end | ruby | def send_batch_request(batch)
post_data = batch.to_json
resp = RestClient.post(@url, post_data, content_type: 'application/json', user_agent: "syncano-ruby-#{Syncano::VERSION}")
if resp.nil? || resp.body.nil? || resp.body.empty?
raise Jimson::ClientError::InvalidResponse.new
end
return resp.body
end | [
"def",
"send_batch_request",
"(",
"batch",
")",
"post_data",
"=",
"batch",
".",
"to_json",
"resp",
"=",
"RestClient",
".",
"post",
"(",
"@url",
",",
"post_data",
",",
"content_type",
":",
"'application/json'",
",",
"user_agent",
":",
"\"syncano-ruby-#{Syncano::VERSION}\"",
")",
"if",
"resp",
".",
"nil?",
"||",
"resp",
".",
"body",
".",
"nil?",
"||",
"resp",
".",
"body",
".",
"empty?",
"raise",
"Jimson",
"::",
"ClientError",
"::",
"InvalidResponse",
".",
"new",
"end",
"return",
"resp",
".",
"body",
"end"
] | Overwritten send_batch_request method, so it now adds header with the user agent
@return [Array] collection of responses | [
"Overwritten",
"send_batch_request",
"method",
"so",
"it",
"now",
"adds",
"header",
"with",
"the",
"user",
"agent"
] | 59155f8afd7a19dd1a168716c4409270a7edc0d3 | https://github.com/Syncano/syncano-ruby/blob/59155f8afd7a19dd1a168716c4409270a7edc0d3/lib/syncano/jimson_client.rb#L27-L35 | train |
Syncano/syncano-ruby | lib/syncano/jimson_client.rb | Jimson.ClientHelper.send_batch | def send_batch
batch = @batch.map(&:first) # get the requests
response = send_batch_request(batch)
begin
responses = JSON.parse(response)
rescue
raise Jimson::ClientError::InvalidJSON.new(json)
end
process_batch_response(responses)
responses = @batch
@batch = []
responses
end | ruby | def send_batch
batch = @batch.map(&:first) # get the requests
response = send_batch_request(batch)
begin
responses = JSON.parse(response)
rescue
raise Jimson::ClientError::InvalidJSON.new(json)
end
process_batch_response(responses)
responses = @batch
@batch = []
responses
end | [
"def",
"send_batch",
"batch",
"=",
"@batch",
".",
"map",
"(",
"&",
":first",
")",
"response",
"=",
"send_batch_request",
"(",
"batch",
")",
"begin",
"responses",
"=",
"JSON",
".",
"parse",
"(",
"response",
")",
"rescue",
"raise",
"Jimson",
"::",
"ClientError",
"::",
"InvalidJSON",
".",
"new",
"(",
"json",
")",
"end",
"process_batch_response",
"(",
"responses",
")",
"responses",
"=",
"@batch",
"@batch",
"=",
"[",
"]",
"responses",
"end"
] | Overwritten send_batch method, so it now returns collection of responses
@return [Array] collection of responses | [
"Overwritten",
"send_batch",
"method",
"so",
"it",
"now",
"returns",
"collection",
"of",
"responses"
] | 59155f8afd7a19dd1a168716c4409270a7edc0d3 | https://github.com/Syncano/syncano-ruby/blob/59155f8afd7a19dd1a168716c4409270a7edc0d3/lib/syncano/jimson_client.rb#L39-L55 | train |
smsified/smsified-ruby | lib/smsified/helpers.rb | Smsified.Helpers.camelcase_keys | def camelcase_keys(options)
options = options.clone
if options[:destination_address]
options[:destinationAddress] = options[:destination_address]
options.delete(:destination_address)
end
if options[:notify_url]
options[:notifyURL] = options[:notify_url]
options.delete(:notify_url)
end
if options[:client_correlator]
options[:clientCorrelator] = options[:client_correlator]
options.delete(:client_correlator)
end
if options[:callback_data]
options[:callbackData] = options[:callback_data]
options.delete(:callback_data)
end
options
end | ruby | def camelcase_keys(options)
options = options.clone
if options[:destination_address]
options[:destinationAddress] = options[:destination_address]
options.delete(:destination_address)
end
if options[:notify_url]
options[:notifyURL] = options[:notify_url]
options.delete(:notify_url)
end
if options[:client_correlator]
options[:clientCorrelator] = options[:client_correlator]
options.delete(:client_correlator)
end
if options[:callback_data]
options[:callbackData] = options[:callback_data]
options.delete(:callback_data)
end
options
end | [
"def",
"camelcase_keys",
"(",
"options",
")",
"options",
"=",
"options",
".",
"clone",
"if",
"options",
"[",
":destination_address",
"]",
"options",
"[",
":destinationAddress",
"]",
"=",
"options",
"[",
":destination_address",
"]",
"options",
".",
"delete",
"(",
":destination_address",
")",
"end",
"if",
"options",
"[",
":notify_url",
"]",
"options",
"[",
":notifyURL",
"]",
"=",
"options",
"[",
":notify_url",
"]",
"options",
".",
"delete",
"(",
":notify_url",
")",
"end",
"if",
"options",
"[",
":client_correlator",
"]",
"options",
"[",
":clientCorrelator",
"]",
"=",
"options",
"[",
":client_correlator",
"]",
"options",
".",
"delete",
"(",
":client_correlator",
")",
"end",
"if",
"options",
"[",
":callback_data",
"]",
"options",
"[",
":callbackData",
"]",
"=",
"options",
"[",
":callback_data",
"]",
"options",
".",
"delete",
"(",
":callback_data",
")",
"end",
"options",
"end"
] | Camelcases the options | [
"Camelcases",
"the",
"options"
] | 1c7a0f445ffe7fe0fb035a1faf44ac55687a4488 | https://github.com/smsified/smsified-ruby/blob/1c7a0f445ffe7fe0fb035a1faf44ac55687a4488/lib/smsified/helpers.rb#L7-L31 | train |
smsified/smsified-ruby | lib/smsified/helpers.rb | Smsified.Helpers.build_query_string | def build_query_string(options)
options = camelcase_keys(options)
query = ''
options.each do |k,v|
if k == :address
if RUBY_VERSION.to_f >= 1.9
if v.instance_of?(String)
v.each_line { |address| query += "#{ '&' if query != '' }address=#{CGI.escape address}" }
else
v.each { |address| query += "#{ '&' if query != '' }address=#{CGI.escape address}" }
end
else
v.each { |address| query += "#{ '&' if query != '' }address=#{CGI.escape address}" }
end
else
query += "#{ '&' if query != '' }#{k.to_s}=#{CGI.escape v}"
end
end
query
end | ruby | def build_query_string(options)
options = camelcase_keys(options)
query = ''
options.each do |k,v|
if k == :address
if RUBY_VERSION.to_f >= 1.9
if v.instance_of?(String)
v.each_line { |address| query += "#{ '&' if query != '' }address=#{CGI.escape address}" }
else
v.each { |address| query += "#{ '&' if query != '' }address=#{CGI.escape address}" }
end
else
v.each { |address| query += "#{ '&' if query != '' }address=#{CGI.escape address}" }
end
else
query += "#{ '&' if query != '' }#{k.to_s}=#{CGI.escape v}"
end
end
query
end | [
"def",
"build_query_string",
"(",
"options",
")",
"options",
"=",
"camelcase_keys",
"(",
"options",
")",
"query",
"=",
"''",
"options",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"if",
"k",
"==",
":address",
"if",
"RUBY_VERSION",
".",
"to_f",
">=",
"1.9",
"if",
"v",
".",
"instance_of?",
"(",
"String",
")",
"v",
".",
"each_line",
"{",
"|",
"address",
"|",
"query",
"+=",
"\"#{ '&' if query != '' }address=#{CGI.escape address}\"",
"}",
"else",
"v",
".",
"each",
"{",
"|",
"address",
"|",
"query",
"+=",
"\"#{ '&' if query != '' }address=#{CGI.escape address}\"",
"}",
"end",
"else",
"v",
".",
"each",
"{",
"|",
"address",
"|",
"query",
"+=",
"\"#{ '&' if query != '' }address=#{CGI.escape address}\"",
"}",
"end",
"else",
"query",
"+=",
"\"#{ '&' if query != '' }#{k.to_s}=#{CGI.escape v}\"",
"end",
"end",
"query",
"end"
] | Builds the necessary query string | [
"Builds",
"the",
"necessary",
"query",
"string"
] | 1c7a0f445ffe7fe0fb035a1faf44ac55687a4488 | https://github.com/smsified/smsified-ruby/blob/1c7a0f445ffe7fe0fb035a1faf44ac55687a4488/lib/smsified/helpers.rb#L35-L57 | train |
cordawyn/redlander | lib/redlander/serializing.rb | Redlander.Serializing.to | def to(options = {})
format = options[:format].to_s
mime_type = options[:mime_type] && options[:mime_type].to_s
type_uri = options[:type_uri] && options[:type_uri].to_s
base_uri = options[:base_uri] && options[:base_uri].to_s
rdf_serializer = Redland.librdf_new_serializer(Redlander.rdf_world, format, mime_type, type_uri)
raise RedlandError, "Failed to create a new serializer" if rdf_serializer.null?
begin
if options[:file]
Redland.librdf_serializer_serialize_model_to_file(rdf_serializer, options[:file], base_uri, @rdf_model).zero?
else
Redland.librdf_serializer_serialize_model_to_string(rdf_serializer, base_uri, @rdf_model)
end
ensure
Redland.librdf_free_serializer(rdf_serializer)
end
end | ruby | def to(options = {})
format = options[:format].to_s
mime_type = options[:mime_type] && options[:mime_type].to_s
type_uri = options[:type_uri] && options[:type_uri].to_s
base_uri = options[:base_uri] && options[:base_uri].to_s
rdf_serializer = Redland.librdf_new_serializer(Redlander.rdf_world, format, mime_type, type_uri)
raise RedlandError, "Failed to create a new serializer" if rdf_serializer.null?
begin
if options[:file]
Redland.librdf_serializer_serialize_model_to_file(rdf_serializer, options[:file], base_uri, @rdf_model).zero?
else
Redland.librdf_serializer_serialize_model_to_string(rdf_serializer, base_uri, @rdf_model)
end
ensure
Redland.librdf_free_serializer(rdf_serializer)
end
end | [
"def",
"to",
"(",
"options",
"=",
"{",
"}",
")",
"format",
"=",
"options",
"[",
":format",
"]",
".",
"to_s",
"mime_type",
"=",
"options",
"[",
":mime_type",
"]",
"&&",
"options",
"[",
":mime_type",
"]",
".",
"to_s",
"type_uri",
"=",
"options",
"[",
":type_uri",
"]",
"&&",
"options",
"[",
":type_uri",
"]",
".",
"to_s",
"base_uri",
"=",
"options",
"[",
":base_uri",
"]",
"&&",
"options",
"[",
":base_uri",
"]",
".",
"to_s",
"rdf_serializer",
"=",
"Redland",
".",
"librdf_new_serializer",
"(",
"Redlander",
".",
"rdf_world",
",",
"format",
",",
"mime_type",
",",
"type_uri",
")",
"raise",
"RedlandError",
",",
"\"Failed to create a new serializer\"",
"if",
"rdf_serializer",
".",
"null?",
"begin",
"if",
"options",
"[",
":file",
"]",
"Redland",
".",
"librdf_serializer_serialize_model_to_file",
"(",
"rdf_serializer",
",",
"options",
"[",
":file",
"]",
",",
"base_uri",
",",
"@rdf_model",
")",
".",
"zero?",
"else",
"Redland",
".",
"librdf_serializer_serialize_model_to_string",
"(",
"rdf_serializer",
",",
"base_uri",
",",
"@rdf_model",
")",
"end",
"ensure",
"Redland",
".",
"librdf_free_serializer",
"(",
"rdf_serializer",
")",
"end",
"end"
] | Serialize model into a string
@param [Hash] options
@option options [String] :format name of the serializer to use,
@option options [String] :mime_type MIME type of the syntax, if applicable,
@option options [String, URI] :type_uri URI of syntax, if applicable,
@option options [String, URI] :base_uri base URI,
to be applied to the nodes with relative URIs.
@raise [RedlandError] if it fails to create a serializer | [
"Serialize",
"model",
"into",
"a",
"string"
] | a5c84e15a7602c674606e531bda6a616b1237c44 | https://github.com/cordawyn/redlander/blob/a5c84e15a7602c674606e531bda6a616b1237c44/lib/redlander/serializing.rb#L14-L32 | train |
craigp/djinn | lib/djinn/base.rb | Djinn.Base.start | def start config={}, &block
@config.update(config).update(load_config)
#@config = (config.empty?) ? load_config : config
log "Starting #{name} in the background.."
logfile = get_logfile(config)
daemonize(logfile, get_pidfile(config)) do
yield(self) if block_given?
trap('TERM') { handle_exit }
trap('INT') { handle_exit }
(respond_to?(:__start!)) ? __start! : perform(@config)
# If this process doesn't loop or otherwise breaks out of
# the loop we still want to clean up after ourselves
handle_exit
end
end | ruby | def start config={}, &block
@config.update(config).update(load_config)
#@config = (config.empty?) ? load_config : config
log "Starting #{name} in the background.."
logfile = get_logfile(config)
daemonize(logfile, get_pidfile(config)) do
yield(self) if block_given?
trap('TERM') { handle_exit }
trap('INT') { handle_exit }
(respond_to?(:__start!)) ? __start! : perform(@config)
# If this process doesn't loop or otherwise breaks out of
# the loop we still want to clean up after ourselves
handle_exit
end
end | [
"def",
"start",
"config",
"=",
"{",
"}",
",",
"&",
"block",
"@config",
".",
"update",
"(",
"config",
")",
".",
"update",
"(",
"load_config",
")",
"log",
"\"Starting #{name} in the background..\"",
"logfile",
"=",
"get_logfile",
"(",
"config",
")",
"daemonize",
"(",
"logfile",
",",
"get_pidfile",
"(",
"config",
")",
")",
"do",
"yield",
"(",
"self",
")",
"if",
"block_given?",
"trap",
"(",
"'TERM'",
")",
"{",
"handle_exit",
"}",
"trap",
"(",
"'INT'",
")",
"{",
"handle_exit",
"}",
"(",
"respond_to?",
"(",
":__start!",
")",
")",
"?",
"__start!",
":",
"perform",
"(",
"@config",
")",
"handle_exit",
"end",
"end"
] | Starts the Djinn in the background. | [
"Starts",
"the",
"Djinn",
"in",
"the",
"background",
"."
] | 4683a3f6d95db54c87e02bd0780d8148c4f8ab7d | https://github.com/craigp/djinn/blob/4683a3f6d95db54c87e02bd0780d8148c4f8ab7d/lib/djinn/base.rb#L39-L53 | train |
craigp/djinn | lib/djinn/base.rb | Djinn.Base.run | def run config={}, &block
@config.update(config).update(load_config)
# @config = (config.empty?) ? load_config : config
log "Starting #{name} in the foreground.."
trap('TERM') { handle_exit }
trap('INT') { handle_exit }
yield(self) if block_given?
(respond_to?(:__start!)) ? __start! : perform(@config)
# If this process doesn't loop or otherwise breaks out of
# the loop we still want to clean up after ourselves
handle_exit
end | ruby | def run config={}, &block
@config.update(config).update(load_config)
# @config = (config.empty?) ? load_config : config
log "Starting #{name} in the foreground.."
trap('TERM') { handle_exit }
trap('INT') { handle_exit }
yield(self) if block_given?
(respond_to?(:__start!)) ? __start! : perform(@config)
# If this process doesn't loop or otherwise breaks out of
# the loop we still want to clean up after ourselves
handle_exit
end | [
"def",
"run",
"config",
"=",
"{",
"}",
",",
"&",
"block",
"@config",
".",
"update",
"(",
"config",
")",
".",
"update",
"(",
"load_config",
")",
"log",
"\"Starting #{name} in the foreground..\"",
"trap",
"(",
"'TERM'",
")",
"{",
"handle_exit",
"}",
"trap",
"(",
"'INT'",
")",
"{",
"handle_exit",
"}",
"yield",
"(",
"self",
")",
"if",
"block_given?",
"(",
"respond_to?",
"(",
":__start!",
")",
")",
"?",
"__start!",
":",
"perform",
"(",
"@config",
")",
"handle_exit",
"end"
] | Starts the Djinn in the foreground, which is often useful for
testing or other noble pursuits. | [
"Starts",
"the",
"Djinn",
"in",
"the",
"foreground",
"which",
"is",
"often",
"useful",
"for",
"testing",
"or",
"other",
"noble",
"pursuits",
"."
] | 4683a3f6d95db54c87e02bd0780d8148c4f8ab7d | https://github.com/craigp/djinn/blob/4683a3f6d95db54c87e02bd0780d8148c4f8ab7d/lib/djinn/base.rb#L57-L68 | train |
userhello/bit_magic | lib/bit_magic/bit_field.rb | BitMagic.BitField.read_bits | def read_bits(*args)
{}.tap do |m|
args.each { |bit| m[bit] = @value[bit] }
end
end | ruby | def read_bits(*args)
{}.tap do |m|
args.each { |bit| m[bit] = @value[bit] }
end
end | [
"def",
"read_bits",
"(",
"*",
"args",
")",
"{",
"}",
".",
"tap",
"do",
"|",
"m",
"|",
"args",
".",
"each",
"{",
"|",
"bit",
"|",
"m",
"[",
"bit",
"]",
"=",
"@value",
"[",
"bit",
"]",
"}",
"end",
"end"
] | Initialize the BitField with an optional value. Default is 0
@param [Integer] value the integer that contains the bit fields
Read the specified bit indices into a hash with bit index as key
@param [Integer] bits one or more bit indices to read.
@example Read a list of bits into a hash
bit_field = BitField.new(5)
bit_field.read_bits(0, 1, 2)
#=> {0=>1, 1=>0, 2=>1}
# because 5 is 101 in binary
@return [Hash] a hash with the bit index as key and bit (1 or 0) as value | [
"Initialize",
"the",
"BitField",
"with",
"an",
"optional",
"value",
".",
"Default",
"is",
"0"
] | 78b7fc28313af9c9506220812573576d229186bb | https://github.com/userhello/bit_magic/blob/78b7fc28313af9c9506220812573576d229186bb/lib/bit_magic/bit_field.rb#L35-L39 | train |
userhello/bit_magic | lib/bit_magic/bit_field.rb | BitMagic.BitField.read_field | def read_field(*args)
m = 0
args.flatten.each_with_index do |bit, i|
if bit.is_a?(Integer)
m |= ((@value[bit] || 0) << i)
end
end
m
end | ruby | def read_field(*args)
m = 0
args.flatten.each_with_index do |bit, i|
if bit.is_a?(Integer)
m |= ((@value[bit] || 0) << i)
end
end
m
end | [
"def",
"read_field",
"(",
"*",
"args",
")",
"m",
"=",
"0",
"args",
".",
"flatten",
".",
"each_with_index",
"do",
"|",
"bit",
",",
"i",
"|",
"if",
"bit",
".",
"is_a?",
"(",
"Integer",
")",
"m",
"|=",
"(",
"(",
"@value",
"[",
"bit",
"]",
"||",
"0",
")",
"<<",
"i",
")",
"end",
"end",
"m",
"end"
] | Read the specified bit indices as a group, in the order given
@param [Integer] bits one or more bit indices to read. Order matters!
@example Read bits or a list of bits into an integer
bit_field = BitField.new(101) # 1100101 in binary, lsb on the right
bit_field.read_field(0, 1, 2) #=> 5 # or 101
bit_field.read_field(0) #= 1
bit_field.read_field( (2..6).to_a ) #=> 25 # or 11001
@return [Integer] the value of the bits read together into an integer | [
"Read",
"the",
"specified",
"bit",
"indices",
"as",
"a",
"group",
"in",
"the",
"order",
"given"
] | 78b7fc28313af9c9506220812573576d229186bb | https://github.com/userhello/bit_magic/blob/78b7fc28313af9c9506220812573576d229186bb/lib/bit_magic/bit_field.rb#L52-L60 | train |
giraffi/zcloudjp | lib/zcloudjp/utils.rb | Zcloudjp.Utils.parse_params | def parse_params(params, key_word)
body = params.has_key?(:path) ? load_file(params[:path], key_word) : params
body = { key_word => body } unless body.has_key?(key_word.to_sym)
body
end | ruby | def parse_params(params, key_word)
body = params.has_key?(:path) ? load_file(params[:path], key_word) : params
body = { key_word => body } unless body.has_key?(key_word.to_sym)
body
end | [
"def",
"parse_params",
"(",
"params",
",",
"key_word",
")",
"body",
"=",
"params",
".",
"has_key?",
"(",
":path",
")",
"?",
"load_file",
"(",
"params",
"[",
":path",
"]",
",",
"key_word",
")",
":",
"params",
"body",
"=",
"{",
"key_word",
"=>",
"body",
"}",
"unless",
"body",
".",
"has_key?",
"(",
"key_word",
".",
"to_sym",
")",
"body",
"end"
] | Parses given params or file and returns Hash including the given key. | [
"Parses",
"given",
"params",
"or",
"file",
"and",
"returns",
"Hash",
"including",
"the",
"given",
"key",
"."
] | 0ee8dd49cf469fd182a48856fae63f606a959de5 | https://github.com/giraffi/zcloudjp/blob/0ee8dd49cf469fd182a48856fae63f606a959de5/lib/zcloudjp/utils.rb#L7-L11 | train |
giraffi/zcloudjp | lib/zcloudjp/utils.rb | Zcloudjp.Utils.load_file | def load_file(path, key_word)
begin
data = MultiJson.load(IO.read(File.expand_path(path)), symbolize_keys: true)
rescue RuntimeError, Errno::ENOENT => e
raise e.message
rescue MultiJson::LoadError => e
raise e.message
end
if data.has_key?(key_word)
data[key_word].map { |k,v| data[key_word][k] = v } if data[key_word].is_a? Hash
end
data
end | ruby | def load_file(path, key_word)
begin
data = MultiJson.load(IO.read(File.expand_path(path)), symbolize_keys: true)
rescue RuntimeError, Errno::ENOENT => e
raise e.message
rescue MultiJson::LoadError => e
raise e.message
end
if data.has_key?(key_word)
data[key_word].map { |k,v| data[key_word][k] = v } if data[key_word].is_a? Hash
end
data
end | [
"def",
"load_file",
"(",
"path",
",",
"key_word",
")",
"begin",
"data",
"=",
"MultiJson",
".",
"load",
"(",
"IO",
".",
"read",
"(",
"File",
".",
"expand_path",
"(",
"path",
")",
")",
",",
"symbolize_keys",
":",
"true",
")",
"rescue",
"RuntimeError",
",",
"Errno",
"::",
"ENOENT",
"=>",
"e",
"raise",
"e",
".",
"message",
"rescue",
"MultiJson",
"::",
"LoadError",
"=>",
"e",
"raise",
"e",
".",
"message",
"end",
"if",
"data",
".",
"has_key?",
"(",
"key_word",
")",
"data",
"[",
"key_word",
"]",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"data",
"[",
"key_word",
"]",
"[",
"k",
"]",
"=",
"v",
"}",
"if",
"data",
"[",
"key_word",
"]",
".",
"is_a?",
"Hash",
"end",
"data",
"end"
] | Loads a specified file and returns Hash including the given key. | [
"Loads",
"a",
"specified",
"file",
"and",
"returns",
"Hash",
"including",
"the",
"given",
"key",
"."
] | 0ee8dd49cf469fd182a48856fae63f606a959de5 | https://github.com/giraffi/zcloudjp/blob/0ee8dd49cf469fd182a48856fae63f606a959de5/lib/zcloudjp/utils.rb#L14-L26 | train |
cespare/pinion | lib/pinion/server.rb | Pinion.Server.bundle_url | def bundle_url(name)
bundle = Bundle[name]
raise "No such bundle: #{name}" unless bundle
return bundle.paths.map { |p| asset_url(p) } unless Pinion.environment == "production"
["#{@mount_point}/#{bundle.name}-#{bundle.checksum}.#{bundle.extension}"]
end | ruby | def bundle_url(name)
bundle = Bundle[name]
raise "No such bundle: #{name}" unless bundle
return bundle.paths.map { |p| asset_url(p) } unless Pinion.environment == "production"
["#{@mount_point}/#{bundle.name}-#{bundle.checksum}.#{bundle.extension}"]
end | [
"def",
"bundle_url",
"(",
"name",
")",
"bundle",
"=",
"Bundle",
"[",
"name",
"]",
"raise",
"\"No such bundle: #{name}\"",
"unless",
"bundle",
"return",
"bundle",
".",
"paths",
".",
"map",
"{",
"|",
"p",
"|",
"asset_url",
"(",
"p",
")",
"}",
"unless",
"Pinion",
".",
"environment",
"==",
"\"production\"",
"[",
"\"#{@mount_point}/#{bundle.name}-#{bundle.checksum}.#{bundle.extension}\"",
"]",
"end"
] | Return the bundle url. In production, the single bundled result is produced; otherwise, each individual
asset_url is returned. | [
"Return",
"the",
"bundle",
"url",
".",
"In",
"production",
"the",
"single",
"bundled",
"result",
"is",
"produced",
";",
"otherwise",
"each",
"individual",
"asset_url",
"is",
"returned",
"."
] | 6dea89da573cef93793a8d9b76e2e692581bddcf | https://github.com/cespare/pinion/blob/6dea89da573cef93793a8d9b76e2e692581bddcf/lib/pinion/server.rb#L148-L153 | train |
yjchen/easy_tag | lib/easy_tag/taggable.rb | EasyTag.Taggable.set_tags | def set_tags(tag_list, options = {})
options.reverse_merge! :context => nil,
:tagger => nil,
:downcase => true,
:delimiter => ','
if block_given?
tags = yield(klass)
else
tags = EasyTag::Tag.compact_tag_list(tag_list, options.slice(:downcase, :delimiter))
end
context = compact_context(options[:context])
tagger = compact_tagger(options[:tagger])
# Remove old tags
self.taggings.where(:tag_context_id => context.try(:id), :tagger_id => tagger.try(:id)).destroy_all
# TODO: should remove unused tags and contexts
if tags
tags.each do |t|
tag = EasyTag::Tag.where(:name => t).first_or_create
raise SimgleTag::InvalidTag if tag.nil?
self.taggings.where(:tagger_id => tagger.try(:id), :tag_context_id => context.try(:id), :tag_id => tag.id).first_or_create
end
end
end | ruby | def set_tags(tag_list, options = {})
options.reverse_merge! :context => nil,
:tagger => nil,
:downcase => true,
:delimiter => ','
if block_given?
tags = yield(klass)
else
tags = EasyTag::Tag.compact_tag_list(tag_list, options.slice(:downcase, :delimiter))
end
context = compact_context(options[:context])
tagger = compact_tagger(options[:tagger])
# Remove old tags
self.taggings.where(:tag_context_id => context.try(:id), :tagger_id => tagger.try(:id)).destroy_all
# TODO: should remove unused tags and contexts
if tags
tags.each do |t|
tag = EasyTag::Tag.where(:name => t).first_or_create
raise SimgleTag::InvalidTag if tag.nil?
self.taggings.where(:tagger_id => tagger.try(:id), :tag_context_id => context.try(:id), :tag_id => tag.id).first_or_create
end
end
end | [
"def",
"set_tags",
"(",
"tag_list",
",",
"options",
"=",
"{",
"}",
")",
"options",
".",
"reverse_merge!",
":context",
"=>",
"nil",
",",
":tagger",
"=>",
"nil",
",",
":downcase",
"=>",
"true",
",",
":delimiter",
"=>",
"','",
"if",
"block_given?",
"tags",
"=",
"yield",
"(",
"klass",
")",
"else",
"tags",
"=",
"EasyTag",
"::",
"Tag",
".",
"compact_tag_list",
"(",
"tag_list",
",",
"options",
".",
"slice",
"(",
":downcase",
",",
":delimiter",
")",
")",
"end",
"context",
"=",
"compact_context",
"(",
"options",
"[",
":context",
"]",
")",
"tagger",
"=",
"compact_tagger",
"(",
"options",
"[",
":tagger",
"]",
")",
"self",
".",
"taggings",
".",
"where",
"(",
":tag_context_id",
"=>",
"context",
".",
"try",
"(",
":id",
")",
",",
":tagger_id",
"=>",
"tagger",
".",
"try",
"(",
":id",
")",
")",
".",
"destroy_all",
"if",
"tags",
"tags",
".",
"each",
"do",
"|",
"t",
"|",
"tag",
"=",
"EasyTag",
"::",
"Tag",
".",
"where",
"(",
":name",
"=>",
"t",
")",
".",
"first_or_create",
"raise",
"SimgleTag",
"::",
"InvalidTag",
"if",
"tag",
".",
"nil?",
"self",
".",
"taggings",
".",
"where",
"(",
":tagger_id",
"=>",
"tagger",
".",
"try",
"(",
":id",
")",
",",
":tag_context_id",
"=>",
"context",
".",
"try",
"(",
":id",
")",
",",
":tag_id",
"=>",
"tag",
".",
"id",
")",
".",
"first_or_create",
"end",
"end",
"end"
] | end of class methods | [
"end",
"of",
"class",
"methods"
] | 960c4cc2407e4f5d7c1a84c2855b936e42626ec0 | https://github.com/yjchen/easy_tag/blob/960c4cc2407e4f5d7c1a84c2855b936e42626ec0/lib/easy_tag/taggable.rb#L67-L93 | train |
caimano/rlocu2 | lib/rlocu2/objects.rb | Rlocu2.Venue.external= | def external=(externals_list)
@external = []
externals_list.each { |external_id| @external << Rlocu2::ExternalID.new(id: external_id['id'], url: external_id['url'], mobile_url: external_id['mobile_url'])}
end | ruby | def external=(externals_list)
@external = []
externals_list.each { |external_id| @external << Rlocu2::ExternalID.new(id: external_id['id'], url: external_id['url'], mobile_url: external_id['mobile_url'])}
end | [
"def",
"external",
"=",
"(",
"externals_list",
")",
"@external",
"=",
"[",
"]",
"externals_list",
".",
"each",
"{",
"|",
"external_id",
"|",
"@external",
"<<",
"Rlocu2",
"::",
"ExternalID",
".",
"new",
"(",
"id",
":",
"external_id",
"[",
"'id'",
"]",
",",
"url",
":",
"external_id",
"[",
"'url'",
"]",
",",
"mobile_url",
":",
"external_id",
"[",
"'mobile_url'",
"]",
")",
"}",
"end"
] | BUILD sub structures | [
"BUILD",
"sub",
"structures"
] | 8117bc034816c03a435160301c99c9a1b4e603df | https://github.com/caimano/rlocu2/blob/8117bc034816c03a435160301c99c9a1b4e603df/lib/rlocu2/objects.rb#L17-L20 | train |
indeep-xyz/ruby-file-char-licker | lib/file_char_licker/licker/licker.rb | FileCharLicker.Licker.forward_lines | def forward_lines(size = 10)
file = @file
result = ""
while result.scan(/\r\n|\r|\n/).size < size && !file.eof?
result += file.gets
end
result
end | ruby | def forward_lines(size = 10)
file = @file
result = ""
while result.scan(/\r\n|\r|\n/).size < size && !file.eof?
result += file.gets
end
result
end | [
"def",
"forward_lines",
"(",
"size",
"=",
"10",
")",
"file",
"=",
"@file",
"result",
"=",
"\"\"",
"while",
"result",
".",
"scan",
"(",
"/",
"\\r",
"\\n",
"\\r",
"\\n",
"/",
")",
".",
"size",
"<",
"size",
"&&",
"!",
"file",
".",
"eof?",
"result",
"+=",
"file",
".",
"gets",
"end",
"result",
"end"
] | get forward lines
args
size ... number of lines
returner
String object as lines | [
"get",
"forward",
"lines"
] | 06d9cee1bf0a40a1f90f35e6b43e211609a03b08 | https://github.com/indeep-xyz/ruby-file-char-licker/blob/06d9cee1bf0a40a1f90f35e6b43e211609a03b08/lib/file_char_licker/licker/licker.rb#L118-L129 | train |
mirego/parole | lib/parole/comment.rb | Parole.Comment.ensure_valid_role_for_commentable | def ensure_valid_role_for_commentable
allowed_roles = commentable.class.commentable_options[:roles]
if allowed_roles.any?
errors.add(:role, :invalid) unless allowed_roles.include?(self.role)
else
errors.add(:role, :invalid) unless self.role.blank?
end
end | ruby | def ensure_valid_role_for_commentable
allowed_roles = commentable.class.commentable_options[:roles]
if allowed_roles.any?
errors.add(:role, :invalid) unless allowed_roles.include?(self.role)
else
errors.add(:role, :invalid) unless self.role.blank?
end
end | [
"def",
"ensure_valid_role_for_commentable",
"allowed_roles",
"=",
"commentable",
".",
"class",
".",
"commentable_options",
"[",
":roles",
"]",
"if",
"allowed_roles",
".",
"any?",
"errors",
".",
"add",
"(",
":role",
",",
":invalid",
")",
"unless",
"allowed_roles",
".",
"include?",
"(",
"self",
".",
"role",
")",
"else",
"errors",
".",
"add",
"(",
":role",
",",
":invalid",
")",
"unless",
"self",
".",
"role",
".",
"blank?",
"end",
"end"
] | Make sure that the value of the `role` attribute is a valid role
for the commentable.
If the commentable doesn't have any comment roles, we make sure
that the value is blank. | [
"Make",
"sure",
"that",
"the",
"value",
"of",
"the",
"role",
"attribute",
"is",
"a",
"valid",
"role",
"for",
"the",
"commentable",
"."
] | b8fb33dc14ef2d2af37c92ed0d0cddec52575951 | https://github.com/mirego/parole/blob/b8fb33dc14ef2d2af37c92ed0d0cddec52575951/lib/parole/comment.rb#L51-L59 | train |
fotonauts/activr | lib/activr/dispatcher.rb | Activr.Dispatcher.route | def route(activity)
raise "Activity must be stored before routing: #{activity.inspect}" if !activity.stored?
result = 0
activity.run_callbacks(:route) do
# iterate on all timelines
Activr.registry.timelines.values.each do |timeline_class|
# check if timeline refuses that activity
next unless timeline_class.should_route_activity?(activity)
# store activity in timelines
self.recipients_for_timeline(timeline_class, activity).each do |recipient, route|
result += 1
timeline = timeline_class.new(recipient)
if timeline.should_handle_activity?(activity, route)
Activr::Async.hook(:timeline_handle, timeline, activity, route)
end
end
end
end
result
end | ruby | def route(activity)
raise "Activity must be stored before routing: #{activity.inspect}" if !activity.stored?
result = 0
activity.run_callbacks(:route) do
# iterate on all timelines
Activr.registry.timelines.values.each do |timeline_class|
# check if timeline refuses that activity
next unless timeline_class.should_route_activity?(activity)
# store activity in timelines
self.recipients_for_timeline(timeline_class, activity).each do |recipient, route|
result += 1
timeline = timeline_class.new(recipient)
if timeline.should_handle_activity?(activity, route)
Activr::Async.hook(:timeline_handle, timeline, activity, route)
end
end
end
end
result
end | [
"def",
"route",
"(",
"activity",
")",
"raise",
"\"Activity must be stored before routing: #{activity.inspect}\"",
"if",
"!",
"activity",
".",
"stored?",
"result",
"=",
"0",
"activity",
".",
"run_callbacks",
"(",
":route",
")",
"do",
"Activr",
".",
"registry",
".",
"timelines",
".",
"values",
".",
"each",
"do",
"|",
"timeline_class",
"|",
"next",
"unless",
"timeline_class",
".",
"should_route_activity?",
"(",
"activity",
")",
"self",
".",
"recipients_for_timeline",
"(",
"timeline_class",
",",
"activity",
")",
".",
"each",
"do",
"|",
"recipient",
",",
"route",
"|",
"result",
"+=",
"1",
"timeline",
"=",
"timeline_class",
".",
"new",
"(",
"recipient",
")",
"if",
"timeline",
".",
"should_handle_activity?",
"(",
"activity",
",",
"route",
")",
"Activr",
"::",
"Async",
".",
"hook",
"(",
":timeline_handle",
",",
"timeline",
",",
"activity",
",",
"route",
")",
"end",
"end",
"end",
"end",
"result",
"end"
] | Route an activity
@param activity [Activity] Activity to route
@return [Integer] The number of resolved recipients that will handle activity | [
"Route",
"an",
"activity"
] | 92c071ad18a76d4130661da3ce47c1f0fb8ae913 | https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/dispatcher.rb#L14-L38 | train |
fotonauts/activr | lib/activr/dispatcher.rb | Activr.Dispatcher.recipients_for_timeline | def recipients_for_timeline(timeline_class, activity)
result = { }
routes = timeline_class.routes_for_activity(activity.class)
routes.each do |route|
route.resolve(activity).each do |recipient|
recipient_id = timeline_class.recipient_id(recipient)
# keep only one route per recipient
if result[recipient_id].nil?
result[recipient_id] = { :rcpt => recipient, :route => route }
end
end
end
result.inject({ }) do |memo, (recipient_id, infos)|
memo[infos[:rcpt]] = infos[:route]
memo
end
end | ruby | def recipients_for_timeline(timeline_class, activity)
result = { }
routes = timeline_class.routes_for_activity(activity.class)
routes.each do |route|
route.resolve(activity).each do |recipient|
recipient_id = timeline_class.recipient_id(recipient)
# keep only one route per recipient
if result[recipient_id].nil?
result[recipient_id] = { :rcpt => recipient, :route => route }
end
end
end
result.inject({ }) do |memo, (recipient_id, infos)|
memo[infos[:rcpt]] = infos[:route]
memo
end
end | [
"def",
"recipients_for_timeline",
"(",
"timeline_class",
",",
"activity",
")",
"result",
"=",
"{",
"}",
"routes",
"=",
"timeline_class",
".",
"routes_for_activity",
"(",
"activity",
".",
"class",
")",
"routes",
".",
"each",
"do",
"|",
"route",
"|",
"route",
".",
"resolve",
"(",
"activity",
")",
".",
"each",
"do",
"|",
"recipient",
"|",
"recipient_id",
"=",
"timeline_class",
".",
"recipient_id",
"(",
"recipient",
")",
"if",
"result",
"[",
"recipient_id",
"]",
".",
"nil?",
"result",
"[",
"recipient_id",
"]",
"=",
"{",
":rcpt",
"=>",
"recipient",
",",
":route",
"=>",
"route",
"}",
"end",
"end",
"end",
"result",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"memo",
",",
"(",
"recipient_id",
",",
"infos",
")",
"|",
"memo",
"[",
"infos",
"[",
":rcpt",
"]",
"]",
"=",
"infos",
"[",
":route",
"]",
"memo",
"end",
"end"
] | Find recipients for given activity in given timeline
@api private
@param timeline_class [Class] Timeline class
@param activity [Activity] Activity instance
@return [Hash{Object=>Timeline::Route}] Recipients with corresponding Routes | [
"Find",
"recipients",
"for",
"given",
"activity",
"in",
"given",
"timeline"
] | 92c071ad18a76d4130661da3ce47c1f0fb8ae913 | https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/dispatcher.rb#L47-L66 | train |
agios/simple_form-dojo | lib/simple_form-dojo/dojo_props_methods.rb | SimpleFormDojo.DojoPropsMethods.get_and_merge_dojo_props! | def get_and_merge_dojo_props!
add_dojo_options_to_dojo_props
if object.id.present?
add_dojo_compliant_id
else
input_html_options["id"] = nil #let dojo generate internal id
end
input_html_options[:'data-dojo-props'] = SimpleFormDojo::FormBuilder.encode_as_dojo_props(@dojo_props) if !@dojo_props.blank?
end | ruby | def get_and_merge_dojo_props!
add_dojo_options_to_dojo_props
if object.id.present?
add_dojo_compliant_id
else
input_html_options["id"] = nil #let dojo generate internal id
end
input_html_options[:'data-dojo-props'] = SimpleFormDojo::FormBuilder.encode_as_dojo_props(@dojo_props) if !@dojo_props.blank?
end | [
"def",
"get_and_merge_dojo_props!",
"add_dojo_options_to_dojo_props",
"if",
"object",
".",
"id",
".",
"present?",
"add_dojo_compliant_id",
"else",
"input_html_options",
"[",
"\"id\"",
"]",
"=",
"nil",
"end",
"input_html_options",
"[",
":'",
"'",
"]",
"=",
"SimpleFormDojo",
"::",
"FormBuilder",
".",
"encode_as_dojo_props",
"(",
"@dojo_props",
")",
"if",
"!",
"@dojo_props",
".",
"blank?",
"end"
] | Retrieves and merges all dojo_props | [
"Retrieves",
"and",
"merges",
"all",
"dojo_props"
] | c4b134f56f4cb68cba81d583038965360c70fba4 | https://github.com/agios/simple_form-dojo/blob/c4b134f56f4cb68cba81d583038965360c70fba4/lib/simple_form-dojo/dojo_props_methods.rb#L5-L13 | train |
nsi-iff/nsisam-ruby | lib/nsisam/client.rb | NSISam.Client.store | def store(data)
request_data = {:value => data}
request_data[:expire] = @expire if @expire
request = prepare_request :POST, request_data.to_json
Response.new(execute_request(request))
end | ruby | def store(data)
request_data = {:value => data}
request_data[:expire] = @expire if @expire
request = prepare_request :POST, request_data.to_json
Response.new(execute_request(request))
end | [
"def",
"store",
"(",
"data",
")",
"request_data",
"=",
"{",
":value",
"=>",
"data",
"}",
"request_data",
"[",
":expire",
"]",
"=",
"@expire",
"if",
"@expire",
"request",
"=",
"prepare_request",
":POST",
",",
"request_data",
".",
"to_json",
"Response",
".",
"new",
"(",
"execute_request",
"(",
"request",
")",
")",
"end"
] | Initialize a client to a SAM node hosted at a specific url
@param [Hash] optional hash with user, password, host and port of the SAM node
@return [Client] the object itself
@example
nsisam = NSISam::Client.new user: 'username' password: 'pass',
host: 'localhost', port: '8888'
Store a given data in SAM
@param [String] data the desired data to store
@return [Hash] response with the data key and checksum
* "key" [String] the key to access the stored data
* "checksum" [String] the sha512 checksum of the stored data
@raise [NSISam::Errors::Client::AuthenticationError] when user and password doesn't match
@example
nsisam.store("something") | [
"Initialize",
"a",
"client",
"to",
"a",
"SAM",
"node",
"hosted",
"at",
"a",
"specific",
"url"
] | 344725ba119899f4ac5b869d31f555a2e365cadb | https://github.com/nsi-iff/nsisam-ruby/blob/344725ba119899f4ac5b869d31f555a2e365cadb/lib/nsisam/client.rb#L42-L47 | train |
nsi-iff/nsisam-ruby | lib/nsisam/client.rb | NSISam.Client.store_file | def store_file(file_content, filename, type=:file)
store(type => Base64.encode64(file_content), :filename => filename)
end | ruby | def store_file(file_content, filename, type=:file)
store(type => Base64.encode64(file_content), :filename => filename)
end | [
"def",
"store_file",
"(",
"file_content",
",",
"filename",
",",
"type",
"=",
":file",
")",
"store",
"(",
"type",
"=>",
"Base64",
".",
"encode64",
"(",
"file_content",
")",
",",
":filename",
"=>",
"filename",
")",
"end"
] | Store a file in SAM. If the file will be used by other NSI's service
you should pass an additional 'type' parameter.
@param [Object] file_content json serializable object
@param [Symbol] type of the file to be stored. Can be either :doc and :video.
@return [Response] object with access to the key and the sha512 checkum of the stored data
@raise [NSISam::Errors::Client::AuthenticationError] when user and password doesn't match
@example
nsisam.store_file(File.read("foo.txt"))
nsisam.store_file(File.read("foo.txt"), :video) | [
"Store",
"a",
"file",
"in",
"SAM",
".",
"If",
"the",
"file",
"will",
"be",
"used",
"by",
"other",
"NSI",
"s",
"service",
"you",
"should",
"pass",
"an",
"additional",
"type",
"parameter",
"."
] | 344725ba119899f4ac5b869d31f555a2e365cadb | https://github.com/nsi-iff/nsisam-ruby/blob/344725ba119899f4ac5b869d31f555a2e365cadb/lib/nsisam/client.rb#L61-L63 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.