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
mnipper/serket
lib/serket/field_decrypter.rb
Serket.FieldDecrypter.parse
def parse(field) case @format when :delimited field.split(field_delimiter) when :json parsed = JSON.parse(field) [parsed['iv'], parsed['key'], parsed['message']] end end
ruby
def parse(field) case @format when :delimited field.split(field_delimiter) when :json parsed = JSON.parse(field) [parsed['iv'], parsed['key'], parsed['message']] end end
[ "def", "parse", "(", "field", ")", "case", "@format", "when", ":delimited", "field", ".", "split", "(", "field_delimiter", ")", "when", ":json", "parsed", "=", "JSON", ".", "parse", "(", "field", ")", "[", "parsed", "[", "'iv'", "]", ",", "parsed", "[", "'key'", "]", ",", "parsed", "[", "'message'", "]", "]", "end", "end" ]
Extracts the initialization vector, encrypted key, and cipher text according to the specified format. delimited: * Expected format: iv::encrypted-key::ciphertext json: * Expected keys: iv, key, message
[ "Extracts", "the", "initialization", "vector", "encrypted", "key", "and", "cipher", "text", "according", "to", "the", "specified", "format", "." ]
a4606071fde8982d794ff1f8fc09c399ac92ba17
https://github.com/mnipper/serket/blob/a4606071fde8982d794ff1f8fc09c399ac92ba17/lib/serket/field_decrypter.rb#L59-L67
train
tonytonyjan/tj-bootstrap-helper
lib/tj_bootstrap_helper/helper.rb
TJBootstrapHelper.Helper.page_header
def page_header *args, &block if block_given? size = (1..6) === args.first ? args.first : 1 content_tag :div, :class => "page-header" do content_tag "h#{size}" do capture(&block) end end else title = args.first size = (1..6) === args.second ? args.second : 1 content_tag :div, content_tag("h#{size}", title), :class => "page-header" end end
ruby
def page_header *args, &block if block_given? size = (1..6) === args.first ? args.first : 1 content_tag :div, :class => "page-header" do content_tag "h#{size}" do capture(&block) end end else title = args.first size = (1..6) === args.second ? args.second : 1 content_tag :div, content_tag("h#{size}", title), :class => "page-header" end end
[ "def", "page_header", "*", "args", ",", "&", "block", "if", "block_given?", "size", "=", "(", "1", "..", "6", ")", "===", "args", ".", "first", "?", "args", ".", "first", ":", "1", "content_tag", ":div", ",", ":class", "=>", "\"page-header\"", "do", "content_tag", "\"h#{size}\"", "do", "capture", "(", "&", "block", ")", "end", "end", "else", "title", "=", "args", ".", "first", "size", "=", "(", "1", "..", "6", ")", "===", "args", ".", "second", "?", "args", ".", "second", ":", "1", "content_tag", ":div", ",", "content_tag", "(", "\"h#{size}\"", ",", "title", ")", ",", ":class", "=>", "\"page-header\"", "end", "end" ]
title, size = 1 size = 1, &block
[ "title", "size", "=", "1" ]
a11c104b8caf582a28a0a903ae4ea9ee200aca75
https://github.com/tonytonyjan/tj-bootstrap-helper/blob/a11c104b8caf582a28a0a903ae4ea9ee200aca75/lib/tj_bootstrap_helper/helper.rb#L25-L38
train
tonytonyjan/tj-bootstrap-helper
lib/tj_bootstrap_helper/helper.rb
TJBootstrapHelper.Helper.nav_li
def nav_li *args, &block options = (block_given? ? args.first : args.second) || {} url = url_for(options) active = "active" if url == request.path || url == request.url content_tag :li, :class => active do link_to *args, &block end end
ruby
def nav_li *args, &block options = (block_given? ? args.first : args.second) || {} url = url_for(options) active = "active" if url == request.path || url == request.url content_tag :li, :class => active do link_to *args, &block end end
[ "def", "nav_li", "*", "args", ",", "&", "block", "options", "=", "(", "block_given?", "?", "args", ".", "first", ":", "args", ".", "second", ")", "||", "{", "}", "url", "=", "url_for", "(", "options", ")", "active", "=", "\"active\"", "if", "url", "==", "request", ".", "path", "||", "url", "==", "request", ".", "url", "content_tag", ":li", ",", ":class", "=>", "active", "do", "link_to", "*", "args", ",", "&", "block", "end", "end" ]
Just like +link_to+, but wrap with li tag and set +class="active"+ to corresponding page.
[ "Just", "like", "+", "link_to", "+", "but", "wrap", "with", "li", "tag", "and", "set", "+", "class", "=", "active", "+", "to", "corresponding", "page", "." ]
a11c104b8caf582a28a0a903ae4ea9ee200aca75
https://github.com/tonytonyjan/tj-bootstrap-helper/blob/a11c104b8caf582a28a0a903ae4ea9ee200aca75/lib/tj_bootstrap_helper/helper.rb#L42-L49
train
spheromak/services
lib/services/connection.rb
Services.Connection.find_servers
def find_servers # need a run_context to find anything in return nil unless run_context # If there are already servers in attribs use those return node[:etcd][:servers] if node.key?(:etcd) && node[:etcd].key?(:servers) # if we have already searched in this run use those return node.run_state[:etcd_servers] if node.run_state.key? :etcd_servers # find nodes and build array of ip's etcd_nodes = search(:node, search_query) servers = etcd_nodes.map { |n| n[:ipaddress] } # store that in the run_state node.run_state[:etcd_servers] = servers end
ruby
def find_servers # need a run_context to find anything in return nil unless run_context # If there are already servers in attribs use those return node[:etcd][:servers] if node.key?(:etcd) && node[:etcd].key?(:servers) # if we have already searched in this run use those return node.run_state[:etcd_servers] if node.run_state.key? :etcd_servers # find nodes and build array of ip's etcd_nodes = search(:node, search_query) servers = etcd_nodes.map { |n| n[:ipaddress] } # store that in the run_state node.run_state[:etcd_servers] = servers end
[ "def", "find_servers", "return", "nil", "unless", "run_context", "return", "node", "[", ":etcd", "]", "[", ":servers", "]", "if", "node", ".", "key?", "(", ":etcd", ")", "&&", "node", "[", ":etcd", "]", ".", "key?", "(", ":servers", ")", "return", "node", ".", "run_state", "[", ":etcd_servers", "]", "if", "node", ".", "run_state", ".", "key?", ":etcd_servers", "etcd_nodes", "=", "search", "(", ":node", ",", "search_query", ")", "servers", "=", "etcd_nodes", ".", "map", "{", "|", "n", "|", "n", "[", ":ipaddress", "]", "}", "node", ".", "run_state", "[", ":etcd_servers", "]", "=", "servers", "end" ]
Find other Etd Servers by looking at node attributes or via Chef Search
[ "Find", "other", "Etd", "Servers", "by", "looking", "at", "node", "attributes", "or", "via", "Chef", "Search" ]
c14445954f4402f1ccdaf61d451e4d47b67de93b
https://github.com/spheromak/services/blob/c14445954f4402f1ccdaf61d451e4d47b67de93b/lib/services/connection.rb#L72-L88
train
spheromak/services
lib/services/connection.rb
Services.Connection.try_connect
def try_connect(server) c = ::Etcd.client(host: server, port: port, allow_redirect: @redirect) begin c.get '/_etcd/machines' return c rescue puts "ETCD: failed to connect to #{c.host}:#{c.port}" return nil end end
ruby
def try_connect(server) c = ::Etcd.client(host: server, port: port, allow_redirect: @redirect) begin c.get '/_etcd/machines' return c rescue puts "ETCD: failed to connect to #{c.host}:#{c.port}" return nil end end
[ "def", "try_connect", "(", "server", ")", "c", "=", "::", "Etcd", ".", "client", "(", "host", ":", "server", ",", "port", ":", "port", ",", "allow_redirect", ":", "@redirect", ")", "begin", "c", ".", "get", "'/_etcd/machines'", "return", "c", "rescue", "puts", "\"ETCD: failed to connect to #{c.host}:#{c.port}\"", "return", "nil", "end", "end" ]
Try to grab an etcd connection @param [String] server () The server to try to connect too
[ "Try", "to", "grab", "an", "etcd", "connection" ]
c14445954f4402f1ccdaf61d451e4d47b67de93b
https://github.com/spheromak/services/blob/c14445954f4402f1ccdaf61d451e4d47b67de93b/lib/services/connection.rb#L130-L139
train
danielbush/RubyCron
lib/CronR/Cron.rb
CronR.Cron.run
def run time=nil puts "[cron] run called #{Time.now}" if @debug time = self.time if time.nil? self.each { |cron_job| ok,details = cron_job.runnable?(time) if ok then @queue.enq(cron_job) if cron_job.once? then cron_job[:delete] = true end end } self.reject! { |cron_job| cron_job[:delete] } end
ruby
def run time=nil puts "[cron] run called #{Time.now}" if @debug time = self.time if time.nil? self.each { |cron_job| ok,details = cron_job.runnable?(time) if ok then @queue.enq(cron_job) if cron_job.once? then cron_job[:delete] = true end end } self.reject! { |cron_job| cron_job[:delete] } end
[ "def", "run", "time", "=", "nil", "puts", "\"[cron] run called #{Time.now}\"", "if", "@debug", "time", "=", "self", ".", "time", "if", "time", ".", "nil?", "self", ".", "each", "{", "|", "cron_job", "|", "ok", ",", "details", "=", "cron_job", ".", "runnable?", "(", "time", ")", "if", "ok", "then", "@queue", ".", "enq", "(", "cron_job", ")", "if", "cron_job", ".", "once?", "then", "cron_job", "[", ":delete", "]", "=", "true", "end", "end", "}", "self", ".", "reject!", "{", "|", "cron_job", "|", "cron_job", "[", ":delete", "]", "}", "end" ]
Check each item in this array, if runnable push it on a queue. We assume that this item is or simlar to CronJob. We don't call cron_job#job. That is the work for another thread esp. if #job is a Proc.
[ "Check", "each", "item", "in", "this", "array", "if", "runnable", "push", "it", "on", "a", "queue", "." ]
24a2f997b81663ded1ac1d01017e8d807d5caffd
https://github.com/danielbush/RubyCron/blob/24a2f997b81663ded1ac1d01017e8d807d5caffd/lib/CronR/Cron.rb#L124-L140
train
danielbush/RubyCron
lib/CronR/Cron.rb
CronR.Cron.start
def start debug=false,method=:every_minute,*args @stopped = false @suspended = false @dead = Queue.new @thread = CronR::Utils.send(method,debug,*args) { time = self.time @mutex.synchronize { if @stopped then # It's important we put something on this queue ONLY AFTER # we've acquired the mutex... @dead.enq(true) true elsif @suspended then else self.run(time) end } } end
ruby
def start debug=false,method=:every_minute,*args @stopped = false @suspended = false @dead = Queue.new @thread = CronR::Utils.send(method,debug,*args) { time = self.time @mutex.synchronize { if @stopped then # It's important we put something on this queue ONLY AFTER # we've acquired the mutex... @dead.enq(true) true elsif @suspended then else self.run(time) end } } end
[ "def", "start", "debug", "=", "false", ",", "method", "=", ":every_minute", ",", "*", "args", "@stopped", "=", "false", "@suspended", "=", "false", "@dead", "=", "Queue", ".", "new", "@thread", "=", "CronR", "::", "Utils", ".", "send", "(", "method", ",", "debug", ",", "*", "args", ")", "{", "time", "=", "self", ".", "time", "@mutex", ".", "synchronize", "{", "if", "@stopped", "then", "@dead", ".", "enq", "(", "true", ")", "true", "elsif", "@suspended", "then", "else", "self", ".", "run", "(", "time", ")", "end", "}", "}", "end" ]
Start cron. Will wake up every minute and perform #run.
[ "Start", "cron", "." ]
24a2f997b81663ded1ac1d01017e8d807d5caffd
https://github.com/danielbush/RubyCron/blob/24a2f997b81663ded1ac1d01017e8d807d5caffd/lib/CronR/Cron.rb#L146-L164
train
danielbush/RubyCron
lib/CronR/Cron.rb
CronR.Cron.stop
def stop &block if block_given? then @stopped = true @suspended = false # Wait till something is put on the dead queue... # This stops us from acquiring the mutex until after @thread # has processed @stopped set to true. sig = @dead.deq # The cron thread should be dead now, or wrapping up (with the # acquired mutex)... @mutex.synchronize { while @thread.alive? sleep 0.2 end block.call(self) } end end
ruby
def stop &block if block_given? then @stopped = true @suspended = false # Wait till something is put on the dead queue... # This stops us from acquiring the mutex until after @thread # has processed @stopped set to true. sig = @dead.deq # The cron thread should be dead now, or wrapping up (with the # acquired mutex)... @mutex.synchronize { while @thread.alive? sleep 0.2 end block.call(self) } end end
[ "def", "stop", "&", "block", "if", "block_given?", "then", "@stopped", "=", "true", "@suspended", "=", "false", "sig", "=", "@dead", ".", "deq", "@mutex", ".", "synchronize", "{", "while", "@thread", ".", "alive?", "sleep", "0.2", "end", "block", ".", "call", "(", "self", ")", "}", "end", "end" ]
Gracefully stop the thread. If block is given, it will be called once the thread has stopped.
[ "Gracefully", "stop", "the", "thread", "." ]
24a2f997b81663ded1ac1d01017e8d807d5caffd
https://github.com/danielbush/RubyCron/blob/24a2f997b81663ded1ac1d01017e8d807d5caffd/lib/CronR/Cron.rb#L190-L207
train
NUBIC/aker
lib/aker/form/middleware/login_renderer.rb
Aker::Form::Middleware.LoginRenderer.provide_login_html
def provide_login_html(env) request = ::Rack::Request.new(env) html = login_html(env, :url => request['url'], :session_expired => request['session_expired']) html_response(html).finish end
ruby
def provide_login_html(env) request = ::Rack::Request.new(env) html = login_html(env, :url => request['url'], :session_expired => request['session_expired']) html_response(html).finish end
[ "def", "provide_login_html", "(", "env", ")", "request", "=", "::", "Rack", "::", "Request", ".", "new", "(", "env", ")", "html", "=", "login_html", "(", "env", ",", ":url", "=>", "request", "[", "'url'", "]", ",", ":session_expired", "=>", "request", "[", "'session_expired'", "]", ")", "html_response", "(", "html", ")", ".", "finish", "end" ]
An HTML form for logging in. @param env the Rack environment @return a finished Rack response
[ "An", "HTML", "form", "for", "logging", "in", "." ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/form/middleware/login_renderer.rb#L55-L60
train
kvokka/active_admin_simple_life
lib/active_admin_simple_life/simple_elements.rb
ActiveAdminSimpleLife.SimpleElements.filter_for_main_fields
def filter_for_main_fields(klass, options ={}) klass.main_fields.each do |f| if f == :gender filter ExtensionedSymbol.new(f).cut_id, collection: genders else filter ExtensionedSymbol.new(f).cut_id end end end
ruby
def filter_for_main_fields(klass, options ={}) klass.main_fields.each do |f| if f == :gender filter ExtensionedSymbol.new(f).cut_id, collection: genders else filter ExtensionedSymbol.new(f).cut_id end end end
[ "def", "filter_for_main_fields", "(", "klass", ",", "options", "=", "{", "}", ")", "klass", ".", "main_fields", ".", "each", "do", "|", "f", "|", "if", "f", "==", ":gender", "filter", "ExtensionedSymbol", ".", "new", "(", "f", ")", ".", "cut_id", ",", "collection", ":", "genders", "else", "filter", "ExtensionedSymbol", ".", "new", "(", "f", ")", ".", "cut_id", "end", "end", "end" ]
it check only for gender field for now
[ "it", "check", "only", "for", "gender", "field", "for", "now" ]
050ac1a87462c2b57bd42bae43df3cb0c238c42b
https://github.com/kvokka/active_admin_simple_life/blob/050ac1a87462c2b57bd42bae43df3cb0c238c42b/lib/active_admin_simple_life/simple_elements.rb#L41-L49
train
kvokka/active_admin_simple_life
lib/active_admin_simple_life/simple_elements.rb
ActiveAdminSimpleLife.SimpleElements.nested_form_for_main_fields
def nested_form_for_main_fields(klass, nested_klass, options={}) form_for_main_fields(klass,options) do |form_field| nested_table_name = nested_klass.to_s.underscore.pluralize.to_sym main_model_name = klass.to_s.underscore.to_sym form_field.has_many nested_table_name, allow_destroy: true do |form| nested_klass.main_fields.map { |f| ExtensionedSymbol.new(f).cut_id }.each do |nested_field| current_options = options.fetch(nested_table_name){{}}.fetch(nested_field){{}} form.input(nested_field, current_options) unless nested_field == main_model_name end end end end
ruby
def nested_form_for_main_fields(klass, nested_klass, options={}) form_for_main_fields(klass,options) do |form_field| nested_table_name = nested_klass.to_s.underscore.pluralize.to_sym main_model_name = klass.to_s.underscore.to_sym form_field.has_many nested_table_name, allow_destroy: true do |form| nested_klass.main_fields.map { |f| ExtensionedSymbol.new(f).cut_id }.each do |nested_field| current_options = options.fetch(nested_table_name){{}}.fetch(nested_field){{}} form.input(nested_field, current_options) unless nested_field == main_model_name end end end end
[ "def", "nested_form_for_main_fields", "(", "klass", ",", "nested_klass", ",", "options", "=", "{", "}", ")", "form_for_main_fields", "(", "klass", ",", "options", ")", "do", "|", "form_field", "|", "nested_table_name", "=", "nested_klass", ".", "to_s", ".", "underscore", ".", "pluralize", ".", "to_sym", "main_model_name", "=", "klass", ".", "to_s", ".", "underscore", ".", "to_sym", "form_field", ".", "has_many", "nested_table_name", ",", "allow_destroy", ":", "true", "do", "|", "form", "|", "nested_klass", ".", "main_fields", ".", "map", "{", "|", "f", "|", "ExtensionedSymbol", ".", "new", "(", "f", ")", ".", "cut_id", "}", ".", "each", "do", "|", "nested_field", "|", "current_options", "=", "options", ".", "fetch", "(", "nested_table_name", ")", "{", "{", "}", "}", ".", "fetch", "(", "nested_field", ")", "{", "{", "}", "}", "form", ".", "input", "(", "nested_field", ",", "current_options", ")", "unless", "nested_field", "==", "main_model_name", "end", "end", "end", "end" ]
simple nested set for 2 classes with defined main_fields
[ "simple", "nested", "set", "for", "2", "classes", "with", "defined", "main_fields" ]
050ac1a87462c2b57bd42bae43df3cb0c238c42b
https://github.com/kvokka/active_admin_simple_life/blob/050ac1a87462c2b57bd42bae43df3cb0c238c42b/lib/active_admin_simple_life/simple_elements.rb#L71-L82
train
pwnall/authpwn_rails
lib/authpwn_rails/http_basic.rb
Authpwn.HttpBasicControllerInstanceMethods.authenticate_using_http_basic
def authenticate_using_http_basic return if current_user authenticate_with_http_basic do |email, password| signin = Session.new email: email, password: password auth = User.authenticate_signin signin self.current_user = auth unless auth.kind_of? Symbol end end
ruby
def authenticate_using_http_basic return if current_user authenticate_with_http_basic do |email, password| signin = Session.new email: email, password: password auth = User.authenticate_signin signin self.current_user = auth unless auth.kind_of? Symbol end end
[ "def", "authenticate_using_http_basic", "return", "if", "current_user", "authenticate_with_http_basic", "do", "|", "email", ",", "password", "|", "signin", "=", "Session", ".", "new", "email", ":", "email", ",", "password", ":", "password", "auth", "=", "User", ".", "authenticate_signin", "signin", "self", ".", "current_user", "=", "auth", "unless", "auth", ".", "kind_of?", "Symbol", "end", "end" ]
The before_action that implements authenticates_using_http_basic. If your ApplicationController contains authenticates_using_http_basic, you can opt out in individual controllers using skip_before_action. skip_before_action :authenticate_using_http_basic
[ "The", "before_action", "that", "implements", "authenticates_using_http_basic", "." ]
de3bd612a00025e8dc8296a73abe3acba948db17
https://github.com/pwnall/authpwn_rails/blob/de3bd612a00025e8dc8296a73abe3acba948db17/lib/authpwn_rails/http_basic.rb#L29-L36
train
sideshowcoder/activerecord_translatable
lib/activerecord_translatable/extension.rb
ActiveRecordTranslatable.ClassMethods.translate
def translate(*attributes) self._translatable ||= Hash.new { |h,k| h[k] = [] } self._translatable[base_name] = translatable.concat(attributes).uniq end
ruby
def translate(*attributes) self._translatable ||= Hash.new { |h,k| h[k] = [] } self._translatable[base_name] = translatable.concat(attributes).uniq end
[ "def", "translate", "(", "*", "attributes", ")", "self", ".", "_translatable", "||=", "Hash", ".", "new", "{", "|", "h", ",", "k", "|", "h", "[", "k", "]", "=", "[", "]", "}", "self", ".", "_translatable", "[", "base_name", "]", "=", "translatable", ".", "concat", "(", "attributes", ")", ".", "uniq", "end" ]
Define attribute as translatable class Thing < ActiveRecord::Base translate :name end
[ "Define", "attribute", "as", "translatable" ]
42f9508530db39d0edaf2d7dc6c5d9ee1b0375fb
https://github.com/sideshowcoder/activerecord_translatable/blob/42f9508530db39d0edaf2d7dc6c5d9ee1b0375fb/lib/activerecord_translatable/extension.rb#L91-L94
train
leoc/em-systemcommand
lib/em-systemcommand.rb
EventMachine.SystemCommand.execute
def execute &block raise 'Previous process still exists' unless pipes.empty? # clear callbacks @callbacks = [] @errbacks = [] pid, stdin, stdout, stderr = POSIX::Spawn.popen4 @command.to_s @pid = pid @stdin = attach_pipe_handler :stdin, stdin @stdout = attach_pipe_handler :stdout, stdout @stderr = attach_pipe_handler :stderr, stderr if block block.call self elsif @execution_proc @execution_proc.call self end self end
ruby
def execute &block raise 'Previous process still exists' unless pipes.empty? # clear callbacks @callbacks = [] @errbacks = [] pid, stdin, stdout, stderr = POSIX::Spawn.popen4 @command.to_s @pid = pid @stdin = attach_pipe_handler :stdin, stdin @stdout = attach_pipe_handler :stdout, stdout @stderr = attach_pipe_handler :stderr, stderr if block block.call self elsif @execution_proc @execution_proc.call self end self end
[ "def", "execute", "&", "block", "raise", "'Previous process still exists'", "unless", "pipes", ".", "empty?", "@callbacks", "=", "[", "]", "@errbacks", "=", "[", "]", "pid", ",", "stdin", ",", "stdout", ",", "stderr", "=", "POSIX", "::", "Spawn", ".", "popen4", "@command", ".", "to_s", "@pid", "=", "pid", "@stdin", "=", "attach_pipe_handler", ":stdin", ",", "stdin", "@stdout", "=", "attach_pipe_handler", ":stdout", ",", "stdout", "@stderr", "=", "attach_pipe_handler", ":stderr", ",", "stderr", "if", "block", "block", ".", "call", "self", "elsif", "@execution_proc", "@execution_proc", ".", "call", "self", "end", "self", "end" ]
Executes the command from the `Builder` object. If there had been given a block at instantiation it will be called after the `popen3` call and after the pipes have been attached.
[ "Executes", "the", "command", "from", "the", "Builder", "object", ".", "If", "there", "had", "been", "given", "a", "block", "at", "instantiation", "it", "will", "be", "called", "after", "the", "popen3", "call", "and", "after", "the", "pipes", "have", "been", "attached", "." ]
e1987253527c4b4dcc8ca7fe5ce6a16235f4810d
https://github.com/leoc/em-systemcommand/blob/e1987253527c4b4dcc8ca7fe5ce6a16235f4810d/lib/em-systemcommand.rb#L63-L83
train
leoc/em-systemcommand
lib/em-systemcommand.rb
EventMachine.SystemCommand.unbind
def unbind name pipes.delete name if pipes.empty? exit_callbacks.each do |cb| EM.next_tick do cb.call status end end if status.exitstatus == 0 EM.next_tick do succeed self end else EM.next_tick do fail self end end end end
ruby
def unbind name pipes.delete name if pipes.empty? exit_callbacks.each do |cb| EM.next_tick do cb.call status end end if status.exitstatus == 0 EM.next_tick do succeed self end else EM.next_tick do fail self end end end end
[ "def", "unbind", "name", "pipes", ".", "delete", "name", "if", "pipes", ".", "empty?", "exit_callbacks", ".", "each", "do", "|", "cb", "|", "EM", ".", "next_tick", "do", "cb", ".", "call", "status", "end", "end", "if", "status", ".", "exitstatus", "==", "0", "EM", ".", "next_tick", "do", "succeed", "self", "end", "else", "EM", ".", "next_tick", "do", "fail", "self", "end", "end", "end", "end" ]
Called by child pipes when they get unbound.
[ "Called", "by", "child", "pipes", "when", "they", "get", "unbound", "." ]
e1987253527c4b4dcc8ca7fe5ce6a16235f4810d
https://github.com/leoc/em-systemcommand/blob/e1987253527c4b4dcc8ca7fe5ce6a16235f4810d/lib/em-systemcommand.rb#L108-L126
train
leoc/em-systemcommand
lib/em-systemcommand.rb
EventMachine.SystemCommand.kill
def kill signal = 'TERM', wait = false Process.kill signal, self.pid val = status if wait @stdin.close @stdout.close @stderr.close val end
ruby
def kill signal = 'TERM', wait = false Process.kill signal, self.pid val = status if wait @stdin.close @stdout.close @stderr.close val end
[ "def", "kill", "signal", "=", "'TERM'", ",", "wait", "=", "false", "Process", ".", "kill", "signal", ",", "self", ".", "pid", "val", "=", "status", "if", "wait", "@stdin", ".", "close", "@stdout", ".", "close", "@stderr", ".", "close", "val", "end" ]
Kills the child process.
[ "Kills", "the", "child", "process", "." ]
e1987253527c4b4dcc8ca7fe5ce6a16235f4810d
https://github.com/leoc/em-systemcommand/blob/e1987253527c4b4dcc8ca7fe5ce6a16235f4810d/lib/em-systemcommand.rb#L130-L137
train
jdno/ai_games-parser
lib/ai_games/parser.rb
AiGames.Parser.run
def run AiGames::Logger.info 'Parser.run : Starting loop' loop do command = read_from_engine break if command.nil? command.strip! next if command.length == 0 response = parse split_line command write_to_engine response unless response.nil? || response.length < 1 end AiGames::Logger.info 'Parser.run : Stopping loop' end
ruby
def run AiGames::Logger.info 'Parser.run : Starting loop' loop do command = read_from_engine break if command.nil? command.strip! next if command.length == 0 response = parse split_line command write_to_engine response unless response.nil? || response.length < 1 end AiGames::Logger.info 'Parser.run : Stopping loop' end
[ "def", "run", "AiGames", "::", "Logger", ".", "info", "'Parser.run : Starting loop'", "loop", "do", "command", "=", "read_from_engine", "break", "if", "command", ".", "nil?", "command", ".", "strip!", "next", "if", "command", ".", "length", "==", "0", "response", "=", "parse", "split_line", "command", "write_to_engine", "response", "unless", "response", ".", "nil?", "||", "response", ".", "length", "<", "1", "end", "AiGames", "::", "Logger", ".", "info", "'Parser.run : Stopping loop'", "end" ]
Initializes the parser. Pass in options using a hash structure. Starts the main loop. This loop runs until the game engine closes the console line. During the loop, the parser reads from the game engine, sanitizes the input a little bit, and then passes it to a method that needs to be overwritten by parsers extending this interface.
[ "Initializes", "the", "parser", ".", "Pass", "in", "options", "using", "a", "hash", "structure", ".", "Starts", "the", "main", "loop", ".", "This", "loop", "runs", "until", "the", "game", "engine", "closes", "the", "console", "line", ".", "During", "the", "loop", "the", "parser", "reads", "from", "the", "game", "engine", "sanitizes", "the", "input", "a", "little", "bit", "and", "then", "passes", "it", "to", "a", "method", "that", "needs", "to", "be", "overwritten", "by", "parsers", "extending", "this", "interface", "." ]
3bee81293ea8f0b3b1e89f98614d98a277365602
https://github.com/jdno/ai_games-parser/blob/3bee81293ea8f0b3b1e89f98614d98a277365602/lib/ai_games/parser.rb#L19-L34
train
Fire-Dragon-DoL/fried-typings
lib/fried/typings/enumerator_of.rb
Fried::Typings.EnumeratorOf.valid?
def valid?(enumerator) return false unless Is[Enumerator].valid?(enumerator) enumerator.all? { |obj| Is[type].valid?(obj) } end
ruby
def valid?(enumerator) return false unless Is[Enumerator].valid?(enumerator) enumerator.all? { |obj| Is[type].valid?(obj) } end
[ "def", "valid?", "(", "enumerator", ")", "return", "false", "unless", "Is", "[", "Enumerator", "]", ".", "valid?", "(", "enumerator", ")", "enumerator", ".", "all?", "{", "|", "obj", "|", "Is", "[", "type", "]", ".", "valid?", "(", "obj", ")", "}", "end" ]
Notice that the method will actually iterate over the enumerator @param enumerator [Enumerator]
[ "Notice", "that", "the", "method", "will", "actually", "iterate", "over", "the", "enumerator" ]
9c7d726c48003b008fd88c1b7ae51c0a3dbca892
https://github.com/Fire-Dragon-DoL/fried-typings/blob/9c7d726c48003b008fd88c1b7ae51c0a3dbca892/lib/fried/typings/enumerator_of.rb#L24-L28
train
fotonauts/activr
lib/activr/activity.rb
Activr.Activity.to_hash
def to_hash result = { } # id result['_id'] = @_id if @_id # timestamp result['at'] = @at # kind result['kind'] = kind.to_s # entities @entities.each do |entity_name, entity| result[entity_name.to_s] = entity.model_id end # meta result['meta'] = @meta.stringify_keys unless @meta.blank? result end
ruby
def to_hash result = { } # id result['_id'] = @_id if @_id # timestamp result['at'] = @at # kind result['kind'] = kind.to_s # entities @entities.each do |entity_name, entity| result[entity_name.to_s] = entity.model_id end # meta result['meta'] = @meta.stringify_keys unless @meta.blank? result end
[ "def", "to_hash", "result", "=", "{", "}", "result", "[", "'_id'", "]", "=", "@_id", "if", "@_id", "result", "[", "'at'", "]", "=", "@at", "result", "[", "'kind'", "]", "=", "kind", ".", "to_s", "@entities", ".", "each", "do", "|", "entity_name", ",", "entity", "|", "result", "[", "entity_name", ".", "to_s", "]", "=", "entity", ".", "model_id", "end", "result", "[", "'meta'", "]", "=", "@meta", ".", "stringify_keys", "unless", "@meta", ".", "blank?", "result", "end" ]
Serialize activity to a hash @note All keys are stringified (ie. there is no Symbol) @return [Hash] Activity hash
[ "Serialize", "activity", "to", "a", "hash" ]
92c071ad18a76d4130661da3ce47c1f0fb8ae913
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/activity.rb#L317-L338
train
fotonauts/activr
lib/activr/activity.rb
Activr.Activity.humanization_bindings
def humanization_bindings(options = { }) result = { } @entities.each do |entity_name, entity| result[entity_name] = entity.humanize(options.merge(:activity => self)) result["#{entity_name}_model".to_sym] = entity.model end result.merge(@meta) end
ruby
def humanization_bindings(options = { }) result = { } @entities.each do |entity_name, entity| result[entity_name] = entity.humanize(options.merge(:activity => self)) result["#{entity_name}_model".to_sym] = entity.model end result.merge(@meta) end
[ "def", "humanization_bindings", "(", "options", "=", "{", "}", ")", "result", "=", "{", "}", "@entities", ".", "each", "do", "|", "entity_name", ",", "entity", "|", "result", "[", "entity_name", "]", "=", "entity", ".", "humanize", "(", "options", ".", "merge", "(", ":activity", "=>", "self", ")", ")", "result", "[", "\"#{entity_name}_model\"", ".", "to_sym", "]", "=", "entity", ".", "model", "end", "result", ".", "merge", "(", "@meta", ")", "end" ]
Bindings for humanization sentence For each entity, returned hash contains: :<entity_name> => <entity humanization> :<entity_name>_model => <entity model instance> All `meta` are merged in returned hash too. @param options [Hash] Humanization options @return [Hash] Humanization bindings
[ "Bindings", "for", "humanization", "sentence" ]
92c071ad18a76d4130661da3ce47c1f0fb8ae913
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/activity.rb#L363-L372
train
fotonauts/activr
lib/activr/activity.rb
Activr.Activity.humanize
def humanize(options = { }) raise "No humanize_tpl defined" if self.humanize_tpl.blank? Activr.sentence(self.humanize_tpl, self.humanization_bindings(options)) end
ruby
def humanize(options = { }) raise "No humanize_tpl defined" if self.humanize_tpl.blank? Activr.sentence(self.humanize_tpl, self.humanization_bindings(options)) end
[ "def", "humanize", "(", "options", "=", "{", "}", ")", "raise", "\"No humanize_tpl defined\"", "if", "self", ".", "humanize_tpl", ".", "blank?", "Activr", ".", "sentence", "(", "self", ".", "humanize_tpl", ",", "self", ".", "humanization_bindings", "(", "options", ")", ")", "end" ]
Humanize that activity @param options [Hash] Options hash @option options [true, false] :html Output HTML (default: `false`) @return [String] Humanized activity
[ "Humanize", "that", "activity" ]
92c071ad18a76d4130661da3ce47c1f0fb8ae913
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/activity.rb#L379-L383
train
fotonauts/activr
lib/activr/activity.rb
Activr.Activity.check!
def check! # check mandatory entities self.allowed_entities.each do |entity_name, entity_options| if !entity_options[:optional] && @entities[entity_name].blank? raise Activr::Activity::MissingEntityError, "Missing '#{entity_name}' entity in this '#{self.kind}' activity: #{self.inspect}" end end end
ruby
def check! # check mandatory entities self.allowed_entities.each do |entity_name, entity_options| if !entity_options[:optional] && @entities[entity_name].blank? raise Activr::Activity::MissingEntityError, "Missing '#{entity_name}' entity in this '#{self.kind}' activity: #{self.inspect}" end end end
[ "def", "check!", "self", ".", "allowed_entities", ".", "each", "do", "|", "entity_name", ",", "entity_options", "|", "if", "!", "entity_options", "[", ":optional", "]", "&&", "@entities", "[", "entity_name", "]", ".", "blank?", "raise", "Activr", "::", "Activity", "::", "MissingEntityError", ",", "\"Missing '#{entity_name}' entity in this '#{self.kind}' activity: #{self.inspect}\"", "end", "end", "end" ]
Check if activity is valid @raise [MissingEntityError] if a mandatory entity is missing @api private
[ "Check", "if", "activity", "is", "valid" ]
92c071ad18a76d4130661da3ce47c1f0fb8ae913
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/activity.rb#L389-L396
train
kron4eg/confrider
lib/confrider/vault.rb
Confrider.Vault.deep_merge!
def deep_merge!(other_hash) other_hash.each_pair do |k,v| tv = self[k] self[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? self.class.new(tv).deep_merge(v) : v end self end
ruby
def deep_merge!(other_hash) other_hash.each_pair do |k,v| tv = self[k] self[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? self.class.new(tv).deep_merge(v) : v end self end
[ "def", "deep_merge!", "(", "other_hash", ")", "other_hash", ".", "each_pair", "do", "|", "k", ",", "v", "|", "tv", "=", "self", "[", "k", "]", "self", "[", "k", "]", "=", "tv", ".", "is_a?", "(", "Hash", ")", "&&", "v", ".", "is_a?", "(", "Hash", ")", "?", "self", ".", "class", ".", "new", "(", "tv", ")", ".", "deep_merge", "(", "v", ")", ":", "v", "end", "self", "end" ]
Returns a new hash with +self+ and +other_hash+ merged recursively. Modifies the receiver in place.
[ "Returns", "a", "new", "hash", "with", "+", "self", "+", "and", "+", "other_hash", "+", "merged", "recursively", ".", "Modifies", "the", "receiver", "in", "place", "." ]
97f381c71ed34dd0f9ee8943ac85f1813efcba22
https://github.com/kron4eg/confrider/blob/97f381c71ed34dd0f9ee8943ac85f1813efcba22/lib/confrider/vault.rb#L10-L16
train
fugroup/easymongo
lib/easymongo/query.rb
Easymongo.Query.ids
def ids(data) # Just return if nothing to do return data if data and data.empty? # Support passing id as string data = {'_id' => data} if !data or data.is_a?(String) # Turn all keys to string data = data.stringify_keys # Convert id to _id for mongo data['_id'] = data.delete('id') if data['id'] # Convert ids to BSON ObjectId data.each do |k, v| if v.is_a?(String) and v =~ /^[0-9a-fA-F]{24}$/ data[k] = oid(v) end end # Return data data end
ruby
def ids(data) # Just return if nothing to do return data if data and data.empty? # Support passing id as string data = {'_id' => data} if !data or data.is_a?(String) # Turn all keys to string data = data.stringify_keys # Convert id to _id for mongo data['_id'] = data.delete('id') if data['id'] # Convert ids to BSON ObjectId data.each do |k, v| if v.is_a?(String) and v =~ /^[0-9a-fA-F]{24}$/ data[k] = oid(v) end end # Return data data end
[ "def", "ids", "(", "data", ")", "return", "data", "if", "data", "and", "data", ".", "empty?", "data", "=", "{", "'_id'", "=>", "data", "}", "if", "!", "data", "or", "data", ".", "is_a?", "(", "String", ")", "data", "=", "data", ".", "stringify_keys", "data", "[", "'_id'", "]", "=", "data", ".", "delete", "(", "'id'", ")", "if", "data", "[", "'id'", "]", "data", ".", "each", "do", "|", "k", ",", "v", "|", "if", "v", ".", "is_a?", "(", "String", ")", "and", "v", "=~", "/", "/", "data", "[", "k", "]", "=", "oid", "(", "v", ")", "end", "end", "data", "end" ]
Make sure data is optimal
[ "Make", "sure", "data", "is", "optimal" ]
a48675248eafcd4885278d3196600c8ebda46240
https://github.com/fugroup/easymongo/blob/a48675248eafcd4885278d3196600c8ebda46240/lib/easymongo/query.rb#L108-L131
train
fugroup/easymongo
lib/easymongo/query.rb
Easymongo.Query.oid
def oid(v = nil) return BSON::ObjectId.new if v.nil?; BSON::ObjectId.from_string(v) rescue v end
ruby
def oid(v = nil) return BSON::ObjectId.new if v.nil?; BSON::ObjectId.from_string(v) rescue v end
[ "def", "oid", "(", "v", "=", "nil", ")", "return", "BSON", "::", "ObjectId", ".", "new", "if", "v", ".", "nil?", ";", "BSON", "::", "ObjectId", ".", "from_string", "(", "v", ")", "rescue", "v", "end" ]
Convert to BSON ObjectId or make a new one
[ "Convert", "to", "BSON", "ObjectId", "or", "make", "a", "new", "one" ]
a48675248eafcd4885278d3196600c8ebda46240
https://github.com/fugroup/easymongo/blob/a48675248eafcd4885278d3196600c8ebda46240/lib/easymongo/query.rb#L134-L136
train
pluginaweek/encrypted_attributes
lib/encrypted_attributes.rb
EncryptedAttributes.MacroMethods.encrypts
def encrypts(*attr_names, &config) base_options = attr_names.last.is_a?(Hash) ? attr_names.pop : {} attr_names.each do |attr_name| options = base_options.dup attr_name = attr_name.to_s to_attr_name = (options.delete(:to) || attr_name).to_s # Figure out what cipher is being configured for the attribute mode = options.delete(:mode) || :sha class_name = "#{mode.to_s.classify}Cipher" if EncryptedAttributes.const_defined?(class_name) cipher_class = EncryptedAttributes.const_get(class_name) else cipher_class = EncryptedStrings.const_get(class_name) end # Define encryption hooks define_callbacks("before_encrypt_#{attr_name}", "after_encrypt_#{attr_name}") send("before_encrypt_#{attr_name}", options.delete(:before)) if options.include?(:before) send("after_encrypt_#{attr_name}", options.delete(:after)) if options.include?(:after) # Set the encrypted value on the configured callback callback = options.delete(:on) || :before_validation # Create a callback method to execute on the callback event send(callback, :if => options.delete(:if), :unless => options.delete(:unless)) do |record| record.send(:write_encrypted_attribute, attr_name, to_attr_name, cipher_class, config || options) true end # Define virtual source attribute if attr_name != to_attr_name && !column_names.include?(attr_name) attr_reader attr_name unless method_defined?(attr_name) attr_writer attr_name unless method_defined?("#{attr_name}=") end # Define the reader when reading the encrypted attribute from the database define_method(to_attr_name) do read_encrypted_attribute(to_attr_name, cipher_class, config || options) end unless included_modules.include?(EncryptedAttributes::InstanceMethods) include EncryptedAttributes::InstanceMethods end end end
ruby
def encrypts(*attr_names, &config) base_options = attr_names.last.is_a?(Hash) ? attr_names.pop : {} attr_names.each do |attr_name| options = base_options.dup attr_name = attr_name.to_s to_attr_name = (options.delete(:to) || attr_name).to_s # Figure out what cipher is being configured for the attribute mode = options.delete(:mode) || :sha class_name = "#{mode.to_s.classify}Cipher" if EncryptedAttributes.const_defined?(class_name) cipher_class = EncryptedAttributes.const_get(class_name) else cipher_class = EncryptedStrings.const_get(class_name) end # Define encryption hooks define_callbacks("before_encrypt_#{attr_name}", "after_encrypt_#{attr_name}") send("before_encrypt_#{attr_name}", options.delete(:before)) if options.include?(:before) send("after_encrypt_#{attr_name}", options.delete(:after)) if options.include?(:after) # Set the encrypted value on the configured callback callback = options.delete(:on) || :before_validation # Create a callback method to execute on the callback event send(callback, :if => options.delete(:if), :unless => options.delete(:unless)) do |record| record.send(:write_encrypted_attribute, attr_name, to_attr_name, cipher_class, config || options) true end # Define virtual source attribute if attr_name != to_attr_name && !column_names.include?(attr_name) attr_reader attr_name unless method_defined?(attr_name) attr_writer attr_name unless method_defined?("#{attr_name}=") end # Define the reader when reading the encrypted attribute from the database define_method(to_attr_name) do read_encrypted_attribute(to_attr_name, cipher_class, config || options) end unless included_modules.include?(EncryptedAttributes::InstanceMethods) include EncryptedAttributes::InstanceMethods end end end
[ "def", "encrypts", "(", "*", "attr_names", ",", "&", "config", ")", "base_options", "=", "attr_names", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "attr_names", ".", "pop", ":", "{", "}", "attr_names", ".", "each", "do", "|", "attr_name", "|", "options", "=", "base_options", ".", "dup", "attr_name", "=", "attr_name", ".", "to_s", "to_attr_name", "=", "(", "options", ".", "delete", "(", ":to", ")", "||", "attr_name", ")", ".", "to_s", "mode", "=", "options", ".", "delete", "(", ":mode", ")", "||", ":sha", "class_name", "=", "\"#{mode.to_s.classify}Cipher\"", "if", "EncryptedAttributes", ".", "const_defined?", "(", "class_name", ")", "cipher_class", "=", "EncryptedAttributes", ".", "const_get", "(", "class_name", ")", "else", "cipher_class", "=", "EncryptedStrings", ".", "const_get", "(", "class_name", ")", "end", "define_callbacks", "(", "\"before_encrypt_#{attr_name}\"", ",", "\"after_encrypt_#{attr_name}\"", ")", "send", "(", "\"before_encrypt_#{attr_name}\"", ",", "options", ".", "delete", "(", ":before", ")", ")", "if", "options", ".", "include?", "(", ":before", ")", "send", "(", "\"after_encrypt_#{attr_name}\"", ",", "options", ".", "delete", "(", ":after", ")", ")", "if", "options", ".", "include?", "(", ":after", ")", "callback", "=", "options", ".", "delete", "(", ":on", ")", "||", ":before_validation", "send", "(", "callback", ",", ":if", "=>", "options", ".", "delete", "(", ":if", ")", ",", ":unless", "=>", "options", ".", "delete", "(", ":unless", ")", ")", "do", "|", "record", "|", "record", ".", "send", "(", ":write_encrypted_attribute", ",", "attr_name", ",", "to_attr_name", ",", "cipher_class", ",", "config", "||", "options", ")", "true", "end", "if", "attr_name", "!=", "to_attr_name", "&&", "!", "column_names", ".", "include?", "(", "attr_name", ")", "attr_reader", "attr_name", "unless", "method_defined?", "(", "attr_name", ")", "attr_writer", "attr_name", "unless", "method_defined?", "(", "\"#{attr_name}=\"", ")", "end", "define_method", "(", "to_attr_name", ")", "do", "read_encrypted_attribute", "(", "to_attr_name", ",", "cipher_class", ",", "config", "||", "options", ")", "end", "unless", "included_modules", ".", "include?", "(", "EncryptedAttributes", "::", "InstanceMethods", ")", "include", "EncryptedAttributes", "::", "InstanceMethods", "end", "end", "end" ]
Encrypts the given attribute. Configuration options: * <tt>:mode</tt> - The mode of encryption to use. Default is <tt>:sha</tt>. See EncryptedStrings for other possible modes. * <tt>:to</tt> - The attribute to write the encrypted value to. Default is the same attribute being encrypted. * <tt>:before</tt> - The callback to invoke every time *before* the attribute is encrypted * <tt>:after</tt> - The callback to invoke every time *after* the attribute is encrypted * <tt>:on</tt> - The ActiveRecord callback to use when triggering the encryption. By default, this will encrypt on <tt>before_validation</tt>. See ActiveRecord::Callbacks for a list of possible callbacks. * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the encryption should occur. The method, proc or string should return or evaluate to a true or false value. * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the encryption should not occur. The method, proc or string should return or evaluate to a true or false value. For additional configuration options used during the actual encryption, see the individual cipher class for the specified mode. == Encryption timeline By default, attributes are encrypted immediately before a record is validated. This means that you can still validate the presence of the encrypted attribute, but other things like password length cannot be validated without either (a) decrypting the value first or (b) using a different encryption target. For example, class User < ActiveRecord::Base encrypts :password, :to => :crypted_password validates_presence_of :password, :crypted_password validates_length_of :password, :maximum => 16 end In the above example, the actual encrypted password will be stored in the +crypted_password+ attribute. This means that validations can still run against the model for the original password value. user = User.new(:password => 'secret') user.password # => "secret" user.crypted_password # => nil user.valid? # => true user.crypted_password # => "8152bc582f58c854f580cb101d3182813dec4afe" user = User.new(:password => 'longer_than_the_maximum_allowed') user.valid? # => false user.crypted_password # => "e80a709f25798f87d9ca8005a7f64a645964d7c2" user.errors[:password] # => "is too long (maximum is 16 characters)" == Encryption mode examples SHA encryption: class User < ActiveRecord::Base encrypts :password # encrypts :password, :salt => 'secret' end Symmetric encryption: class User < ActiveRecord::Base encrypts :password, :mode => :symmetric # encrypts :password, :mode => :symmetric, :key => 'custom' end Asymmetric encryption: class User < ActiveRecord::Base encrypts :password, :mode => :asymmetric # encrypts :password, :mode => :asymmetric, :public_key_file => '/keys/public', :private_key_file => '/keys/private' end == Dynamic configuration For better security, the encryption options (such as the salt value) can be based on values in each individual record. In order to dynamically configure the encryption options so that individual records can be referenced, an optional block can be specified. For example, class User < ActiveRecord::Base encrypts :password, :mode => :sha, :before => :create_salt do |user| {:salt => user.salt} end private def create_salt self.salt = "#{login}-#{Time.now}" end end In the above example, the SHA encryption's <tt>salt</tt> is configured dynamically based on the user's login and the time at which it was encrypted. This helps improve the security of the user's password.
[ "Encrypts", "the", "given", "attribute", "." ]
2f5fba00800ab846b3b5a513d21ede19efcf681c
https://github.com/pluginaweek/encrypted_attributes/blob/2f5fba00800ab846b3b5a513d21ede19efcf681c/lib/encrypted_attributes.rb#L106-L152
train
pluginaweek/encrypted_attributes
lib/encrypted_attributes.rb
EncryptedAttributes.InstanceMethods.write_encrypted_attribute
def write_encrypted_attribute(attr_name, to_attr_name, cipher_class, options) value = send(attr_name) # Only encrypt values that actually have content and have not already # been encrypted unless value.blank? || value.encrypted? callback("before_encrypt_#{attr_name}") # Create the cipher configured for this attribute cipher = create_cipher(cipher_class, options, value) # Encrypt the value value = cipher.encrypt(value) value.cipher = cipher # Update the value based on the target attribute send("#{to_attr_name}=", value) callback("after_encrypt_#{attr_name}") end end
ruby
def write_encrypted_attribute(attr_name, to_attr_name, cipher_class, options) value = send(attr_name) # Only encrypt values that actually have content and have not already # been encrypted unless value.blank? || value.encrypted? callback("before_encrypt_#{attr_name}") # Create the cipher configured for this attribute cipher = create_cipher(cipher_class, options, value) # Encrypt the value value = cipher.encrypt(value) value.cipher = cipher # Update the value based on the target attribute send("#{to_attr_name}=", value) callback("after_encrypt_#{attr_name}") end end
[ "def", "write_encrypted_attribute", "(", "attr_name", ",", "to_attr_name", ",", "cipher_class", ",", "options", ")", "value", "=", "send", "(", "attr_name", ")", "unless", "value", ".", "blank?", "||", "value", ".", "encrypted?", "callback", "(", "\"before_encrypt_#{attr_name}\"", ")", "cipher", "=", "create_cipher", "(", "cipher_class", ",", "options", ",", "value", ")", "value", "=", "cipher", ".", "encrypt", "(", "value", ")", "value", ".", "cipher", "=", "cipher", "send", "(", "\"#{to_attr_name}=\"", ",", "value", ")", "callback", "(", "\"after_encrypt_#{attr_name}\"", ")", "end", "end" ]
Encrypts the given attribute to a target location using the encryption options configured for that attribute
[ "Encrypts", "the", "given", "attribute", "to", "a", "target", "location", "using", "the", "encryption", "options", "configured", "for", "that", "attribute" ]
2f5fba00800ab846b3b5a513d21ede19efcf681c
https://github.com/pluginaweek/encrypted_attributes/blob/2f5fba00800ab846b3b5a513d21ede19efcf681c/lib/encrypted_attributes.rb#L159-L179
train
pluginaweek/encrypted_attributes
lib/encrypted_attributes.rb
EncryptedAttributes.InstanceMethods.read_encrypted_attribute
def read_encrypted_attribute(to_attr_name, cipher_class, options) value = read_attribute(to_attr_name) # Make sure we set the cipher for equality comparison when reading # from the database. This should only be done if the value is *not* # blank, is *not* encrypted, and hasn't changed since it was read from # the database. The dirty checking is important when the encypted value # is written to the same attribute as the unencrypted value (i.e. you # don't want to encrypt when a new value has been set) unless value.blank? || value.encrypted? || attribute_changed?(to_attr_name) # Create the cipher configured for this attribute value.cipher = create_cipher(cipher_class, options, value) end value end
ruby
def read_encrypted_attribute(to_attr_name, cipher_class, options) value = read_attribute(to_attr_name) # Make sure we set the cipher for equality comparison when reading # from the database. This should only be done if the value is *not* # blank, is *not* encrypted, and hasn't changed since it was read from # the database. The dirty checking is important when the encypted value # is written to the same attribute as the unencrypted value (i.e. you # don't want to encrypt when a new value has been set) unless value.blank? || value.encrypted? || attribute_changed?(to_attr_name) # Create the cipher configured for this attribute value.cipher = create_cipher(cipher_class, options, value) end value end
[ "def", "read_encrypted_attribute", "(", "to_attr_name", ",", "cipher_class", ",", "options", ")", "value", "=", "read_attribute", "(", "to_attr_name", ")", "unless", "value", ".", "blank?", "||", "value", ".", "encrypted?", "||", "attribute_changed?", "(", "to_attr_name", ")", "value", ".", "cipher", "=", "create_cipher", "(", "cipher_class", ",", "options", ",", "value", ")", "end", "value", "end" ]
Reads the given attribute from the database, adding contextual information about how it was encrypted so that equality comparisons can be used
[ "Reads", "the", "given", "attribute", "from", "the", "database", "adding", "contextual", "information", "about", "how", "it", "was", "encrypted", "so", "that", "equality", "comparisons", "can", "be", "used" ]
2f5fba00800ab846b3b5a513d21ede19efcf681c
https://github.com/pluginaweek/encrypted_attributes/blob/2f5fba00800ab846b3b5a513d21ede19efcf681c/lib/encrypted_attributes.rb#L184-L199
train
pluginaweek/encrypted_attributes
lib/encrypted_attributes.rb
EncryptedAttributes.InstanceMethods.create_cipher
def create_cipher(klass, options, value) options = options.is_a?(Proc) ? options.call(self) : options.dup # Only use the contextual information for this plugin's ciphers klass.parent == EncryptedAttributes ? klass.new(value, options) : klass.new(options) end
ruby
def create_cipher(klass, options, value) options = options.is_a?(Proc) ? options.call(self) : options.dup # Only use the contextual information for this plugin's ciphers klass.parent == EncryptedAttributes ? klass.new(value, options) : klass.new(options) end
[ "def", "create_cipher", "(", "klass", ",", "options", ",", "value", ")", "options", "=", "options", ".", "is_a?", "(", "Proc", ")", "?", "options", ".", "call", "(", "self", ")", ":", "options", ".", "dup", "klass", ".", "parent", "==", "EncryptedAttributes", "?", "klass", ".", "new", "(", "value", ",", "options", ")", ":", "klass", ".", "new", "(", "options", ")", "end" ]
Creates a new cipher with the given configuration options
[ "Creates", "a", "new", "cipher", "with", "the", "given", "configuration", "options" ]
2f5fba00800ab846b3b5a513d21ede19efcf681c
https://github.com/pluginaweek/encrypted_attributes/blob/2f5fba00800ab846b3b5a513d21ede19efcf681c/lib/encrypted_attributes.rb#L202-L207
train
jeremyz/edoors-ruby
lib/edoors/room.rb
Edoors.Room.add_iota
def add_iota i raise Edoors::Exception.new "Iota #{i.name} already has #{i.parent.name} as parent" if not i.parent.nil? and i.parent!=self raise Edoors::Exception.new "Iota #{i.name} already exists in #{path}" if @iotas.has_key? i.name i.parent = self if i.parent.nil? @iotas[i.name]=i end
ruby
def add_iota i raise Edoors::Exception.new "Iota #{i.name} already has #{i.parent.name} as parent" if not i.parent.nil? and i.parent!=self raise Edoors::Exception.new "Iota #{i.name} already exists in #{path}" if @iotas.has_key? i.name i.parent = self if i.parent.nil? @iotas[i.name]=i end
[ "def", "add_iota", "i", "raise", "Edoors", "::", "Exception", ".", "new", "\"Iota #{i.name} already has #{i.parent.name} as parent\"", "if", "not", "i", ".", "parent", ".", "nil?", "and", "i", ".", "parent!", "=", "self", "raise", "Edoors", "::", "Exception", ".", "new", "\"Iota #{i.name} already exists in #{path}\"", "if", "@iotas", ".", "has_key?", "i", ".", "name", "i", ".", "parent", "=", "self", "if", "i", ".", "parent", ".", "nil?", "@iotas", "[", "i", ".", "name", "]", "=", "i", "end" ]
adds the given Iota to this Room @param [Iota] i the Iota to add @raise Edoors::Exception if i already has a parent or if a Iota with the same name already exists
[ "adds", "the", "given", "Iota", "to", "this", "Room" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/room.rb#L90-L95
train
jeremyz/edoors-ruby
lib/edoors/room.rb
Edoors.Room.add_link
def add_link l l.door = @iotas[l.src] raise Edoors::Exception.new "Link source #{l.src} does not exist in #{path}" if l.door.nil? (@links[l.src] ||= [])<< l end
ruby
def add_link l l.door = @iotas[l.src] raise Edoors::Exception.new "Link source #{l.src} does not exist in #{path}" if l.door.nil? (@links[l.src] ||= [])<< l end
[ "def", "add_link", "l", "l", ".", "door", "=", "@iotas", "[", "l", ".", "src", "]", "raise", "Edoors", "::", "Exception", ".", "new", "\"Link source #{l.src} does not exist in #{path}\"", "if", "l", ".", "door", ".", "nil?", "(", "@links", "[", "l", ".", "src", "]", "||=", "[", "]", ")", "<<", "l", "end" ]
adds the given Link to this Room @param [Link] l the Link to add @raise Edoors::Exception if the link source can't be found in this Room
[ "adds", "the", "given", "Link", "to", "this", "Room" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/room.rb#L103-L107
train
jeremyz/edoors-ruby
lib/edoors/room.rb
Edoors.Room._try_links
def _try_links p puts " -> try_links ..." if @spin.debug_routing links = @links[p.src.name] return false if links.nil? pending_link = nil links.each do |link| if p.link_with? link if pending_link p2 = @spin.require_p p.class p2.clone_data p p2.apply_link! pending_link send_p p2 end pending_link = link end end if pending_link p.apply_link! pending_link _send p end pending_link end
ruby
def _try_links p puts " -> try_links ..." if @spin.debug_routing links = @links[p.src.name] return false if links.nil? pending_link = nil links.each do |link| if p.link_with? link if pending_link p2 = @spin.require_p p.class p2.clone_data p p2.apply_link! pending_link send_p p2 end pending_link = link end end if pending_link p.apply_link! pending_link _send p end pending_link end
[ "def", "_try_links", "p", "puts", "\" -> try_links ...\"", "if", "@spin", ".", "debug_routing", "links", "=", "@links", "[", "p", ".", "src", ".", "name", "]", "return", "false", "if", "links", ".", "nil?", "pending_link", "=", "nil", "links", ".", "each", "do", "|", "link", "|", "if", "p", ".", "link_with?", "link", "if", "pending_link", "p2", "=", "@spin", ".", "require_p", "p", ".", "class", "p2", ".", "clone_data", "p", "p2", ".", "apply_link!", "pending_link", "send_p", "p2", "end", "pending_link", "=", "link", "end", "end", "if", "pending_link", "p", ".", "apply_link!", "pending_link", "_send", "p", "end", "pending_link", "end" ]
search for a matching link @param [Particle] p the Particle searching for a matching link
[ "search", "for", "a", "matching", "link" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/room.rb#L149-L170
train
jeremyz/edoors-ruby
lib/edoors/room.rb
Edoors.Room._route
def _route p if p.room.nil? or p.room==path if door = @iotas[p.door] p.dst_routed! door else p.error! Edoors::ERROR_ROUTE_RRWD end elsif door = @spin.search_world(p.room+Edoors::PATH_SEP+p.door) p.dst_routed! door else p.error! Edoors::ERROR_ROUTE_DNE end end
ruby
def _route p if p.room.nil? or p.room==path if door = @iotas[p.door] p.dst_routed! door else p.error! Edoors::ERROR_ROUTE_RRWD end elsif door = @spin.search_world(p.room+Edoors::PATH_SEP+p.door) p.dst_routed! door else p.error! Edoors::ERROR_ROUTE_DNE end end
[ "def", "_route", "p", "if", "p", ".", "room", ".", "nil?", "or", "p", ".", "room", "==", "path", "if", "door", "=", "@iotas", "[", "p", ".", "door", "]", "p", ".", "dst_routed!", "door", "else", "p", ".", "error!", "Edoors", "::", "ERROR_ROUTE_RRWD", "end", "elsif", "door", "=", "@spin", ".", "search_world", "(", "p", ".", "room", "+", "Edoors", "::", "PATH_SEP", "+", "p", ".", "door", ")", "p", ".", "dst_routed!", "door", "else", "p", ".", "error!", "Edoors", "::", "ERROR_ROUTE_DNE", "end", "end" ]
route the given Particle @param [Particle] p the Particle to be routed
[ "route", "the", "given", "Particle" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/room.rb#L177-L189
train
jeremyz/edoors-ruby
lib/edoors/room.rb
Edoors.Room._send
def _send p, sys=false if not sys and p.src.nil? # do not route non system orphan particles !! p.error! Edoors::ERROR_ROUTE_NS, @spin elsif p.dst # direct routing through pointer return elsif p.door # direct routing through path _route p elsif p.next_dst p.split_dst! if p.door _route p elsif not sys # boomerang p.dst_routed! p.src elsif p.action p.dst_routed! @spin end elsif not sys and _try_links p return else p.error!( sys ? Edoors::ERROR_ROUTE_SND : Edoors::ERROR_ROUTE_NDNL) end end
ruby
def _send p, sys=false if not sys and p.src.nil? # do not route non system orphan particles !! p.error! Edoors::ERROR_ROUTE_NS, @spin elsif p.dst # direct routing through pointer return elsif p.door # direct routing through path _route p elsif p.next_dst p.split_dst! if p.door _route p elsif not sys # boomerang p.dst_routed! p.src elsif p.action p.dst_routed! @spin end elsif not sys and _try_links p return else p.error!( sys ? Edoors::ERROR_ROUTE_SND : Edoors::ERROR_ROUTE_NDNL) end end
[ "def", "_send", "p", ",", "sys", "=", "false", "if", "not", "sys", "and", "p", ".", "src", ".", "nil?", "p", ".", "error!", "Edoors", "::", "ERROR_ROUTE_NS", ",", "@spin", "elsif", "p", ".", "dst", "return", "elsif", "p", ".", "door", "_route", "p", "elsif", "p", ".", "next_dst", "p", ".", "split_dst!", "if", "p", ".", "door", "_route", "p", "elsif", "not", "sys", "p", ".", "dst_routed!", "p", ".", "src", "elsif", "p", ".", "action", "p", ".", "dst_routed!", "@spin", "end", "elsif", "not", "sys", "and", "_try_links", "p", "return", "else", "p", ".", "error!", "(", "sys", "?", "Edoors", "::", "ERROR_ROUTE_SND", ":", "Edoors", "::", "ERROR_ROUTE_NDNL", ")", "end", "end" ]
send the given Particle @param [Particle] p the Particle to send @param [Boolean] sys if true send to system Particle fifo
[ "send", "the", "given", "Particle" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/room.rb#L197-L222
train
jeremyz/edoors-ruby
lib/edoors/room.rb
Edoors.Room.send_p
def send_p p puts " * send_p #{(p.next_dst.nil? ? 'no dst' : p.next_dst)} ..." if @spin.debug_routing _send p puts " -> #{p.dst.path}#{Edoors::ACT_SEP}#{p.action}" if @spin.debug_routing @spin.post_p p end
ruby
def send_p p puts " * send_p #{(p.next_dst.nil? ? 'no dst' : p.next_dst)} ..." if @spin.debug_routing _send p puts " -> #{p.dst.path}#{Edoors::ACT_SEP}#{p.action}" if @spin.debug_routing @spin.post_p p end
[ "def", "send_p", "p", "puts", "\" * send_p #{(p.next_dst.nil? ? 'no dst' : p.next_dst)} ...\"", "if", "@spin", ".", "debug_routing", "_send", "p", "puts", "\" -> #{p.dst.path}#{Edoors::ACT_SEP}#{p.action}\"", "if", "@spin", ".", "debug_routing", "@spin", ".", "post_p", "p", "end" ]
send the given Particle to application Particle fifo @param [Particle] p the Particle to send
[ "send", "the", "given", "Particle", "to", "application", "Particle", "fifo" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/room.rb#L229-L234
train
jeremyz/edoors-ruby
lib/edoors/room.rb
Edoors.Room.send_sys_p
def send_sys_p p puts " * send_sys_p #{(p.next_dst.nil? ? 'no dst' : p.next_dst)} ..." if @spin.debug_routing _send p, true puts " -> #{p.dst.path}#{Edoors::ACT_SEP}#{p.action}" if @spin.debug_routing @spin.post_sys_p p end
ruby
def send_sys_p p puts " * send_sys_p #{(p.next_dst.nil? ? 'no dst' : p.next_dst)} ..." if @spin.debug_routing _send p, true puts " -> #{p.dst.path}#{Edoors::ACT_SEP}#{p.action}" if @spin.debug_routing @spin.post_sys_p p end
[ "def", "send_sys_p", "p", "puts", "\" * send_sys_p #{(p.next_dst.nil? ? 'no dst' : p.next_dst)} ...\"", "if", "@spin", ".", "debug_routing", "_send", "p", ",", "true", "puts", "\" -> #{p.dst.path}#{Edoors::ACT_SEP}#{p.action}\"", "if", "@spin", ".", "debug_routing", "@spin", ".", "post_sys_p", "p", "end" ]
send the given Particle to system Particle fifo @param [Particle] p the Particle to send
[ "send", "the", "given", "Particle", "to", "system", "Particle", "fifo" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/room.rb#L240-L245
train
jeremyz/edoors-ruby
lib/edoors/room.rb
Edoors.Room.process_sys_p
def process_sys_p p if p.action==Edoors::SYS_ACT_ADD_LINK add_link Edoors::Link.from_particle p elsif p.action==Edoors::SYS_ACT_ADD_ROOM Edoors::Room.from_particle p, self end @spin.release_p p end
ruby
def process_sys_p p if p.action==Edoors::SYS_ACT_ADD_LINK add_link Edoors::Link.from_particle p elsif p.action==Edoors::SYS_ACT_ADD_ROOM Edoors::Room.from_particle p, self end @spin.release_p p end
[ "def", "process_sys_p", "p", "if", "p", ".", "action", "==", "Edoors", "::", "SYS_ACT_ADD_LINK", "add_link", "Edoors", "::", "Link", ".", "from_particle", "p", "elsif", "p", ".", "action", "==", "Edoors", "::", "SYS_ACT_ADD_ROOM", "Edoors", "::", "Room", ".", "from_particle", "p", ",", "self", "end", "@spin", ".", "release_p", "p", "end" ]
process the given system Particle @param [Particle] p the Particle to be processed @note the Particle is automatically released
[ "process", "the", "given", "system", "Particle" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/room.rb#L253-L260
train
nobuhiko-ido/Ixyml
lib/ixyml/xyml.rb
Xyml.Document.out_XML
def out_XML io,indent=nil if indent Xyml.rawobj2domobj(@root).write(io,indent.to_i) else sio=StringIO.new Xyml.rawobj2domobj(@root).write(sio) sio.rewind io.print sio.read,"\n" end io.close end
ruby
def out_XML io,indent=nil if indent Xyml.rawobj2domobj(@root).write(io,indent.to_i) else sio=StringIO.new Xyml.rawobj2domobj(@root).write(sio) sio.rewind io.print sio.read,"\n" end io.close end
[ "def", "out_XML", "io", ",", "indent", "=", "nil", "if", "indent", "Xyml", ".", "rawobj2domobj", "(", "@root", ")", ".", "write", "(", "io", ",", "indent", ".", "to_i", ")", "else", "sio", "=", "StringIO", ".", "new", "Xyml", ".", "rawobj2domobj", "(", "@root", ")", ".", "write", "(", "sio", ")", "sio", ".", "rewind", "io", ".", "print", "sio", ".", "read", ",", "\"\\n\"", "end", "io", ".", "close", "end" ]
save an XML file corresponding to the tree data in the self through the designated IO. 自身のツリーデータを、指定されたIOを通して、XMLファイルに保存する。 ==== Args _indent_(if not nil) :: a saved XML file is formatted with the designaged indent. xyml_tree=Xyml::Document.new({a: [{b: "ccc"},{d: ["eee"]}]}) #-> [{a: [{b: "ccc"},{d: ["eee"]}]}] xyml_tree.out_XML(File.open("aaa.xml","w")) #-> aaa.xml # <a b="ccc"> # <d>eee</d> # </a>
[ "save", "an", "XML", "file", "corresponding", "to", "the", "tree", "data", "in", "the", "self", "through", "the", "designated", "IO", "." ]
6a540024cdf5f1fc92f7ec86c98badeeb18d5694
https://github.com/nobuhiko-ido/Ixyml/blob/6a540024cdf5f1fc92f7ec86c98badeeb18d5694/lib/ixyml/xyml.rb#L430-L441
train
nobuhiko-ido/Ixyml
lib/ixyml/xyml.rb
Xyml.Document.load_XYML
def load_XYML io raw_yaml=YAML.load(io) @root=Xyml.rawobj2element raw_yaml[0] self.clear.push @root io.close end
ruby
def load_XYML io raw_yaml=YAML.load(io) @root=Xyml.rawobj2element raw_yaml[0] self.clear.push @root io.close end
[ "def", "load_XYML", "io", "raw_yaml", "=", "YAML", ".", "load", "(", "io", ")", "@root", "=", "Xyml", ".", "rawobj2element", "raw_yaml", "[", "0", "]", "self", ".", "clear", ".", "push", "@root", "io", ".", "close", "end" ]
load an XYML file through the designated IO and set the tree data in the file to the self. XYMLファイルをIOよりロードして、そのツリーデータを自身に設定する。 # aaa.xyml # - a: # -b: ccc # -d: # - eee xyml_tree=Xyml::Document.new xyml_tree.load_XYML(File.open("aaa.xyml")) #-> [{a: [{b: "ccc"},{d: ["eee"]}]}]
[ "load", "an", "XYML", "file", "through", "the", "designated", "IO", "and", "set", "the", "tree", "data", "in", "the", "file", "to", "the", "self", "." ]
6a540024cdf5f1fc92f7ec86c98badeeb18d5694
https://github.com/nobuhiko-ido/Ixyml/blob/6a540024cdf5f1fc92f7ec86c98badeeb18d5694/lib/ixyml/xyml.rb#L495-L500
train
nobuhiko-ido/Ixyml
lib/ixyml/xyml.rb
Xyml.Document.out_JSON
def out_JSON io serialized=JSON.generate(Xyml.remove_parent_rcsv(self)) io.print serialized io.close end
ruby
def out_JSON io serialized=JSON.generate(Xyml.remove_parent_rcsv(self)) io.print serialized io.close end
[ "def", "out_JSON", "io", "serialized", "=", "JSON", ".", "generate", "(", "Xyml", ".", "remove_parent_rcsv", "(", "self", ")", ")", "io", ".", "print", "serialized", "io", ".", "close", "end" ]
save a JSON file corresponding to the tree data in the self through the designated IO. Note that a JSON file can be loaded by load_XYML method because JSON is a part of YAML. 自身のツリーデータを、指定されたIOを通して、JSONファイルに保存する。JSONファイルのロードは、 _load_XYML_メソッドで実施できることに注意(JSONはYAML仕様の一部分となっているため)。 xyml_tree=Xyml::Document.new({a: [{b: "ccc"},{d: ["eee"]}]}) #-> [{a: [{b: "ccc"},{d: ["eee"]}]}] xyml_tree.out_JSON(File.open("aaa.json","w")) #-> aaa.jdon # [{"a":[{"b":"ccc"},{"d":["eee"]}]}]
[ "save", "a", "JSON", "file", "corresponding", "to", "the", "tree", "data", "in", "the", "self", "through", "the", "designated", "IO", ".", "Note", "that", "a", "JSON", "file", "can", "be", "loaded", "by", "load_XYML", "method", "because", "JSON", "is", "a", "part", "of", "YAML", "." ]
6a540024cdf5f1fc92f7ec86c98badeeb18d5694
https://github.com/nobuhiko-ido/Ixyml/blob/6a540024cdf5f1fc92f7ec86c98badeeb18d5694/lib/ixyml/xyml.rb#L512-L516
train
conversation/raca
lib/raca/account.rb
Raca.Account.public_endpoint
def public_endpoint(service_name, region = nil) return IDENTITY_URL if service_name == "identity" endpoints = service_endpoints(service_name) if endpoints.size > 1 && region region = region.to_s.upcase endpoints = endpoints.select { |e| e["region"] == region } || {} elsif endpoints.size > 1 && region.nil? raise ArgumentError, "The requested service exists in multiple regions, please specify a region code" end if endpoints.size == 0 raise ArgumentError, "No matching services found" else endpoints.first["publicURL"] end end
ruby
def public_endpoint(service_name, region = nil) return IDENTITY_URL if service_name == "identity" endpoints = service_endpoints(service_name) if endpoints.size > 1 && region region = region.to_s.upcase endpoints = endpoints.select { |e| e["region"] == region } || {} elsif endpoints.size > 1 && region.nil? raise ArgumentError, "The requested service exists in multiple regions, please specify a region code" end if endpoints.size == 0 raise ArgumentError, "No matching services found" else endpoints.first["publicURL"] end end
[ "def", "public_endpoint", "(", "service_name", ",", "region", "=", "nil", ")", "return", "IDENTITY_URL", "if", "service_name", "==", "\"identity\"", "endpoints", "=", "service_endpoints", "(", "service_name", ")", "if", "endpoints", ".", "size", ">", "1", "&&", "region", "region", "=", "region", ".", "to_s", ".", "upcase", "endpoints", "=", "endpoints", ".", "select", "{", "|", "e", "|", "e", "[", "\"region\"", "]", "==", "region", "}", "||", "{", "}", "elsif", "endpoints", ".", "size", ">", "1", "&&", "region", ".", "nil?", "raise", "ArgumentError", ",", "\"The requested service exists in multiple regions, please specify a region code\"", "end", "if", "endpoints", ".", "size", "==", "0", "raise", "ArgumentError", ",", "\"No matching services found\"", "else", "endpoints", ".", "first", "[", "\"publicURL\"", "]", "end", "end" ]
Return the public API URL for a particular rackspace service. Use Account#service_names to see a list of valid service_name's for this. Check the project README for an updated list of the available regions. account = Raca::Account.new("username", "secret") puts account.public_endpoint("cloudServers", :syd) Some service APIs are not regioned. In those cases, the region code can be left off: account = Raca::Account.new("username", "secret") puts account.public_endpoint("cloudDNS")
[ "Return", "the", "public", "API", "URL", "for", "a", "particular", "rackspace", "service", "." ]
fa69dfde22359cc0e06f655055be4eadcc7019c0
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/account.rb#L47-L63
train
conversation/raca
lib/raca/account.rb
Raca.Account.refresh_cache
def refresh_cache # Raca::HttpClient depends on Raca::Account, so we intentionally don't use it here # to avoid a circular dependency Net::HTTP.new(identity_host, 443).tap {|http| http.use_ssl = true }.start {|http| payload = { auth: { 'RAX-KSKEY:apiKeyCredentials' => { username: @username, apiKey: @key } } } response = http.post( tokens_path, JSON.dump(payload), {'Content-Type' => 'application/json'}, ) if response.is_a?(Net::HTTPSuccess) cache_write(cache_key, JSON.load(response.body)) else raise_on_error(response) end } end
ruby
def refresh_cache # Raca::HttpClient depends on Raca::Account, so we intentionally don't use it here # to avoid a circular dependency Net::HTTP.new(identity_host, 443).tap {|http| http.use_ssl = true }.start {|http| payload = { auth: { 'RAX-KSKEY:apiKeyCredentials' => { username: @username, apiKey: @key } } } response = http.post( tokens_path, JSON.dump(payload), {'Content-Type' => 'application/json'}, ) if response.is_a?(Net::HTTPSuccess) cache_write(cache_key, JSON.load(response.body)) else raise_on_error(response) end } end
[ "def", "refresh_cache", "Net", "::", "HTTP", ".", "new", "(", "identity_host", ",", "443", ")", ".", "tap", "{", "|", "http", "|", "http", ".", "use_ssl", "=", "true", "}", ".", "start", "{", "|", "http", "|", "payload", "=", "{", "auth", ":", "{", "'RAX-KSKEY:apiKeyCredentials'", "=>", "{", "username", ":", "@username", ",", "apiKey", ":", "@key", "}", "}", "}", "response", "=", "http", ".", "post", "(", "tokens_path", ",", "JSON", ".", "dump", "(", "payload", ")", ",", "{", "'Content-Type'", "=>", "'application/json'", "}", ",", ")", "if", "response", ".", "is_a?", "(", "Net", "::", "HTTPSuccess", ")", "cache_write", "(", "cache_key", ",", "JSON", ".", "load", "(", "response", ".", "body", ")", ")", "else", "raise_on_error", "(", "response", ")", "end", "}", "end" ]
Raca classes use this method to occasionally re-authenticate with the rackspace servers. You can probably ignore it.
[ "Raca", "classes", "use", "this", "method", "to", "occasionally", "re", "-", "authenticate", "with", "the", "rackspace", "servers", ".", "You", "can", "probably", "ignore", "it", "." ]
fa69dfde22359cc0e06f655055be4eadcc7019c0
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/account.rb#L114-L139
train
conversation/raca
lib/raca/account.rb
Raca.Account.extract_value
def extract_value(data, *keys) if keys.empty? data elsif data.respond_to?(:[]) && data[keys.first] extract_value(data[keys.first], *keys.slice(1,100)) else nil end end
ruby
def extract_value(data, *keys) if keys.empty? data elsif data.respond_to?(:[]) && data[keys.first] extract_value(data[keys.first], *keys.slice(1,100)) else nil end end
[ "def", "extract_value", "(", "data", ",", "*", "keys", ")", "if", "keys", ".", "empty?", "data", "elsif", "data", ".", "respond_to?", "(", ":[]", ")", "&&", "data", "[", "keys", ".", "first", "]", "extract_value", "(", "data", "[", "keys", ".", "first", "]", ",", "*", "keys", ".", "slice", "(", "1", ",", "100", ")", ")", "else", "nil", "end", "end" ]
This method is opaque, but it was the best I could come up with using just the standard library. Sorry. Use this to safely extract values from nested hashes: data = {a: {b: {c: 1}}} extract_value(data, :a, :b, :c) => 1 extract_value(data, :a, :b, :d) => nil extract_value(data, :d) => nil
[ "This", "method", "is", "opaque", "but", "it", "was", "the", "best", "I", "could", "come", "up", "with", "using", "just", "the", "standard", "library", ".", "Sorry", "." ]
fa69dfde22359cc0e06f655055be4eadcc7019c0
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/account.rb#L192-L200
train
mikemackintosh/slackdraft
lib/slackdraft/message.rb
Slackdraft.Message.generate_payload
def generate_payload payload = {} payload[:channel] = self.channel unless self.channel.nil? payload[:username] = self.username unless self.username.nil? payload[:icon_url] = self.icon_url unless self.icon_url.nil? payload[:icon_emoji] = self.icon_emoji unless self.icon_emoji.nil? payload[:text] = self.text unless self.text.nil? payload[:attachments] = self.attachments unless self.attachments.empty? payload end
ruby
def generate_payload payload = {} payload[:channel] = self.channel unless self.channel.nil? payload[:username] = self.username unless self.username.nil? payload[:icon_url] = self.icon_url unless self.icon_url.nil? payload[:icon_emoji] = self.icon_emoji unless self.icon_emoji.nil? payload[:text] = self.text unless self.text.nil? payload[:attachments] = self.attachments unless self.attachments.empty? payload end
[ "def", "generate_payload", "payload", "=", "{", "}", "payload", "[", ":channel", "]", "=", "self", ".", "channel", "unless", "self", ".", "channel", ".", "nil?", "payload", "[", ":username", "]", "=", "self", ".", "username", "unless", "self", ".", "username", ".", "nil?", "payload", "[", ":icon_url", "]", "=", "self", ".", "icon_url", "unless", "self", ".", "icon_url", ".", "nil?", "payload", "[", ":icon_emoji", "]", "=", "self", ".", "icon_emoji", "unless", "self", ".", "icon_emoji", ".", "nil?", "payload", "[", ":text", "]", "=", "self", ".", "text", "unless", "self", ".", "text", ".", "nil?", "payload", "[", ":attachments", "]", "=", "self", ".", "attachments", "unless", "self", ".", "attachments", ".", "empty?", "payload", "end" ]
Generate the payload if stuff was provided
[ "Generate", "the", "payload", "if", "stuff", "was", "provided" ]
4025fe370f468750fdf5a0dc9741871bca897c0a
https://github.com/mikemackintosh/slackdraft/blob/4025fe370f468750fdf5a0dc9741871bca897c0a/lib/slackdraft/message.rb#L55-L65
train
zh/rss-client
lib/rss-client/http-access2.rb
HTTPAccess2.Client.set_basic_auth
def set_basic_auth(uri, user, passwd) uri = urify(uri) @www_auth.basic_auth.set(uri, user, passwd) reset_all end
ruby
def set_basic_auth(uri, user, passwd) uri = urify(uri) @www_auth.basic_auth.set(uri, user, passwd) reset_all end
[ "def", "set_basic_auth", "(", "uri", ",", "user", ",", "passwd", ")", "uri", "=", "urify", "(", "uri", ")", "@www_auth", ".", "basic_auth", ".", "set", "(", "uri", ",", "user", ",", "passwd", ")", "reset_all", "end" ]
for backward compatibility
[ "for", "backward", "compatibility" ]
cbc4c5146e3b5d8188e221076f56d9471f752237
https://github.com/zh/rss-client/blob/cbc4c5146e3b5d8188e221076f56d9471f752237/lib/rss-client/http-access2.rb#L269-L273
train
zh/rss-client
lib/rss-client/http-access2.rb
HTTPAccess2.SSLConfig.set_client_cert_file
def set_client_cert_file(cert_file, key_file) @client_cert = OpenSSL::X509::Certificate.new(File.open(cert_file).read) @client_key = OpenSSL::PKey::RSA.new(File.open(key_file).read) change_notify end
ruby
def set_client_cert_file(cert_file, key_file) @client_cert = OpenSSL::X509::Certificate.new(File.open(cert_file).read) @client_key = OpenSSL::PKey::RSA.new(File.open(key_file).read) change_notify end
[ "def", "set_client_cert_file", "(", "cert_file", ",", "key_file", ")", "@client_cert", "=", "OpenSSL", "::", "X509", "::", "Certificate", ".", "new", "(", "File", ".", "open", "(", "cert_file", ")", ".", "read", ")", "@client_key", "=", "OpenSSL", "::", "PKey", "::", "RSA", ".", "new", "(", "File", ".", "open", "(", "key_file", ")", ".", "read", ")", "change_notify", "end" ]
don't use if you don't know what it is.
[ "don", "t", "use", "if", "you", "don", "t", "know", "what", "it", "is", "." ]
cbc4c5146e3b5d8188e221076f56d9471f752237
https://github.com/zh/rss-client/blob/cbc4c5146e3b5d8188e221076f56d9471f752237/lib/rss-client/http-access2.rb#L641-L645
train
zh/rss-client
lib/rss-client/http-access2.rb
HTTPAccess2.SSLConfig.set_context
def set_context(ctx) # Verification: Use Store#verify_callback instead of SSLContext#verify*? ctx.cert_store = @cert_store ctx.verify_mode = @verify_mode ctx.verify_depth = @verify_depth if @verify_depth ctx.verify_callback = @verify_callback || method(:default_verify_callback) # SSL config ctx.cert = @client_cert ctx.key = @client_key ctx.client_ca = @client_ca ctx.timeout = @timeout ctx.options = @options ctx.ciphers = @ciphers end
ruby
def set_context(ctx) # Verification: Use Store#verify_callback instead of SSLContext#verify*? ctx.cert_store = @cert_store ctx.verify_mode = @verify_mode ctx.verify_depth = @verify_depth if @verify_depth ctx.verify_callback = @verify_callback || method(:default_verify_callback) # SSL config ctx.cert = @client_cert ctx.key = @client_key ctx.client_ca = @client_ca ctx.timeout = @timeout ctx.options = @options ctx.ciphers = @ciphers end
[ "def", "set_context", "(", "ctx", ")", "ctx", ".", "cert_store", "=", "@cert_store", "ctx", ".", "verify_mode", "=", "@verify_mode", "ctx", ".", "verify_depth", "=", "@verify_depth", "if", "@verify_depth", "ctx", ".", "verify_callback", "=", "@verify_callback", "||", "method", "(", ":default_verify_callback", ")", "ctx", ".", "cert", "=", "@client_cert", "ctx", ".", "key", "=", "@client_key", "ctx", ".", "client_ca", "=", "@client_ca", "ctx", ".", "timeout", "=", "@timeout", "ctx", ".", "options", "=", "@options", "ctx", ".", "ciphers", "=", "@ciphers", "end" ]
interfaces for SSLSocketWrap.
[ "interfaces", "for", "SSLSocketWrap", "." ]
cbc4c5146e3b5d8188e221076f56d9471f752237
https://github.com/zh/rss-client/blob/cbc4c5146e3b5d8188e221076f56d9471f752237/lib/rss-client/http-access2.rb#L721-L734
train
zh/rss-client
lib/rss-client/http-access2.rb
HTTPAccess2.BasicAuth.set
def set(uri, user, passwd) if uri.nil? @cred = ["#{user}:#{passwd}"].pack('m').tr("\n", '') else uri = Util.uri_dirname(uri) @auth[uri] = ["#{user}:#{passwd}"].pack('m').tr("\n", '') end end
ruby
def set(uri, user, passwd) if uri.nil? @cred = ["#{user}:#{passwd}"].pack('m').tr("\n", '') else uri = Util.uri_dirname(uri) @auth[uri] = ["#{user}:#{passwd}"].pack('m').tr("\n", '') end end
[ "def", "set", "(", "uri", ",", "user", ",", "passwd", ")", "if", "uri", ".", "nil?", "@cred", "=", "[", "\"#{user}:#{passwd}\"", "]", ".", "pack", "(", "'m'", ")", ".", "tr", "(", "\"\\n\"", ",", "''", ")", "else", "uri", "=", "Util", ".", "uri_dirname", "(", "uri", ")", "@auth", "[", "uri", "]", "=", "[", "\"#{user}:#{passwd}\"", "]", ".", "pack", "(", "'m'", ")", ".", "tr", "(", "\"\\n\"", ",", "''", ")", "end", "end" ]
uri == nil for generic purpose
[ "uri", "==", "nil", "for", "generic", "purpose" ]
cbc4c5146e3b5d8188e221076f56d9471f752237
https://github.com/zh/rss-client/blob/cbc4c5146e3b5d8188e221076f56d9471f752237/lib/rss-client/http-access2.rb#L892-L899
train
zh/rss-client
lib/rss-client/http-access2.rb
HTTPAccess2.Session.connect
def connect site = @proxy || @dest begin retry_number = 0 timeout(@connect_timeout) do @socket = create_socket(site) begin @src.host = @socket.addr[3] @src.port = @socket.addr[1] rescue SocketError # to avoid IPSocket#addr problem on Mac OS X 10.3 + ruby-1.8.1. # cf. [ruby-talk:84909], [ruby-talk:95827] end if @dest.scheme == 'https' @socket = create_ssl_socket(@socket) connect_ssl_proxy(@socket) if @proxy @socket.ssl_connect @socket.post_connection_check(@dest) @ssl_peer_cert = @socket.peer_cert end # Use Ruby internal buffering instead of passing data immediatly # to the underlying layer # => we need to to call explicitely flush on the socket @socket.sync = @socket_sync end rescue TimeoutError if @connect_retry == 0 retry else retry_number += 1 retry if retry_number < @connect_retry end close raise end @state = :WAIT @readbuf = '' end
ruby
def connect site = @proxy || @dest begin retry_number = 0 timeout(@connect_timeout) do @socket = create_socket(site) begin @src.host = @socket.addr[3] @src.port = @socket.addr[1] rescue SocketError # to avoid IPSocket#addr problem on Mac OS X 10.3 + ruby-1.8.1. # cf. [ruby-talk:84909], [ruby-talk:95827] end if @dest.scheme == 'https' @socket = create_ssl_socket(@socket) connect_ssl_proxy(@socket) if @proxy @socket.ssl_connect @socket.post_connection_check(@dest) @ssl_peer_cert = @socket.peer_cert end # Use Ruby internal buffering instead of passing data immediatly # to the underlying layer # => we need to to call explicitely flush on the socket @socket.sync = @socket_sync end rescue TimeoutError if @connect_retry == 0 retry else retry_number += 1 retry if retry_number < @connect_retry end close raise end @state = :WAIT @readbuf = '' end
[ "def", "connect", "site", "=", "@proxy", "||", "@dest", "begin", "retry_number", "=", "0", "timeout", "(", "@connect_timeout", ")", "do", "@socket", "=", "create_socket", "(", "site", ")", "begin", "@src", ".", "host", "=", "@socket", ".", "addr", "[", "3", "]", "@src", ".", "port", "=", "@socket", ".", "addr", "[", "1", "]", "rescue", "SocketError", "end", "if", "@dest", ".", "scheme", "==", "'https'", "@socket", "=", "create_ssl_socket", "(", "@socket", ")", "connect_ssl_proxy", "(", "@socket", ")", "if", "@proxy", "@socket", ".", "ssl_connect", "@socket", ".", "post_connection_check", "(", "@dest", ")", "@ssl_peer_cert", "=", "@socket", ".", "peer_cert", "end", "@socket", ".", "sync", "=", "@socket_sync", "end", "rescue", "TimeoutError", "if", "@connect_retry", "==", "0", "retry", "else", "retry_number", "+=", "1", "retry", "if", "retry_number", "<", "@connect_retry", "end", "close", "raise", "end", "@state", "=", ":WAIT", "@readbuf", "=", "''", "end" ]
Connect to the server
[ "Connect", "to", "the", "server" ]
cbc4c5146e3b5d8188e221076f56d9471f752237
https://github.com/zh/rss-client/blob/cbc4c5146e3b5d8188e221076f56d9471f752237/lib/rss-client/http-access2.rb#L1783-L1821
train
zh/rss-client
lib/rss-client/http-access2.rb
HTTPAccess2.Session.read_header
def read_header if @state == :DATA get_data {} check_state() end unless @state == :META raise InvalidState, 'state != :META' end parse_header(@socket) @content_length = nil @chunked = false @headers.each do |line| case line when /^Content-Length:\s+(\d+)/i @content_length = $1.to_i when /^Transfer-Encoding:\s+chunked/i @chunked = true @content_length = true # how? @chunk_length = 0 when /^Connection:\s+([\-\w]+)/i, /^Proxy-Connection:\s+([\-\w]+)/i case $1 when /^Keep-Alive$/i @next_connection = true when /^close$/i @next_connection = false end else # Nothing to parse. end end # Head of the request has been parsed. @state = :DATA req = @requests.shift if req.header.request_method == 'HEAD' @content_length = 0 if @next_connection @state = :WAIT else close end end @next_connection = false unless @content_length return [@version, @status, @reason] end
ruby
def read_header if @state == :DATA get_data {} check_state() end unless @state == :META raise InvalidState, 'state != :META' end parse_header(@socket) @content_length = nil @chunked = false @headers.each do |line| case line when /^Content-Length:\s+(\d+)/i @content_length = $1.to_i when /^Transfer-Encoding:\s+chunked/i @chunked = true @content_length = true # how? @chunk_length = 0 when /^Connection:\s+([\-\w]+)/i, /^Proxy-Connection:\s+([\-\w]+)/i case $1 when /^Keep-Alive$/i @next_connection = true when /^close$/i @next_connection = false end else # Nothing to parse. end end # Head of the request has been parsed. @state = :DATA req = @requests.shift if req.header.request_method == 'HEAD' @content_length = 0 if @next_connection @state = :WAIT else close end end @next_connection = false unless @content_length return [@version, @status, @reason] end
[ "def", "read_header", "if", "@state", "==", ":DATA", "get_data", "{", "}", "check_state", "(", ")", "end", "unless", "@state", "==", ":META", "raise", "InvalidState", ",", "'state != :META'", "end", "parse_header", "(", "@socket", ")", "@content_length", "=", "nil", "@chunked", "=", "false", "@headers", ".", "each", "do", "|", "line", "|", "case", "line", "when", "/", "\\s", "\\d", "/i", "@content_length", "=", "$1", ".", "to_i", "when", "/", "\\s", "/i", "@chunked", "=", "true", "@content_length", "=", "true", "@chunk_length", "=", "0", "when", "/", "\\s", "\\-", "\\w", "/i", ",", "/", "\\s", "\\-", "\\w", "/i", "case", "$1", "when", "/", "/i", "@next_connection", "=", "true", "when", "/", "/i", "@next_connection", "=", "false", "end", "else", "end", "end", "@state", "=", ":DATA", "req", "=", "@requests", ".", "shift", "if", "req", ".", "header", ".", "request_method", "==", "'HEAD'", "@content_length", "=", "0", "if", "@next_connection", "@state", "=", ":WAIT", "else", "close", "end", "end", "@next_connection", "=", "false", "unless", "@content_length", "return", "[", "@version", ",", "@status", ",", "@reason", "]", "end" ]
Read status block.
[ "Read", "status", "block", "." ]
cbc4c5146e3b5d8188e221076f56d9471f752237
https://github.com/zh/rss-client/blob/cbc4c5146e3b5d8188e221076f56d9471f752237/lib/rss-client/http-access2.rb#L1854-L1899
train
marcboeker/mongolicious
lib/mongolicious/storage.rb
Mongolicious.Storage.upload
def upload(bucket, key, path) Mongolicious.logger.info("Uploading archive to #{key}") @con.put_object( bucket, key, File.open(path, 'r'), {'x-amz-acl' => 'private', 'Content-Type' => 'application/x-tar'} ) end
ruby
def upload(bucket, key, path) Mongolicious.logger.info("Uploading archive to #{key}") @con.put_object( bucket, key, File.open(path, 'r'), {'x-amz-acl' => 'private', 'Content-Type' => 'application/x-tar'} ) end
[ "def", "upload", "(", "bucket", ",", "key", ",", "path", ")", "Mongolicious", ".", "logger", ".", "info", "(", "\"Uploading archive to #{key}\"", ")", "@con", ".", "put_object", "(", "bucket", ",", "key", ",", "File", ".", "open", "(", "path", ",", "'r'", ")", ",", "{", "'x-amz-acl'", "=>", "'private'", ",", "'Content-Type'", "=>", "'application/x-tar'", "}", ")", "end" ]
Upload the given path to S3. @param [String] bucket the bucket where to store the archive in. @param [String] key the key where the archive is stored under. @param [String] path the path, where the archive is located. @return [Hash]
[ "Upload", "the", "given", "path", "to", "S3", "." ]
bc1553188df97d3df825de6d826b34ab7185a431
https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/storage.rb#L36-L43
train
marcboeker/mongolicious
lib/mongolicious/storage.rb
Mongolicious.Storage.upload_part
def upload_part(bucket, key, upload_id, part_number, data) response = @con.upload_part(bucket, key, upload_id, part_number, data) return response.headers['ETag'] end
ruby
def upload_part(bucket, key, upload_id, part_number, data) response = @con.upload_part(bucket, key, upload_id, part_number, data) return response.headers['ETag'] end
[ "def", "upload_part", "(", "bucket", ",", "key", ",", "upload_id", ",", "part_number", ",", "data", ")", "response", "=", "@con", ".", "upload_part", "(", "bucket", ",", "key", ",", "upload_id", ",", "part_number", ",", "data", ")", "return", "response", ".", "headers", "[", "'ETag'", "]", "end" ]
Upload a part for a multipart upload @param [String] bucket Name of bucket to add part to @param [String] key Name of object to add part to @param [String] upload_id Id of upload to add part to @param [String] part_number Index of part in upload @param [String] data Contect of part @return [String] ETag etag of new object. Will be needed to complete upload
[ "Upload", "a", "part", "for", "a", "multipart", "upload" ]
bc1553188df97d3df825de6d826b34ab7185a431
https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/storage.rb#L69-L73
train
marcboeker/mongolicious
lib/mongolicious/storage.rb
Mongolicious.Storage.complete_multipart_upload
def complete_multipart_upload(bucket, key, upload_id, parts) response = @con.complete_multipart_upload(bucket, key, upload_id, parts) return response end
ruby
def complete_multipart_upload(bucket, key, upload_id, parts) response = @con.complete_multipart_upload(bucket, key, upload_id, parts) return response end
[ "def", "complete_multipart_upload", "(", "bucket", ",", "key", ",", "upload_id", ",", "parts", ")", "response", "=", "@con", ".", "complete_multipart_upload", "(", "bucket", ",", "key", ",", "upload_id", ",", "parts", ")", "return", "response", "end" ]
Complete a multipart upload @param [String] bucket Name of bucket to complete multipart upload for @param [String] key Name of object to complete multipart upload for @param [String] upload_id Id of upload to add part to @param [String] parts Array of etags for parts @return [Excon::Response]
[ "Complete", "a", "multipart", "upload" ]
bc1553188df97d3df825de6d826b34ab7185a431
https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/storage.rb#L83-L87
train
marcboeker/mongolicious
lib/mongolicious/storage.rb
Mongolicious.Storage.cleanup
def cleanup(bucket, prefix, versions) objects = @con.get_bucket(bucket, :prefix => prefix).body['Contents'] return if objects.size <= versions objects[0...(objects.size - versions)].each do |o| Mongolicious.logger.info("Removing outdated version #{o['Key']}") @con.delete_object(bucket, o['Key']) end end
ruby
def cleanup(bucket, prefix, versions) objects = @con.get_bucket(bucket, :prefix => prefix).body['Contents'] return if objects.size <= versions objects[0...(objects.size - versions)].each do |o| Mongolicious.logger.info("Removing outdated version #{o['Key']}") @con.delete_object(bucket, o['Key']) end end
[ "def", "cleanup", "(", "bucket", ",", "prefix", ",", "versions", ")", "objects", "=", "@con", ".", "get_bucket", "(", "bucket", ",", ":prefix", "=>", "prefix", ")", ".", "body", "[", "'Contents'", "]", "return", "if", "objects", ".", "size", "<=", "versions", "objects", "[", "0", "...", "(", "objects", ".", "size", "-", "versions", ")", "]", ".", "each", "do", "|", "o", "|", "Mongolicious", ".", "logger", ".", "info", "(", "\"Removing outdated version #{o['Key']}\"", ")", "@con", ".", "delete_object", "(", "bucket", ",", "o", "[", "'Key'", "]", ")", "end", "end" ]
Remove old versions of a backup. @param [String] bucket the bucket where the archive is stored in. @param [String] prefix the prefix where to look for outdated versions. @param [Integer] versions number of versions to keep. @return [nil]
[ "Remove", "old", "versions", "of", "a", "backup", "." ]
bc1553188df97d3df825de6d826b34ab7185a431
https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/storage.rb#L107-L116
train
richo/twat
lib/twat/subcommands/base.rb
Twat::Subcommands.Base.format
def format(twt, idx = nil) idx = pad(idx) if idx text = deentitize(twt.text) if config.colors? buf = idx ? "#{idx.cyan}:" : "" if twt.as_user == config.account_name.to_s buf += "#{twt.as_user.bold.blue}: #{text}" elsif text.mentions?(config.account_name) buf += "#{twt.as_user.bold.red}: #{text}" else buf += "#{twt.as_user.bold.cyan}: #{text}" end buf.colorise! else buf = idx ? "#{idx}: " : "" buf += "#{twt.as_user}: #{text}" end end
ruby
def format(twt, idx = nil) idx = pad(idx) if idx text = deentitize(twt.text) if config.colors? buf = idx ? "#{idx.cyan}:" : "" if twt.as_user == config.account_name.to_s buf += "#{twt.as_user.bold.blue}: #{text}" elsif text.mentions?(config.account_name) buf += "#{twt.as_user.bold.red}: #{text}" else buf += "#{twt.as_user.bold.cyan}: #{text}" end buf.colorise! else buf = idx ? "#{idx}: " : "" buf += "#{twt.as_user}: #{text}" end end
[ "def", "format", "(", "twt", ",", "idx", "=", "nil", ")", "idx", "=", "pad", "(", "idx", ")", "if", "idx", "text", "=", "deentitize", "(", "twt", ".", "text", ")", "if", "config", ".", "colors?", "buf", "=", "idx", "?", "\"#{idx.cyan}:\"", ":", "\"\"", "if", "twt", ".", "as_user", "==", "config", ".", "account_name", ".", "to_s", "buf", "+=", "\"#{twt.as_user.bold.blue}: #{text}\"", "elsif", "text", ".", "mentions?", "(", "config", ".", "account_name", ")", "buf", "+=", "\"#{twt.as_user.bold.red}: #{text}\"", "else", "buf", "+=", "\"#{twt.as_user.bold.cyan}: #{text}\"", "end", "buf", ".", "colorise!", "else", "buf", "=", "idx", "?", "\"#{idx}: \"", ":", "\"\"", "buf", "+=", "\"#{twt.as_user}: #{text}\"", "end", "end" ]
Format a tweet all pretty like
[ "Format", "a", "tweet", "all", "pretty", "like" ]
0354059c2d9643a8c3b855dbb18105fa80bf651e
https://github.com/richo/twat/blob/0354059c2d9643a8c3b855dbb18105fa80bf651e/lib/twat/subcommands/base.rb#L66-L83
train
teodor-pripoae/scalaroid
lib/scalaroid/transaction.rb
Scalaroid.Transaction.write
def write(key, value, binary = false) result = req_list(new_req_list().add_write(key, value, binary))[0] _process_result_commit(result) end
ruby
def write(key, value, binary = false) result = req_list(new_req_list().add_write(key, value, binary))[0] _process_result_commit(result) end
[ "def", "write", "(", "key", ",", "value", ",", "binary", "=", "false", ")", "result", "=", "req_list", "(", "new_req_list", "(", ")", ".", "add_write", "(", "key", ",", "value", ",", "binary", ")", ")", "[", "0", "]", "_process_result_commit", "(", "result", ")", "end" ]
Issues a write operation to Scalaris and adds it to the current transaction.
[ "Issues", "a", "write", "operation", "to", "Scalaris", "and", "adds", "it", "to", "the", "current", "transaction", "." ]
4e9e90e71ce3008da79a72eae40fe2f187580be2
https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/transaction.rb#L117-L120
train
teodor-pripoae/scalaroid
lib/scalaroid/transaction.rb
Scalaroid.Transaction.add_del_on_list
def add_del_on_list(key, to_add, to_remove) result = req_list(new_req_list().add_add_del_on_list(key, to_add, to_remove))[0] process_result_add_del_on_list(result) end
ruby
def add_del_on_list(key, to_add, to_remove) result = req_list(new_req_list().add_add_del_on_list(key, to_add, to_remove))[0] process_result_add_del_on_list(result) end
[ "def", "add_del_on_list", "(", "key", ",", "to_add", ",", "to_remove", ")", "result", "=", "req_list", "(", "new_req_list", "(", ")", ".", "add_add_del_on_list", "(", "key", ",", "to_add", ",", "to_remove", ")", ")", "[", "0", "]", "process_result_add_del_on_list", "(", "result", ")", "end" ]
Issues a add_del_on_list operation to scalaris and adds it to the current transaction. Changes the list stored at the given key, i.e. first adds all items in to_add then removes all items in to_remove. Both, to_add and to_remove, must be lists. Assumes en empty list if no value exists at key.
[ "Issues", "a", "add_del_on_list", "operation", "to", "scalaris", "and", "adds", "it", "to", "the", "current", "transaction", ".", "Changes", "the", "list", "stored", "at", "the", "given", "key", "i", ".", "e", ".", "first", "adds", "all", "items", "in", "to_add", "then", "removes", "all", "items", "in", "to_remove", ".", "Both", "to_add", "and", "to_remove", "must", "be", "lists", ".", "Assumes", "en", "empty", "list", "if", "no", "value", "exists", "at", "key", "." ]
4e9e90e71ce3008da79a72eae40fe2f187580be2
https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/transaction.rb#L128-L131
train
teodor-pripoae/scalaroid
lib/scalaroid/transaction.rb
Scalaroid.Transaction.add_on_nr
def add_on_nr(key, to_add) result = req_list(new_req_list().add_add_on_nr(key, to_add))[0] process_result_add_on_nr(result) end
ruby
def add_on_nr(key, to_add) result = req_list(new_req_list().add_add_on_nr(key, to_add))[0] process_result_add_on_nr(result) end
[ "def", "add_on_nr", "(", "key", ",", "to_add", ")", "result", "=", "req_list", "(", "new_req_list", "(", ")", ".", "add_add_on_nr", "(", "key", ",", "to_add", ")", ")", "[", "0", "]", "process_result_add_on_nr", "(", "result", ")", "end" ]
Issues a add_on_nr operation to scalaris and adds it to the current transaction. Changes the number stored at the given key, i.e. adds some value. Assumes 0 if no value exists at key.
[ "Issues", "a", "add_on_nr", "operation", "to", "scalaris", "and", "adds", "it", "to", "the", "current", "transaction", ".", "Changes", "the", "number", "stored", "at", "the", "given", "key", "i", ".", "e", ".", "adds", "some", "value", ".", "Assumes", "0", "if", "no", "value", "exists", "at", "key", "." ]
4e9e90e71ce3008da79a72eae40fe2f187580be2
https://github.com/teodor-pripoae/scalaroid/blob/4e9e90e71ce3008da79a72eae40fe2f187580be2/lib/scalaroid/transaction.rb#L137-L140
train
nigel-lowry/random_outcome
lib/random_outcome/simulator.rb
RandomOutcome.Simulator.outcome
def outcome num = random_float_including_zero_and_excluding_one # don't inline @probability_range_to_outcome.detect { |probability_range, _| num.in? probability_range }.last end
ruby
def outcome num = random_float_including_zero_and_excluding_one # don't inline @probability_range_to_outcome.detect { |probability_range, _| num.in? probability_range }.last end
[ "def", "outcome", "num", "=", "random_float_including_zero_and_excluding_one", "@probability_range_to_outcome", ".", "detect", "{", "|", "probability_range", ",", "_", "|", "num", ".", "in?", "probability_range", "}", ".", "last", "end" ]
creates a new Simulator which will return the desired outcomes with the given probability @param outcome_to_probability [Hash<Symbol, Number>] hash of outcomes to their probability (represented as numbers between zero and one) @note raises errors if there is only one possible outcome (why bother using this if there's only one outcome?), if the probabilities don't total one (use Rationals if this proves problematic with rounding) or if any of the outcomes are impossible (why include them if they can never happen?) generate an outcome with the initialised probabilities @return [Symbol] symbol for outcome
[ "creates", "a", "new", "Simulator", "which", "will", "return", "the", "desired", "outcomes", "with", "the", "given", "probability" ]
f124cfcfd9077ee4b05bdfc2110fd1d2edf40985
https://github.com/nigel-lowry/random_outcome/blob/f124cfcfd9077ee4b05bdfc2110fd1d2edf40985/lib/random_outcome/simulator.rb#L23-L26
train
device-independent/restless_router
lib/restless_router/routes.rb
RestlessRouter.Routes.add_route
def add_route(route) raise InvalidRouteError.new('Route must respond to #url_for') unless valid_route?(route) @routes << route unless route_exists?(route) end
ruby
def add_route(route) raise InvalidRouteError.new('Route must respond to #url_for') unless valid_route?(route) @routes << route unless route_exists?(route) end
[ "def", "add_route", "(", "route", ")", "raise", "InvalidRouteError", ".", "new", "(", "'Route must respond to #url_for'", ")", "unless", "valid_route?", "(", "route", ")", "@routes", "<<", "route", "unless", "route_exists?", "(", "route", ")", "end" ]
Add a new route to the Routes collection @return [Array] Routes collection
[ "Add", "a", "new", "route", "to", "the", "Routes", "collection" ]
c20ea03ec53b889d192393c7ab18bcacb0b5e46f
https://github.com/device-independent/restless_router/blob/c20ea03ec53b889d192393c7ab18bcacb0b5e46f/lib/restless_router/routes.rb#L38-L41
train
device-independent/restless_router
lib/restless_router/routes.rb
RestlessRouter.Routes.add_route!
def add_route!(route) # Raise exception if the route is existing, too raise InvalidRouteError.new('Route must respond to #url_for') unless valid_route?(route) raise ExistingRouteError.new(("Route already exists for %s" % [route.name])) if route_exists?(route) @routes << route end
ruby
def add_route!(route) # Raise exception if the route is existing, too raise InvalidRouteError.new('Route must respond to #url_for') unless valid_route?(route) raise ExistingRouteError.new(("Route already exists for %s" % [route.name])) if route_exists?(route) @routes << route end
[ "def", "add_route!", "(", "route", ")", "raise", "InvalidRouteError", ".", "new", "(", "'Route must respond to #url_for'", ")", "unless", "valid_route?", "(", "route", ")", "raise", "ExistingRouteError", ".", "new", "(", "(", "\"Route already exists for %s\"", "%", "[", "route", ".", "name", "]", ")", ")", "if", "route_exists?", "(", "route", ")", "@routes", "<<", "route", "end" ]
Raise an exception if the route is invalid or already exists
[ "Raise", "an", "exception", "if", "the", "route", "is", "invalid", "or", "already", "exists" ]
c20ea03ec53b889d192393c7ab18bcacb0b5e46f
https://github.com/device-independent/restless_router/blob/c20ea03ec53b889d192393c7ab18bcacb0b5e46f/lib/restless_router/routes.rb#L46-L52
train
device-independent/restless_router
lib/restless_router/routes.rb
RestlessRouter.Routes.route_for
def route_for(name) name = name.to_s @routes.select { |entry| entry.name == name }.first end
ruby
def route_for(name) name = name.to_s @routes.select { |entry| entry.name == name }.first end
[ "def", "route_for", "(", "name", ")", "name", "=", "name", ".", "to_s", "@routes", ".", "select", "{", "|", "entry", "|", "entry", ".", "name", "==", "name", "}", ".", "first", "end" ]
Retrieve a route by it's link relationship name @return [Route, nil] Instance of the route by name or nil
[ "Retrieve", "a", "route", "by", "it", "s", "link", "relationship", "name" ]
c20ea03ec53b889d192393c7ab18bcacb0b5e46f
https://github.com/device-independent/restless_router/blob/c20ea03ec53b889d192393c7ab18bcacb0b5e46f/lib/restless_router/routes.rb#L57-L60
train
device-independent/restless_router
lib/restless_router/routes.rb
RestlessRouter.Routes.route_for!
def route_for!(name) route = route_for(name) raise RouteNotFoundError.new(("Route not found for %s" % [name])) if route.nil? route end
ruby
def route_for!(name) route = route_for(name) raise RouteNotFoundError.new(("Route not found for %s" % [name])) if route.nil? route end
[ "def", "route_for!", "(", "name", ")", "route", "=", "route_for", "(", "name", ")", "raise", "RouteNotFoundError", ".", "new", "(", "(", "\"Route not found for %s\"", "%", "[", "name", "]", ")", ")", "if", "route", ".", "nil?", "route", "end" ]
Raise an exception of the route's not found
[ "Raise", "an", "exception", "of", "the", "route", "s", "not", "found" ]
c20ea03ec53b889d192393c7ab18bcacb0b5e46f
https://github.com/device-independent/restless_router/blob/c20ea03ec53b889d192393c7ab18bcacb0b5e46f/lib/restless_router/routes.rb#L65-L69
train
bcantin/auditing
lib/auditing/base.rb
Auditing.Base.audit_enabled
def audit_enabled(opts={}) include InstanceMethods class_attribute :auditing_fields has_many :audits, :as => :auditable, :order => 'created_at DESC, id DESC' self.auditing_fields = gather_fields_for_auditing(opts[:fields]) after_create :log_creation after_update :log_update end
ruby
def audit_enabled(opts={}) include InstanceMethods class_attribute :auditing_fields has_many :audits, :as => :auditable, :order => 'created_at DESC, id DESC' self.auditing_fields = gather_fields_for_auditing(opts[:fields]) after_create :log_creation after_update :log_update end
[ "def", "audit_enabled", "(", "opts", "=", "{", "}", ")", "include", "InstanceMethods", "class_attribute", ":auditing_fields", "has_many", ":audits", ",", ":as", "=>", ":auditable", ",", ":order", "=>", "'created_at DESC, id DESC'", "self", ".", "auditing_fields", "=", "gather_fields_for_auditing", "(", "opts", "[", ":fields", "]", ")", "after_create", ":log_creation", "after_update", ":log_update", "end" ]
Auditing creates audit objects for a record. @examples class School < ActiveRecord::Base audit_enabled end class School < ActiveRecord::Base audit_enabled :fields => [:name, :established_on] end
[ "Auditing", "creates", "audit", "objects", "for", "a", "record", "." ]
495b9e2d465c8263e7709623a003bb933ff540b7
https://github.com/bcantin/auditing/blob/495b9e2d465c8263e7709623a003bb933ff540b7/lib/auditing/base.rb#L13-L24
train
scotdalton/institutions
lib/institutions/institution/util.rb
Institutions.Util.method_missing
def method_missing(method, *args, &block) instance_variable = instance_variablize(method) if respond_to_missing?(method) and instance_variable_defined?(instance_variable) self.class.send :attr_reader, method.to_sym instance_variable_get instance_variable else super end end
ruby
def method_missing(method, *args, &block) instance_variable = instance_variablize(method) if respond_to_missing?(method) and instance_variable_defined?(instance_variable) self.class.send :attr_reader, method.to_sym instance_variable_get instance_variable else super end end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "instance_variable", "=", "instance_variablize", "(", "method", ")", "if", "respond_to_missing?", "(", "method", ")", "and", "instance_variable_defined?", "(", "instance_variable", ")", "self", ".", "class", ".", "send", ":attr_reader", ",", "method", ".", "to_sym", "instance_variable_get", "instance_variable", "else", "super", "end", "end" ]
Dynamically sets attr_readers for elements
[ "Dynamically", "sets", "attr_readers", "for", "elements" ]
e979f42d54abca3cc629b70eb3dd82aa84f19982
https://github.com/scotdalton/institutions/blob/e979f42d54abca3cc629b70eb3dd82aa84f19982/lib/institutions/institution/util.rb#L23-L31
train
scotdalton/institutions
lib/institutions/institution/util.rb
Institutions.Util.respond_to_missing?
def respond_to_missing?(method, include_private = false) # Short circuit if we have invalid instance variable name, # otherwise we get an exception that we don't need. return super unless valid_instance_variable? method if instance_variable_defined? instance_variablize(method) true else super end end
ruby
def respond_to_missing?(method, include_private = false) # Short circuit if we have invalid instance variable name, # otherwise we get an exception that we don't need. return super unless valid_instance_variable? method if instance_variable_defined? instance_variablize(method) true else super end end
[ "def", "respond_to_missing?", "(", "method", ",", "include_private", "=", "false", ")", "return", "super", "unless", "valid_instance_variable?", "method", "if", "instance_variable_defined?", "instance_variablize", "(", "method", ")", "true", "else", "super", "end", "end" ]
Tells users that we respond to missing methods if they are instance variables.
[ "Tells", "users", "that", "we", "respond", "to", "missing", "methods", "if", "they", "are", "instance", "variables", "." ]
e979f42d54abca3cc629b70eb3dd82aa84f19982
https://github.com/scotdalton/institutions/blob/e979f42d54abca3cc629b70eb3dd82aa84f19982/lib/institutions/institution/util.rb#L37-L46
train
threez/mapkit
lib/mapkit.rb
MapKit.Point.in?
def in?(bounding_box) top, left, bottom, right = bounding_box.coords (left..right) === @lng && (top..bottom) === @lat end
ruby
def in?(bounding_box) top, left, bottom, right = bounding_box.coords (left..right) === @lng && (top..bottom) === @lat end
[ "def", "in?", "(", "bounding_box", ")", "top", ",", "left", ",", "bottom", ",", "right", "=", "bounding_box", ".", "coords", "(", "left", "..", "right", ")", "===", "@lng", "&&", "(", "top", "..", "bottom", ")", "===", "@lat", "end" ]
initializes a point object using latitude and longitude returns true if point is in bounding_box, false otherwise
[ "initializes", "a", "point", "object", "using", "latitude", "and", "longitude", "returns", "true", "if", "point", "is", "in", "bounding_box", "false", "otherwise" ]
ffd212e6748b457c946f82cf4556a61d68e0939a
https://github.com/threez/mapkit/blob/ffd212e6748b457c946f82cf4556a61d68e0939a/lib/mapkit.rb#L40-L43
train
threez/mapkit
lib/mapkit.rb
MapKit.Point.pixel
def pixel(bounding_box) x, y = MapKit.latlng2pixel(@lat, @lng, bounding_box.zoom) tile_x, tile_y = MapKit.latlng2pixel(bounding_box.top, bounding_box.left, bounding_box.zoom) [x-tile_x, y-tile_y] end
ruby
def pixel(bounding_box) x, y = MapKit.latlng2pixel(@lat, @lng, bounding_box.zoom) tile_x, tile_y = MapKit.latlng2pixel(bounding_box.top, bounding_box.left, bounding_box.zoom) [x-tile_x, y-tile_y] end
[ "def", "pixel", "(", "bounding_box", ")", "x", ",", "y", "=", "MapKit", ".", "latlng2pixel", "(", "@lat", ",", "@lng", ",", "bounding_box", ".", "zoom", ")", "tile_x", ",", "tile_y", "=", "MapKit", ".", "latlng2pixel", "(", "bounding_box", ".", "top", ",", "bounding_box", ".", "left", ",", "bounding_box", ".", "zoom", ")", "[", "x", "-", "tile_x", ",", "y", "-", "tile_y", "]", "end" ]
returns relative x and y for point in bounding_box
[ "returns", "relative", "x", "and", "y", "for", "point", "in", "bounding_box" ]
ffd212e6748b457c946f82cf4556a61d68e0939a
https://github.com/threez/mapkit/blob/ffd212e6748b457c946f82cf4556a61d68e0939a/lib/mapkit.rb#L46-L50
train
threez/mapkit
lib/mapkit.rb
MapKit.BoundingBox.grow!
def grow!(percent) lng = ((100.0 + percent) * (width / 2.0 / 100.0)) / 2.0 lat = ((100.0 + percent) * (height / 2.0 / 100.0)) / 2.0 @top += lat @left -= lng @bottom -= lat @right += lng end
ruby
def grow!(percent) lng = ((100.0 + percent) * (width / 2.0 / 100.0)) / 2.0 lat = ((100.0 + percent) * (height / 2.0 / 100.0)) / 2.0 @top += lat @left -= lng @bottom -= lat @right += lng end
[ "def", "grow!", "(", "percent", ")", "lng", "=", "(", "(", "100.0", "+", "percent", ")", "*", "(", "width", "/", "2.0", "/", "100.0", ")", ")", "/", "2.0", "lat", "=", "(", "(", "100.0", "+", "percent", ")", "*", "(", "height", "/", "2.0", "/", "100.0", ")", ")", "/", "2.0", "@top", "+=", "lat", "@left", "-=", "lng", "@bottom", "-=", "lat", "@right", "+=", "lng", "end" ]
grow bounding box by percentage
[ "grow", "bounding", "box", "by", "percentage" ]
ffd212e6748b457c946f82cf4556a61d68e0939a
https://github.com/threez/mapkit/blob/ffd212e6748b457c946f82cf4556a61d68e0939a/lib/mapkit.rb#L98-L105
train
ideonetwork/lato-blog
lib/lato_blog/interfaces/fields.rb
LatoBlog.Interface::Fields.blog__sync_config_post_fields_with_db_post_fields
def blog__sync_config_post_fields_with_db_post_fields posts = LatoBlog::Post.all # create / update fields on database posts.map { |p| blog__sync_config_post_fields_with_db_post_fields_for_post(p) } end
ruby
def blog__sync_config_post_fields_with_db_post_fields posts = LatoBlog::Post.all # create / update fields on database posts.map { |p| blog__sync_config_post_fields_with_db_post_fields_for_post(p) } end
[ "def", "blog__sync_config_post_fields_with_db_post_fields", "posts", "=", "LatoBlog", "::", "Post", ".", "all", "posts", ".", "map", "{", "|", "p", "|", "blog__sync_config_post_fields_with_db_post_fields_for_post", "(", "p", ")", "}", "end" ]
This function syncronizes the config post fields with the post fields on database.
[ "This", "function", "syncronizes", "the", "config", "post", "fields", "with", "the", "post", "fields", "on", "database", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/fields.rb#L7-L11
train
ideonetwork/lato-blog
lib/lato_blog/interfaces/fields.rb
LatoBlog.Interface::Fields.blog__sync_config_post_fields_with_db_post_fields_for_post
def blog__sync_config_post_fields_with_db_post_fields_for_post(post) # save or update post fields from config post_fields = CONFIGS[:lato_blog][:post_fields] post_fields.map { |key, content| blog__sync_config_post_field(post, key, content) } # remove old post fields db_post_fields = post.post_fields.visibles.roots db_post_fields.map { |dbpf| blog__sync_db_post_field(post, dbpf) } end
ruby
def blog__sync_config_post_fields_with_db_post_fields_for_post(post) # save or update post fields from config post_fields = CONFIGS[:lato_blog][:post_fields] post_fields.map { |key, content| blog__sync_config_post_field(post, key, content) } # remove old post fields db_post_fields = post.post_fields.visibles.roots db_post_fields.map { |dbpf| blog__sync_db_post_field(post, dbpf) } end
[ "def", "blog__sync_config_post_fields_with_db_post_fields_for_post", "(", "post", ")", "post_fields", "=", "CONFIGS", "[", ":lato_blog", "]", "[", ":post_fields", "]", "post_fields", ".", "map", "{", "|", "key", ",", "content", "|", "blog__sync_config_post_field", "(", "post", ",", "key", ",", "content", ")", "}", "db_post_fields", "=", "post", ".", "post_fields", ".", "visibles", ".", "roots", "db_post_fields", ".", "map", "{", "|", "dbpf", "|", "blog__sync_db_post_field", "(", "post", ",", "dbpf", ")", "}", "end" ]
This function syncronizes the config post fields with the post fields on database for a single post object.
[ "This", "function", "syncronizes", "the", "config", "post", "fields", "with", "the", "post", "fields", "on", "database", "for", "a", "single", "post", "object", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/fields.rb#L15-L22
train
ideonetwork/lato-blog
lib/lato_blog/interfaces/fields.rb
LatoBlog.Interface::Fields.blog__sync_config_post_field
def blog__sync_config_post_field(post, key, content) db_post_field = LatoBlog::PostField.find_by( key: key, lato_blog_post_id: post.id, lato_blog_post_field_id: nil ) # check if post field can be created for the post if content[:categories] && !content[:categories].empty? db_categories = LatoBlog::Category.where(meta_permalink: content[:categories]) return if (post.categories.pluck(:id) & db_categories.pluck(:id)).empty? end # run correct action for field if db_post_field blog__update_db_post_field(db_post_field, content) else blog__create_db_post_field(post, key, content) end end
ruby
def blog__sync_config_post_field(post, key, content) db_post_field = LatoBlog::PostField.find_by( key: key, lato_blog_post_id: post.id, lato_blog_post_field_id: nil ) # check if post field can be created for the post if content[:categories] && !content[:categories].empty? db_categories = LatoBlog::Category.where(meta_permalink: content[:categories]) return if (post.categories.pluck(:id) & db_categories.pluck(:id)).empty? end # run correct action for field if db_post_field blog__update_db_post_field(db_post_field, content) else blog__create_db_post_field(post, key, content) end end
[ "def", "blog__sync_config_post_field", "(", "post", ",", "key", ",", "content", ")", "db_post_field", "=", "LatoBlog", "::", "PostField", ".", "find_by", "(", "key", ":", "key", ",", "lato_blog_post_id", ":", "post", ".", "id", ",", "lato_blog_post_field_id", ":", "nil", ")", "if", "content", "[", ":categories", "]", "&&", "!", "content", "[", ":categories", "]", ".", "empty?", "db_categories", "=", "LatoBlog", "::", "Category", ".", "where", "(", "meta_permalink", ":", "content", "[", ":categories", "]", ")", "return", "if", "(", "post", ".", "categories", ".", "pluck", "(", ":id", ")", "&", "db_categories", ".", "pluck", "(", ":id", ")", ")", ".", "empty?", "end", "if", "db_post_field", "blog__update_db_post_field", "(", "db_post_field", ",", "content", ")", "else", "blog__create_db_post_field", "(", "post", ",", "key", ",", "content", ")", "end", "end" ]
This function syncronizes a single post field of a specific post with database.
[ "This", "function", "syncronizes", "a", "single", "post", "field", "of", "a", "specific", "post", "with", "database", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/fields.rb#L25-L42
train
ideonetwork/lato-blog
lib/lato_blog/interfaces/fields.rb
LatoBlog.Interface::Fields.blog__sync_db_post_field
def blog__sync_db_post_field(post, db_post_field) post_fields = CONFIGS[:lato_blog][:post_fields] # search db post field on config file content = post_fields[db_post_field.key] db_post_field.update(meta_visible: false) && return unless content # check category of post field is accepted if content[:categories] && !content[:categories].empty? db_categories = LatoBlog::Category.where(meta_permalink: content[:categories]) db_post_field.update(meta_visible: false) && return if (post.categories.pluck(:id) & db_categories.pluck(:id)).empty? end end
ruby
def blog__sync_db_post_field(post, db_post_field) post_fields = CONFIGS[:lato_blog][:post_fields] # search db post field on config file content = post_fields[db_post_field.key] db_post_field.update(meta_visible: false) && return unless content # check category of post field is accepted if content[:categories] && !content[:categories].empty? db_categories = LatoBlog::Category.where(meta_permalink: content[:categories]) db_post_field.update(meta_visible: false) && return if (post.categories.pluck(:id) & db_categories.pluck(:id)).empty? end end
[ "def", "blog__sync_db_post_field", "(", "post", ",", "db_post_field", ")", "post_fields", "=", "CONFIGS", "[", ":lato_blog", "]", "[", ":post_fields", "]", "content", "=", "post_fields", "[", "db_post_field", ".", "key", "]", "db_post_field", ".", "update", "(", "meta_visible", ":", "false", ")", "&&", "return", "unless", "content", "if", "content", "[", ":categories", "]", "&&", "!", "content", "[", ":categories", "]", ".", "empty?", "db_categories", "=", "LatoBlog", "::", "Category", ".", "where", "(", "meta_permalink", ":", "content", "[", ":categories", "]", ")", "db_post_field", ".", "update", "(", "meta_visible", ":", "false", ")", "&&", "return", "if", "(", "post", ".", "categories", ".", "pluck", "(", ":id", ")", "&", "db_categories", ".", "pluck", "(", ":id", ")", ")", ".", "empty?", "end", "end" ]
This function syncronizes a single post field of a specific post with config file.
[ "This", "function", "syncronizes", "a", "single", "post", "field", "of", "a", "specific", "post", "with", "config", "file", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/fields.rb#L45-L55
train
ideonetwork/lato-blog
lib/lato_blog/interfaces/fields.rb
LatoBlog.Interface::Fields.blog__update_db_post_field
def blog__update_db_post_field(db_post_field, content, post_field_parent = nil) # run minimum updates db_post_field.update( position: content[:position], meta_visible: true ) # run custom update for type case db_post_field.typology when 'text' update_db_post_field_text(db_post_field, content, post_field_parent) when 'textarea' update_db_post_field_textarea(db_post_field, content, post_field_parent) when 'datetime' update_db_post_field_datetime(db_post_field, content, post_field_parent) when 'editor' update_db_post_field_editor(db_post_field, content, post_field_parent) when 'geolocalization' update_db_post_field_geolocalization(db_post_field, content, post_field_parent) when 'image' update_db_post_field_image(db_post_field, content, post_field_parent) when 'gallery' update_db_post_field_gallery(db_post_field, content, post_field_parent) when 'youtube' update_db_post_field_youtube(db_post_field, content, post_field_parent) when 'composed' update_db_post_field_composed(db_post_field, content, post_field_parent) when 'relay' update_db_post_field_relay(db_post_field, content, post_field_parent) end end
ruby
def blog__update_db_post_field(db_post_field, content, post_field_parent = nil) # run minimum updates db_post_field.update( position: content[:position], meta_visible: true ) # run custom update for type case db_post_field.typology when 'text' update_db_post_field_text(db_post_field, content, post_field_parent) when 'textarea' update_db_post_field_textarea(db_post_field, content, post_field_parent) when 'datetime' update_db_post_field_datetime(db_post_field, content, post_field_parent) when 'editor' update_db_post_field_editor(db_post_field, content, post_field_parent) when 'geolocalization' update_db_post_field_geolocalization(db_post_field, content, post_field_parent) when 'image' update_db_post_field_image(db_post_field, content, post_field_parent) when 'gallery' update_db_post_field_gallery(db_post_field, content, post_field_parent) when 'youtube' update_db_post_field_youtube(db_post_field, content, post_field_parent) when 'composed' update_db_post_field_composed(db_post_field, content, post_field_parent) when 'relay' update_db_post_field_relay(db_post_field, content, post_field_parent) end end
[ "def", "blog__update_db_post_field", "(", "db_post_field", ",", "content", ",", "post_field_parent", "=", "nil", ")", "db_post_field", ".", "update", "(", "position", ":", "content", "[", ":position", "]", ",", "meta_visible", ":", "true", ")", "case", "db_post_field", ".", "typology", "when", "'text'", "update_db_post_field_text", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'textarea'", "update_db_post_field_textarea", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'datetime'", "update_db_post_field_datetime", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'editor'", "update_db_post_field_editor", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'geolocalization'", "update_db_post_field_geolocalization", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'image'", "update_db_post_field_image", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'gallery'", "update_db_post_field_gallery", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'youtube'", "update_db_post_field_youtube", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'composed'", "update_db_post_field_composed", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "when", "'relay'", "update_db_post_field_relay", "(", "db_post_field", ",", "content", ",", "post_field_parent", ")", "end", "end" ]
This function update an existing post field on database with new content.
[ "This", "function", "update", "an", "existing", "post", "field", "on", "database", "with", "new", "content", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/fields.rb#L75-L104
train
westlakedesign/auth_net_receiver
app/models/auth_net_receiver/raw_transaction.rb
AuthNetReceiver.RawTransaction.json_data
def json_data begin return JSON.parse(self.data) rescue JSON::ParserError, TypeError => e logger.warn "Error while parsing raw transaction data: #{e.message}" return {} end end
ruby
def json_data begin return JSON.parse(self.data) rescue JSON::ParserError, TypeError => e logger.warn "Error while parsing raw transaction data: #{e.message}" return {} end end
[ "def", "json_data", "begin", "return", "JSON", ".", "parse", "(", "self", ".", "data", ")", "rescue", "JSON", "::", "ParserError", ",", "TypeError", "=>", "e", "logger", ".", "warn", "\"Error while parsing raw transaction data: #{e.message}\"", "return", "{", "}", "end", "end" ]
Return the JSON data on this record as a hash
[ "Return", "the", "JSON", "data", "on", "this", "record", "as", "a", "hash" ]
723887c2ce39d08431c676a72bf7dc3041b7f27e
https://github.com/westlakedesign/auth_net_receiver/blob/723887c2ce39d08431c676a72bf7dc3041b7f27e/app/models/auth_net_receiver/raw_transaction.rb#L29-L36
train
westlakedesign/auth_net_receiver
app/models/auth_net_receiver/raw_transaction.rb
AuthNetReceiver.RawTransaction.md5_hash_is_valid?
def md5_hash_is_valid?(json) if AuthNetReceiver.config.hash_value.nil? || AuthNetReceiver.config.gateway_login.nil? raise StandardError, 'AuthNetReceiver hash_value and gateway_login cannot be nil!' end parts = [] parts << AuthNetReceiver.config.hash_value parts << AuthNetReceiver.config.gateway_login if json['x_subscription_id'].blank? parts << json['x_trans_id'] parts << json['x_amount'] hash = Digest::MD5.hexdigest(parts.join()).upcase return hash == json['x_MD5_Hash'] end
ruby
def md5_hash_is_valid?(json) if AuthNetReceiver.config.hash_value.nil? || AuthNetReceiver.config.gateway_login.nil? raise StandardError, 'AuthNetReceiver hash_value and gateway_login cannot be nil!' end parts = [] parts << AuthNetReceiver.config.hash_value parts << AuthNetReceiver.config.gateway_login if json['x_subscription_id'].blank? parts << json['x_trans_id'] parts << json['x_amount'] hash = Digest::MD5.hexdigest(parts.join()).upcase return hash == json['x_MD5_Hash'] end
[ "def", "md5_hash_is_valid?", "(", "json", ")", "if", "AuthNetReceiver", ".", "config", ".", "hash_value", ".", "nil?", "||", "AuthNetReceiver", ".", "config", ".", "gateway_login", ".", "nil?", "raise", "StandardError", ",", "'AuthNetReceiver hash_value and gateway_login cannot be nil!'", "end", "parts", "=", "[", "]", "parts", "<<", "AuthNetReceiver", ".", "config", ".", "hash_value", "parts", "<<", "AuthNetReceiver", ".", "config", ".", "gateway_login", "if", "json", "[", "'x_subscription_id'", "]", ".", "blank?", "parts", "<<", "json", "[", "'x_trans_id'", "]", "parts", "<<", "json", "[", "'x_amount'", "]", "hash", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "parts", ".", "join", "(", ")", ")", ".", "upcase", "return", "hash", "==", "json", "[", "'x_MD5_Hash'", "]", "end" ]
Check that the x_MD5_Hash value matches our expectations The formula for the hash differs for subscription vs regular transactions. Regular transactions will be associated with the gateway ID that was used in the originating API call. Subscriptions however are ran on the server at later date, and therefore will not be associated to a gateway ID. * Subscriptions: MD5 Digest(AUTH_NET_HASH_VAL + TRANSACTION_ID + TRANSACTION_AMOUNT) * Other Transactions: MD5 Digest(AUTH_NET_HASH_VAL + GATEWAY_LOGIN + TRANSACTION_ID + TRANSACTION_AMOUNT)
[ "Check", "that", "the", "x_MD5_Hash", "value", "matches", "our", "expectations" ]
723887c2ce39d08431c676a72bf7dc3041b7f27e
https://github.com/westlakedesign/auth_net_receiver/blob/723887c2ce39d08431c676a72bf7dc3041b7f27e/app/models/auth_net_receiver/raw_transaction.rb#L78-L89
train
agios/simple_form-dojo
lib/simple_form-dojo/form_builder.rb
SimpleFormDojo.FormBuilder.button
def button(type, *args, &block) # set options to value if first arg is a Hash options = args.extract_options! button_type = 'dijit/form/Button' button_type = 'dojox/form/BusyButton' if options[:busy] options.reverse_merge!(:'data-dojo-type' => button_type) content = '' if value = options.delete(:value) content = value.html_safe else content = button_default_value end options.reverse_merge!({ :type => type, :value => content }) dojo_props = {} dojo_props.merge!(options[:dojo_html]) if options.include?(:dojo_html) options[:'data-dojo-props'] = SimpleFormDojo::FormBuilder.encode_as_dojo_props(dojo_props) options[:class] = "button #{options[:class]}".strip template.content_tag(:button, content, *(args << options), &block) end
ruby
def button(type, *args, &block) # set options to value if first arg is a Hash options = args.extract_options! button_type = 'dijit/form/Button' button_type = 'dojox/form/BusyButton' if options[:busy] options.reverse_merge!(:'data-dojo-type' => button_type) content = '' if value = options.delete(:value) content = value.html_safe else content = button_default_value end options.reverse_merge!({ :type => type, :value => content }) dojo_props = {} dojo_props.merge!(options[:dojo_html]) if options.include?(:dojo_html) options[:'data-dojo-props'] = SimpleFormDojo::FormBuilder.encode_as_dojo_props(dojo_props) options[:class] = "button #{options[:class]}".strip template.content_tag(:button, content, *(args << options), &block) end
[ "def", "button", "(", "type", ",", "*", "args", ",", "&", "block", ")", "options", "=", "args", ".", "extract_options!", "button_type", "=", "'dijit/form/Button'", "button_type", "=", "'dojox/form/BusyButton'", "if", "options", "[", ":busy", "]", "options", ".", "reverse_merge!", "(", ":'", "'", "=>", "button_type", ")", "content", "=", "''", "if", "value", "=", "options", ".", "delete", "(", ":value", ")", "content", "=", "value", ".", "html_safe", "else", "content", "=", "button_default_value", "end", "options", ".", "reverse_merge!", "(", "{", ":type", "=>", "type", ",", ":value", "=>", "content", "}", ")", "dojo_props", "=", "{", "}", "dojo_props", ".", "merge!", "(", "options", "[", ":dojo_html", "]", ")", "if", "options", ".", "include?", "(", ":dojo_html", ")", "options", "[", ":'", "'", "]", "=", "SimpleFormDojo", "::", "FormBuilder", ".", "encode_as_dojo_props", "(", "dojo_props", ")", "options", "[", ":class", "]", "=", "\"button #{options[:class]}\"", ".", "strip", "template", ".", "content_tag", "(", ":button", ",", "content", ",", "*", "(", "args", "<<", "options", ")", ",", "&", "block", ")", "end" ]
Simple override of initializer in order to add in the dojo_props attribute Creates a button overrides simple_form's button method dojo_form_for @user do |f| f.button :submit, :value => 'Save Me' end To use dojox/form/BusyButton, pass :busy => true dojo_form_for @uswer do |f| f.button :submit, :busy => true, :value => 'Save Me' end If :value doesn't exist, tries to determine the the value based on the current object
[ "Simple", "override", "of", "initializer", "in", "order", "to", "add", "in", "the", "dojo_props", "attribute", "Creates", "a", "button" ]
c4b134f56f4cb68cba81d583038965360c70fba4
https://github.com/agios/simple_form-dojo/blob/c4b134f56f4cb68cba81d583038965360c70fba4/lib/simple_form-dojo/form_builder.rb#L41-L59
train
agios/simple_form-dojo
lib/simple_form-dojo/form_builder.rb
SimpleFormDojo.FormBuilder.button_default_value
def button_default_value obj = object.respond_to?(:to_model) ? object.to_model : object key = obj ? (obj.persisted? ? :edit : :new) : :submit model = if obj.class.respond_to?(:model_name) obj.class.model_name.human else object_name.to_s.humanize end defaults = [] defaults << "helpers.submit.#{object_name}.#{key}" defaults << "#{key.to_s.humanize} #{model}" I18n.t(defaults.shift, :default => defaults) end
ruby
def button_default_value obj = object.respond_to?(:to_model) ? object.to_model : object key = obj ? (obj.persisted? ? :edit : :new) : :submit model = if obj.class.respond_to?(:model_name) obj.class.model_name.human else object_name.to_s.humanize end defaults = [] defaults << "helpers.submit.#{object_name}.#{key}" defaults << "#{key.to_s.humanize} #{model}" I18n.t(defaults.shift, :default => defaults) end
[ "def", "button_default_value", "obj", "=", "object", ".", "respond_to?", "(", ":to_model", ")", "?", "object", ".", "to_model", ":", "object", "key", "=", "obj", "?", "(", "obj", ".", "persisted?", "?", ":edit", ":", ":new", ")", ":", ":submit", "model", "=", "if", "obj", ".", "class", ".", "respond_to?", "(", ":model_name", ")", "obj", ".", "class", ".", "model_name", ".", "human", "else", "object_name", ".", "to_s", ".", "humanize", "end", "defaults", "=", "[", "]", "defaults", "<<", "\"helpers.submit.#{object_name}.#{key}\"", "defaults", "<<", "\"#{key.to_s.humanize} #{model}\"", "I18n", ".", "t", "(", "defaults", ".", "shift", ",", ":default", "=>", "defaults", ")", "end" ]
Basically the same as rails submit_default_value
[ "Basically", "the", "same", "as", "rails", "submit_default_value" ]
c4b134f56f4cb68cba81d583038965360c70fba4
https://github.com/agios/simple_form-dojo/blob/c4b134f56f4cb68cba81d583038965360c70fba4/lib/simple_form-dojo/form_builder.rb#L62-L76
train
LAS-IT/open_directory_utils
lib/open_directory_utils/connection.rb
OpenDirectoryUtils.Connection.run
def run(command:, params:, output: nil) answer = {} params[:format] = output # just in case clear record_name and calculate later params[:record_name] = nil ssh_cmds = send(command, params, dir_info) # pp ssh_cmds results = send_cmds_to_od_server(ssh_cmds) # pp results answer = process_results(results, command, params, ssh_cmds ) params[:value] = nil return answer rescue ArgumentError, NoMethodError => error format_results(error.message, command, params, ssh_cmds, 'error') end
ruby
def run(command:, params:, output: nil) answer = {} params[:format] = output # just in case clear record_name and calculate later params[:record_name] = nil ssh_cmds = send(command, params, dir_info) # pp ssh_cmds results = send_cmds_to_od_server(ssh_cmds) # pp results answer = process_results(results, command, params, ssh_cmds ) params[:value] = nil return answer rescue ArgumentError, NoMethodError => error format_results(error.message, command, params, ssh_cmds, 'error') end
[ "def", "run", "(", "command", ":", ",", "params", ":", ",", "output", ":", "nil", ")", "answer", "=", "{", "}", "params", "[", ":format", "]", "=", "output", "params", "[", ":record_name", "]", "=", "nil", "ssh_cmds", "=", "send", "(", "command", ",", "params", ",", "dir_info", ")", "results", "=", "send_cmds_to_od_server", "(", "ssh_cmds", ")", "answer", "=", "process_results", "(", "results", ",", "command", ",", "params", ",", "ssh_cmds", ")", "params", "[", ":value", "]", "=", "nil", "return", "answer", "rescue", "ArgumentError", ",", "NoMethodError", "=>", "error", "format_results", "(", "error", ".", "message", ",", "command", ",", "params", ",", "ssh_cmds", ",", "'error'", ")", "end" ]
after configuring a connection with .new - send commands via ssh to open directory @command [Symbol] - required -- to choose the action wanted @params [Hash] - required -- necessary information to accomplish action @output [String] - optional -- 'xml' or 'plist' will return responses using xml format response [Hash] - { response: results, status: status, command: command, attributes: params, dscl_cmds: ssh_clean }
[ "after", "configuring", "a", "connection", "with", ".", "new", "-", "send", "commands", "via", "ssh", "to", "open", "directory" ]
dd29b04728fa261c755577af066c9f817642998a
https://github.com/LAS-IT/open_directory_utils/blob/dd29b04728fa261c755577af066c9f817642998a/lib/open_directory_utils/connection.rb#L50-L64
train
octoai/gem-octocore-mongo
lib/octocore-mongo/counter.rb
Octo.Counter.local_count
def local_count(duration, type) aggr = {} Octo::Enterprise.each do |enterprise| args = { enterprise_id: enterprise.id, ts: duration, type: type } aggr[enterprise.id.to_s] = {} unless aggr.has_key?(enterprise.id.to_s) results = where(args) results_group = results.group_by { |x| x.uid } results_group.each do |uid, counters| _sum = counters.inject(0) do |sum, counter| sum + counter.count end aggr[enterprise.id.to_s][uid] = _sum end end aggr end
ruby
def local_count(duration, type) aggr = {} Octo::Enterprise.each do |enterprise| args = { enterprise_id: enterprise.id, ts: duration, type: type } aggr[enterprise.id.to_s] = {} unless aggr.has_key?(enterprise.id.to_s) results = where(args) results_group = results.group_by { |x| x.uid } results_group.each do |uid, counters| _sum = counters.inject(0) do |sum, counter| sum + counter.count end aggr[enterprise.id.to_s][uid] = _sum end end aggr end
[ "def", "local_count", "(", "duration", ",", "type", ")", "aggr", "=", "{", "}", "Octo", "::", "Enterprise", ".", "each", "do", "|", "enterprise", "|", "args", "=", "{", "enterprise_id", ":", "enterprise", ".", "id", ",", "ts", ":", "duration", ",", "type", ":", "type", "}", "aggr", "[", "enterprise", ".", "id", ".", "to_s", "]", "=", "{", "}", "unless", "aggr", ".", "has_key?", "(", "enterprise", ".", "id", ".", "to_s", ")", "results", "=", "where", "(", "args", ")", "results_group", "=", "results", ".", "group_by", "{", "|", "x", "|", "x", ".", "uid", "}", "results_group", ".", "each", "do", "|", "uid", ",", "counters", "|", "_sum", "=", "counters", ".", "inject", "(", "0", ")", "do", "|", "sum", ",", "counter", "|", "sum", "+", "counter", ".", "count", "end", "aggr", "[", "enterprise", ".", "id", ".", "to_s", "]", "[", "uid", "]", "=", "_sum", "end", "end", "aggr", "end" ]
Does the counting from DB. Unlike the other counter that uses Redis. Hence the name local_count @param [Time] duration A time/time range object @param [Fixnum] type The type of counter to look for
[ "Does", "the", "counting", "from", "DB", ".", "Unlike", "the", "other", "counter", "that", "uses", "Redis", ".", "Hence", "the", "name", "local_count" ]
bf7fa833fd7e08947697d0341ab5e80e89c8d05a
https://github.com/octoai/gem-octocore-mongo/blob/bf7fa833fd7e08947697d0341ab5e80e89c8d05a/lib/octocore-mongo/counter.rb#L128-L147
train
jarrett/ichiban
lib/ichiban/scripts.rb
Ichiban.ScriptRunner.script_file_changed
def script_file_changed(path) Ichiban.logger.script_run(path) script = Ichiban::Script.new(path).run end
ruby
def script_file_changed(path) Ichiban.logger.script_run(path) script = Ichiban::Script.new(path).run end
[ "def", "script_file_changed", "(", "path", ")", "Ichiban", ".", "logger", ".", "script_run", "(", "path", ")", "script", "=", "Ichiban", "::", "Script", ".", "new", "(", "path", ")", ".", "run", "end" ]
Takes an absolute path
[ "Takes", "an", "absolute", "path" ]
310f96b0981ea19bf01246995f3732c986915d5b
https://github.com/jarrett/ichiban/blob/310f96b0981ea19bf01246995f3732c986915d5b/lib/ichiban/scripts.rb#L8-L11
train
aub/tumble
lib/tumble/blog.rb
Tumble.Blog.reblog_post
def reblog_post(id, reblog_key, options={}) @connection.post("/blog/#{name}/post/reblog", options.merge('id' => id, 'reblog_key' => reblog_key)).response end
ruby
def reblog_post(id, reblog_key, options={}) @connection.post("/blog/#{name}/post/reblog", options.merge('id' => id, 'reblog_key' => reblog_key)).response end
[ "def", "reblog_post", "(", "id", ",", "reblog_key", ",", "options", "=", "{", "}", ")", "@connection", ".", "post", "(", "\"/blog/#{name}/post/reblog\"", ",", "options", ".", "merge", "(", "'id'", "=>", "id", ",", "'reblog_key'", "=>", "reblog_key", ")", ")", ".", "response", "end" ]
Reblog a Post @see http://www.tumblr.com/docs/en/api/v2#reblogging @requires_authentication Yes @param id [Integer] The ID of the reblogged post on tumblelog @param reblog_key [Integer] The reblog key for the reblogged post – get the reblog key with a /posts request @param options [Hash] A customizable set of options @option options [String] :comment A comment added to the reblogged post
[ "Reblog", "a", "Post" ]
dad342fabd2dfc30031d94392927f3fe86953cc1
https://github.com/aub/tumble/blob/dad342fabd2dfc30031d94392927f3fe86953cc1/lib/tumble/blog.rb#L181-L183
train
pwnall/file_blobs_rails
lib/file_blobs_rails/active_record_migration_extensions.rb
FileBlobs.ActiveRecordMigrationExtensions.create_file_blobs_table
def create_file_blobs_table(table_name = :file_blobs, options = {}, &block) blob_limit = options[:blob_limit] || 1.megabyte create_table table_name, id: false do |t| t.primary_key :id, :string, null: false, limit: 48 t.binary :data, null: false, limit: blob_limit # Block capturing and calling is a bit slower than using yield. This is # not a concern because migrations aren't run in tight loops. block.call t end end
ruby
def create_file_blobs_table(table_name = :file_blobs, options = {}, &block) blob_limit = options[:blob_limit] || 1.megabyte create_table table_name, id: false do |t| t.primary_key :id, :string, null: false, limit: 48 t.binary :data, null: false, limit: blob_limit # Block capturing and calling is a bit slower than using yield. This is # not a concern because migrations aren't run in tight loops. block.call t end end
[ "def", "create_file_blobs_table", "(", "table_name", "=", ":file_blobs", ",", "options", "=", "{", "}", ",", "&", "block", ")", "blob_limit", "=", "options", "[", ":blob_limit", "]", "||", "1", ".", "megabyte", "create_table", "table_name", ",", "id", ":", "false", "do", "|", "t", "|", "t", ".", "primary_key", ":id", ",", ":string", ",", "null", ":", "false", ",", "limit", ":", "48", "t", ".", "binary", ":data", ",", "null", ":", "false", ",", "limit", ":", "blob_limit", "block", ".", "call", "t", "end", "end" ]
Creates the table used to hold file blobs. @param [Symbol] table_name the name of the table used to hold file data @param [Hash<Symbol, Object>] options @option options [Integer] blob_limit the maximum file size that can be stored in the table; defaults to 1 megabyte
[ "Creates", "the", "table", "used", "to", "hold", "file", "blobs", "." ]
688d43ec8547856f3572b0e6716e6faeff56345b
https://github.com/pwnall/file_blobs_rails/blob/688d43ec8547856f3572b0e6716e6faeff56345b/lib/file_blobs_rails/active_record_migration_extensions.rb#L13-L24
train
culturecode/s3_asset
lib/s3_asset/acts_as_s3_asset.rb
S3Asset.ActsAsS3Asset.crop_resized
def crop_resized(image, size, gravity = "Center") size =~ /(\d+)x(\d+)/ width = $1.to_i height = $2.to_i # Grab the width and height of the current image in one go. cols, rows = image[:dimensions] # Only do anything if needs be. Who knows, maybe it's already the exact # dimensions we're looking for. if(width != cols && height != rows) image.combine_options do |c| # Scale the image down to the widest dimension. if(width != cols || height != rows) scale = [width / cols.to_f, height / rows.to_f].max * 100 c.resize("#{scale}%") end # Align how things will be cropped. c.gravity(gravity) # Crop the image to size. c.crop("#{width}x#{height}+0+0") end end end
ruby
def crop_resized(image, size, gravity = "Center") size =~ /(\d+)x(\d+)/ width = $1.to_i height = $2.to_i # Grab the width and height of the current image in one go. cols, rows = image[:dimensions] # Only do anything if needs be. Who knows, maybe it's already the exact # dimensions we're looking for. if(width != cols && height != rows) image.combine_options do |c| # Scale the image down to the widest dimension. if(width != cols || height != rows) scale = [width / cols.to_f, height / rows.to_f].max * 100 c.resize("#{scale}%") end # Align how things will be cropped. c.gravity(gravity) # Crop the image to size. c.crop("#{width}x#{height}+0+0") end end end
[ "def", "crop_resized", "(", "image", ",", "size", ",", "gravity", "=", "\"Center\"", ")", "size", "=~", "/", "\\d", "\\d", "/", "width", "=", "$1", ".", "to_i", "height", "=", "$2", ".", "to_i", "cols", ",", "rows", "=", "image", "[", ":dimensions", "]", "if", "(", "width", "!=", "cols", "&&", "height", "!=", "rows", ")", "image", ".", "combine_options", "do", "|", "c", "|", "if", "(", "width", "!=", "cols", "||", "height", "!=", "rows", ")", "scale", "=", "[", "width", "/", "cols", ".", "to_f", ",", "height", "/", "rows", ".", "to_f", "]", ".", "max", "*", "100", "c", ".", "resize", "(", "\"#{scale}%\"", ")", "end", "c", ".", "gravity", "(", "gravity", ")", "c", ".", "crop", "(", "\"#{width}x#{height}+0+0\"", ")", "end", "end", "end" ]
Scale an image down and crop away any extra to achieve a certain size. This is handy for creating thumbnails of the same dimensions without changing the aspect ratio.
[ "Scale", "an", "image", "down", "and", "crop", "away", "any", "extra", "to", "achieve", "a", "certain", "size", ".", "This", "is", "handy", "for", "creating", "thumbnails", "of", "the", "same", "dimensions", "without", "changing", "the", "aspect", "ratio", "." ]
9db578f316e110592ac47f0371214c3daf58f55f
https://github.com/culturecode/s3_asset/blob/9db578f316e110592ac47f0371214c3daf58f55f/lib/s3_asset/acts_as_s3_asset.rb#L183-L208
train
megamsys/megam_api
lib/megam/core/rest_adapter.rb
Megam.RestAdapter.megam_rest
def megam_rest options = { :email => email, :api_key => api_key, :org_id => org_id, :password_hash => password_hash, :master_key => master_key, :host => host } if headers options[:headers] = headers end Megam::API.new(options) end
ruby
def megam_rest options = { :email => email, :api_key => api_key, :org_id => org_id, :password_hash => password_hash, :master_key => master_key, :host => host } if headers options[:headers] = headers end Megam::API.new(options) end
[ "def", "megam_rest", "options", "=", "{", ":email", "=>", "email", ",", ":api_key", "=>", "api_key", ",", ":org_id", "=>", "org_id", ",", ":password_hash", "=>", "password_hash", ",", ":master_key", "=>", "master_key", ",", ":host", "=>", "host", "}", "if", "headers", "options", "[", ":headers", "]", "=", "headers", "end", "Megam", "::", "API", ".", "new", "(", "options", ")", "end" ]
clean up this module later. Build a megam api client === Parameters api:: The Megam::API client
[ "clean", "up", "this", "module", "later", ".", "Build", "a", "megam", "api", "client" ]
c28e743311706dfef9c7745ae64058a468f5b1a4
https://github.com/megamsys/megam_api/blob/c28e743311706dfef9c7745ae64058a468f5b1a4/lib/megam/core/rest_adapter.rb#L29-L42
train
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.add_attribute
def add_attribute(name, type, metadata={}) attr_reader name attributes << (metadata || {}).merge(:name => name.to_sym, :type => type.to_sym) end
ruby
def add_attribute(name, type, metadata={}) attr_reader name attributes << (metadata || {}).merge(:name => name.to_sym, :type => type.to_sym) end
[ "def", "add_attribute", "(", "name", ",", "type", ",", "metadata", "=", "{", "}", ")", "attr_reader", "name", "attributes", "<<", "(", "metadata", "||", "{", "}", ")", ".", "merge", "(", ":name", "=>", "name", ".", "to_sym", ",", ":type", "=>", "type", ".", "to_sym", ")", "end" ]
Attribute macros Defines an attribute @param [String] name The name of the attribute @param [Symbol] type The type of the attribute @param [Hash{Symbol => Object}] metadata The metadata for the attribute
[ "Attribute", "macros", "Defines", "an", "attribute" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L80-L83
train
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.string
def string(attr, metadata={}) add_attribute(attr, :string, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : arg.to_s) end end
ruby
def string(attr, metadata={}) add_attribute(attr, :string, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : arg.to_s) end end
[ "def", "string", "(", "attr", ",", "metadata", "=", "{", "}", ")", "add_attribute", "(", "attr", ",", ":string", ",", "metadata", ")", "define_method", "(", "\"#{attr}=\"", ")", "do", "|", "arg", "|", "instance_variable_set", "(", "\"@#{attr}\"", ",", "arg", ".", "nil?", "?", "nil", ":", "arg", ".", "to_s", ")", "end", "end" ]
Defines a string attribute @param [Symbol] attr The name of the attribute @param [Hash{Symbol => Object}] metadata The metadata for the attribute
[ "Defines", "a", "string", "attribute" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L89-L94
train
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.boolean
def boolean(attr, metadata={}) add_attribute(attr, :boolean, metadata) define_method("#{attr}=") do |arg| v = case arg when String then BOOLEAN_TRUE_STRINGS.include?(arg.downcase) when Numeric then arg == 1 when nil then nil else !!arg end instance_variable_set("@#{attr}", v) end alias_method "#{attr}?", attr end
ruby
def boolean(attr, metadata={}) add_attribute(attr, :boolean, metadata) define_method("#{attr}=") do |arg| v = case arg when String then BOOLEAN_TRUE_STRINGS.include?(arg.downcase) when Numeric then arg == 1 when nil then nil else !!arg end instance_variable_set("@#{attr}", v) end alias_method "#{attr}?", attr end
[ "def", "boolean", "(", "attr", ",", "metadata", "=", "{", "}", ")", "add_attribute", "(", "attr", ",", ":boolean", ",", "metadata", ")", "define_method", "(", "\"#{attr}=\"", ")", "do", "|", "arg", "|", "v", "=", "case", "arg", "when", "String", "then", "BOOLEAN_TRUE_STRINGS", ".", "include?", "(", "arg", ".", "downcase", ")", "when", "Numeric", "then", "arg", "==", "1", "when", "nil", "then", "nil", "else", "!", "!", "arg", "end", "instance_variable_set", "(", "\"@#{attr}\"", ",", "v", ")", "end", "alias_method", "\"#{attr}?\"", ",", "attr", "end" ]
Defines a boolean attribute @param [Symbol] attr The name of the attribute @param [Hash{Symbol => Object}] metadata The metadata for the attribute
[ "Defines", "a", "boolean", "attribute" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L100-L112
train
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.integer
def integer(attr, metadata={}) add_attribute(attr, :integer, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : arg.to_i) end end
ruby
def integer(attr, metadata={}) add_attribute(attr, :integer, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : arg.to_i) end end
[ "def", "integer", "(", "attr", ",", "metadata", "=", "{", "}", ")", "add_attribute", "(", "attr", ",", ":integer", ",", "metadata", ")", "define_method", "(", "\"#{attr}=\"", ")", "do", "|", "arg", "|", "instance_variable_set", "(", "\"@#{attr}\"", ",", "arg", ".", "nil?", "?", "nil", ":", "arg", ".", "to_i", ")", "end", "end" ]
Defines a integer attribute @param [Symbol] attr The name of the attribute @param [Hash{Symbol => Object}] metadata The metadata for the attribute
[ "Defines", "a", "integer", "attribute" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L118-L123
train
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.float
def float(attr, metadata={}) add_attribute(attr, :float, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : arg.to_f) end end
ruby
def float(attr, metadata={}) add_attribute(attr, :float, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : arg.to_f) end end
[ "def", "float", "(", "attr", ",", "metadata", "=", "{", "}", ")", "add_attribute", "(", "attr", ",", ":float", ",", "metadata", ")", "define_method", "(", "\"#{attr}=\"", ")", "do", "|", "arg", "|", "instance_variable_set", "(", "\"@#{attr}\"", ",", "arg", ".", "nil?", "?", "nil", ":", "arg", ".", "to_f", ")", "end", "end" ]
Defines a float attribute @param [Symbol] attr The name of the attribute @param [Hash{Symbol => Object}] metadata The metadata for the attribute
[ "Defines", "a", "float", "attribute" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L129-L134
train
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.decimal
def decimal(attr, metadata={}) add_attribute(attr, :decimal, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : BigDecimal.new(arg.to_s)) end end
ruby
def decimal(attr, metadata={}) add_attribute(attr, :decimal, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", arg.nil? ? nil : BigDecimal.new(arg.to_s)) end end
[ "def", "decimal", "(", "attr", ",", "metadata", "=", "{", "}", ")", "add_attribute", "(", "attr", ",", ":decimal", ",", "metadata", ")", "define_method", "(", "\"#{attr}=\"", ")", "do", "|", "arg", "|", "instance_variable_set", "(", "\"@#{attr}\"", ",", "arg", ".", "nil?", "?", "nil", ":", "BigDecimal", ".", "new", "(", "arg", ".", "to_s", ")", ")", "end", "end" ]
Defines a decimal attribute @param [Symbol] attr The name of the attribute @param [Hash{Symbol => Object}] metadata The metadata for the attribute
[ "Defines", "a", "decimal", "attribute" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L140-L145
train
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.date
def date(attr, metadata={}) add_attribute(attr, :date, metadata) define_method("#{attr}=") do |arg| v = case arg when Date then arg when Time, DateTime then arg.to_date when String then Date.parse(arg) when Hash args = Util.extract_values(arg, :year, :month, :day) args.present? ? Date.new(*args.map(&:to_i)) : nil when nil then nil else raise ArgumentError.new("can't convert #{arg.class} to Date") end instance_variable_set("@#{attr}", v) end end
ruby
def date(attr, metadata={}) add_attribute(attr, :date, metadata) define_method("#{attr}=") do |arg| v = case arg when Date then arg when Time, DateTime then arg.to_date when String then Date.parse(arg) when Hash args = Util.extract_values(arg, :year, :month, :day) args.present? ? Date.new(*args.map(&:to_i)) : nil when nil then nil else raise ArgumentError.new("can't convert #{arg.class} to Date") end instance_variable_set("@#{attr}", v) end end
[ "def", "date", "(", "attr", ",", "metadata", "=", "{", "}", ")", "add_attribute", "(", "attr", ",", ":date", ",", "metadata", ")", "define_method", "(", "\"#{attr}=\"", ")", "do", "|", "arg", "|", "v", "=", "case", "arg", "when", "Date", "then", "arg", "when", "Time", ",", "DateTime", "then", "arg", ".", "to_date", "when", "String", "then", "Date", ".", "parse", "(", "arg", ")", "when", "Hash", "args", "=", "Util", ".", "extract_values", "(", "arg", ",", ":year", ",", ":month", ",", ":day", ")", "args", ".", "present?", "?", "Date", ".", "new", "(", "*", "args", ".", "map", "(", "&", ":to_i", ")", ")", ":", "nil", "when", "nil", "then", "nil", "else", "raise", "ArgumentError", ".", "new", "(", "\"can't convert #{arg.class} to Date\"", ")", "end", "instance_variable_set", "(", "\"@#{attr}\"", ",", "v", ")", "end", "end" ]
Defines a date attribute @param [Symbol] attr The name of the attribute @param [Hash{Symbol => Object}] metadata The metadata for the attribute
[ "Defines", "a", "date", "attribute" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L151-L166
train
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.array
def array(attr, metadata={}) add_attribute(attr, :array, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", Array(arg)) end end
ruby
def array(attr, metadata={}) add_attribute(attr, :array, metadata) define_method("#{attr}=") do |arg| instance_variable_set("@#{attr}", Array(arg)) end end
[ "def", "array", "(", "attr", ",", "metadata", "=", "{", "}", ")", "add_attribute", "(", "attr", ",", ":array", ",", "metadata", ")", "define_method", "(", "\"#{attr}=\"", ")", "do", "|", "arg", "|", "instance_variable_set", "(", "\"@#{attr}\"", ",", "Array", "(", "arg", ")", ")", "end", "end" ]
Defines an array attribute @param [Symbol] attr The name of the attribute @param [Hash{Symbol => Object}] metadata The metadata for the attribute
[ "Defines", "an", "array", "attribute" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L204-L209
train
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.add_association
def add_association(name, type, metadata={}) associations << (metadata || {}).merge(:name => name.to_sym, :type => type.to_sym) end
ruby
def add_association(name, type, metadata={}) associations << (metadata || {}).merge(:name => name.to_sym, :type => type.to_sym) end
[ "def", "add_association", "(", "name", ",", "type", ",", "metadata", "=", "{", "}", ")", "associations", "<<", "(", "metadata", "||", "{", "}", ")", ".", "merge", "(", ":name", "=>", "name", ".", "to_sym", ",", ":type", "=>", "type", ".", "to_sym", ")", "end" ]
Defines an association @param [String] name The name of the association @param [Symbol] type The type of the association @param [Hash{Symbol => Object}] metadata The metadata for the association
[ "Defines", "an", "association" ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L239-L241
train
pjb3/attribution
lib/attribution.rb
Attribution.ClassMethods.has_many
def has_many(association_name, metadata={}) add_association association_name, :has_many, metadata association_class_name = metadata.try(:fetch, :class_name, [name.split('::')[0..-2].join('::'), association_name.to_s.classify].reject(&:blank?).join('::')) # foos define_method(association_name) do |*query| association_class = association_class_name.constantize # TODO: Support a more generic version of lazy-loading if query.empty? # Ex: Books.all, so we want to cache it. ivar = "@#{association_name}" if instance_variable_defined?(ivar) instance_variable_get(ivar) elsif self.class.autoload_associations? && association_class.respond_to?(:all) instance_variable_set(ivar, Array(association_class.all("#{self.class.name.underscore}_id" => id))) else [] end else # Ex: Book.all(:name => "The..."), so we do not want to cache it if self.class.autoload_associations? && association_class.respond_to?(:all) Array(association_class.all({"#{self.class.name.demodulize.underscore}_id" => id}.merge(query.first))) end end end # foos= define_method("#{association_name}=") do |arg| association_class = association_class_name.constantize attr_name = self.class.name.demodulize.underscore objs = (arg.is_a?(Hash) ? arg.values : Array(arg)).map do |obj| o = association_class.cast(obj) if o.respond_to?("#{attr_name}=") o.send("#{attr_name}=", self) end if o.respond_to?("#{attr_name}_id=") && respond_to?(:id) o.send("#{attr_name}_id=", id) end o end instance_variable_set("@#{association_name}", objs) end end
ruby
def has_many(association_name, metadata={}) add_association association_name, :has_many, metadata association_class_name = metadata.try(:fetch, :class_name, [name.split('::')[0..-2].join('::'), association_name.to_s.classify].reject(&:blank?).join('::')) # foos define_method(association_name) do |*query| association_class = association_class_name.constantize # TODO: Support a more generic version of lazy-loading if query.empty? # Ex: Books.all, so we want to cache it. ivar = "@#{association_name}" if instance_variable_defined?(ivar) instance_variable_get(ivar) elsif self.class.autoload_associations? && association_class.respond_to?(:all) instance_variable_set(ivar, Array(association_class.all("#{self.class.name.underscore}_id" => id))) else [] end else # Ex: Book.all(:name => "The..."), so we do not want to cache it if self.class.autoload_associations? && association_class.respond_to?(:all) Array(association_class.all({"#{self.class.name.demodulize.underscore}_id" => id}.merge(query.first))) end end end # foos= define_method("#{association_name}=") do |arg| association_class = association_class_name.constantize attr_name = self.class.name.demodulize.underscore objs = (arg.is_a?(Hash) ? arg.values : Array(arg)).map do |obj| o = association_class.cast(obj) if o.respond_to?("#{attr_name}=") o.send("#{attr_name}=", self) end if o.respond_to?("#{attr_name}_id=") && respond_to?(:id) o.send("#{attr_name}_id=", id) end o end instance_variable_set("@#{association_name}", objs) end end
[ "def", "has_many", "(", "association_name", ",", "metadata", "=", "{", "}", ")", "add_association", "association_name", ",", ":has_many", ",", "metadata", "association_class_name", "=", "metadata", ".", "try", "(", ":fetch", ",", ":class_name", ",", "[", "name", ".", "split", "(", "'::'", ")", "[", "0", "..", "-", "2", "]", ".", "join", "(", "'::'", ")", ",", "association_name", ".", "to_s", ".", "classify", "]", ".", "reject", "(", "&", ":blank?", ")", ".", "join", "(", "'::'", ")", ")", "define_method", "(", "association_name", ")", "do", "|", "*", "query", "|", "association_class", "=", "association_class_name", ".", "constantize", "if", "query", ".", "empty?", "ivar", "=", "\"@#{association_name}\"", "if", "instance_variable_defined?", "(", "ivar", ")", "instance_variable_get", "(", "ivar", ")", "elsif", "self", ".", "class", ".", "autoload_associations?", "&&", "association_class", ".", "respond_to?", "(", ":all", ")", "instance_variable_set", "(", "ivar", ",", "Array", "(", "association_class", ".", "all", "(", "\"#{self.class.name.underscore}_id\"", "=>", "id", ")", ")", ")", "else", "[", "]", "end", "else", "if", "self", ".", "class", ".", "autoload_associations?", "&&", "association_class", ".", "respond_to?", "(", ":all", ")", "Array", "(", "association_class", ".", "all", "(", "{", "\"#{self.class.name.demodulize.underscore}_id\"", "=>", "id", "}", ".", "merge", "(", "query", ".", "first", ")", ")", ")", "end", "end", "end", "define_method", "(", "\"#{association_name}=\"", ")", "do", "|", "arg", "|", "association_class", "=", "association_class_name", ".", "constantize", "attr_name", "=", "self", ".", "class", ".", "name", ".", "demodulize", ".", "underscore", "objs", "=", "(", "arg", ".", "is_a?", "(", "Hash", ")", "?", "arg", ".", "values", ":", "Array", "(", "arg", ")", ")", ".", "map", "do", "|", "obj", "|", "o", "=", "association_class", ".", "cast", "(", "obj", ")", "if", "o", ".", "respond_to?", "(", "\"#{attr_name}=\"", ")", "o", ".", "send", "(", "\"#{attr_name}=\"", ",", "self", ")", "end", "if", "o", ".", "respond_to?", "(", "\"#{attr_name}_id=\"", ")", "&&", "respond_to?", "(", ":id", ")", "o", ".", "send", "(", "\"#{attr_name}_id=\"", ",", "id", ")", "end", "o", "end", "instance_variable_set", "(", "\"@#{association_name}\"", ",", "objs", ")", "end", "end" ]
Defines an association that is a reference to an Array of another Attribution class. @param [Symbol] association_name The name of the association @param [Hash] metadata Extra information about the association. @option metadata [String] :class_name Class of the association, defaults to a class name based on the association name
[ "Defines", "an", "association", "that", "is", "a", "reference", "to", "an", "Array", "of", "another", "Attribution", "class", "." ]
0fc1af52b969addb80b347d2c608e31c56a3c6de
https://github.com/pjb3/attribution/blob/0fc1af52b969addb80b347d2c608e31c56a3c6de/lib/attribution.rb#L326-L373
train
sinsoku/ponytail
lib/ponytail/config.rb
Ponytail.Configuration.update_schema
def update_schema config.update_schema = config.update_schema.call if config.update_schema.respond_to?(:call) config.update_schema end
ruby
def update_schema config.update_schema = config.update_schema.call if config.update_schema.respond_to?(:call) config.update_schema end
[ "def", "update_schema", "config", ".", "update_schema", "=", "config", ".", "update_schema", ".", "call", "if", "config", ".", "update_schema", ".", "respond_to?", "(", ":call", ")", "config", ".", "update_schema", "end" ]
for lazy load
[ "for", "lazy", "load" ]
0025018a9e0531df3aa04cee7bcc8318c605ae21
https://github.com/sinsoku/ponytail/blob/0025018a9e0531df3aa04cee7bcc8318c605ae21/lib/ponytail/config.rb#L28-L31
train
jeffwilliams/quartz-flow
lib/quartz_flow/wrappers.rb
QuartzTorrent.TorrentDataDelegate.to_h
def to_h result = {} ## Extra fields added by this method: # Length of the torrent result[:dataLength] = @info ? @info.dataLength : 0 # Percent complete pct = withCurrentAndTotalBytes{ |cur, total| (cur.to_f / total.to_f * 100.0).round 1 } result[:percentComplete] = pct # Time left secondsLeft = withCurrentAndTotalBytes do |cur, total| if @downloadRateDataOnly && @downloadRateDataOnly > 0 (total.to_f - cur.to_f) / @downloadRateDataOnly else 0 end end # Cap estimated time at 9999 hours secondsLeft = 35996400 if secondsLeft > 35996400 result[:timeLeft] = Formatter.formatTime(secondsLeft) ## Regular fields result[:info] = @info ? @info.to_h : nil result[:infoHash] = @infoHash result[:recommendedName] = @recommendedName result[:downloadRate] = @downloadRate result[:uploadRate] = @uploadRate result[:downloadRateDataOnly] = @downloadRateDataOnly result[:uploadRateDataOnly] = @uploadRateDataOnly result[:completedBytes] = @completedBytes result[:peers] = @peers.collect{ |p| p.to_h } result[:state] = @state #result[:completePieceBitfield] = @completePieceBitfield result[:metainfoLength] = @metainfoLength result[:metainfoCompletedLength] = @metainfoCompletedLength result[:paused] = @paused result[:queued] = @queued result[:uploadRateLimit] = @uploadRateLimit result[:downloadRateLimit] = @downloadRateLimit result[:ratio] = @ratio result[:uploadDuration] = @uploadDuration result[:bytesUploaded] = @bytesUploaded result[:bytesDownloaded] = @bytesDownloaded result[:alarms] = @alarms.collect{ |a| a.to_h } result end
ruby
def to_h result = {} ## Extra fields added by this method: # Length of the torrent result[:dataLength] = @info ? @info.dataLength : 0 # Percent complete pct = withCurrentAndTotalBytes{ |cur, total| (cur.to_f / total.to_f * 100.0).round 1 } result[:percentComplete] = pct # Time left secondsLeft = withCurrentAndTotalBytes do |cur, total| if @downloadRateDataOnly && @downloadRateDataOnly > 0 (total.to_f - cur.to_f) / @downloadRateDataOnly else 0 end end # Cap estimated time at 9999 hours secondsLeft = 35996400 if secondsLeft > 35996400 result[:timeLeft] = Formatter.formatTime(secondsLeft) ## Regular fields result[:info] = @info ? @info.to_h : nil result[:infoHash] = @infoHash result[:recommendedName] = @recommendedName result[:downloadRate] = @downloadRate result[:uploadRate] = @uploadRate result[:downloadRateDataOnly] = @downloadRateDataOnly result[:uploadRateDataOnly] = @uploadRateDataOnly result[:completedBytes] = @completedBytes result[:peers] = @peers.collect{ |p| p.to_h } result[:state] = @state #result[:completePieceBitfield] = @completePieceBitfield result[:metainfoLength] = @metainfoLength result[:metainfoCompletedLength] = @metainfoCompletedLength result[:paused] = @paused result[:queued] = @queued result[:uploadRateLimit] = @uploadRateLimit result[:downloadRateLimit] = @downloadRateLimit result[:ratio] = @ratio result[:uploadDuration] = @uploadDuration result[:bytesUploaded] = @bytesUploaded result[:bytesDownloaded] = @bytesDownloaded result[:alarms] = @alarms.collect{ |a| a.to_h } result end
[ "def", "to_h", "result", "=", "{", "}", "result", "[", ":dataLength", "]", "=", "@info", "?", "@info", ".", "dataLength", ":", "0", "pct", "=", "withCurrentAndTotalBytes", "{", "|", "cur", ",", "total", "|", "(", "cur", ".", "to_f", "/", "total", ".", "to_f", "*", "100.0", ")", ".", "round", "1", "}", "result", "[", ":percentComplete", "]", "=", "pct", "secondsLeft", "=", "withCurrentAndTotalBytes", "do", "|", "cur", ",", "total", "|", "if", "@downloadRateDataOnly", "&&", "@downloadRateDataOnly", ">", "0", "(", "total", ".", "to_f", "-", "cur", ".", "to_f", ")", "/", "@downloadRateDataOnly", "else", "0", "end", "end", "secondsLeft", "=", "35996400", "if", "secondsLeft", ">", "35996400", "result", "[", ":timeLeft", "]", "=", "Formatter", ".", "formatTime", "(", "secondsLeft", ")", "result", "[", ":info", "]", "=", "@info", "?", "@info", ".", "to_h", ":", "nil", "result", "[", ":infoHash", "]", "=", "@infoHash", "result", "[", ":recommendedName", "]", "=", "@recommendedName", "result", "[", ":downloadRate", "]", "=", "@downloadRate", "result", "[", ":uploadRate", "]", "=", "@uploadRate", "result", "[", ":downloadRateDataOnly", "]", "=", "@downloadRateDataOnly", "result", "[", ":uploadRateDataOnly", "]", "=", "@uploadRateDataOnly", "result", "[", ":completedBytes", "]", "=", "@completedBytes", "result", "[", ":peers", "]", "=", "@peers", ".", "collect", "{", "|", "p", "|", "p", ".", "to_h", "}", "result", "[", ":state", "]", "=", "@state", "result", "[", ":metainfoLength", "]", "=", "@metainfoLength", "result", "[", ":metainfoCompletedLength", "]", "=", "@metainfoCompletedLength", "result", "[", ":paused", "]", "=", "@paused", "result", "[", ":queued", "]", "=", "@queued", "result", "[", ":uploadRateLimit", "]", "=", "@uploadRateLimit", "result", "[", ":downloadRateLimit", "]", "=", "@downloadRateLimit", "result", "[", ":ratio", "]", "=", "@ratio", "result", "[", ":uploadDuration", "]", "=", "@uploadDuration", "result", "[", ":bytesUploaded", "]", "=", "@bytesUploaded", "result", "[", ":bytesDownloaded", "]", "=", "@bytesDownloaded", "result", "[", ":alarms", "]", "=", "@alarms", ".", "collect", "{", "|", "a", "|", "a", ".", "to_h", "}", "result", "end" ]
Convert to a hash. Also flattens some of the data into new fields.
[ "Convert", "to", "a", "hash", ".", "Also", "flattens", "some", "of", "the", "data", "into", "new", "fields", "." ]
775c40c597e608baf7e7eade3e20bcdc99c702a7
https://github.com/jeffwilliams/quartz-flow/blob/775c40c597e608baf7e7eade3e20bcdc99c702a7/lib/quartz_flow/wrappers.rb#L65-L111
train
woodruffw/dreck
lib/dreck/result.rb
Dreck.Result.list
def list(type, sym, count: nil) if count raise BadCountError unless count.positive? end @expected << [:list, type, sym, count] end
ruby
def list(type, sym, count: nil) if count raise BadCountError unless count.positive? end @expected << [:list, type, sym, count] end
[ "def", "list", "(", "type", ",", "sym", ",", "count", ":", "nil", ")", "if", "count", "raise", "BadCountError", "unless", "count", ".", "positive?", "end", "@expected", "<<", "[", ":list", ",", "type", ",", "sym", ",", "count", "]", "end" ]
Specifies a list of arguments of a given type to be parsed. @param type [Symbol] the type of the arguments @param sym [Symbol] the name of the argument in {results} @param count [Integer] the number of arguments in the list
[ "Specifies", "a", "list", "of", "arguments", "of", "a", "given", "type", "to", "be", "parsed", "." ]
9a9d79810b3b193583396cc2bf4801f236fc2f76
https://github.com/woodruffw/dreck/blob/9a9d79810b3b193583396cc2bf4801f236fc2f76/lib/dreck/result.rb#L45-L51
train
woodruffw/dreck
lib/dreck/result.rb
Dreck.Result.parse!
def parse! check_absorption! @expected.each do |type, *rest| case type when :list parse_list!(*rest) else parse_type!(type, *rest) end end self end
ruby
def parse! check_absorption! @expected.each do |type, *rest| case type when :list parse_list!(*rest) else parse_type!(type, *rest) end end self end
[ "def", "parse!", "check_absorption!", "@expected", ".", "each", "do", "|", "type", ",", "*", "rest", "|", "case", "type", "when", ":list", "parse_list!", "(", "*", "rest", ")", "else", "parse_type!", "(", "type", ",", "*", "rest", ")", "end", "end", "self", "end" ]
Perform the actual parsing. @return [Result] this instance @api private
[ "Perform", "the", "actual", "parsing", "." ]
9a9d79810b3b193583396cc2bf4801f236fc2f76
https://github.com/woodruffw/dreck/blob/9a9d79810b3b193583396cc2bf4801f236fc2f76/lib/dreck/result.rb#L56-L69
train
woodruffw/dreck
lib/dreck/result.rb
Dreck.Result.check_absorption!
def check_absorption! count, greedy = count_expected return unless strict? raise GreedyAbsorptionError.new(count, @args.size) if count >= @args.size && greedy raise AbsorptionError.new(count, @args.size) if count != @args.size && !greedy end
ruby
def check_absorption! count, greedy = count_expected return unless strict? raise GreedyAbsorptionError.new(count, @args.size) if count >= @args.size && greedy raise AbsorptionError.new(count, @args.size) if count != @args.size && !greedy end
[ "def", "check_absorption!", "count", ",", "greedy", "=", "count_expected", "return", "unless", "strict?", "raise", "GreedyAbsorptionError", ".", "new", "(", "count", ",", "@args", ".", "size", ")", "if", "count", ">=", "@args", ".", "size", "&&", "greedy", "raise", "AbsorptionError", ".", "new", "(", "count", ",", "@args", ".", "size", ")", "if", "count", "!=", "@args", ".", "size", "&&", "!", "greedy", "end" ]
Check whether the expected arguments absorb all supplied arguments. @raise [AbsoptionError] if absorption fails and {strict?} is not true @api private
[ "Check", "whether", "the", "expected", "arguments", "absorb", "all", "supplied", "arguments", "." ]
9a9d79810b3b193583396cc2bf4801f236fc2f76
https://github.com/woodruffw/dreck/blob/9a9d79810b3b193583396cc2bf4801f236fc2f76/lib/dreck/result.rb#L74-L81
train