id
int32
0
24.9k
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
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
17,400
cryo28/sidekiq_status
lib/sidekiq_status/container.rb
SidekiqStatus.Container.save
def save data = dump data = Sidekiq.dump_json(data) Sidekiq.redis do |conn| conn.multi do conn.setex(status_key, self.ttl, data) conn.zadd(self.class.statuses_key, Time.now.to_f.to_s, self.jid) end end end
ruby
def save data = dump data = Sidekiq.dump_json(data) Sidekiq.redis do |conn| conn.multi do conn.setex(status_key, self.ttl, data) conn.zadd(self.class.statuses_key, Time.now.to_f.to_s, self.jid) end end end
[ "def", "save", "data", "=", "dump", "data", "=", "Sidekiq", ".", "dump_json", "(", "data", ")", "Sidekiq", ".", "redis", "do", "|", "conn", "|", "conn", ".", "multi", "do", "conn", ".", "setex", "(", "status_key", ",", "self", ".", "ttl", ",", "data", ")", "conn", ".", "zadd", "(", "self", ".", "class", ".", "statuses_key", ",", "Time", ".", "now", ".", "to_f", ".", "to_s", ",", "self", ".", "jid", ")", "end", "end", "end" ]
Save current container attribute values to redis
[ "Save", "current", "container", "attribute", "values", "to", "redis" ]
afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27
https://github.com/cryo28/sidekiq_status/blob/afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27/lib/sidekiq_status/container.rb#L205-L215
17,401
cryo28/sidekiq_status
lib/sidekiq_status/container.rb
SidekiqStatus.Container.delete
def delete Sidekiq.redis do |conn| conn.multi do conn.del(status_key) conn.zrem(self.class.kill_key, self.jid) conn.zrem(self.class.statuses_key, self.jid) end end end
ruby
def delete Sidekiq.redis do |conn| conn.multi do conn.del(status_key) conn.zrem(self.class.kill_key, self.jid) conn.zrem(self.class.statuses_key, self.jid) end end end
[ "def", "delete", "Sidekiq", ".", "redis", "do", "|", "conn", "|", "conn", ".", "multi", "do", "conn", ".", "del", "(", "status_key", ")", "conn", ".", "zrem", "(", "self", ".", "class", ".", "kill_key", ",", "self", ".", "jid", ")", "conn", ".", "zrem", "(", "self", ".", "class", ".", "statuses_key", ",", "self", ".", "jid", ")", "end", "end", "end" ]
Delete current container data from redis
[ "Delete", "current", "container", "data", "from", "redis" ]
afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27
https://github.com/cryo28/sidekiq_status/blob/afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27/lib/sidekiq_status/container.rb#L218-L227
17,402
cryo28/sidekiq_status
lib/sidekiq_status/container.rb
SidekiqStatus.Container.kill
def kill self.status = 'killed' Sidekiq.redis do |conn| conn.multi do save conn.zrem(self.class.kill_key, self.jid) end end end
ruby
def kill self.status = 'killed' Sidekiq.redis do |conn| conn.multi do save conn.zrem(self.class.kill_key, self.jid) end end end
[ "def", "kill", "self", ".", "status", "=", "'killed'", "Sidekiq", ".", "redis", "do", "|", "conn", "|", "conn", ".", "multi", "do", "save", "conn", ".", "zrem", "(", "self", ".", "class", ".", "kill_key", ",", "self", ".", "jid", ")", "end", "end", "end" ]
Reflect the fact that a job has been killed in redis
[ "Reflect", "the", "fact", "that", "a", "job", "has", "been", "killed", "in", "redis" ]
afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27
https://github.com/cryo28/sidekiq_status/blob/afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27/lib/sidekiq_status/container.rb#L245-L254
17,403
cryo28/sidekiq_status
lib/sidekiq_status/container.rb
SidekiqStatus.Container.load
def load(data) data = DEFAULTS.merge(data) @args, @worker, @queue = data.values_at('args', 'worker', 'queue') @status, @at, @total, @message = data.values_at('status', 'at', 'total', 'message') @payload = data['payload'] @last_updated_at = data['last_updated_at'] && Time.at(data['last_updated_at'].to_i) end
ruby
def load(data) data = DEFAULTS.merge(data) @args, @worker, @queue = data.values_at('args', 'worker', 'queue') @status, @at, @total, @message = data.values_at('status', 'at', 'total', 'message') @payload = data['payload'] @last_updated_at = data['last_updated_at'] && Time.at(data['last_updated_at'].to_i) end
[ "def", "load", "(", "data", ")", "data", "=", "DEFAULTS", ".", "merge", "(", "data", ")", "@args", ",", "@worker", ",", "@queue", "=", "data", ".", "values_at", "(", "'args'", ",", "'worker'", ",", "'queue'", ")", "@status", ",", "@at", ",", "@total", ",", "@message", "=", "data", ".", "values_at", "(", "'status'", ",", "'at'", ",", "'total'", ",", "'message'", ")", "@payload", "=", "data", "[", "'payload'", "]", "@last_updated_at", "=", "data", "[", "'last_updated_at'", "]", "&&", "Time", ".", "at", "(", "data", "[", "'last_updated_at'", "]", ".", "to_i", ")", "end" ]
Merge-in given data to the current container @private @param [Hash] data
[ "Merge", "-", "in", "given", "data", "to", "the", "current", "container" ]
afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27
https://github.com/cryo28/sidekiq_status/blob/afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27/lib/sidekiq_status/container.rb#L327-L334
17,404
cryo28/sidekiq_status
lib/sidekiq_status/container.rb
SidekiqStatus.Container.dump
def dump { 'args' => self.args, 'worker' => self.worker, 'queue' => self.queue, 'status' => self.status, 'at' => self.at, 'total' => self.total, 'message' => self.message, 'payload' => self.payload, 'last_updated_at' => Time.now.to_i } end
ruby
def dump { 'args' => self.args, 'worker' => self.worker, 'queue' => self.queue, 'status' => self.status, 'at' => self.at, 'total' => self.total, 'message' => self.message, 'payload' => self.payload, 'last_updated_at' => Time.now.to_i } end
[ "def", "dump", "{", "'args'", "=>", "self", ".", "args", ",", "'worker'", "=>", "self", ".", "worker", ",", "'queue'", "=>", "self", ".", "queue", ",", "'status'", "=>", "self", ".", "status", ",", "'at'", "=>", "self", ".", "at", ",", "'total'", "=>", "self", ".", "total", ",", "'message'", "=>", "self", ".", "message", ",", "'payload'", "=>", "self", ".", "payload", ",", "'last_updated_at'", "=>", "Time", ".", "now", ".", "to_i", "}", "end" ]
Dump current container attribute values to json-serializable hash @private @return [Hash] Data for subsequent json-serialization
[ "Dump", "current", "container", "attribute", "values", "to", "json", "-", "serializable", "hash" ]
afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27
https://github.com/cryo28/sidekiq_status/blob/afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27/lib/sidekiq_status/container.rb#L340-L354
17,405
messagebird/ruby-rest-api
lib/messagebird/client.rb
MessageBird.Client.send_conversation_message
def send_conversation_message(from, to, params={}) ConversationMessage.new(conversation_request( :post, 'send', params.merge({ :from => from, :to => to, }))) end
ruby
def send_conversation_message(from, to, params={}) ConversationMessage.new(conversation_request( :post, 'send', params.merge({ :from => from, :to => to, }))) end
[ "def", "send_conversation_message", "(", "from", ",", "to", ",", "params", "=", "{", "}", ")", "ConversationMessage", ".", "new", "(", "conversation_request", "(", ":post", ",", "'send'", ",", "params", ".", "merge", "(", "{", ":from", "=>", "from", ",", ":to", "=>", "to", ",", "}", ")", ")", ")", "end" ]
Conversations Send a conversation message
[ "Conversations", "Send", "a", "conversation", "message" ]
5a4d5f12a97b52e3fa170c23d7a12b91770687a4
https://github.com/messagebird/ruby-rest-api/blob/5a4d5f12a97b52e3fa170c23d7a12b91770687a4/lib/messagebird/client.rb#L64-L72
17,406
messagebird/ruby-rest-api
lib/messagebird/client.rb
MessageBird.Client.start_conversation
def start_conversation(to, channelId, params={}) Conversation.new(conversation_request( :post, 'conversations/start', params.merge({ :to => to, :channelId => channelId, }))) end
ruby
def start_conversation(to, channelId, params={}) Conversation.new(conversation_request( :post, 'conversations/start', params.merge({ :to => to, :channelId => channelId, }))) end
[ "def", "start_conversation", "(", "to", ",", "channelId", ",", "params", "=", "{", "}", ")", "Conversation", ".", "new", "(", "conversation_request", "(", ":post", ",", "'conversations/start'", ",", "params", ".", "merge", "(", "{", ":to", "=>", "to", ",", ":channelId", "=>", "channelId", ",", "}", ")", ")", ")", "end" ]
Start a conversation
[ "Start", "a", "conversation" ]
5a4d5f12a97b52e3fa170c23d7a12b91770687a4
https://github.com/messagebird/ruby-rest-api/blob/5a4d5f12a97b52e3fa170c23d7a12b91770687a4/lib/messagebird/client.rb#L75-L83
17,407
messagebird/ruby-rest-api
lib/messagebird/client.rb
MessageBird.Client.message_create
def message_create(originator, recipients, body, params={}) # Convert an array of recipients to a comma-separated string. recipients = recipients.join(',') if recipients.kind_of?(Array) Message.new(request( :post, 'messages', params.merge({ :originator => originator.to_s, :body => body.to_s, :recipients => recipients }))) end
ruby
def message_create(originator, recipients, body, params={}) # Convert an array of recipients to a comma-separated string. recipients = recipients.join(',') if recipients.kind_of?(Array) Message.new(request( :post, 'messages', params.merge({ :originator => originator.to_s, :body => body.to_s, :recipients => recipients }))) end
[ "def", "message_create", "(", "originator", ",", "recipients", ",", "body", ",", "params", "=", "{", "}", ")", "# Convert an array of recipients to a comma-separated string.", "recipients", "=", "recipients", ".", "join", "(", "','", ")", "if", "recipients", ".", "kind_of?", "(", "Array", ")", "Message", ".", "new", "(", "request", "(", ":post", ",", "'messages'", ",", "params", ".", "merge", "(", "{", ":originator", "=>", "originator", ".", "to_s", ",", ":body", "=>", "body", ".", "to_s", ",", ":recipients", "=>", "recipients", "}", ")", ")", ")", "end" ]
Create a new message.
[ "Create", "a", "new", "message", "." ]
5a4d5f12a97b52e3fa170c23d7a12b91770687a4
https://github.com/messagebird/ruby-rest-api/blob/5a4d5f12a97b52e3fa170c23d7a12b91770687a4/lib/messagebird/client.rb#L186-L197
17,408
messagebird/ruby-rest-api
lib/messagebird/client.rb
MessageBird.Client.voice_message_create
def voice_message_create(recipients, body, params={}) # Convert an array of recipients to a comma-separated string. recipients = recipients.join(',') if recipients.kind_of?(Array) VoiceMessage.new(request( :post, 'voicemessages', params.merge({ :recipients => recipients, :body => body.to_s }))) end
ruby
def voice_message_create(recipients, body, params={}) # Convert an array of recipients to a comma-separated string. recipients = recipients.join(',') if recipients.kind_of?(Array) VoiceMessage.new(request( :post, 'voicemessages', params.merge({ :recipients => recipients, :body => body.to_s }))) end
[ "def", "voice_message_create", "(", "recipients", ",", "body", ",", "params", "=", "{", "}", ")", "# Convert an array of recipients to a comma-separated string.", "recipients", "=", "recipients", ".", "join", "(", "','", ")", "if", "recipients", ".", "kind_of?", "(", "Array", ")", "VoiceMessage", ".", "new", "(", "request", "(", ":post", ",", "'voicemessages'", ",", "params", ".", "merge", "(", "{", ":recipients", "=>", "recipients", ",", ":body", "=>", "body", ".", "to_s", "}", ")", ")", ")", "end" ]
Create a new voice message.
[ "Create", "a", "new", "voice", "message", "." ]
5a4d5f12a97b52e3fa170c23d7a12b91770687a4
https://github.com/messagebird/ruby-rest-api/blob/5a4d5f12a97b52e3fa170c23d7a12b91770687a4/lib/messagebird/client.rb#L205-L213
17,409
zolrath/marky_markov
lib/marky_markov.rb
MarkyMarkov.TemporaryDictionary.method_missing
def method_missing(method_sym, *args, &block) if method_sym.to_s =~ /^generate_(\d*)_word[s]*$/ generate_n_words($1.to_i) elsif method_sym.to_s =~ /^generate_(\d*)_sentence[s]*$/ generate_n_sentences($1.to_i) else super end end
ruby
def method_missing(method_sym, *args, &block) if method_sym.to_s =~ /^generate_(\d*)_word[s]*$/ generate_n_words($1.to_i) elsif method_sym.to_s =~ /^generate_(\d*)_sentence[s]*$/ generate_n_sentences($1.to_i) else super end end
[ "def", "method_missing", "(", "method_sym", ",", "*", "args", ",", "&", "block", ")", "if", "method_sym", ".", "to_s", "=~", "/", "\\d", "/", "generate_n_words", "(", "$1", ".", "to_i", ")", "elsif", "method_sym", ".", "to_s", "=~", "/", "\\d", "/", "generate_n_sentences", "(", "$1", ".", "to_i", ")", "else", "super", "end", "end" ]
Dynamically call generate_n_words or generate_n_sentences if an Int is substituted for the n in the method call. @since 0.1.4 @example Generate a 40 and a 1 word long string of words. markov.generate_40_words markov.generate_1_word @example Generate 2 sentences markov.generate_2_sentences @return [String] the sentence generated by the dictionary.
[ "Dynamically", "call", "generate_n_words", "or", "generate_n_sentences", "if", "an", "Int", "is", "substituted", "for", "the", "n", "in", "the", "method", "call", "." ]
79b12a84a1e63cd69f3a0b0eda72062d8c6eb3aa
https://github.com/zolrath/marky_markov/blob/79b12a84a1e63cd69f3a0b0eda72062d8c6eb3aa/lib/marky_markov.rb#L91-L99
17,410
tarcieri/cool.io
lib/cool.io/loop.rb
Coolio.Loop.run
def run(timeout = nil) raise RuntimeError, "no watchers for this loop" if @watchers.empty? @running = true while @running and not @active_watchers.zero? run_once(timeout) end @running = false end
ruby
def run(timeout = nil) raise RuntimeError, "no watchers for this loop" if @watchers.empty? @running = true while @running and not @active_watchers.zero? run_once(timeout) end @running = false end
[ "def", "run", "(", "timeout", "=", "nil", ")", "raise", "RuntimeError", ",", "\"no watchers for this loop\"", "if", "@watchers", ".", "empty?", "@running", "=", "true", "while", "@running", "and", "not", "@active_watchers", ".", "zero?", "run_once", "(", "timeout", ")", "end", "@running", "=", "false", "end" ]
Run the event loop and dispatch events back to Ruby. If there are no watchers associated with the event loop it will return immediately. Otherwise, run will continue blocking and making event callbacks to watchers until all watchers associated with the loop have been disabled or detached. The loop may be explicitly stopped by calling the stop method on the loop object.
[ "Run", "the", "event", "loop", "and", "dispatch", "events", "back", "to", "Ruby", ".", "If", "there", "are", "no", "watchers", "associated", "with", "the", "event", "loop", "it", "will", "return", "immediately", ".", "Otherwise", "run", "will", "continue", "blocking", "and", "making", "event", "callbacks", "to", "watchers", "until", "all", "watchers", "associated", "with", "the", "loop", "have", "been", "disabled", "or", "detached", ".", "The", "loop", "may", "be", "explicitly", "stopped", "by", "calling", "the", "stop", "method", "on", "the", "loop", "object", "." ]
0fd3fd1d8e8d81e24f79f809979367abc3f52b92
https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/loop.rb#L83-L91
17,411
tarcieri/cool.io
lib/cool.io/io.rb
Coolio.IO.on_readable
def on_readable begin on_read @_io.read_nonblock(INPUT_SIZE) rescue Errno::EAGAIN, Errno::EINTR return # SystemCallError catches Errno::ECONNRESET amongst others. rescue SystemCallError, EOFError, IOError, SocketError close end end
ruby
def on_readable begin on_read @_io.read_nonblock(INPUT_SIZE) rescue Errno::EAGAIN, Errno::EINTR return # SystemCallError catches Errno::ECONNRESET amongst others. rescue SystemCallError, EOFError, IOError, SocketError close end end
[ "def", "on_readable", "begin", "on_read", "@_io", ".", "read_nonblock", "(", "INPUT_SIZE", ")", "rescue", "Errno", "::", "EAGAIN", ",", "Errno", "::", "EINTR", "return", "# SystemCallError catches Errno::ECONNRESET amongst others.", "rescue", "SystemCallError", ",", "EOFError", ",", "IOError", ",", "SocketError", "close", "end", "end" ]
Read from the input buffer and dispatch to on_read
[ "Read", "from", "the", "input", "buffer", "and", "dispatch", "to", "on_read" ]
0fd3fd1d8e8d81e24f79f809979367abc3f52b92
https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/io.rb#L121-L131
17,412
tarcieri/cool.io
lib/cool.io/io.rb
Coolio.IO.on_writable
def on_writable begin @_write_buffer.write_to(@_io) rescue Errno::EINTR return # SystemCallError catches Errno::EPIPE & Errno::ECONNRESET amongst others. rescue SystemCallError, IOError, SocketError return close end if @_write_buffer.empty? disable_write_watcher on_write_complete end end
ruby
def on_writable begin @_write_buffer.write_to(@_io) rescue Errno::EINTR return # SystemCallError catches Errno::EPIPE & Errno::ECONNRESET amongst others. rescue SystemCallError, IOError, SocketError return close end if @_write_buffer.empty? disable_write_watcher on_write_complete end end
[ "def", "on_writable", "begin", "@_write_buffer", ".", "write_to", "(", "@_io", ")", "rescue", "Errno", "::", "EINTR", "return", "# SystemCallError catches Errno::EPIPE & Errno::ECONNRESET amongst others.", "rescue", "SystemCallError", ",", "IOError", ",", "SocketError", "return", "close", "end", "if", "@_write_buffer", ".", "empty?", "disable_write_watcher", "on_write_complete", "end", "end" ]
Write the contents of the output buffer
[ "Write", "the", "contents", "of", "the", "output", "buffer" ]
0fd3fd1d8e8d81e24f79f809979367abc3f52b92
https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/io.rb#L134-L149
17,413
tarcieri/cool.io
lib/cool.io/dns_resolver.rb
Coolio.DNSResolver.send_request
def send_request nameserver = @nameservers.shift @nameservers << nameserver # rotate them begin @socket.send request_message, 0, @nameservers.first, DNS_PORT rescue Errno::EHOSTUNREACH # TODO figure out why it has to be wrapper here, when the other wrapper should be wrapping this one! end end
ruby
def send_request nameserver = @nameservers.shift @nameservers << nameserver # rotate them begin @socket.send request_message, 0, @nameservers.first, DNS_PORT rescue Errno::EHOSTUNREACH # TODO figure out why it has to be wrapper here, when the other wrapper should be wrapping this one! end end
[ "def", "send_request", "nameserver", "=", "@nameservers", ".", "shift", "@nameservers", "<<", "nameserver", "# rotate them", "begin", "@socket", ".", "send", "request_message", ",", "0", ",", "@nameservers", ".", "first", ",", "DNS_PORT", "rescue", "Errno", "::", "EHOSTUNREACH", "# TODO figure out why it has to be wrapper here, when the other wrapper should be wrapping this one!", "end", "end" ]
Send a request to the DNS server
[ "Send", "a", "request", "to", "the", "DNS", "server" ]
0fd3fd1d8e8d81e24f79f809979367abc3f52b92
https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/dns_resolver.rb#L106-L113
17,414
tarcieri/cool.io
lib/cool.io/dns_resolver.rb
Coolio.DNSResolver.on_readable
def on_readable datagram = nil begin datagram = @socket.recvfrom_nonblock(DATAGRAM_SIZE).first rescue Errno::ECONNREFUSED end address = response_address datagram rescue nil address ? on_success(address) : on_failure detach end
ruby
def on_readable datagram = nil begin datagram = @socket.recvfrom_nonblock(DATAGRAM_SIZE).first rescue Errno::ECONNREFUSED end address = response_address datagram rescue nil address ? on_success(address) : on_failure detach end
[ "def", "on_readable", "datagram", "=", "nil", "begin", "datagram", "=", "@socket", ".", "recvfrom_nonblock", "(", "DATAGRAM_SIZE", ")", ".", "first", "rescue", "Errno", "::", "ECONNREFUSED", "end", "address", "=", "response_address", "datagram", "rescue", "nil", "address", "?", "on_success", "(", "address", ")", ":", "on_failure", "detach", "end" ]
Called by the subclass when the DNS response is available
[ "Called", "by", "the", "subclass", "when", "the", "DNS", "response", "is", "available" ]
0fd3fd1d8e8d81e24f79f809979367abc3f52b92
https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/dns_resolver.rb#L116-L126
17,415
tarcieri/cool.io
lib/cool.io/socket.rb
Coolio.TCPSocket.preinitialize
def preinitialize(addr, port, *args) @_write_buffer = ::IO::Buffer.new # allow for writing BEFORE DNS has resolved @remote_host, @remote_addr, @remote_port = addr, addr, port @_resolver = TCPConnectResolver.new(self, addr, port, *args) end
ruby
def preinitialize(addr, port, *args) @_write_buffer = ::IO::Buffer.new # allow for writing BEFORE DNS has resolved @remote_host, @remote_addr, @remote_port = addr, addr, port @_resolver = TCPConnectResolver.new(self, addr, port, *args) end
[ "def", "preinitialize", "(", "addr", ",", "port", ",", "*", "args", ")", "@_write_buffer", "=", "::", "IO", "::", "Buffer", ".", "new", "# allow for writing BEFORE DNS has resolved", "@remote_host", ",", "@remote_addr", ",", "@remote_port", "=", "addr", ",", "addr", ",", "port", "@_resolver", "=", "TCPConnectResolver", ".", "new", "(", "self", ",", "addr", ",", "port", ",", "args", ")", "end" ]
Called by precreate during asyncronous DNS resolution
[ "Called", "by", "precreate", "during", "asyncronous", "DNS", "resolution" ]
0fd3fd1d8e8d81e24f79f809979367abc3f52b92
https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/socket.rb#L132-L136
17,416
tarcieri/cool.io
lib/cool.io/dsl.rb
Coolio.DSL.connect
def connect(host, port, connection_name = nil, *initializer_args, &block) if block_given? initializer_args.unshift connection_name if connection_name klass = Class.new Cool.io::TCPSocket connection_builder = ConnectionBuilder.new klass connection_builder.instance_eval(&block) else raise ArgumentError, "no connection name or block given" unless connection_name klass = self[connection_name] end client = klass.connect host, port, *initializer_args client.attach Cool.io::Loop.default client end
ruby
def connect(host, port, connection_name = nil, *initializer_args, &block) if block_given? initializer_args.unshift connection_name if connection_name klass = Class.new Cool.io::TCPSocket connection_builder = ConnectionBuilder.new klass connection_builder.instance_eval(&block) else raise ArgumentError, "no connection name or block given" unless connection_name klass = self[connection_name] end client = klass.connect host, port, *initializer_args client.attach Cool.io::Loop.default client end
[ "def", "connect", "(", "host", ",", "port", ",", "connection_name", "=", "nil", ",", "*", "initializer_args", ",", "&", "block", ")", "if", "block_given?", "initializer_args", ".", "unshift", "connection_name", "if", "connection_name", "klass", "=", "Class", ".", "new", "Cool", ".", "io", "::", "TCPSocket", "connection_builder", "=", "ConnectionBuilder", ".", "new", "klass", "connection_builder", ".", "instance_eval", "(", "block", ")", "else", "raise", "ArgumentError", ",", "\"no connection name or block given\"", "unless", "connection_name", "klass", "=", "self", "[", "connection_name", "]", "end", "client", "=", "klass", ".", "connect", "host", ",", "port", ",", "initializer_args", "client", ".", "attach", "Cool", ".", "io", "::", "Loop", ".", "default", "client", "end" ]
Connect to the given host and port using the given connection class
[ "Connect", "to", "the", "given", "host", "and", "port", "using", "the", "given", "connection", "class" ]
0fd3fd1d8e8d81e24f79f809979367abc3f52b92
https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/dsl.rb#L22-L37
17,417
tarcieri/cool.io
lib/cool.io/dsl.rb
Coolio.DSL.[]
def [](connection_name) class_name = connection_name.to_s.split('_').map { |s| s.capitalize }.join begin Coolio::Connections.const_get class_name rescue NameError raise NameError, "No connection type registered for #{connection_name.inspect}" end end
ruby
def [](connection_name) class_name = connection_name.to_s.split('_').map { |s| s.capitalize }.join begin Coolio::Connections.const_get class_name rescue NameError raise NameError, "No connection type registered for #{connection_name.inspect}" end end
[ "def", "[]", "(", "connection_name", ")", "class_name", "=", "connection_name", ".", "to_s", ".", "split", "(", "'_'", ")", ".", "map", "{", "|", "s", "|", "s", ".", "capitalize", "}", ".", "join", "begin", "Coolio", "::", "Connections", ".", "const_get", "class_name", "rescue", "NameError", "raise", "NameError", ",", "\"No connection type registered for #{connection_name.inspect}\"", "end", "end" ]
Look up a connection class by its name
[ "Look", "up", "a", "connection", "class", "by", "its", "name" ]
0fd3fd1d8e8d81e24f79f809979367abc3f52b92
https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/dsl.rb#L70-L78
17,418
tas50/chef-api
lib/chef-api/util.rb
ChefAPI.Util.safe_read
def safe_read(path) path = File.expand_path(path) name = File.basename(path, '.*') contents = File.read(path) [name, contents] rescue Errno::EACCES raise Error::InsufficientFilePermissions.new(path: path) rescue Errno::ENOENT raise Error::FileNotFound.new(path: path) end
ruby
def safe_read(path) path = File.expand_path(path) name = File.basename(path, '.*') contents = File.read(path) [name, contents] rescue Errno::EACCES raise Error::InsufficientFilePermissions.new(path: path) rescue Errno::ENOENT raise Error::FileNotFound.new(path: path) end
[ "def", "safe_read", "(", "path", ")", "path", "=", "File", ".", "expand_path", "(", "path", ")", "name", "=", "File", ".", "basename", "(", "path", ",", "'.*'", ")", "contents", "=", "File", ".", "read", "(", "path", ")", "[", "name", ",", "contents", "]", "rescue", "Errno", "::", "EACCES", "raise", "Error", "::", "InsufficientFilePermissions", ".", "new", "(", "path", ":", "path", ")", "rescue", "Errno", "::", "ENOENT", "raise", "Error", "::", "FileNotFound", ".", "new", "(", "path", ":", "path", ")", "end" ]
"Safely" read the contents of a file on disk, catching any permission errors or not found errors and raising a nicer exception. @example Reading a file that does not exist safe_read('/non-existent/file') #=> Error::FileNotFound @example Reading a file with improper permissions safe_read('/bad-permissions') #=> Error::InsufficientFilePermissions @example Reading a regular file safe_read('my-file.txt') #=> ["my-file", "..."] @param [String] path the path to the file on disk @return [Array<String>] A array where the first value is the basename of the file and the second value is the literal contents from +File.read+.
[ "Safely", "read", "the", "contents", "of", "a", "file", "on", "disk", "catching", "any", "permission", "errors", "or", "not", "found", "errors", "and", "raising", "a", "nicer", "exception", "." ]
a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f
https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/util.rb#L78-L88
17,419
tas50/chef-api
lib/chef-api/util.rb
ChefAPI.Util.fast_collect
def fast_collect(collection, &block) collection.map do |item| Thread.new do Thread.current[:result] = block.call(item) end end.collect do |thread| thread.join thread[:result] end end
ruby
def fast_collect(collection, &block) collection.map do |item| Thread.new do Thread.current[:result] = block.call(item) end end.collect do |thread| thread.join thread[:result] end end
[ "def", "fast_collect", "(", "collection", ",", "&", "block", ")", "collection", ".", "map", "do", "|", "item", "|", "Thread", ".", "new", "do", "Thread", ".", "current", "[", ":result", "]", "=", "block", ".", "call", "(", "item", ")", "end", "end", ".", "collect", "do", "|", "thread", "|", "thread", ".", "join", "thread", "[", ":result", "]", "end", "end" ]
Quickly iterate over a collection using native Ruby threads, preserving the original order of elements and being all thread-safe and stuff. @example Parse a collection of JSON files fast_collect(Dir['**/*.json']) do |item| JSON.parse(File.read(item)) end @param [#each] collection the collection to iterate @param [Proc] block the block to evaluate (typically an expensive operation) @return [Array] the result of the iteration
[ "Quickly", "iterate", "over", "a", "collection", "using", "native", "Ruby", "threads", "preserving", "the", "original", "order", "of", "elements", "and", "being", "all", "thread", "-", "safe", "and", "stuff", "." ]
a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f
https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/util.rb#L108-L117
17,420
tas50/chef-api
lib/chef-api/resources/base.rb
ChefAPI.Resource::Base.save!
def save! validate! response = if new_resource? self.class.post(to_json, _prefix) else self.class.put(id, to_json, _prefix) end # Update our local copy with any partial information that was returned # from the server, ignoring an "bad" attributes that aren't defined in # our schema. response.each do |key, value| update_attribute(key, value) if attribute?(key) end true end
ruby
def save! validate! response = if new_resource? self.class.post(to_json, _prefix) else self.class.put(id, to_json, _prefix) end # Update our local copy with any partial information that was returned # from the server, ignoring an "bad" attributes that aren't defined in # our schema. response.each do |key, value| update_attribute(key, value) if attribute?(key) end true end
[ "def", "save!", "validate!", "response", "=", "if", "new_resource?", "self", ".", "class", ".", "post", "(", "to_json", ",", "_prefix", ")", "else", "self", ".", "class", ".", "put", "(", "id", ",", "to_json", ",", "_prefix", ")", "end", "# Update our local copy with any partial information that was returned", "# from the server, ignoring an \"bad\" attributes that aren't defined in", "# our schema.", "response", ".", "each", "do", "|", "key", ",", "value", "|", "update_attribute", "(", "key", ",", "value", ")", "if", "attribute?", "(", "key", ")", "end", "true", "end" ]
Commit the resource and any changes to the remote Chef Server. Any errors will raise an exception in the main thread and the resource will not be committed back to the Chef Server. Any response errors (such as server-side responses) that ChefAPI failed to account for in validations will also raise an exception. @return [Boolean] true if the resource was saved
[ "Commit", "the", "resource", "and", "any", "changes", "to", "the", "remote", "Chef", "Server", ".", "Any", "errors", "will", "raise", "an", "exception", "in", "the", "main", "thread", "and", "the", "resource", "will", "not", "be", "committed", "back", "to", "the", "Chef", "Server", "." ]
a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f
https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/base.rb#L679-L696
17,421
tas50/chef-api
lib/chef-api/resources/base.rb
ChefAPI.Resource::Base.update_attribute
def update_attribute(key, value) unless attribute?(key.to_sym) raise Error::UnknownAttribute.new(attribute: key) end _attributes[key.to_sym] = value end
ruby
def update_attribute(key, value) unless attribute?(key.to_sym) raise Error::UnknownAttribute.new(attribute: key) end _attributes[key.to_sym] = value end
[ "def", "update_attribute", "(", "key", ",", "value", ")", "unless", "attribute?", "(", "key", ".", "to_sym", ")", "raise", "Error", "::", "UnknownAttribute", ".", "new", "(", "attribute", ":", "key", ")", "end", "_attributes", "[", "key", ".", "to_sym", "]", "=", "value", "end" ]
Update a single attribute in the attributes hash. @raise
[ "Update", "a", "single", "attribute", "in", "the", "attributes", "hash", "." ]
a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f
https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/base.rb#L745-L751
17,422
tas50/chef-api
lib/chef-api/resources/base.rb
ChefAPI.Resource::Base.validate!
def validate! unless valid? sentence = errors.full_messages.join(', ') raise Error::InvalidResource.new(errors: sentence) end true end
ruby
def validate! unless valid? sentence = errors.full_messages.join(', ') raise Error::InvalidResource.new(errors: sentence) end true end
[ "def", "validate!", "unless", "valid?", "sentence", "=", "errors", ".", "full_messages", ".", "join", "(", "', '", ")", "raise", "Error", "::", "InvalidResource", ".", "new", "(", "errors", ":", "sentence", ")", "end", "true", "end" ]
Run all of this resource's validations, raising an exception if any validations fail. @raise [Error::InvalidResource] if any of the validations fail @return [Boolean] true if the validation was successful - this method will never return anything other than true because an exception is raised if validations fail
[ "Run", "all", "of", "this", "resource", "s", "validations", "raising", "an", "exception", "if", "any", "validations", "fail", "." ]
a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f
https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/base.rb#L776-L783
17,423
tas50/chef-api
lib/chef-api/resources/base.rb
ChefAPI.Resource::Base.valid?
def valid? errors.clear validators.each do |validator| validator.validate(self) end errors.empty? end
ruby
def valid? errors.clear validators.each do |validator| validator.validate(self) end errors.empty? end
[ "def", "valid?", "errors", ".", "clear", "validators", ".", "each", "do", "|", "validator", "|", "validator", ".", "validate", "(", "self", ")", "end", "errors", ".", "empty?", "end" ]
Determine if the current resource is valid. This relies on the validations defined in the schema at initialization. @return [Boolean] true if the resource is valid, false otherwise
[ "Determine", "if", "the", "current", "resource", "is", "valid", ".", "This", "relies", "on", "the", "validations", "defined", "in", "the", "schema", "at", "initialization", "." ]
a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f
https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/base.rb#L792-L800
17,424
tas50/chef-api
lib/chef-api/resources/base.rb
ChefAPI.Resource::Base.diff
def diff diff = {} remote = self.class.fetch(id, _prefix) || self.class.new({}, _prefix) remote._attributes.each do |key, value| unless _attributes[key] == value diff[key] = { local: _attributes[key], remote: value } end end diff end
ruby
def diff diff = {} remote = self.class.fetch(id, _prefix) || self.class.new({}, _prefix) remote._attributes.each do |key, value| unless _attributes[key] == value diff[key] = { local: _attributes[key], remote: value } end end diff end
[ "def", "diff", "diff", "=", "{", "}", "remote", "=", "self", ".", "class", ".", "fetch", "(", "id", ",", "_prefix", ")", "||", "self", ".", "class", ".", "new", "(", "{", "}", ",", "_prefix", ")", "remote", ".", "_attributes", ".", "each", "do", "|", "key", ",", "value", "|", "unless", "_attributes", "[", "key", "]", "==", "value", "diff", "[", "key", "]", "=", "{", "local", ":", "_attributes", "[", "key", "]", ",", "remote", ":", "value", "}", "end", "end", "diff", "end" ]
Calculate a differential of the attributes on the local resource with it's remote Chef Server counterpart. @example when the local resource is in sync with the remote resource bacon = Bacon.first bacon.diff #=> {} @example when the local resource differs from the remote resource bacon = Bacon.first bacon.description = "My new description" bacon.diff #=> { :description => { :local => "My new description", :remote => "Old description" } } @note This is a VERY expensive operation - use it sparringly! @return [Hash]
[ "Calculate", "a", "differential", "of", "the", "attributes", "on", "the", "local", "resource", "with", "it", "s", "remote", "Chef", "Server", "counterpart", "." ]
a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f
https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/base.rb#L862-L873
17,425
tas50/chef-api
lib/chef-api/resources/base.rb
ChefAPI.Resource::Base.to_hash
def to_hash {}.tap do |hash| _attributes.each do |key, value| hash[key] = value.respond_to?(:to_hash) ? value.to_hash : value end end end
ruby
def to_hash {}.tap do |hash| _attributes.each do |key, value| hash[key] = value.respond_to?(:to_hash) ? value.to_hash : value end end end
[ "def", "to_hash", "{", "}", ".", "tap", "do", "|", "hash", "|", "_attributes", ".", "each", "do", "|", "key", ",", "value", "|", "hash", "[", "key", "]", "=", "value", ".", "respond_to?", "(", ":to_hash", ")", "?", "value", ".", "to_hash", ":", "value", "end", "end", "end" ]
The hash representation of this resource. All attributes are serialized and any values that respond to +to_hash+ are also serialized. @return [Hash]
[ "The", "hash", "representation", "of", "this", "resource", ".", "All", "attributes", "are", "serialized", "and", "any", "values", "that", "respond", "to", "+", "to_hash", "+", "are", "also", "serialized", "." ]
a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f
https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/base.rb#L917-L923
17,426
tas50/chef-api
lib/chef-api/resources/base.rb
ChefAPI.Resource::Base.inspect
def inspect attrs = (_prefix).merge(_attributes).map do |key, value| if value.is_a?(String) "#{key}: #{Util.truncate(value, length: 50).inspect}" else "#{key}: #{value.inspect}" end end "#<#{self.class.classname} #{attrs.join(', ')}>" end
ruby
def inspect attrs = (_prefix).merge(_attributes).map do |key, value| if value.is_a?(String) "#{key}: #{Util.truncate(value, length: 50).inspect}" else "#{key}: #{value.inspect}" end end "#<#{self.class.classname} #{attrs.join(', ')}>" end
[ "def", "inspect", "attrs", "=", "(", "_prefix", ")", ".", "merge", "(", "_attributes", ")", ".", "map", "do", "|", "key", ",", "value", "|", "if", "value", ".", "is_a?", "(", "String", ")", "\"#{key}: #{Util.truncate(value, length: 50).inspect}\"", "else", "\"#{key}: #{value.inspect}\"", "end", "end", "\"#<#{self.class.classname} #{attrs.join(', ')}>\"", "end" ]
Custom inspect method for easier readability. @return [String]
[ "Custom", "inspect", "method", "for", "easier", "readability", "." ]
a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f
https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/base.rb#L948-L958
17,427
tas50/chef-api
lib/chef-api/validators/type.rb
ChefAPI.Validator::Type.validate
def validate(resource) value = resource._attributes[attribute] if value && !types.any? { |type| value.is_a?(type) } short_name = type.to_s.split('::').last resource.errors.add(attribute, "must be a kind of #{short_name}") end end
ruby
def validate(resource) value = resource._attributes[attribute] if value && !types.any? { |type| value.is_a?(type) } short_name = type.to_s.split('::').last resource.errors.add(attribute, "must be a kind of #{short_name}") end end
[ "def", "validate", "(", "resource", ")", "value", "=", "resource", ".", "_attributes", "[", "attribute", "]", "if", "value", "&&", "!", "types", ".", "any?", "{", "|", "type", "|", "value", ".", "is_a?", "(", "type", ")", "}", "short_name", "=", "type", ".", "to_s", ".", "split", "(", "'::'", ")", ".", "last", "resource", ".", "errors", ".", "add", "(", "attribute", ",", "\"must be a kind of #{short_name}\"", ")", "end", "end" ]
Overload the super method to capture the type attribute in the options hash.
[ "Overload", "the", "super", "method", "to", "capture", "the", "type", "attribute", "in", "the", "options", "hash", "." ]
a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f
https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/validators/type.rb#L14-L21
17,428
tas50/chef-api
lib/chef-api/authentication.rb
ChefAPI.Authentication.digest_io
def digest_io(io) digester = Digest::SHA1.new while buffer = io.read(1024) digester.update(buffer) end io.rewind Base64.encode64(digester.digest) end
ruby
def digest_io(io) digester = Digest::SHA1.new while buffer = io.read(1024) digester.update(buffer) end io.rewind Base64.encode64(digester.digest) end
[ "def", "digest_io", "(", "io", ")", "digester", "=", "Digest", "::", "SHA1", ".", "new", "while", "buffer", "=", "io", ".", "read", "(", "1024", ")", "digester", ".", "update", "(", "buffer", ")", "end", "io", ".", "rewind", "Base64", ".", "encode64", "(", "digester", ".", "digest", ")", "end" ]
Hash the given object. @param [String, IO] object a string or IO object to hash @return [String] the hashed value Digest the given IO, reading in 1024 bytes at one time. @param [IO] io the IO (or File object) @return [String]
[ "Hash", "the", "given", "object", "." ]
a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f
https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/authentication.rb#L276-L286
17,429
tas50/chef-api
lib/chef-api/resources/collection_proxy.rb
ChefAPI.Resource::CollectionProxy.fetch
def fetch(id) return nil unless exists?(id) cached(id) { klass.from_url(get(id), prefix) } end
ruby
def fetch(id) return nil unless exists?(id) cached(id) { klass.from_url(get(id), prefix) } end
[ "def", "fetch", "(", "id", ")", "return", "nil", "unless", "exists?", "(", "id", ")", "cached", "(", "id", ")", "{", "klass", ".", "from_url", "(", "get", "(", "id", ")", ",", "prefix", ")", "}", "end" ]
Fetch a specific resource in the collection by id. @example Fetch a resource Bacon.first.items.fetch('crispy') @param [String, Symbol] id the id of the resource to fetch @return [Resource::Base, nil] the fetched class, or nil if it does not exists
[ "Fetch", "a", "specific", "resource", "in", "the", "collection", "by", "id", "." ]
a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f
https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/collection_proxy.rb#L60-L63
17,430
tas50/chef-api
lib/chef-api/resources/collection_proxy.rb
ChefAPI.Resource::CollectionProxy.each
def each(&block) collection.each do |id, url| object = cached(id) { klass.from_url(url, prefix) } block.call(object) if block end end
ruby
def each(&block) collection.each do |id, url| object = cached(id) { klass.from_url(url, prefix) } block.call(object) if block end end
[ "def", "each", "(", "&", "block", ")", "collection", ".", "each", "do", "|", "id", ",", "url", "|", "object", "=", "cached", "(", "id", ")", "{", "klass", ".", "from_url", "(", "url", ",", "prefix", ")", "}", "block", ".", "call", "(", "object", ")", "if", "block", "end", "end" ]
The custom iterator for looping over each object in this collection. For more information, please see the +Enumerator+ module in Ruby core.
[ "The", "custom", "iterator", "for", "looping", "over", "each", "object", "in", "this", "collection", ".", "For", "more", "information", "please", "see", "the", "+", "Enumerator", "+", "module", "in", "Ruby", "core", "." ]
a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f
https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/collection_proxy.rb#L100-L105
17,431
tas50/chef-api
lib/chef-api/resources/collection_proxy.rb
ChefAPI.Resource::CollectionProxy.inspect
def inspect objects = collection .map { |id, _| cached(id) || klass.new(klass.schema.primary_key => id) } .map { |object| object.to_s } "#<#{self.class.name} [#{objects.join(', ')}]>" end
ruby
def inspect objects = collection .map { |id, _| cached(id) || klass.new(klass.schema.primary_key => id) } .map { |object| object.to_s } "#<#{self.class.name} [#{objects.join(', ')}]>" end
[ "def", "inspect", "objects", "=", "collection", ".", "map", "{", "|", "id", ",", "_", "|", "cached", "(", "id", ")", "||", "klass", ".", "new", "(", "klass", ".", "schema", ".", "primary_key", "=>", "id", ")", "}", ".", "map", "{", "|", "object", "|", "object", ".", "to_s", "}", "\"#<#{self.class.name} [#{objects.join(', ')}]>\"", "end" ]
The detailed string representation of this collection proxy. @return [String]
[ "The", "detailed", "string", "representation", "of", "this", "collection", "proxy", "." ]
a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f
https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/collection_proxy.rb#L131-L137
17,432
tas50/chef-api
lib/chef-api/connection.rb
ChefAPI.Connection.add_request_headers
def add_request_headers(request) log.info "Adding request headers..." headers = { 'Accept' => 'application/json', 'Content-Type' => 'application/json', 'Connection' => 'keep-alive', 'Keep-Alive' => '30', 'User-Agent' => user_agent, 'X-Chef-Version' => '11.4.0', } headers.each do |key, value| log.debug "#{key}: #{value}" request[key] = value end end
ruby
def add_request_headers(request) log.info "Adding request headers..." headers = { 'Accept' => 'application/json', 'Content-Type' => 'application/json', 'Connection' => 'keep-alive', 'Keep-Alive' => '30', 'User-Agent' => user_agent, 'X-Chef-Version' => '11.4.0', } headers.each do |key, value| log.debug "#{key}: #{value}" request[key] = value end end
[ "def", "add_request_headers", "(", "request", ")", "log", ".", "info", "\"Adding request headers...\"", "headers", "=", "{", "'Accept'", "=>", "'application/json'", ",", "'Content-Type'", "=>", "'application/json'", ",", "'Connection'", "=>", "'keep-alive'", ",", "'Keep-Alive'", "=>", "'30'", ",", "'User-Agent'", "=>", "user_agent", ",", "'X-Chef-Version'", "=>", "'11.4.0'", ",", "}", "headers", ".", "each", "do", "|", "key", ",", "value", "|", "log", ".", "debug", "\"#{key}: #{value}\"", "request", "[", "key", "]", "=", "value", "end", "end" ]
Adds the default headers to the request object. @param [Net::HTTP::Request] request
[ "Adds", "the", "default", "headers", "to", "the", "request", "object", "." ]
a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f
https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/connection.rb#L457-L473
17,433
tas50/chef-api
lib/chef-api/schema.rb
ChefAPI.Schema.attribute
def attribute(key, options = {}) if primary_key = options.delete(:primary) @primary_key = key.to_sym end @attributes[key] = options.delete(:default) # All remaining options are assumed to be validations options.each do |validation, options| if options @validators << Validator.find(validation).new(key, options) end end key end
ruby
def attribute(key, options = {}) if primary_key = options.delete(:primary) @primary_key = key.to_sym end @attributes[key] = options.delete(:default) # All remaining options are assumed to be validations options.each do |validation, options| if options @validators << Validator.find(validation).new(key, options) end end key end
[ "def", "attribute", "(", "key", ",", "options", "=", "{", "}", ")", "if", "primary_key", "=", "options", ".", "delete", "(", ":primary", ")", "@primary_key", "=", "key", ".", "to_sym", "end", "@attributes", "[", "key", "]", "=", "options", ".", "delete", "(", ":default", ")", "# All remaining options are assumed to be validations", "options", ".", "each", "do", "|", "validation", ",", "options", "|", "if", "options", "@validators", "<<", "Validator", ".", "find", "(", "validation", ")", ".", "new", "(", "key", ",", "options", ")", "end", "end", "key", "end" ]
DSL method for defining an attribute. @param [Symbol] key the key to use @param [Hash] options a list of options to create the attribute with @return [Symbol] the attribute
[ "DSL", "method", "for", "defining", "an", "attribute", "." ]
a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f
https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/schema.rb#L96-L111
17,434
laserlemon/vestal_versions
lib/vestal_versions/version.rb
VestalVersions.Version.original_number
def original_number if reverted_from.nil? number else version = versioned.versions.at(reverted_from) version.nil? ? 1 : version.original_number end end
ruby
def original_number if reverted_from.nil? number else version = versioned.versions.at(reverted_from) version.nil? ? 1 : version.original_number end end
[ "def", "original_number", "if", "reverted_from", ".", "nil?", "number", "else", "version", "=", "versioned", ".", "versions", ".", "at", "(", "reverted_from", ")", "version", ".", "nil?", "?", "1", ":", "version", ".", "original_number", "end", "end" ]
Returns the original version number that this version was.
[ "Returns", "the", "original", "version", "number", "that", "this", "version", "was", "." ]
beccc5744ec030664f003d61ffb617edefd7885b
https://github.com/laserlemon/vestal_versions/blob/beccc5744ec030664f003d61ffb617edefd7885b/lib/vestal_versions/version.rb#L41-L48
17,435
laserlemon/vestal_versions
lib/vestal_versions/creation.rb
VestalVersions.Creation.update_version
def update_version return create_version unless v = versions.last v.modifications_will_change! v.update_attribute(:modifications, v.changes.append_changes(version_changes)) reset_version_changes reset_version end
ruby
def update_version return create_version unless v = versions.last v.modifications_will_change! v.update_attribute(:modifications, v.changes.append_changes(version_changes)) reset_version_changes reset_version end
[ "def", "update_version", "return", "create_version", "unless", "v", "=", "versions", ".", "last", "v", ".", "modifications_will_change!", "v", ".", "update_attribute", "(", ":modifications", ",", "v", ".", "changes", ".", "append_changes", "(", "version_changes", ")", ")", "reset_version_changes", "reset_version", "end" ]
Updates the last version's changes by appending the current version changes.
[ "Updates", "the", "last", "version", "s", "changes", "by", "appending", "the", "current", "version", "changes", "." ]
beccc5744ec030664f003d61ffb617edefd7885b
https://github.com/laserlemon/vestal_versions/blob/beccc5744ec030664f003d61ffb617edefd7885b/lib/vestal_versions/creation.rb#L65-L71
17,436
laserlemon/vestal_versions
lib/vestal_versions/reset.rb
VestalVersions.Reset.reset_to!
def reset_to!(value) if saved = skip_version{ revert_to!(value) } versions.send(:delete, versions.after(value)) reset_version end saved end
ruby
def reset_to!(value) if saved = skip_version{ revert_to!(value) } versions.send(:delete, versions.after(value)) reset_version end saved end
[ "def", "reset_to!", "(", "value", ")", "if", "saved", "=", "skip_version", "{", "revert_to!", "(", "value", ")", "}", "versions", ".", "send", "(", ":delete", ",", "versions", ".", "after", "(", "value", ")", ")", "reset_version", "end", "saved", "end" ]
Adds the instance methods required to reset an object to a previous version. Similar to +revert_to!+, the +reset_to!+ method reverts an object to a previous version, only instead of creating a new record in the version history, +reset_to!+ deletes all of the version history that occurs after the version reverted to. The action taken on each version record after the point of reversion is determined by the <tt>:dependent</tt> option given to the +versioned+ method. See the +versioned+ method documentation for more details.
[ "Adds", "the", "instance", "methods", "required", "to", "reset", "an", "object", "to", "a", "previous", "version", ".", "Similar", "to", "+", "revert_to!", "+", "the", "+", "reset_to!", "+", "method", "reverts", "an", "object", "to", "a", "previous", "version", "only", "instead", "of", "creating", "a", "new", "record", "in", "the", "version", "history", "+", "reset_to!", "+", "deletes", "all", "of", "the", "version", "history", "that", "occurs", "after", "the", "version", "reverted", "to", "." ]
beccc5744ec030664f003d61ffb617edefd7885b
https://github.com/laserlemon/vestal_versions/blob/beccc5744ec030664f003d61ffb617edefd7885b/lib/vestal_versions/reset.rb#L15-L21
17,437
laserlemon/vestal_versions
lib/vestal_versions/version_tagging.rb
VestalVersions.VersionTagging.tag_version
def tag_version(tag) v = versions.at(version) || versions.build(:number => 1) t = v.tag!(tag) versions.reload t end
ruby
def tag_version(tag) v = versions.at(version) || versions.build(:number => 1) t = v.tag!(tag) versions.reload t end
[ "def", "tag_version", "(", "tag", ")", "v", "=", "versions", ".", "at", "(", "version", ")", "||", "versions", ".", "build", "(", ":number", "=>", "1", ")", "t", "=", "v", ".", "tag!", "(", "tag", ")", "versions", ".", "reload", "t", "end" ]
Adds an instance method which allows version tagging through the parent object. Accepts a single string argument which is attached to the version record associated with the current version number of the parent object. Returns the given tag if successful, nil if not. Tags must be unique within the scope of the parent object. Tag creation will fail if non-unique. Version records corresponding to version number 1 are not typically created, but one will be built to house the given tag if the parent object's current version number is 1.
[ "Adds", "an", "instance", "method", "which", "allows", "version", "tagging", "through", "the", "parent", "object", ".", "Accepts", "a", "single", "string", "argument", "which", "is", "attached", "to", "the", "version", "record", "associated", "with", "the", "current", "version", "number", "of", "the", "parent", "object", "." ]
beccc5744ec030664f003d61ffb617edefd7885b
https://github.com/laserlemon/vestal_versions/blob/beccc5744ec030664f003d61ffb617edefd7885b/lib/vestal_versions/version_tagging.rb#L17-L22
17,438
laserlemon/vestal_versions
lib/vestal_versions/reversion.rb
VestalVersions.Reversion.revert_to
def revert_to(value) to_number = versions.number_at(value) changes_between(version, to_number).each do |attribute, change| write_attribute(attribute, change.last) end reset_version(to_number) end
ruby
def revert_to(value) to_number = versions.number_at(value) changes_between(version, to_number).each do |attribute, change| write_attribute(attribute, change.last) end reset_version(to_number) end
[ "def", "revert_to", "(", "value", ")", "to_number", "=", "versions", ".", "number_at", "(", "value", ")", "changes_between", "(", "version", ",", "to_number", ")", ".", "each", "do", "|", "attribute", ",", "change", "|", "write_attribute", "(", "attribute", ",", "change", ".", "last", ")", "end", "reset_version", "(", "to_number", ")", "end" ]
Accepts a value corresponding to a specific version record, builds a history of changes between that version and the current version, and then iterates over that history updating the object's attributes until the it's reverted to its prior state. The single argument should adhere to one of the formats as documented in the +at+ method of VestalVersions::Versions. After the object is reverted to the target version, it is not saved. In order to save the object after the reversion, use the +revert_to!+ method. The version number of the object will reflect whatever version has been reverted to, and the return value of the +revert_to+ method is also the target version number.
[ "Accepts", "a", "value", "corresponding", "to", "a", "specific", "version", "record", "builds", "a", "history", "of", "changes", "between", "that", "version", "and", "the", "current", "version", "and", "then", "iterates", "over", "that", "history", "updating", "the", "object", "s", "attributes", "until", "the", "it", "s", "reverted", "to", "its", "prior", "state", "." ]
beccc5744ec030664f003d61ffb617edefd7885b
https://github.com/laserlemon/vestal_versions/blob/beccc5744ec030664f003d61ffb617edefd7885b/lib/vestal_versions/reversion.rb#L25-L33
17,439
realestate-com-au/stackup
lib/stackup/stack_watcher.rb
Stackup.StackWatcher.zero
def zero last_event = stack.events.first @last_processed_event_id = last_event.id unless last_event.nil? nil rescue Aws::CloudFormation::Errors::ValidationError end
ruby
def zero last_event = stack.events.first @last_processed_event_id = last_event.id unless last_event.nil? nil rescue Aws::CloudFormation::Errors::ValidationError end
[ "def", "zero", "last_event", "=", "stack", ".", "events", ".", "first", "@last_processed_event_id", "=", "last_event", ".", "id", "unless", "last_event", ".", "nil?", "nil", "rescue", "Aws", "::", "CloudFormation", "::", "Errors", "::", "ValidationError", "end" ]
Consume all new events
[ "Consume", "all", "new", "events" ]
3bb0012bc89ad3c22d344a34ff221473ae5934d9
https://github.com/realestate-com-au/stackup/blob/3bb0012bc89ad3c22d344a34ff221473ae5934d9/lib/stackup/stack_watcher.rb#L36-L41
17,440
realestate-com-au/stackup
lib/stackup/stack.rb
Stackup.Stack.on_event
def on_event(event_handler = nil, &block) event_handler ||= block raise ArgumentError, "no event_handler provided" if event_handler.nil? @event_handler = event_handler end
ruby
def on_event(event_handler = nil, &block) event_handler ||= block raise ArgumentError, "no event_handler provided" if event_handler.nil? @event_handler = event_handler end
[ "def", "on_event", "(", "event_handler", "=", "nil", ",", "&", "block", ")", "event_handler", "||=", "block", "raise", "ArgumentError", ",", "\"no event_handler provided\"", "if", "event_handler", ".", "nil?", "@event_handler", "=", "event_handler", "end" ]
Register a handler for reporting of stack events. @param [Proc] event_handler
[ "Register", "a", "handler", "for", "reporting", "of", "stack", "events", "." ]
3bb0012bc89ad3c22d344a34ff221473ae5934d9
https://github.com/realestate-com-au/stackup/blob/3bb0012bc89ad3c22d344a34ff221473ae5934d9/lib/stackup/stack.rb#L41-L45
17,441
realestate-com-au/stackup
lib/stackup/stack.rb
Stackup.Stack.create_or_update
def create_or_update(options) options = options.dup if (template_data = options.delete(:template)) options[:template_body] = MultiJson.dump(template_data) end if (parameters = options[:parameters]) options[:parameters] = Parameters.new(parameters).to_a end if (tags = options[:tags]) options[:tags] = normalize_tags(tags) end if (policy_data = options.delete(:stack_policy)) options[:stack_policy_body] = MultiJson.dump(policy_data) end if (policy_data = options.delete(:stack_policy_during_update)) options[:stack_policy_during_update_body] = MultiJson.dump(policy_data) end options[:capabilities] ||= ["CAPABILITY_NAMED_IAM"] delete if ALMOST_DEAD_STATUSES.include?(status) update(options) rescue NoSuchStack create(options) end
ruby
def create_or_update(options) options = options.dup if (template_data = options.delete(:template)) options[:template_body] = MultiJson.dump(template_data) end if (parameters = options[:parameters]) options[:parameters] = Parameters.new(parameters).to_a end if (tags = options[:tags]) options[:tags] = normalize_tags(tags) end if (policy_data = options.delete(:stack_policy)) options[:stack_policy_body] = MultiJson.dump(policy_data) end if (policy_data = options.delete(:stack_policy_during_update)) options[:stack_policy_during_update_body] = MultiJson.dump(policy_data) end options[:capabilities] ||= ["CAPABILITY_NAMED_IAM"] delete if ALMOST_DEAD_STATUSES.include?(status) update(options) rescue NoSuchStack create(options) end
[ "def", "create_or_update", "(", "options", ")", "options", "=", "options", ".", "dup", "if", "(", "template_data", "=", "options", ".", "delete", "(", ":template", ")", ")", "options", "[", ":template_body", "]", "=", "MultiJson", ".", "dump", "(", "template_data", ")", "end", "if", "(", "parameters", "=", "options", "[", ":parameters", "]", ")", "options", "[", ":parameters", "]", "=", "Parameters", ".", "new", "(", "parameters", ")", ".", "to_a", "end", "if", "(", "tags", "=", "options", "[", ":tags", "]", ")", "options", "[", ":tags", "]", "=", "normalize_tags", "(", "tags", ")", "end", "if", "(", "policy_data", "=", "options", ".", "delete", "(", ":stack_policy", ")", ")", "options", "[", ":stack_policy_body", "]", "=", "MultiJson", ".", "dump", "(", "policy_data", ")", "end", "if", "(", "policy_data", "=", "options", ".", "delete", "(", ":stack_policy_during_update", ")", ")", "options", "[", ":stack_policy_during_update_body", "]", "=", "MultiJson", ".", "dump", "(", "policy_data", ")", "end", "options", "[", ":capabilities", "]", "||=", "[", "\"CAPABILITY_NAMED_IAM\"", "]", "delete", "if", "ALMOST_DEAD_STATUSES", ".", "include?", "(", "status", ")", "update", "(", "options", ")", "rescue", "NoSuchStack", "create", "(", "options", ")", "end" ]
Create or update the stack. @param [Hash] options create/update options accepts a superset of the options supported by +Aws::CloudFormation::Stack#update+ (see http://docs.aws.amazon.com/sdkforruby/api/Aws/CloudFormation/Stack.html#update-instance_method) @option options [Array<String>] :capabilities (CAPABILITY_NAMED_IAM) list of capabilities required for stack template @option options [boolean] :disable_rollback (false) if true, disable rollback if stack creation fails @option options [String] :notification_arns ARNs for the Amazon SNS topics associated with this stack @option options [String] :on_failure (ROLLBACK) if stack creation fails: DO_NOTHING, ROLLBACK, or DELETE @option options [Hash, Array<Hash>] :parameters stack parameters, either as a Hash, or an Array of +Aws::CloudFormation::Types::Parameter+ structures @option options [Hash, Array<Hash>] :tags stack tags, either as a Hash, or an Array of +Aws::CloudFormation::Types::Tag+ structures @option options [Array<String>] :resource_types resource types that you have permissions to work with @option options [Hash] :stack_policy stack policy, as Ruby data @option options [String] :stack_policy_body stack policy, as JSON @option options [String] :stack_policy_url location of stack policy @option options [Hash] :stack_policy_during_update temporary stack policy, as Ruby data @option options [String] :stack_policy_during_update_body temporary stack policy, as JSON @option options [String] :stack_policy_during_update_url location of temporary stack policy @option options [Hash] :template stack template, as Ruby data @option options [String] :template_body stack template, as JSON or YAML @option options [String] :template_url location of stack template @option options [Integer] :timeout_in_minutes stack creation timeout @option options [boolean] :use_previous_template if true, reuse the existing template @return [String] resulting stack status @raise [Stackup::StackUpdateError] if operation fails
[ "Create", "or", "update", "the", "stack", "." ]
3bb0012bc89ad3c22d344a34ff221473ae5934d9
https://github.com/realestate-com-au/stackup/blob/3bb0012bc89ad3c22d344a34ff221473ae5934d9/lib/stackup/stack.rb#L114-L136
17,442
realestate-com-au/stackup
lib/stackup/stack.rb
Stackup.Stack.modify_stack
def modify_stack(target_status, failure_message, &block) if wait? status = modify_stack_synchronously(&block) raise StackUpdateError, failure_message unless target_status === status status else modify_stack_asynchronously(&block) end end
ruby
def modify_stack(target_status, failure_message, &block) if wait? status = modify_stack_synchronously(&block) raise StackUpdateError, failure_message unless target_status === status status else modify_stack_asynchronously(&block) end end
[ "def", "modify_stack", "(", "target_status", ",", "failure_message", ",", "&", "block", ")", "if", "wait?", "status", "=", "modify_stack_synchronously", "(", "block", ")", "raise", "StackUpdateError", ",", "failure_message", "unless", "target_status", "===", "status", "status", "else", "modify_stack_asynchronously", "(", "block", ")", "end", "end" ]
Execute a block, to modify the stack. @return the stack status
[ "Execute", "a", "block", "to", "modify", "the", "stack", "." ]
3bb0012bc89ad3c22d344a34ff221473ae5934d9
https://github.com/realestate-com-au/stackup/blob/3bb0012bc89ad3c22d344a34ff221473ae5934d9/lib/stackup/stack.rb#L323-L331
17,443
realestate-com-au/stackup
lib/stackup/stack.rb
Stackup.Stack.modify_stack_synchronously
def modify_stack_synchronously watch do |watcher| handling_cf_errors do yield end loop do watcher.each_new_event(&event_handler) status = self.status logger.debug("stack_status=#{status}") return status if status.nil? || status =~ /_(COMPLETE|FAILED)$/ sleep(wait_poll_interval) end end end
ruby
def modify_stack_synchronously watch do |watcher| handling_cf_errors do yield end loop do watcher.each_new_event(&event_handler) status = self.status logger.debug("stack_status=#{status}") return status if status.nil? || status =~ /_(COMPLETE|FAILED)$/ sleep(wait_poll_interval) end end end
[ "def", "modify_stack_synchronously", "watch", "do", "|", "watcher", "|", "handling_cf_errors", "do", "yield", "end", "loop", "do", "watcher", ".", "each_new_event", "(", "event_handler", ")", "status", "=", "self", ".", "status", "logger", ".", "debug", "(", "\"stack_status=#{status}\"", ")", "return", "status", "if", "status", ".", "nil?", "||", "status", "=~", "/", "/", "sleep", "(", "wait_poll_interval", ")", "end", "end", "end" ]
Execute a block, reporting stack events, until the stack is stable. @return the final stack status
[ "Execute", "a", "block", "reporting", "stack", "events", "until", "the", "stack", "is", "stable", "." ]
3bb0012bc89ad3c22d344a34ff221473ae5934d9
https://github.com/realestate-com-au/stackup/blob/3bb0012bc89ad3c22d344a34ff221473ae5934d9/lib/stackup/stack.rb#L337-L350
17,444
realestate-com-au/stackup
lib/stackup/stack.rb
Stackup.Stack.extract_hash
def extract_hash(collection_name, key_name, value_name) handling_cf_errors do {}.tap do |result| cf_stack.public_send(collection_name).each do |item| key = item.public_send(key_name) value = item.public_send(value_name) result[key] = value end end end end
ruby
def extract_hash(collection_name, key_name, value_name) handling_cf_errors do {}.tap do |result| cf_stack.public_send(collection_name).each do |item| key = item.public_send(key_name) value = item.public_send(value_name) result[key] = value end end end end
[ "def", "extract_hash", "(", "collection_name", ",", "key_name", ",", "value_name", ")", "handling_cf_errors", "do", "{", "}", ".", "tap", "do", "|", "result", "|", "cf_stack", ".", "public_send", "(", "collection_name", ")", ".", "each", "do", "|", "item", "|", "key", "=", "item", ".", "public_send", "(", "key_name", ")", "value", "=", "item", ".", "public_send", "(", "value_name", ")", "result", "[", "key", "]", "=", "value", "end", "end", "end", "end" ]
Extract data from a collection attribute of the stack. @param [Symbol] collection_name collection attribute name @param [Symbol] key_name name of item attribute that provides key @param [Symbol] value_name name of item attribute that provides value @return [Hash<String, String>] mapping of collection
[ "Extract", "data", "from", "a", "collection", "attribute", "of", "the", "stack", "." ]
3bb0012bc89ad3c22d344a34ff221473ae5934d9
https://github.com/realestate-com-au/stackup/blob/3bb0012bc89ad3c22d344a34ff221473ae5934d9/lib/stackup/stack.rb#L380-L390
17,445
realestate-com-au/stackup
lib/stackup/change_set.rb
Stackup.ChangeSet.create
def create(options = {}) options = options.dup options[:stack_name] = stack.name options[:change_set_name] = name options[:change_set_type] = stack.exists? ? "UPDATE" : "CREATE" force = options.delete(:force) options[:template_body] = MultiJson.dump(options.delete(:template)) if options[:template] options[:parameters] = Parameters.new(options[:parameters]).to_a if options[:parameters] options[:tags] = normalize_tags(options[:tags]) if options[:tags] options[:capabilities] ||= ["CAPABILITY_NAMED_IAM"] delete if force handling_cf_errors do cf_client.create_change_set(options) loop do current = describe logger.debug("change_set_status=#{current.status}") case current.status when /COMPLETE/ return current.status when "FAILED" logger.error(current.status_reason) raise StackUpdateError, "change-set creation failed" if status == "FAILED" end sleep(wait_poll_interval) end status end end
ruby
def create(options = {}) options = options.dup options[:stack_name] = stack.name options[:change_set_name] = name options[:change_set_type] = stack.exists? ? "UPDATE" : "CREATE" force = options.delete(:force) options[:template_body] = MultiJson.dump(options.delete(:template)) if options[:template] options[:parameters] = Parameters.new(options[:parameters]).to_a if options[:parameters] options[:tags] = normalize_tags(options[:tags]) if options[:tags] options[:capabilities] ||= ["CAPABILITY_NAMED_IAM"] delete if force handling_cf_errors do cf_client.create_change_set(options) loop do current = describe logger.debug("change_set_status=#{current.status}") case current.status when /COMPLETE/ return current.status when "FAILED" logger.error(current.status_reason) raise StackUpdateError, "change-set creation failed" if status == "FAILED" end sleep(wait_poll_interval) end status end end
[ "def", "create", "(", "options", "=", "{", "}", ")", "options", "=", "options", ".", "dup", "options", "[", ":stack_name", "]", "=", "stack", ".", "name", "options", "[", ":change_set_name", "]", "=", "name", "options", "[", ":change_set_type", "]", "=", "stack", ".", "exists?", "?", "\"UPDATE\"", ":", "\"CREATE\"", "force", "=", "options", ".", "delete", "(", ":force", ")", "options", "[", ":template_body", "]", "=", "MultiJson", ".", "dump", "(", "options", ".", "delete", "(", ":template", ")", ")", "if", "options", "[", ":template", "]", "options", "[", ":parameters", "]", "=", "Parameters", ".", "new", "(", "options", "[", ":parameters", "]", ")", ".", "to_a", "if", "options", "[", ":parameters", "]", "options", "[", ":tags", "]", "=", "normalize_tags", "(", "options", "[", ":tags", "]", ")", "if", "options", "[", ":tags", "]", "options", "[", ":capabilities", "]", "||=", "[", "\"CAPABILITY_NAMED_IAM\"", "]", "delete", "if", "force", "handling_cf_errors", "do", "cf_client", ".", "create_change_set", "(", "options", ")", "loop", "do", "current", "=", "describe", "logger", ".", "debug", "(", "\"change_set_status=#{current.status}\"", ")", "case", "current", ".", "status", "when", "/", "/", "return", "current", ".", "status", "when", "\"FAILED\"", "logger", ".", "error", "(", "current", ".", "status_reason", ")", "raise", "StackUpdateError", ",", "\"change-set creation failed\"", "if", "status", "==", "\"FAILED\"", "end", "sleep", "(", "wait_poll_interval", ")", "end", "status", "end", "end" ]
Create the change-set. Refer +Aws::CloudFormation::Client#create_change_set+ (see http://docs.aws.amazon.com/sdkforruby/api/Aws/CloudFormation/Client.html#create_change_set-instance_method) @param [Hash] options change-set options @option options [Array<String>] :capabilities (CAPABILITY_NAMED_IAM) list of capabilities required for stack template @option options [String] :description change-set description @option options [String] :notification_arns ARNs for the Amazon SNS topics associated with this stack @option options [Hash, Array<Hash>] :parameters stack parameters, either as a Hash, or an Array of +Aws::CloudFormation::Types::Parameter+ structures @option options [Hash, Array<Hash>] :tags stack tags, either as a Hash, or an Array of +Aws::CloudFormation::Types::Tag+ structures @option options [Array<String>] :resource_types resource types that you have permissions to work with @option options [Hash] :template stack template, as Ruby data @option options [String] :template_body stack template, as JSON or YAML @option options [String] :template_url location of stack template @option options [boolean] :use_previous_template if true, reuse the existing template @option options [boolean] :force if true, delete any existing change-set of the same name @return [String] change-set id @raise [Stackup::NoSuchStack] if the stack doesn't exist
[ "Create", "the", "change", "-", "set", "." ]
3bb0012bc89ad3c22d344a34ff221473ae5934d9
https://github.com/realestate-com-au/stackup/blob/3bb0012bc89ad3c22d344a34ff221473ae5934d9/lib/stackup/change_set.rb#L53-L80
17,446
kristianmandrup/cantango
spec/active_record/scenarios/shared/permits/account_permits/user_account_permit.rb
UserAccountPermits.UserRolePermit.static_rules
def static_rules cannot :manage, User can :read, Comment can :read, any(/Post/) can :read, Article can :write, any(/Article/) author_of(Article) do |author| author.can :manage end author_of(Post) do |author| author.can :manage end author_of(Comment) do |author| author.can :manage end # # can :manage, :all # scope :account do |account| # account.author_of(Article) do |author| # author.can :manage # author.cannot :delete # end # # account.writer_of(Post).can :manage # end # # scope :user do |user| # user.writer_of(Comment).can :manage # end end
ruby
def static_rules cannot :manage, User can :read, Comment can :read, any(/Post/) can :read, Article can :write, any(/Article/) author_of(Article) do |author| author.can :manage end author_of(Post) do |author| author.can :manage end author_of(Comment) do |author| author.can :manage end # # can :manage, :all # scope :account do |account| # account.author_of(Article) do |author| # author.can :manage # author.cannot :delete # end # # account.writer_of(Post).can :manage # end # # scope :user do |user| # user.writer_of(Comment).can :manage # end end
[ "def", "static_rules", "cannot", ":manage", ",", "User", "can", ":read", ",", "Comment", "can", ":read", ",", "any", "(", "/", "/", ")", "can", ":read", ",", "Article", "can", ":write", ",", "any", "(", "/", "/", ")", "author_of", "(", "Article", ")", "do", "|", "author", "|", "author", ".", "can", ":manage", "end", "author_of", "(", "Post", ")", "do", "|", "author", "|", "author", ".", "can", ":manage", "end", "author_of", "(", "Comment", ")", "do", "|", "author", "|", "author", ".", "can", ":manage", "end", "# # can :manage, :all ", "# scope :account do |account|", "# account.author_of(Article) do |author|", "# author.can :manage", "# author.cannot :delete", "# end ", "# ", "# account.writer_of(Post).can :manage", "# end", "# ", "# scope :user do |user| ", "# user.writer_of(Comment).can :manage", "# end", "end" ]
should take user and options args here ???
[ "should", "take", "user", "and", "options", "args", "here", "???" ]
1920ea616ab27f702203949c4d199f1534bba89b
https://github.com/kristianmandrup/cantango/blob/1920ea616ab27f702203949c4d199f1534bba89b/spec/active_record/scenarios/shared/permits/account_permits/user_account_permit.rb#L10-L44
17,447
hanklords/flickraw
lib/flickraw/flickr.rb
FlickRaw.Flickr.call
def call(req, args={}, &block) oauth_args = args.delete(:oauth) || {} http_response = @oauth_consumer.post_form(REST_PATH, @access_secret, {:oauth_token => @access_token}.merge(oauth_args), build_args(args, req)) process_response(req, http_response.body) end
ruby
def call(req, args={}, &block) oauth_args = args.delete(:oauth) || {} http_response = @oauth_consumer.post_form(REST_PATH, @access_secret, {:oauth_token => @access_token}.merge(oauth_args), build_args(args, req)) process_response(req, http_response.body) end
[ "def", "call", "(", "req", ",", "args", "=", "{", "}", ",", "&", "block", ")", "oauth_args", "=", "args", ".", "delete", "(", ":oauth", ")", "||", "{", "}", "http_response", "=", "@oauth_consumer", ".", "post_form", "(", "REST_PATH", ",", "@access_secret", ",", "{", ":oauth_token", "=>", "@access_token", "}", ".", "merge", "(", "oauth_args", ")", ",", "build_args", "(", "args", ",", "req", ")", ")", "process_response", "(", "req", ",", "http_response", ".", "body", ")", "end" ]
This is the central method. It does the actual request to the flickr server. Raises FailedResponse if the response status is _failed_.
[ "This", "is", "the", "central", "method", ".", "It", "does", "the", "actual", "request", "to", "the", "flickr", "server", "." ]
6bf254681f8d57e65b352d93fb49237bd178e695
https://github.com/hanklords/flickraw/blob/6bf254681f8d57e65b352d93fb49237bd178e695/lib/flickraw/flickr.rb#L33-L37
17,448
hanklords/flickraw
lib/flickraw/flickr.rb
FlickRaw.Flickr.get_access_token
def get_access_token(token, secret, verify) access_token = @oauth_consumer.access_token(FLICKR_OAUTH_ACCESS_TOKEN, secret, :oauth_token => token, :oauth_verifier => verify) @access_token, @access_secret = access_token['oauth_token'], access_token['oauth_token_secret'] access_token end
ruby
def get_access_token(token, secret, verify) access_token = @oauth_consumer.access_token(FLICKR_OAUTH_ACCESS_TOKEN, secret, :oauth_token => token, :oauth_verifier => verify) @access_token, @access_secret = access_token['oauth_token'], access_token['oauth_token_secret'] access_token end
[ "def", "get_access_token", "(", "token", ",", "secret", ",", "verify", ")", "access_token", "=", "@oauth_consumer", ".", "access_token", "(", "FLICKR_OAUTH_ACCESS_TOKEN", ",", "secret", ",", ":oauth_token", "=>", "token", ",", ":oauth_verifier", "=>", "verify", ")", "@access_token", ",", "@access_secret", "=", "access_token", "[", "'oauth_token'", "]", ",", "access_token", "[", "'oauth_token_secret'", "]", "access_token", "end" ]
Get an oauth access token. flickr.get_access_token(token['oauth_token'], token['oauth_token_secret'], oauth_verifier)
[ "Get", "an", "oauth", "access", "token", "." ]
6bf254681f8d57e65b352d93fb49237bd178e695
https://github.com/hanklords/flickraw/blob/6bf254681f8d57e65b352d93fb49237bd178e695/lib/flickraw/flickr.rb#L56-L60
17,449
slideshow-s9/slideshow
slideshow-models/lib/slideshow/helpers/capture_helper.rb
Slideshow.CaptureHelper.capture_erb
def capture_erb( *args, &block ) # get the buffer from the block's binding buffer = _erb_buffer(block.binding) rescue nil # If there is no buffer, just call the block and get the contents if buffer.nil? block.call(*args) # If there is a buffer, execute the block, then extract its contents else pos = buffer.length block.call(*args) # extract the block data = buffer[pos..-1] # replace it in the original with empty string buffer[pos..-1] = "" data end end
ruby
def capture_erb( *args, &block ) # get the buffer from the block's binding buffer = _erb_buffer(block.binding) rescue nil # If there is no buffer, just call the block and get the contents if buffer.nil? block.call(*args) # If there is a buffer, execute the block, then extract its contents else pos = buffer.length block.call(*args) # extract the block data = buffer[pos..-1] # replace it in the original with empty string buffer[pos..-1] = "" data end end
[ "def", "capture_erb", "(", "*", "args", ",", "&", "block", ")", "# get the buffer from the block's binding\r", "buffer", "=", "_erb_buffer", "(", "block", ".", "binding", ")", "rescue", "nil", "# If there is no buffer, just call the block and get the contents\r", "if", "buffer", ".", "nil?", "block", ".", "call", "(", "args", ")", "# If there is a buffer, execute the block, then extract its contents\r", "else", "pos", "=", "buffer", ".", "length", "block", ".", "call", "(", "args", ")", "# extract the block\r", "data", "=", "buffer", "[", "pos", "..", "-", "1", "]", "# replace it in the original with empty string\r", "buffer", "[", "pos", "..", "-", "1", "]", "=", "\"\"", "data", "end", "end" ]
This method is used to capture content from an ERB filter evaluation. It is useful to helpers that need to process chunks of data during ERB filter processing. ==== Parameters *args:: Arguments to pass to the block. &block:: The ERB block to call. ==== Returns String:: The output of the block. ==== Examples Capture being used in an ERB page: <% @foo = capture_erb do %> <p>Some Foo content!</p> <% end %>
[ "This", "method", "is", "used", "to", "capture", "content", "from", "an", "ERB", "filter", "evaluation", ".", "It", "is", "useful", "to", "helpers", "that", "need", "to", "process", "chunks", "of", "data", "during", "ERB", "filter", "processing", "." ]
b7a397f9136f623589816bef498914943980a313
https://github.com/slideshow-s9/slideshow/blob/b7a397f9136f623589816bef498914943980a313/slideshow-models/lib/slideshow/helpers/capture_helper.rb#L89-L109
17,450
slideshow-s9/slideshow
slideshow-models/lib/slideshow/filters/debug_filter.rb
Slideshow.DebugFilter.dump_content_to_file_debug_text_erb
def dump_content_to_file_debug_text_erb( content ) # NB: using attribs from mixed in class # - opts # - outdir return content unless config.verbose? outname = "#{outdir}/#{@name}.debug.text.erb" puts " Dumping content before erb merge to #{outname}..." File.open( outname, 'w' ) do |f| f.write( content ) end content end
ruby
def dump_content_to_file_debug_text_erb( content ) # NB: using attribs from mixed in class # - opts # - outdir return content unless config.verbose? outname = "#{outdir}/#{@name}.debug.text.erb" puts " Dumping content before erb merge to #{outname}..." File.open( outname, 'w' ) do |f| f.write( content ) end content end
[ "def", "dump_content_to_file_debug_text_erb", "(", "content", ")", "# NB: using attribs from mixed in class", "# - opts", "# - outdir", "return", "content", "unless", "config", ".", "verbose?", "outname", "=", "\"#{outdir}/#{@name}.debug.text.erb\"", "puts", "\" Dumping content before erb merge to #{outname}...\"", "File", ".", "open", "(", "outname", ",", "'w'", ")", "do", "|", "f", "|", "f", ".", "write", "(", "content", ")", "end", "content", "end" ]
use it to dump content before erb merge
[ "use", "it", "to", "dump", "content", "before", "erb", "merge" ]
b7a397f9136f623589816bef498914943980a313
https://github.com/slideshow-s9/slideshow/blob/b7a397f9136f623589816bef498914943980a313/slideshow-models/lib/slideshow/filters/debug_filter.rb#L8-L25
17,451
sjke/pg_ltree
lib/pg_ltree/ltree.rb
PgLtree.Ltree.ltree
def ltree(column = :path, options: { cascade: true }) cattr_accessor :ltree_path_column self.ltree_path_column = column if options[:cascade] after_update :cascade_update after_destroy :cascade_destroy end extend ClassMethods include InstanceMethods end
ruby
def ltree(column = :path, options: { cascade: true }) cattr_accessor :ltree_path_column self.ltree_path_column = column if options[:cascade] after_update :cascade_update after_destroy :cascade_destroy end extend ClassMethods include InstanceMethods end
[ "def", "ltree", "(", "column", "=", ":path", ",", "options", ":", "{", "cascade", ":", "true", "}", ")", "cattr_accessor", ":ltree_path_column", "self", ".", "ltree_path_column", "=", "column", "if", "options", "[", ":cascade", "]", "after_update", ":cascade_update", "after_destroy", ":cascade_destroy", "end", "extend", "ClassMethods", "include", "InstanceMethods", "end" ]
Initialzie ltree for active model @param column [String] ltree column name
[ "Initialzie", "ltree", "for", "active", "model" ]
cbd7d4fd7d5d4a04004ee2dd5b185958d7280e2f
https://github.com/sjke/pg_ltree/blob/cbd7d4fd7d5d4a04004ee2dd5b185958d7280e2f/lib/pg_ltree/ltree.rb#L12-L24
17,452
ryz310/rubocop_challenger
lib/rubocop_challenger/go.rb
RubocopChallenger.Go.regenerate_rubocop_todo!
def regenerate_rubocop_todo! before_version = scan_rubocop_version_in_rubocop_todo_file pull_request.commit! ':police_car: regenerate rubocop todo' do Rubocop::Command.new.auto_gen_config end after_version = scan_rubocop_version_in_rubocop_todo_file [before_version, after_version] end
ruby
def regenerate_rubocop_todo! before_version = scan_rubocop_version_in_rubocop_todo_file pull_request.commit! ':police_car: regenerate rubocop todo' do Rubocop::Command.new.auto_gen_config end after_version = scan_rubocop_version_in_rubocop_todo_file [before_version, after_version] end
[ "def", "regenerate_rubocop_todo!", "before_version", "=", "scan_rubocop_version_in_rubocop_todo_file", "pull_request", ".", "commit!", "':police_car: regenerate rubocop todo'", "do", "Rubocop", "::", "Command", ".", "new", ".", "auto_gen_config", "end", "after_version", "=", "scan_rubocop_version_in_rubocop_todo_file", "[", "before_version", ",", "after_version", "]", "end" ]
Re-generate .rubocop_todo.yml and run git commit. @return [Array<String>] Returns the versions of RuboCop which created ".rubocop_todo.yml" before and after re-generate.
[ "Re", "-", "generate", ".", "rubocop_todo", ".", "yml", "and", "run", "git", "commit", "." ]
267f3b48d1a32f1ef32ab8816cefafa9ee96ea50
https://github.com/ryz310/rubocop_challenger/blob/267f3b48d1a32f1ef32ab8816cefafa9ee96ea50/lib/rubocop_challenger/go.rb#L49-L57
17,453
ryz310/rubocop_challenger
lib/rubocop_challenger/go.rb
RubocopChallenger.Go.rubocop_challenge!
def rubocop_challenge!(before_version, after_version) Rubocop::Challenge.exec(options[:file_path], options[:mode]).tap do |rule| pull_request.commit! ":police_car: #{rule.title}" end rescue Errors::NoAutoCorrectableRule => e create_another_pull_request!(before_version, after_version) raise e end
ruby
def rubocop_challenge!(before_version, after_version) Rubocop::Challenge.exec(options[:file_path], options[:mode]).tap do |rule| pull_request.commit! ":police_car: #{rule.title}" end rescue Errors::NoAutoCorrectableRule => e create_another_pull_request!(before_version, after_version) raise e end
[ "def", "rubocop_challenge!", "(", "before_version", ",", "after_version", ")", "Rubocop", "::", "Challenge", ".", "exec", "(", "options", "[", ":file_path", "]", ",", "options", "[", ":mode", "]", ")", ".", "tap", "do", "|", "rule", "|", "pull_request", ".", "commit!", "\":police_car: #{rule.title}\"", "end", "rescue", "Errors", "::", "NoAutoCorrectableRule", "=>", "e", "create_another_pull_request!", "(", "before_version", ",", "after_version", ")", "raise", "e", "end" ]
Run rubocop challenge. @param before_version [String] The version of RuboCop which created ".rubocop_todo.yml" before re-generate. @param after_version [String] The version of RuboCop which created ".rubocop_todo.yml" after re-generate @return [Rubocop::Rule] The corrected rule @raise [Errors::NoAutoCorrectableRule] Raises if there is no auto correctable rule in ".rubocop_todo.yml"
[ "Run", "rubocop", "challenge", "." ]
267f3b48d1a32f1ef32ab8816cefafa9ee96ea50
https://github.com/ryz310/rubocop_challenger/blob/267f3b48d1a32f1ef32ab8816cefafa9ee96ea50/lib/rubocop_challenger/go.rb#L76-L83
17,454
ryz310/rubocop_challenger
lib/rubocop_challenger/go.rb
RubocopChallenger.Go.add_to_ignore_list_if_challenge_is_incomplete
def add_to_ignore_list_if_challenge_is_incomplete(rule) return unless auto_correct_incomplete?(rule) pull_request.commit! ':police_car: add the rule to the ignore list' do config_editor = Rubocop::ConfigEditor.new config_editor.add_ignore(rule) config_editor.save end color_puts DESCRIPTION_THAT_CHALLENGE_IS_INCOMPLETE, PrComet::CommandLine::YELLOW end
ruby
def add_to_ignore_list_if_challenge_is_incomplete(rule) return unless auto_correct_incomplete?(rule) pull_request.commit! ':police_car: add the rule to the ignore list' do config_editor = Rubocop::ConfigEditor.new config_editor.add_ignore(rule) config_editor.save end color_puts DESCRIPTION_THAT_CHALLENGE_IS_INCOMPLETE, PrComet::CommandLine::YELLOW end
[ "def", "add_to_ignore_list_if_challenge_is_incomplete", "(", "rule", ")", "return", "unless", "auto_correct_incomplete?", "(", "rule", ")", "pull_request", ".", "commit!", "':police_car: add the rule to the ignore list'", "do", "config_editor", "=", "Rubocop", "::", "ConfigEditor", ".", "new", "config_editor", ".", "add_ignore", "(", "rule", ")", "config_editor", ".", "save", "end", "color_puts", "DESCRIPTION_THAT_CHALLENGE_IS_INCOMPLETE", ",", "PrComet", "::", "CommandLine", "::", "YELLOW", "end" ]
If still exist the rule after a challenge, the rule regard as cannot correct automatically then add to ignore list and it is not chosen as target rule from next time. @param rule [Rubocop::Rule] The corrected rule
[ "If", "still", "exist", "the", "rule", "after", "a", "challenge", "the", "rule", "regard", "as", "cannot", "correct", "automatically", "then", "add", "to", "ignore", "list", "and", "it", "is", "not", "chosen", "as", "target", "rule", "from", "next", "time", "." ]
267f3b48d1a32f1ef32ab8816cefafa9ee96ea50
https://github.com/ryz310/rubocop_challenger/blob/267f3b48d1a32f1ef32ab8816cefafa9ee96ea50/lib/rubocop_challenger/go.rb#L121-L131
17,455
ryz310/rubocop_challenger
lib/rubocop_challenger/go.rb
RubocopChallenger.Go.auto_correct_incomplete?
def auto_correct_incomplete?(rule) todo_reader = Rubocop::TodoReader.new(options[:file_path]) todo_reader.all_rules.include?(rule) end
ruby
def auto_correct_incomplete?(rule) todo_reader = Rubocop::TodoReader.new(options[:file_path]) todo_reader.all_rules.include?(rule) end
[ "def", "auto_correct_incomplete?", "(", "rule", ")", "todo_reader", "=", "Rubocop", "::", "TodoReader", ".", "new", "(", "options", "[", ":file_path", "]", ")", "todo_reader", ".", "all_rules", ".", "include?", "(", "rule", ")", "end" ]
Checks the challenge result. If the challenge is successed, the rule should not exist in the ".rubocop_todo.yml" after regenerate. @param rule [Rubocop::Rule] The corrected rule @return [Boolean] Return true if the challenge successed
[ "Checks", "the", "challenge", "result", ".", "If", "the", "challenge", "is", "successed", "the", "rule", "should", "not", "exist", "in", "the", ".", "rubocop_todo", ".", "yml", "after", "regenerate", "." ]
267f3b48d1a32f1ef32ab8816cefafa9ee96ea50
https://github.com/ryz310/rubocop_challenger/blob/267f3b48d1a32f1ef32ab8816cefafa9ee96ea50/lib/rubocop_challenger/go.rb#L138-L141
17,456
ryz310/rubocop_challenger
lib/rubocop_challenger/pull_request.rb
RubocopChallenger.PullRequest.create_rubocop_challenge_pr!
def create_rubocop_challenge_pr!(rule, template_file_path = nil) create_pull_request!( title: "#{rule.title}-#{timestamp}", body: Github::PrTemplate.new(rule, template_file_path).generate, labels: labels ) end
ruby
def create_rubocop_challenge_pr!(rule, template_file_path = nil) create_pull_request!( title: "#{rule.title}-#{timestamp}", body: Github::PrTemplate.new(rule, template_file_path).generate, labels: labels ) end
[ "def", "create_rubocop_challenge_pr!", "(", "rule", ",", "template_file_path", "=", "nil", ")", "create_pull_request!", "(", "title", ":", "\"#{rule.title}-#{timestamp}\"", ",", "body", ":", "Github", "::", "PrTemplate", ".", "new", "(", "rule", ",", "template_file_path", ")", ".", "generate", ",", "labels", ":", "labels", ")", "end" ]
Creates a pull request for the Rubocop Challenge @param rule [Rubocop::Rule] The corrected rule @param template_file_path [String, nil] The template file name which use to generate the pull request body @return [Boolean] Return true if its successed
[ "Creates", "a", "pull", "request", "for", "the", "Rubocop", "Challenge" ]
267f3b48d1a32f1ef32ab8816cefafa9ee96ea50
https://github.com/ryz310/rubocop_challenger/blob/267f3b48d1a32f1ef32ab8816cefafa9ee96ea50/lib/rubocop_challenger/pull_request.rb#L42-L48
17,457
ryz310/rubocop_challenger
lib/rubocop_challenger/pull_request.rb
RubocopChallenger.PullRequest.create_regenerate_todo_pr!
def create_regenerate_todo_pr!(before_version, after_version) create_pull_request!( title: "Re-generate .rubocop_todo.yml with RuboCop v#{after_version}", body: generate_pull_request_body(before_version, after_version), labels: labels ) end
ruby
def create_regenerate_todo_pr!(before_version, after_version) create_pull_request!( title: "Re-generate .rubocop_todo.yml with RuboCop v#{after_version}", body: generate_pull_request_body(before_version, after_version), labels: labels ) end
[ "def", "create_regenerate_todo_pr!", "(", "before_version", ",", "after_version", ")", "create_pull_request!", "(", "title", ":", "\"Re-generate .rubocop_todo.yml with RuboCop v#{after_version}\"", ",", "body", ":", "generate_pull_request_body", "(", "before_version", ",", "after_version", ")", ",", "labels", ":", "labels", ")", "end" ]
Creates a pull request which re-generate ".rubocop_todo.yml" with new version RuboCop. @param before_version [String] The version of RuboCop which created ".rubocop_todo.yml" before re-generate. @param after_version [String] The version of RuboCop which created ".rubocop_todo.yml" after re-generate @return [Boolean] Return true if its successed
[ "Creates", "a", "pull", "request", "which", "re", "-", "generate", ".", "rubocop_todo", ".", "yml", "with", "new", "version", "RuboCop", "." ]
267f3b48d1a32f1ef32ab8816cefafa9ee96ea50
https://github.com/ryz310/rubocop_challenger/blob/267f3b48d1a32f1ef32ab8816cefafa9ee96ea50/lib/rubocop_challenger/pull_request.rb#L61-L67
17,458
ealdent/lda-ruby
lib/lda-ruby.rb
Lda.Lda.print_topics
def print_topics(words_per_topic = 10) raise 'No vocabulary loaded.' unless @vocab beta.each_with_index do |topic, topic_num| # Sort the topic array and return the sorted indices of the best scores indices = topic.zip((0...@vocab.size).to_a).sort { |x| x[0] }.map { |_i, j| j }.reverse[0...words_per_topic] puts "Topic #{topic_num}" puts "\t#{indices.map { |i| @vocab[i] }.join("\n\t")}" puts '' end nil end
ruby
def print_topics(words_per_topic = 10) raise 'No vocabulary loaded.' unless @vocab beta.each_with_index do |topic, topic_num| # Sort the topic array and return the sorted indices of the best scores indices = topic.zip((0...@vocab.size).to_a).sort { |x| x[0] }.map { |_i, j| j }.reverse[0...words_per_topic] puts "Topic #{topic_num}" puts "\t#{indices.map { |i| @vocab[i] }.join("\n\t")}" puts '' end nil end
[ "def", "print_topics", "(", "words_per_topic", "=", "10", ")", "raise", "'No vocabulary loaded.'", "unless", "@vocab", "beta", ".", "each_with_index", "do", "|", "topic", ",", "topic_num", "|", "# Sort the topic array and return the sorted indices of the best scores", "indices", "=", "topic", ".", "zip", "(", "(", "0", "...", "@vocab", ".", "size", ")", ".", "to_a", ")", ".", "sort", "{", "|", "x", "|", "x", "[", "0", "]", "}", ".", "map", "{", "|", "_i", ",", "j", "|", "j", "}", ".", "reverse", "[", "0", "...", "words_per_topic", "]", "puts", "\"Topic #{topic_num}\"", "puts", "\"\\t#{indices.map { |i| @vocab[i] }.join(\"\\n\\t\")}\"", "puts", "''", "end", "nil", "end" ]
Visualization method for printing out the top +words_per_topic+ words for each topic. See also +top_words+.
[ "Visualization", "method", "for", "printing", "out", "the", "top", "+", "words_per_topic", "+", "words", "for", "each", "topic", "." ]
c8f5f52074cb1518822892b17c769541e1e8f7fc
https://github.com/ealdent/lda-ruby/blob/c8f5f52074cb1518822892b17c769541e1e8f7fc/lib/lda-ruby.rb#L64-L77
17,459
ealdent/lda-ruby
lib/lda-ruby.rb
Lda.Lda.to_s
def to_s outp = ['LDA Settings:'] outp << ' Initial alpha: %0.6f'.format(init_alpha) outp << ' # of topics: %d'.format(num_topics) outp << ' Max iterations: %d'.format(max_iter) outp << ' Convergence: %0.6f'.format(convergence) outp << 'EM max iterations: %d'.format(em_max_iter) outp << ' EM convergence: %0.6f'.format(em_convergence) outp << ' Estimate alpha: %d'.format(est_alpha) outp.join("\n") end
ruby
def to_s outp = ['LDA Settings:'] outp << ' Initial alpha: %0.6f'.format(init_alpha) outp << ' # of topics: %d'.format(num_topics) outp << ' Max iterations: %d'.format(max_iter) outp << ' Convergence: %0.6f'.format(convergence) outp << 'EM max iterations: %d'.format(em_max_iter) outp << ' EM convergence: %0.6f'.format(em_convergence) outp << ' Estimate alpha: %d'.format(est_alpha) outp.join("\n") end
[ "def", "to_s", "outp", "=", "[", "'LDA Settings:'", "]", "outp", "<<", "' Initial alpha: %0.6f'", ".", "format", "(", "init_alpha", ")", "outp", "<<", "' # of topics: %d'", ".", "format", "(", "num_topics", ")", "outp", "<<", "' Max iterations: %d'", ".", "format", "(", "max_iter", ")", "outp", "<<", "' Convergence: %0.6f'", ".", "format", "(", "convergence", ")", "outp", "<<", "'EM max iterations: %d'", ".", "format", "(", "em_max_iter", ")", "outp", "<<", "' EM convergence: %0.6f'", ".", "format", "(", "em_convergence", ")", "outp", "<<", "' Estimate alpha: %d'", ".", "format", "(", "est_alpha", ")", "outp", ".", "join", "(", "\"\\n\"", ")", "end" ]
String representation displaying current settings.
[ "String", "representation", "displaying", "current", "settings", "." ]
c8f5f52074cb1518822892b17c769541e1e8f7fc
https://github.com/ealdent/lda-ruby/blob/c8f5f52074cb1518822892b17c769541e1e8f7fc/lib/lda-ruby.rb#L154-L165
17,460
saturnflyer/casting
lib/casting/super_delegate.rb
Casting.SuperDelegate.super_delegate
def super_delegate(*args, &block) method_name = name_of_calling_method(caller) owner = args.first || method_delegate(method_name) super_delegate_method = unbound_method_from_next_delegate(method_name, owner) if super_delegate_method.arity == 0 super_delegate_method.bind(self).call else super_delegate_method.bind(self).call(*args, &block) end rescue NameError raise NoMethodError.new("super_delegate: no delegate method `#{method_name}' for #{self.inspect} from #{owner}") end
ruby
def super_delegate(*args, &block) method_name = name_of_calling_method(caller) owner = args.first || method_delegate(method_name) super_delegate_method = unbound_method_from_next_delegate(method_name, owner) if super_delegate_method.arity == 0 super_delegate_method.bind(self).call else super_delegate_method.bind(self).call(*args, &block) end rescue NameError raise NoMethodError.new("super_delegate: no delegate method `#{method_name}' for #{self.inspect} from #{owner}") end
[ "def", "super_delegate", "(", "*", "args", ",", "&", "block", ")", "method_name", "=", "name_of_calling_method", "(", "caller", ")", "owner", "=", "args", ".", "first", "||", "method_delegate", "(", "method_name", ")", "super_delegate_method", "=", "unbound_method_from_next_delegate", "(", "method_name", ",", "owner", ")", "if", "super_delegate_method", ".", "arity", "==", "0", "super_delegate_method", ".", "bind", "(", "self", ")", ".", "call", "else", "super_delegate_method", ".", "bind", "(", "self", ")", ".", "call", "(", "args", ",", "block", ")", "end", "rescue", "NameError", "raise", "NoMethodError", ".", "new", "(", "\"super_delegate: no delegate method `#{method_name}' for #{self.inspect} from #{owner}\"", ")", "end" ]
Call the method of the same name defined in the next delegate stored in your object Because Casting creates an alternative method lookup path using a collection of delegates, you may use `super_delegate` to work like `super`. If you use this feature, be sure that you have created a delegate collection which does have the method you need or you'll see a NoMethodError. Example: module Greeter def greet "Hello" end end module FormalGreeter include Casting::Super def greet "#{super_delegate}, how do you do?" end end some_object.cast_as(Greeter, FormalGreeter) some_object.greet #=> 'Hello, how do you do?'
[ "Call", "the", "method", "of", "the", "same", "name", "defined", "in", "the", "next", "delegate", "stored", "in", "your", "object" ]
1609cfd2979fab9fc50304275f3524257eb1a45c
https://github.com/saturnflyer/casting/blob/1609cfd2979fab9fc50304275f3524257eb1a45c/lib/casting/super_delegate.rb#L31-L44
17,461
stitchfix/merch_calendar
lib/merch_calendar/merch_week.rb
MerchCalendar.MerchWeek.merch_month
def merch_month # TODO: This is very inefficient, but less complex than strategic guessing # maybe switch to a binary search or something merch_year = calendar.merch_year_from_date(date) @merch_month ||= (1..12).detect do |num| calendar.end_of_month(merch_year, num) >= date && date >= calendar.start_of_month(merch_year, num) end end
ruby
def merch_month # TODO: This is very inefficient, but less complex than strategic guessing # maybe switch to a binary search or something merch_year = calendar.merch_year_from_date(date) @merch_month ||= (1..12).detect do |num| calendar.end_of_month(merch_year, num) >= date && date >= calendar.start_of_month(merch_year, num) end end
[ "def", "merch_month", "# TODO: This is very inefficient, but less complex than strategic guessing", "# maybe switch to a binary search or something", "merch_year", "=", "calendar", ".", "merch_year_from_date", "(", "date", ")", "@merch_month", "||=", "(", "1", "..", "12", ")", ".", "detect", "do", "|", "num", "|", "calendar", ".", "end_of_month", "(", "merch_year", ",", "num", ")", ">=", "date", "&&", "date", ">=", "calendar", ".", "start_of_month", "(", "merch_year", ",", "num", ")", "end", "end" ]
This returns the "merch month" number for a date Month 1 is Feb for the retail calendar Month 1 is August for the fiscal calendar @return [Integer]
[ "This", "returns", "the", "merch", "month", "number", "for", "a", "date", "Month", "1", "is", "Feb", "for", "the", "retail", "calendar", "Month", "1", "is", "August", "for", "the", "fiscal", "calendar" ]
b24f1f47685928eeec8e808838e2474ddf473afd
https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/merch_week.rb#L100-L107
17,462
stitchfix/merch_calendar
lib/merch_calendar/retail_calendar.rb
MerchCalendar.RetailCalendar.end_of_year
def end_of_year(year) year_end = Date.new((year + 1), Date::MONTHNAMES.index(LAST_MONTH_OF_THE_YEAR), LAST_DAY_OF_THE_YEAR) # Jan 31st wday = (year_end.wday + 1) % 7 if wday > 3 year_end += 7 - wday else year_end -= wday end year_end end
ruby
def end_of_year(year) year_end = Date.new((year + 1), Date::MONTHNAMES.index(LAST_MONTH_OF_THE_YEAR), LAST_DAY_OF_THE_YEAR) # Jan 31st wday = (year_end.wday + 1) % 7 if wday > 3 year_end += 7 - wday else year_end -= wday end year_end end
[ "def", "end_of_year", "(", "year", ")", "year_end", "=", "Date", ".", "new", "(", "(", "year", "+", "1", ")", ",", "Date", "::", "MONTHNAMES", ".", "index", "(", "LAST_MONTH_OF_THE_YEAR", ")", ",", "LAST_DAY_OF_THE_YEAR", ")", "# Jan 31st", "wday", "=", "(", "year_end", ".", "wday", "+", "1", ")", "%", "7", "if", "wday", ">", "3", "year_end", "+=", "7", "-", "wday", "else", "year_end", "-=", "wday", "end", "year_end", "end" ]
The the first date of the retail year @param year [Integer] the retail year @return [Date] the first date of the retail year
[ "The", "the", "first", "date", "of", "the", "retail", "year" ]
b24f1f47685928eeec8e808838e2474ddf473afd
https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/retail_calendar.rb#L20-L30
17,463
stitchfix/merch_calendar
lib/merch_calendar/retail_calendar.rb
MerchCalendar.RetailCalendar.start_of_month
def start_of_month(year, merch_month) # 91 = number of days in a single 4-5-4 set start = start_of_year(year) + ((merch_month - 1) / 3).to_i * 91 case merch_month when *FOUR_WEEK_MONTHS # 28 = 4 weeks start = start + 28 when *FIVE_WEEK_MONTHS # The 5 week months # 63 = 4 weeks + 5 weeks start = start + 63 end start end
ruby
def start_of_month(year, merch_month) # 91 = number of days in a single 4-5-4 set start = start_of_year(year) + ((merch_month - 1) / 3).to_i * 91 case merch_month when *FOUR_WEEK_MONTHS # 28 = 4 weeks start = start + 28 when *FIVE_WEEK_MONTHS # The 5 week months # 63 = 4 weeks + 5 weeks start = start + 63 end start end
[ "def", "start_of_month", "(", "year", ",", "merch_month", ")", "# 91 = number of days in a single 4-5-4 set ", "start", "=", "start_of_year", "(", "year", ")", "+", "(", "(", "merch_month", "-", "1", ")", "/", "3", ")", ".", "to_i", "*", "91", "case", "merch_month", "when", "FOUR_WEEK_MONTHS", "# 28 = 4 weeks", "start", "=", "start", "+", "28", "when", "FIVE_WEEK_MONTHS", "# The 5 week months", "# 63 = 4 weeks + 5 weeks", "start", "=", "start", "+", "63", "end", "start", "end" ]
The starting date of the given merch month @param year [Integer] the retail year @param merch_month [Integer] the nth merch month of the retail calendar @return [Date] the start date of the merch month
[ "The", "starting", "date", "of", "the", "given", "merch", "month" ]
b24f1f47685928eeec8e808838e2474ddf473afd
https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/retail_calendar.rb#L45-L60
17,464
stitchfix/merch_calendar
lib/merch_calendar/retail_calendar.rb
MerchCalendar.RetailCalendar.start_of_quarter
def start_of_quarter(year, quarter) case quarter when QUARTER_1 start_of_month(year, 1) when QUARTER_2 start_of_month(year, 4) when QUARTER_3 start_of_month(year, 7) when QUARTER_4 start_of_month(year, 10) else raise "invalid quarter" end end
ruby
def start_of_quarter(year, quarter) case quarter when QUARTER_1 start_of_month(year, 1) when QUARTER_2 start_of_month(year, 4) when QUARTER_3 start_of_month(year, 7) when QUARTER_4 start_of_month(year, 10) else raise "invalid quarter" end end
[ "def", "start_of_quarter", "(", "year", ",", "quarter", ")", "case", "quarter", "when", "QUARTER_1", "start_of_month", "(", "year", ",", "1", ")", "when", "QUARTER_2", "start_of_month", "(", "year", ",", "4", ")", "when", "QUARTER_3", "start_of_month", "(", "year", ",", "7", ")", "when", "QUARTER_4", "start_of_month", "(", "year", ",", "10", ")", "else", "raise", "\"invalid quarter\"", "end", "end" ]
Return the starting date for a particular quarter @param year [Integer] the retail year @param quarter [Integer] the quarter of the year, a number from 1 - 4 @return [Date] the start date of the quarter
[ "Return", "the", "starting", "date", "for", "a", "particular", "quarter" ]
b24f1f47685928eeec8e808838e2474ddf473afd
https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/retail_calendar.rb#L100-L113
17,465
stitchfix/merch_calendar
lib/merch_calendar/retail_calendar.rb
MerchCalendar.RetailCalendar.end_of_quarter
def end_of_quarter(year, quarter) case quarter when QUARTER_1 end_of_month(year, 3) when QUARTER_2 end_of_month(year, 6) when QUARTER_3 end_of_month(year, 9) when QUARTER_4 end_of_month(year, 12) else raise "invalid quarter" end end
ruby
def end_of_quarter(year, quarter) case quarter when QUARTER_1 end_of_month(year, 3) when QUARTER_2 end_of_month(year, 6) when QUARTER_3 end_of_month(year, 9) when QUARTER_4 end_of_month(year, 12) else raise "invalid quarter" end end
[ "def", "end_of_quarter", "(", "year", ",", "quarter", ")", "case", "quarter", "when", "QUARTER_1", "end_of_month", "(", "year", ",", "3", ")", "when", "QUARTER_2", "end_of_month", "(", "year", ",", "6", ")", "when", "QUARTER_3", "end_of_month", "(", "year", ",", "9", ")", "when", "QUARTER_4", "end_of_month", "(", "year", ",", "12", ")", "else", "raise", "\"invalid quarter\"", "end", "end" ]
Return the ending date for a particular quarter @param year [Integer] the retail year @param quarter [Integer] the quarter of the year, a number from 1 - 4 @return [Date] the end date of the quarter
[ "Return", "the", "ending", "date", "for", "a", "particular", "quarter" ]
b24f1f47685928eeec8e808838e2474ddf473afd
https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/retail_calendar.rb#L120-L133
17,466
stitchfix/merch_calendar
lib/merch_calendar/retail_calendar.rb
MerchCalendar.RetailCalendar.merch_year_from_date
def merch_year_from_date(date) date_end_of_year = end_of_year(date.year) date_start_of_year = start_of_year(date.year) if date < date_start_of_year date.year - 1 else date.year end end
ruby
def merch_year_from_date(date) date_end_of_year = end_of_year(date.year) date_start_of_year = start_of_year(date.year) if date < date_start_of_year date.year - 1 else date.year end end
[ "def", "merch_year_from_date", "(", "date", ")", "date_end_of_year", "=", "end_of_year", "(", "date", ".", "year", ")", "date_start_of_year", "=", "start_of_year", "(", "date", ".", "year", ")", "if", "date", "<", "date_start_of_year", "date", ".", "year", "-", "1", "else", "date", ".", "year", "end", "end" ]
Given any julian date it will return what retail year it belongs to @param date [Date] the julian date to convert to its Retail Year @return [Integer] the retail year that the julian date falls into
[ "Given", "any", "julian", "date", "it", "will", "return", "what", "retail", "year", "it", "belongs", "to" ]
b24f1f47685928eeec8e808838e2474ddf473afd
https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/retail_calendar.rb#L181-L189
17,467
stitchfix/merch_calendar
lib/merch_calendar/retail_calendar.rb
MerchCalendar.RetailCalendar.merch_months_in
def merch_months_in(start_date, end_date) merch_months = [] prev_date = start_date - 2 date = start_date while date <= end_date do date = MerchCalendar.start_of_month(date.year, merch_month: date.month) next if prev_date == date merch_months.push(date) prev_date = date date += 14 end merch_months end
ruby
def merch_months_in(start_date, end_date) merch_months = [] prev_date = start_date - 2 date = start_date while date <= end_date do date = MerchCalendar.start_of_month(date.year, merch_month: date.month) next if prev_date == date merch_months.push(date) prev_date = date date += 14 end merch_months end
[ "def", "merch_months_in", "(", "start_date", ",", "end_date", ")", "merch_months", "=", "[", "]", "prev_date", "=", "start_date", "-", "2", "date", "=", "start_date", "while", "date", "<=", "end_date", "do", "date", "=", "MerchCalendar", ".", "start_of_month", "(", "date", ".", "year", ",", "merch_month", ":", "date", ".", "month", ")", "next", "if", "prev_date", "==", "date", "merch_months", ".", "push", "(", "date", ")", "prev_date", "=", "date", "date", "+=", "14", "end", "merch_months", "end" ]
Given beginning and end dates it will return an array of Retail Month's Start date @param start_date [Date] the starting date @param end_date [Date] the ending date @return [Array] Array of start dates of each Retail Month from given dates
[ "Given", "beginning", "and", "end", "dates", "it", "will", "return", "an", "array", "of", "Retail", "Month", "s", "Start", "date" ]
b24f1f47685928eeec8e808838e2474ddf473afd
https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/retail_calendar.rb#L229-L241
17,468
stitchfix/merch_calendar
lib/merch_calendar/retail_calendar.rb
MerchCalendar.RetailCalendar.weeks_for_month
def weeks_for_month(year, month_param) merch_month = get_merch_month_param(month_param) start_date = start_of_month(year, merch_month) weeks = (end_of_month(year, merch_month) - start_date + 1) / 7 (1..weeks).map do |week_num| week_start = start_date + ((week_num - 1) * 7) week_end = week_start + 6 MerchWeek.new(week_start, { start_of_week: week_start, end_of_week: week_end, week: week_num, calendar: RetailCalendar.new }) end end
ruby
def weeks_for_month(year, month_param) merch_month = get_merch_month_param(month_param) start_date = start_of_month(year, merch_month) weeks = (end_of_month(year, merch_month) - start_date + 1) / 7 (1..weeks).map do |week_num| week_start = start_date + ((week_num - 1) * 7) week_end = week_start + 6 MerchWeek.new(week_start, { start_of_week: week_start, end_of_week: week_end, week: week_num, calendar: RetailCalendar.new }) end end
[ "def", "weeks_for_month", "(", "year", ",", "month_param", ")", "merch_month", "=", "get_merch_month_param", "(", "month_param", ")", "start_date", "=", "start_of_month", "(", "year", ",", "merch_month", ")", "weeks", "=", "(", "end_of_month", "(", "year", ",", "merch_month", ")", "-", "start_date", "+", "1", ")", "/", "7", "(", "1", "..", "weeks", ")", ".", "map", "do", "|", "week_num", "|", "week_start", "=", "start_date", "+", "(", "(", "week_num", "-", "1", ")", "*", "7", ")", "week_end", "=", "week_start", "+", "6", "MerchWeek", ".", "new", "(", "week_start", ",", "{", "start_of_week", ":", "week_start", ",", "end_of_week", ":", "week_end", ",", "week", ":", "week_num", ",", "calendar", ":", "RetailCalendar", ".", "new", "}", ")", "end", "end" ]
Returns an array of Merch Weeks that pertains to the Julian Month of a Retail Year @param year [Integer] the Retail year @param month_param [Integer] the julian month @return [Array] Array of MerchWeeks
[ "Returns", "an", "array", "of", "Merch", "Weeks", "that", "pertains", "to", "the", "Julian", "Month", "of", "a", "Retail", "Year" ]
b24f1f47685928eeec8e808838e2474ddf473afd
https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/retail_calendar.rb#L248-L266
17,469
stitchfix/merch_calendar
lib/merch_calendar/stitch_fix_fiscal_year_calendar.rb
MerchCalendar.StitchFixFiscalYearCalendar.merch_year_from_date
def merch_year_from_date(date) if end_of_year(date.year) >= date return date.year else return date.year + 1 end end
ruby
def merch_year_from_date(date) if end_of_year(date.year) >= date return date.year else return date.year + 1 end end
[ "def", "merch_year_from_date", "(", "date", ")", "if", "end_of_year", "(", "date", ".", "year", ")", ">=", "date", "return", "date", ".", "year", "else", "return", "date", ".", "year", "+", "1", "end", "end" ]
Given any julian date it will return what Fiscal Year it belongs to @param date [Date] the julian date to convert to its Fiscal Year @return [Integer] the fiscal year that the julian date falls into
[ "Given", "any", "julian", "date", "it", "will", "return", "what", "Fiscal", "Year", "it", "belongs", "to" ]
b24f1f47685928eeec8e808838e2474ddf473afd
https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/stitch_fix_fiscal_year_calendar.rb#L179-L185
17,470
stitchfix/merch_calendar
lib/merch_calendar/stitch_fix_fiscal_year_calendar.rb
MerchCalendar.StitchFixFiscalYearCalendar.merch_months_in
def merch_months_in(start_date, end_date) merch_months_combos = merch_year_and_month_from_dates(start_date, end_date) merch_months_combos.map { | merch_month_combo | start_of_month(merch_month_combo[0], merch_month_combo[1]) } end
ruby
def merch_months_in(start_date, end_date) merch_months_combos = merch_year_and_month_from_dates(start_date, end_date) merch_months_combos.map { | merch_month_combo | start_of_month(merch_month_combo[0], merch_month_combo[1]) } end
[ "def", "merch_months_in", "(", "start_date", ",", "end_date", ")", "merch_months_combos", "=", "merch_year_and_month_from_dates", "(", "start_date", ",", "end_date", ")", "merch_months_combos", ".", "map", "{", "|", "merch_month_combo", "|", "start_of_month", "(", "merch_month_combo", "[", "0", "]", ",", "merch_month_combo", "[", "1", "]", ")", "}", "end" ]
Given beginning and end dates it will return an array of Fiscal Month's Start date @param start_date [Date] the starting date @param end_date [Date] the ending date @return [Array] Array of start dates of each Fiscal Month from given dates
[ "Given", "beginning", "and", "end", "dates", "it", "will", "return", "an", "array", "of", "Fiscal", "Month", "s", "Start", "date" ]
b24f1f47685928eeec8e808838e2474ddf473afd
https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/stitch_fix_fiscal_year_calendar.rb#L224-L227
17,471
stitchfix/merch_calendar
lib/merch_calendar/stitch_fix_fiscal_year_calendar.rb
MerchCalendar.StitchFixFiscalYearCalendar.merch_year_and_month_from_dates
def merch_year_and_month_from_dates(start_date, end_date) merch_months = [] middle_of_start_month = Date.new(start_date.year, start_date.month, 14) middle_of_end_month = Date.new(end_date.year, end_date.month, 14) date = middle_of_start_month while date <= middle_of_end_month do merch_months.push(date_conversion(date)) date = date >> 1 end merch_months end
ruby
def merch_year_and_month_from_dates(start_date, end_date) merch_months = [] middle_of_start_month = Date.new(start_date.year, start_date.month, 14) middle_of_end_month = Date.new(end_date.year, end_date.month, 14) date = middle_of_start_month while date <= middle_of_end_month do merch_months.push(date_conversion(date)) date = date >> 1 end merch_months end
[ "def", "merch_year_and_month_from_dates", "(", "start_date", ",", "end_date", ")", "merch_months", "=", "[", "]", "middle_of_start_month", "=", "Date", ".", "new", "(", "start_date", ".", "year", ",", "start_date", ".", "month", ",", "14", ")", "middle_of_end_month", "=", "Date", ".", "new", "(", "end_date", ".", "year", ",", "end_date", ".", "month", ",", "14", ")", "date", "=", "middle_of_start_month", "while", "date", "<=", "middle_of_end_month", "do", "merch_months", ".", "push", "(", "date_conversion", "(", "date", ")", ")", "date", "=", "date", ">>", "1", "end", "merch_months", "end" ]
Returns an array of merch_months and year combination that falls in and between the start and end date Ex: if start_date = August 1, 2018 and end_date = October 1, 2018 it returns [[2019, 1], [ 2019, 2], [2019, 3]]
[ "Returns", "an", "array", "of", "merch_months", "and", "year", "combination", "that", "falls", "in", "and", "between", "the", "start", "and", "end", "date" ]
b24f1f47685928eeec8e808838e2474ddf473afd
https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/stitch_fix_fiscal_year_calendar.rb#L260-L272
17,472
stitchfix/merch_calendar
lib/merch_calendar/util.rb
MerchCalendar.Util.start_of_week
def start_of_week(year, month, week) retail_calendar.start_of_week(year, julian_to_merch(month), week) end
ruby
def start_of_week(year, month, week) retail_calendar.start_of_week(year, julian_to_merch(month), week) end
[ "def", "start_of_week", "(", "year", ",", "month", ",", "week", ")", "retail_calendar", ".", "start_of_week", "(", "year", ",", "julian_to_merch", "(", "month", ")", ",", "week", ")", "end" ]
The start date of the week @param year [Integer] the merch year @param month [Integer] an integer specifying the julian month. @param week [Integer] an integer specifying the merch week. @return [Date] the starting date of the specified week
[ "The", "start", "date", "of", "the", "week" ]
b24f1f47685928eeec8e808838e2474ddf473afd
https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/util.rb#L16-L18
17,473
stitchfix/merch_calendar
lib/merch_calendar/util.rb
MerchCalendar.Util.end_of_week
def end_of_week(year, month, week) retail_calendar.end_of_week(year, julian_to_merch(month), week) end
ruby
def end_of_week(year, month, week) retail_calendar.end_of_week(year, julian_to_merch(month), week) end
[ "def", "end_of_week", "(", "year", ",", "month", ",", "week", ")", "retail_calendar", ".", "end_of_week", "(", "year", ",", "julian_to_merch", "(", "month", ")", ",", "week", ")", "end" ]
The end date of the week @param year [Integer] the merch year @param month [Integer] an integer specifying the julian month. @param week [Integer] an integer specifying the merch week. @return [Date] the ending date of the specified week
[ "The", "end", "date", "of", "the", "week" ]
b24f1f47685928eeec8e808838e2474ddf473afd
https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/util.rb#L27-L29
17,474
stitchfix/merch_calendar
lib/merch_calendar/util.rb
MerchCalendar.Util.start_of_month
def start_of_month(year, month_param) merch_month = get_merch_month_param(month_param) retail_calendar.start_of_month(year, merch_month) end
ruby
def start_of_month(year, month_param) merch_month = get_merch_month_param(month_param) retail_calendar.start_of_month(year, merch_month) end
[ "def", "start_of_month", "(", "year", ",", "month_param", ")", "merch_month", "=", "get_merch_month_param", "(", "month_param", ")", "retail_calendar", ".", "start_of_month", "(", "year", ",", "merch_month", ")", "end" ]
The start date of the month @example # The following are all equivalent, and refer to May 2015 MerchCalendar.start_of_month(2015, 5) MerchCalendar.start_of_month(2015, month: 5) MerchCalendar.start_of_month(2015, julian_month: 5) MerchCalendar.start_of_month(2015, merch_month: 4) @param year [Integer] the merch year @param month_param [Integer,Hash] an integer specifying the julian month. This can also be a named hash @option month_param [Integer] :month the julian month @option month_param [Integer] :julian_month the julian month @option month_param [Integer] :merch_month the MERCH month @return [Date] the starting date of the specified month
[ "The", "start", "date", "of", "the", "month" ]
b24f1f47685928eeec8e808838e2474ddf473afd
https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/util.rb#L47-L50
17,475
stitchfix/merch_calendar
lib/merch_calendar/util.rb
MerchCalendar.Util.end_of_month
def end_of_month(year, month_param) merch_month = get_merch_month_param(month_param) retail_calendar.end_of_month(year, merch_month) end
ruby
def end_of_month(year, month_param) merch_month = get_merch_month_param(month_param) retail_calendar.end_of_month(year, merch_month) end
[ "def", "end_of_month", "(", "year", ",", "month_param", ")", "merch_month", "=", "get_merch_month_param", "(", "month_param", ")", "retail_calendar", ".", "end_of_month", "(", "year", ",", "merch_month", ")", "end" ]
The end date of the month @param year [Integer] the merch year @param month_param [Hash] month hash @see #start_of_month The start_of_month method for examples using month_param @return [Date]
[ "The", "end", "date", "of", "the", "month" ]
b24f1f47685928eeec8e808838e2474ddf473afd
https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/util.rb#L60-L63
17,476
LeFnord/grape-starter
lib/starter/builder/base_file.rb
Starter.BaseFile.add_to_base
def add_to_base(file) occurence = file.scan(/(\s+mount\s.*?\n)/).last.first replacement = occurence + mount_point file.sub!(occurence, replacement) end
ruby
def add_to_base(file) occurence = file.scan(/(\s+mount\s.*?\n)/).last.first replacement = occurence + mount_point file.sub!(occurence, replacement) end
[ "def", "add_to_base", "(", "file", ")", "occurence", "=", "file", ".", "scan", "(", "/", "\\s", "\\s", "\\n", "/", ")", ".", "last", ".", "first", "replacement", "=", "occurence", "+", "mount_point", "file", ".", "sub!", "(", "occurence", ",", "replacement", ")", "end" ]
adding mount point to base class
[ "adding", "mount", "point", "to", "base", "class" ]
f7c967143519e408617bba6d761a53f81b60fd6e
https://github.com/LeFnord/grape-starter/blob/f7c967143519e408617bba6d761a53f81b60fd6e/lib/starter/builder/base_file.rb#L11-L15
17,477
iZettle/ninetails
app/components/ninetails/element.rb
Ninetails.Element.valid?
def valid? validations = properties_instances.collect do |property_type| if property_type.property.respond_to?(:valid?) property_type.property.valid? else true end end validations.all? end
ruby
def valid? validations = properties_instances.collect do |property_type| if property_type.property.respond_to?(:valid?) property_type.property.valid? else true end end validations.all? end
[ "def", "valid?", "validations", "=", "properties_instances", ".", "collect", "do", "|", "property_type", "|", "if", "property_type", ".", "property", ".", "respond_to?", "(", ":valid?", ")", "property_type", ".", "property", ".", "valid?", "else", "true", "end", "end", "validations", ".", "all?", "end" ]
Validate each property_type's property. If the property_type doesn't respond to valid?, then it means it must be a native type, or at least not something which inherits Ninetails::Property, so we will class it as valid blindly.
[ "Validate", "each", "property_type", "s", "property", "." ]
a1e7c05db0b3d01ac86f5bd8382ea951cf8895c7
https://github.com/iZettle/ninetails/blob/a1e7c05db0b3d01ac86f5bd8382ea951cf8895c7/app/components/ninetails/element.rb#L25-L35
17,478
iZettle/ninetails
app/models/ninetails/content_section.rb
Ninetails.ContentSection.store_settings
def store_settings(settings_hash) settings_hash.each do |key, value| section.public_send "#{key}=", value end self.settings = section.attributes end
ruby
def store_settings(settings_hash) settings_hash.each do |key, value| section.public_send "#{key}=", value end self.settings = section.attributes end
[ "def", "store_settings", "(", "settings_hash", ")", "settings_hash", ".", "each", "do", "|", "key", ",", "value", "|", "section", ".", "public_send", "\"#{key}=\"", ",", "value", "end", "self", ".", "settings", "=", "section", ".", "attributes", "end" ]
Because the submitted data is always strings, send everything through virtus attrs so it gets cast to the correct class. Then, use the newly cast attributes to store in the settings json blob
[ "Because", "the", "submitted", "data", "is", "always", "strings", "send", "everything", "through", "virtus", "attrs", "so", "it", "gets", "cast", "to", "the", "correct", "class", "." ]
a1e7c05db0b3d01ac86f5bd8382ea951cf8895c7
https://github.com/iZettle/ninetails/blob/a1e7c05db0b3d01ac86f5bd8382ea951cf8895c7/app/models/ninetails/content_section.rb#L42-L48
17,479
iZettle/ninetails
app/models/ninetails/revision.rb
Ninetails.Revision.sections_are_all_valid
def sections_are_all_valid sections.each do |section| unless section.valid? errors.add :base, section.errors.messages[:base] end end end
ruby
def sections_are_all_valid sections.each do |section| unless section.valid? errors.add :base, section.errors.messages[:base] end end end
[ "def", "sections_are_all_valid", "sections", ".", "each", "do", "|", "section", "|", "unless", "section", ".", "valid?", "errors", ".", "add", ":base", ",", "section", ".", "errors", ".", "messages", "[", ":base", "]", "end", "end", "end" ]
Validate all sections and rebuild the sections array with the instances which now contain error messages
[ "Validate", "all", "sections", "and", "rebuild", "the", "sections", "array", "with", "the", "instances", "which", "now", "contain", "error", "messages" ]
a1e7c05db0b3d01ac86f5bd8382ea951cf8895c7
https://github.com/iZettle/ninetails/blob/a1e7c05db0b3d01ac86f5bd8382ea951cf8895c7/app/models/ninetails/revision.rb#L21-L27
17,480
iZettle/ninetails
app/models/ninetails/revision.rb
Ninetails.Revision.url_is_unique
def url_is_unique if container.is_a?(Page) && url.present? url_exists = Ninetails::Container. where.not(id: container.id). includes(:current_revision). where(ninetails_revisions: { url: url }). exists? errors.add :url, "is already in use" if url_exists end end
ruby
def url_is_unique if container.is_a?(Page) && url.present? url_exists = Ninetails::Container. where.not(id: container.id). includes(:current_revision). where(ninetails_revisions: { url: url }). exists? errors.add :url, "is already in use" if url_exists end end
[ "def", "url_is_unique", "if", "container", ".", "is_a?", "(", "Page", ")", "&&", "url", ".", "present?", "url_exists", "=", "Ninetails", "::", "Container", ".", "where", ".", "not", "(", "id", ":", "container", ".", "id", ")", ".", "includes", "(", ":current_revision", ")", ".", "where", "(", "ninetails_revisions", ":", "{", "url", ":", "url", "}", ")", ".", "exists?", "errors", ".", "add", ":url", ",", "\"is already in use\"", "if", "url_exists", "end", "end" ]
Check the url is unique across revisions, but only if a container has a matching revision set as its `current_revision`. Otherwise it'd be impossible to change one page's url to a url which was previously used by another page in the past.
[ "Check", "the", "url", "is", "unique", "across", "revisions", "but", "only", "if", "a", "container", "has", "a", "matching", "revision", "set", "as", "its", "current_revision", ".", "Otherwise", "it", "d", "be", "impossible", "to", "change", "one", "page", "s", "url", "to", "a", "url", "which", "was", "previously", "used", "by", "another", "page", "in", "the", "past", "." ]
a1e7c05db0b3d01ac86f5bd8382ea951cf8895c7
https://github.com/iZettle/ninetails/blob/a1e7c05db0b3d01ac86f5bd8382ea951cf8895c7/app/models/ninetails/revision.rb#L42-L52
17,481
bdurand/lumberjack
lib/lumberjack/formatter.rb
Lumberjack.Formatter.add
def add(klass, formatter = nil, &block) formatter ||= block if formatter.is_a?(Symbol) formatter_class_name = "#{formatter.to_s.gsub(/(^|_)([a-z])/){|m| $~[2].upcase}}Formatter" formatter = Formatter.const_get(formatter_class_name).new end @class_formatters[klass] = formatter self end
ruby
def add(klass, formatter = nil, &block) formatter ||= block if formatter.is_a?(Symbol) formatter_class_name = "#{formatter.to_s.gsub(/(^|_)([a-z])/){|m| $~[2].upcase}}Formatter" formatter = Formatter.const_get(formatter_class_name).new end @class_formatters[klass] = formatter self end
[ "def", "add", "(", "klass", ",", "formatter", "=", "nil", ",", "&", "block", ")", "formatter", "||=", "block", "if", "formatter", ".", "is_a?", "(", "Symbol", ")", "formatter_class_name", "=", "\"#{formatter.to_s.gsub(/(^|_)([a-z])/){|m| $~[2].upcase}}Formatter\"", "formatter", "=", "Formatter", ".", "const_get", "(", "formatter_class_name", ")", ".", "new", "end", "@class_formatters", "[", "klass", "]", "=", "formatter", "self", "end" ]
Add a formatter for a class. The formatter can be specified as either an object that responds to the +call+ method or as a symbol representing one of the predefined formatters, or as a block to the method call. The predefined formatters are: <tt>:inspect</tt>, <tt>:string</tt>, <tt>:exception</tt>, and <tt>:pretty_print</tt>. === Examples # Use a predefined formatter formatter.add(MyClass, :pretty_print) # Pass in a formatter object formatter.add(MyClass, Lumberjack::Formatter::PrettyPrintFormatter.new) # Use a block formatter.add(MyClass){|obj| obj.humanize} # Add statements can be chained together formatter.add(MyClass, :pretty_print).add(YourClass){|obj| obj.humanize}
[ "Add", "a", "formatter", "for", "a", "class", ".", "The", "formatter", "can", "be", "specified", "as", "either", "an", "object", "that", "responds", "to", "the", "+", "call", "+", "method", "or", "as", "a", "symbol", "representing", "one", "of", "the", "predefined", "formatters", "or", "as", "a", "block", "to", "the", "method", "call", "." ]
04b44186433223d110dc95374851e26b888a8855
https://github.com/bdurand/lumberjack/blob/04b44186433223d110dc95374851e26b888a8855/lib/lumberjack/formatter.rb#L45-L53
17,482
bdurand/lumberjack
lib/lumberjack/formatter.rb
Lumberjack.Formatter.formatter_for
def formatter_for(klass) #:nodoc: while klass != nil do formatter = @class_formatters[klass] return formatter if formatter klass = klass.superclass end @_default_formatter end
ruby
def formatter_for(klass) #:nodoc: while klass != nil do formatter = @class_formatters[klass] return formatter if formatter klass = klass.superclass end @_default_formatter end
[ "def", "formatter_for", "(", "klass", ")", "#:nodoc:", "while", "klass", "!=", "nil", "do", "formatter", "=", "@class_formatters", "[", "klass", "]", "return", "formatter", "if", "formatter", "klass", "=", "klass", ".", "superclass", "end", "@_default_formatter", "end" ]
Find the formatter for a class by looking it up using the class hierarchy.
[ "Find", "the", "formatter", "for", "a", "class", "by", "looking", "it", "up", "using", "the", "class", "hierarchy", "." ]
04b44186433223d110dc95374851e26b888a8855
https://github.com/bdurand/lumberjack/blob/04b44186433223d110dc95374851e26b888a8855/lib/lumberjack/formatter.rb#L74-L81
17,483
bdurand/lumberjack
lib/lumberjack/logger.rb
Lumberjack.Logger.add
def add(severity, message = nil, progname = nil) severity = Severity.label_to_level(severity) if severity.is_a?(String) || severity.is_a?(Symbol) return unless severity && severity >= level time = Time.now if message.nil? if block_given? message = yield else message = progname progname = nil end end message = @_formatter.format(message) progname ||= self.progname entry = LogEntry.new(time, severity, message, progname, $$, Lumberjack.unit_of_work_id) begin device.write(entry) rescue => e $stderr.puts("#{e.class.name}: #{e.message}#{' at ' + e.backtrace.first if e.backtrace}") $stderr.puts(entry.to_s) end nil end
ruby
def add(severity, message = nil, progname = nil) severity = Severity.label_to_level(severity) if severity.is_a?(String) || severity.is_a?(Symbol) return unless severity && severity >= level time = Time.now if message.nil? if block_given? message = yield else message = progname progname = nil end end message = @_formatter.format(message) progname ||= self.progname entry = LogEntry.new(time, severity, message, progname, $$, Lumberjack.unit_of_work_id) begin device.write(entry) rescue => e $stderr.puts("#{e.class.name}: #{e.message}#{' at ' + e.backtrace.first if e.backtrace}") $stderr.puts(entry.to_s) end nil end
[ "def", "add", "(", "severity", ",", "message", "=", "nil", ",", "progname", "=", "nil", ")", "severity", "=", "Severity", ".", "label_to_level", "(", "severity", ")", "if", "severity", ".", "is_a?", "(", "String", ")", "||", "severity", ".", "is_a?", "(", "Symbol", ")", "return", "unless", "severity", "&&", "severity", ">=", "level", "time", "=", "Time", ".", "now", "if", "message", ".", "nil?", "if", "block_given?", "message", "=", "yield", "else", "message", "=", "progname", "progname", "=", "nil", "end", "end", "message", "=", "@_formatter", ".", "format", "(", "message", ")", "progname", "||=", "self", ".", "progname", "entry", "=", "LogEntry", ".", "new", "(", "time", ",", "severity", ",", "message", ",", "progname", ",", "$$", ",", "Lumberjack", ".", "unit_of_work_id", ")", "begin", "device", ".", "write", "(", "entry", ")", "rescue", "=>", "e", "$stderr", ".", "puts", "(", "\"#{e.class.name}: #{e.message}#{' at ' + e.backtrace.first if e.backtrace}\"", ")", "$stderr", ".", "puts", "(", "entry", ".", "to_s", ")", "end", "nil", "end" ]
Add a message to the log with a given severity. The message can be either passed in the +message+ argument or supplied with a block. This method is not normally called. Instead call one of the helper functions +fatal+, +error+, +warn+, +info+, or +debug+. The severity can be passed in either as one of the Severity constants, or as a Severity label. === Example logger.add(Lumberjack::Severity::ERROR, exception) logger.add(Lumberjack::Severity::INFO, "Request completed") logger.add(:warn, "Request took a long time") logger.add(Lumberjack::Severity::DEBUG){"Start processing with options #{options.inspect}"}
[ "Add", "a", "message", "to", "the", "log", "with", "a", "given", "severity", ".", "The", "message", "can", "be", "either", "passed", "in", "the", "+", "message", "+", "argument", "or", "supplied", "with", "a", "block", ".", "This", "method", "is", "not", "normally", "called", ".", "Instead", "call", "one", "of", "the", "helper", "functions", "+", "fatal", "+", "+", "error", "+", "+", "warn", "+", "+", "info", "+", "or", "+", "debug", "+", "." ]
04b44186433223d110dc95374851e26b888a8855
https://github.com/bdurand/lumberjack/blob/04b44186433223d110dc95374851e26b888a8855/lib/lumberjack/logger.rb#L101-L127
17,484
bdurand/lumberjack
lib/lumberjack/logger.rb
Lumberjack.Logger.set_thread_local_value
def set_thread_local_value(name, value) #:nodoc: values = Thread.current[name] unless values values = {} Thread.current[name] = values end if value.nil? values.delete(self) Thread.current[name] = nil if values.empty? else values[self] = value end end
ruby
def set_thread_local_value(name, value) #:nodoc: values = Thread.current[name] unless values values = {} Thread.current[name] = values end if value.nil? values.delete(self) Thread.current[name] = nil if values.empty? else values[self] = value end end
[ "def", "set_thread_local_value", "(", "name", ",", "value", ")", "#:nodoc:", "values", "=", "Thread", ".", "current", "[", "name", "]", "unless", "values", "values", "=", "{", "}", "Thread", ".", "current", "[", "name", "]", "=", "values", "end", "if", "value", ".", "nil?", "values", ".", "delete", "(", "self", ")", "Thread", ".", "current", "[", "name", "]", "=", "nil", "if", "values", ".", "empty?", "else", "values", "[", "self", "]", "=", "value", "end", "end" ]
Set a local value for a thread tied to this object.
[ "Set", "a", "local", "value", "for", "a", "thread", "tied", "to", "this", "object", "." ]
04b44186433223d110dc95374851e26b888a8855
https://github.com/bdurand/lumberjack/blob/04b44186433223d110dc95374851e26b888a8855/lib/lumberjack/logger.rb#L246-L258
17,485
bdurand/lumberjack
lib/lumberjack/logger.rb
Lumberjack.Logger.push_thread_local_value
def push_thread_local_value(name, value) #:nodoc: save_val = thread_local_value(name) set_thread_local_value(name, value) begin yield ensure set_thread_local_value(name, save_val) end end
ruby
def push_thread_local_value(name, value) #:nodoc: save_val = thread_local_value(name) set_thread_local_value(name, value) begin yield ensure set_thread_local_value(name, save_val) end end
[ "def", "push_thread_local_value", "(", "name", ",", "value", ")", "#:nodoc:", "save_val", "=", "thread_local_value", "(", "name", ")", "set_thread_local_value", "(", "name", ",", "value", ")", "begin", "yield", "ensure", "set_thread_local_value", "(", "name", ",", "save_val", ")", "end", "end" ]
Set a local value for a thread tied to this object within a block.
[ "Set", "a", "local", "value", "for", "a", "thread", "tied", "to", "this", "object", "within", "a", "block", "." ]
04b44186433223d110dc95374851e26b888a8855
https://github.com/bdurand/lumberjack/blob/04b44186433223d110dc95374851e26b888a8855/lib/lumberjack/logger.rb#L267-L275
17,486
bdurand/lumberjack
lib/lumberjack/logger.rb
Lumberjack.Logger.open_device
def open_device(device, options) #:nodoc: if device.is_a?(Device) device elsif device.respond_to?(:write) && device.respond_to?(:flush) Device::Writer.new(device, options) elsif device == :null Device::Null.new else device = device.to_s if options[:roll] Device::DateRollingLogFile.new(device, options) elsif options[:max_size] Device::SizeRollingLogFile.new(device, options) else Device::LogFile.new(device, options) end end end
ruby
def open_device(device, options) #:nodoc: if device.is_a?(Device) device elsif device.respond_to?(:write) && device.respond_to?(:flush) Device::Writer.new(device, options) elsif device == :null Device::Null.new else device = device.to_s if options[:roll] Device::DateRollingLogFile.new(device, options) elsif options[:max_size] Device::SizeRollingLogFile.new(device, options) else Device::LogFile.new(device, options) end end end
[ "def", "open_device", "(", "device", ",", "options", ")", "#:nodoc:", "if", "device", ".", "is_a?", "(", "Device", ")", "device", "elsif", "device", ".", "respond_to?", "(", ":write", ")", "&&", "device", ".", "respond_to?", "(", ":flush", ")", "Device", "::", "Writer", ".", "new", "(", "device", ",", "options", ")", "elsif", "device", "==", ":null", "Device", "::", "Null", ".", "new", "else", "device", "=", "device", ".", "to_s", "if", "options", "[", ":roll", "]", "Device", "::", "DateRollingLogFile", ".", "new", "(", "device", ",", "options", ")", "elsif", "options", "[", ":max_size", "]", "Device", "::", "SizeRollingLogFile", ".", "new", "(", "device", ",", "options", ")", "else", "Device", "::", "LogFile", ".", "new", "(", "device", ",", "options", ")", "end", "end", "end" ]
Open a logging device.
[ "Open", "a", "logging", "device", "." ]
04b44186433223d110dc95374851e26b888a8855
https://github.com/bdurand/lumberjack/blob/04b44186433223d110dc95374851e26b888a8855/lib/lumberjack/logger.rb#L278-L295
17,487
bdurand/lumberjack
lib/lumberjack/logger.rb
Lumberjack.Logger.create_flusher_thread
def create_flusher_thread(flush_seconds) #:nodoc: if flush_seconds > 0 begin logger = self Thread.new do loop do begin sleep(flush_seconds) logger.flush if Time.now - logger.last_flushed_at >= flush_seconds rescue => e STDERR.puts("Error flushing log: #{e.inspect}") end end end end end end
ruby
def create_flusher_thread(flush_seconds) #:nodoc: if flush_seconds > 0 begin logger = self Thread.new do loop do begin sleep(flush_seconds) logger.flush if Time.now - logger.last_flushed_at >= flush_seconds rescue => e STDERR.puts("Error flushing log: #{e.inspect}") end end end end end end
[ "def", "create_flusher_thread", "(", "flush_seconds", ")", "#:nodoc:", "if", "flush_seconds", ">", "0", "begin", "logger", "=", "self", "Thread", ".", "new", "do", "loop", "do", "begin", "sleep", "(", "flush_seconds", ")", "logger", ".", "flush", "if", "Time", ".", "now", "-", "logger", ".", "last_flushed_at", ">=", "flush_seconds", "rescue", "=>", "e", "STDERR", ".", "puts", "(", "\"Error flushing log: #{e.inspect}\"", ")", "end", "end", "end", "end", "end", "end" ]
Create a thread that will periodically call flush.
[ "Create", "a", "thread", "that", "will", "periodically", "call", "flush", "." ]
04b44186433223d110dc95374851e26b888a8855
https://github.com/bdurand/lumberjack/blob/04b44186433223d110dc95374851e26b888a8855/lib/lumberjack/logger.rb#L298-L314
17,488
bdurand/lumberjack
lib/lumberjack/template.rb
Lumberjack.Template.compile
def compile(template) #:nodoc: template.gsub(/:[a-z0-9_]+/) do |match| position = TEMPLATE_ARGUMENT_ORDER.index(match) if position "%#{position + 1}$s" else match end end end
ruby
def compile(template) #:nodoc: template.gsub(/:[a-z0-9_]+/) do |match| position = TEMPLATE_ARGUMENT_ORDER.index(match) if position "%#{position + 1}$s" else match end end end
[ "def", "compile", "(", "template", ")", "#:nodoc:", "template", ".", "gsub", "(", "/", "/", ")", "do", "|", "match", "|", "position", "=", "TEMPLATE_ARGUMENT_ORDER", ".", "index", "(", "match", ")", "if", "position", "\"%#{position + 1}$s\"", "else", "match", "end", "end", "end" ]
Compile the template string into a value that can be used with sprintf.
[ "Compile", "the", "template", "string", "into", "a", "value", "that", "can", "be", "used", "with", "sprintf", "." ]
04b44186433223d110dc95374851e26b888a8855
https://github.com/bdurand/lumberjack/blob/04b44186433223d110dc95374851e26b888a8855/lib/lumberjack/template.rb#L62-L71
17,489
theforeman/foreman_fog_proxmox
app/models/foreman_fog_proxmox/proxmox.rb
ForemanFogProxmox.Proxmox.vm_compute_attributes
def vm_compute_attributes(vm) vm_attrs = vm.attributes.reject { |key,value| [:config, :vmid].include?(key.to_sym) || value.to_s.empty? } vm_attrs = set_vm_config_attributes(vm, vm_attrs) vm_attrs = set_vm_volumes_attributes(vm, vm_attrs) vm_attrs = set_vm_interfaces_attributes(vm, vm_attrs) vm_attrs end
ruby
def vm_compute_attributes(vm) vm_attrs = vm.attributes.reject { |key,value| [:config, :vmid].include?(key.to_sym) || value.to_s.empty? } vm_attrs = set_vm_config_attributes(vm, vm_attrs) vm_attrs = set_vm_volumes_attributes(vm, vm_attrs) vm_attrs = set_vm_interfaces_attributes(vm, vm_attrs) vm_attrs end
[ "def", "vm_compute_attributes", "(", "vm", ")", "vm_attrs", "=", "vm", ".", "attributes", ".", "reject", "{", "|", "key", ",", "value", "|", "[", ":config", ",", ":vmid", "]", ".", "include?", "(", "key", ".", "to_sym", ")", "||", "value", ".", "to_s", ".", "empty?", "}", "vm_attrs", "=", "set_vm_config_attributes", "(", "vm", ",", "vm_attrs", ")", "vm_attrs", "=", "set_vm_volumes_attributes", "(", "vm", ",", "vm_attrs", ")", "vm_attrs", "=", "set_vm_interfaces_attributes", "(", "vm", ",", "vm_attrs", ")", "vm_attrs", "end" ]
used by host.clone
[ "used", "by", "host", ".", "clone" ]
62319d08ddd95f9e34a1a33b999428c05d5c4a5e
https://github.com/theforeman/foreman_fog_proxmox/blob/62319d08ddd95f9e34a1a33b999428c05d5c4a5e/app/models/foreman_fog_proxmox/proxmox.rb#L191-L197
17,490
sporkmonger/uuidtools
lib/uuidtools.rb
UUIDTools.UUID.timestamp
def timestamp return nil if self.version != 1 gmt_timestamp_100_nanoseconds = 0 gmt_timestamp_100_nanoseconds += ((self.time_hi_and_version & 0x0FFF) << 48) gmt_timestamp_100_nanoseconds += (self.time_mid << 32) gmt_timestamp_100_nanoseconds += self.time_low return Time.at( (gmt_timestamp_100_nanoseconds - 0x01B21DD213814000) / 10000000.0) end
ruby
def timestamp return nil if self.version != 1 gmt_timestamp_100_nanoseconds = 0 gmt_timestamp_100_nanoseconds += ((self.time_hi_and_version & 0x0FFF) << 48) gmt_timestamp_100_nanoseconds += (self.time_mid << 32) gmt_timestamp_100_nanoseconds += self.time_low return Time.at( (gmt_timestamp_100_nanoseconds - 0x01B21DD213814000) / 10000000.0) end
[ "def", "timestamp", "return", "nil", "if", "self", ".", "version", "!=", "1", "gmt_timestamp_100_nanoseconds", "=", "0", "gmt_timestamp_100_nanoseconds", "+=", "(", "(", "self", ".", "time_hi_and_version", "&", "0x0FFF", ")", "<<", "48", ")", "gmt_timestamp_100_nanoseconds", "+=", "(", "self", ".", "time_mid", "<<", "32", ")", "gmt_timestamp_100_nanoseconds", "+=", "self", ".", "time_low", "return", "Time", ".", "at", "(", "(", "gmt_timestamp_100_nanoseconds", "-", "0x01B21DD213814000", ")", "/", "10000000.0", ")", "end" ]
Returns the timestamp used to generate this UUID
[ "Returns", "the", "timestamp", "used", "to", "generate", "this", "UUID" ]
a10724236cefd922ee5cd3de7695fb6e5fd703f5
https://github.com/sporkmonger/uuidtools/blob/a10724236cefd922ee5cd3de7695fb6e5fd703f5/lib/uuidtools.rb#L382-L391
17,491
sporkmonger/uuidtools
lib/uuidtools.rb
UUIDTools.UUID.generate_s
def generate_s result = sprintf("%8.8x-%4.4x-%4.4x-%2.2x%2.2x-", @time_low, @time_mid, @time_hi_and_version, @clock_seq_hi_and_reserved, @clock_seq_low); 6.times do |i| result << sprintf("%2.2x", @nodes[i]) end return result.downcase end
ruby
def generate_s result = sprintf("%8.8x-%4.4x-%4.4x-%2.2x%2.2x-", @time_low, @time_mid, @time_hi_and_version, @clock_seq_hi_and_reserved, @clock_seq_low); 6.times do |i| result << sprintf("%2.2x", @nodes[i]) end return result.downcase end
[ "def", "generate_s", "result", "=", "sprintf", "(", "\"%8.8x-%4.4x-%4.4x-%2.2x%2.2x-\"", ",", "@time_low", ",", "@time_mid", ",", "@time_hi_and_version", ",", "@clock_seq_hi_and_reserved", ",", "@clock_seq_low", ")", ";", "6", ".", "times", "do", "|", "i", "|", "result", "<<", "sprintf", "(", "\"%2.2x\"", ",", "@nodes", "[", "i", "]", ")", "end", "return", "result", ".", "downcase", "end" ]
Generates a string representation for this UUID. @api private
[ "Generates", "a", "string", "representation", "for", "this", "UUID", "." ]
a10724236cefd922ee5cd3de7695fb6e5fd703f5
https://github.com/sporkmonger/uuidtools/blob/a10724236cefd922ee5cd3de7695fb6e5fd703f5/lib/uuidtools.rb#L500-L507
17,492
lostisland/sawyer
lib/sawyer/resource.rb
Sawyer.Resource.process_value
def process_value(value) case value when Hash then self.class.new(@_agent, value) when Array then value.map { |v| process_value(v) } else value end end
ruby
def process_value(value) case value when Hash then self.class.new(@_agent, value) when Array then value.map { |v| process_value(v) } else value end end
[ "def", "process_value", "(", "value", ")", "case", "value", "when", "Hash", "then", "self", ".", "class", ".", "new", "(", "@_agent", ",", "value", ")", "when", "Array", "then", "value", ".", "map", "{", "|", "v", "|", "process_value", "(", "v", ")", "}", "else", "value", "end", "end" ]
Initializes a Resource with the given data. agent - The Sawyer::Agent that made the API request. data - Hash of key/value properties. Processes an individual value of this resource. Hashes get exploded into another Resource, and Arrays get their values processed too. value - An Object value of a Resource's data. Returns an Object to set as the value of a Resource key.
[ "Initializes", "a", "Resource", "with", "the", "given", "data", "." ]
a541a68be349a7982e24b80d94fe380a37b4805c
https://github.com/lostisland/sawyer/blob/a541a68be349a7982e24b80d94fe380a37b4805c/lib/sawyer/resource.rb#L32-L38
17,493
lostisland/sawyer
lib/sawyer/resource.rb
Sawyer.Resource.method_missing
def method_missing(method, *args) attr_name, suffix = method.to_s.scan(/([a-z0-9\_]+)(\?|\=)?$/i).first if suffix == ATTR_SETTER @_metaclass.send(:attr_accessor, attr_name) @_fields << attr_name.to_sym send(method, args.first) elsif attr_name && @_fields.include?(attr_name.to_sym) value = @attrs[attr_name.to_sym] case suffix when nil @_metaclass.send(:attr_accessor, attr_name) value when ATTR_PREDICATE then !!value end elsif suffix.nil? && SPECIAL_METHODS.include?(attr_name) instance_variable_get "@_#{attr_name}" elsif attr_name && !@_fields.include?(attr_name.to_sym) nil else super end end
ruby
def method_missing(method, *args) attr_name, suffix = method.to_s.scan(/([a-z0-9\_]+)(\?|\=)?$/i).first if suffix == ATTR_SETTER @_metaclass.send(:attr_accessor, attr_name) @_fields << attr_name.to_sym send(method, args.first) elsif attr_name && @_fields.include?(attr_name.to_sym) value = @attrs[attr_name.to_sym] case suffix when nil @_metaclass.send(:attr_accessor, attr_name) value when ATTR_PREDICATE then !!value end elsif suffix.nil? && SPECIAL_METHODS.include?(attr_name) instance_variable_get "@_#{attr_name}" elsif attr_name && !@_fields.include?(attr_name.to_sym) nil else super end end
[ "def", "method_missing", "(", "method", ",", "*", "args", ")", "attr_name", ",", "suffix", "=", "method", ".", "to_s", ".", "scan", "(", "/", "\\_", "\\?", "\\=", "/i", ")", ".", "first", "if", "suffix", "==", "ATTR_SETTER", "@_metaclass", ".", "send", "(", ":attr_accessor", ",", "attr_name", ")", "@_fields", "<<", "attr_name", ".", "to_sym", "send", "(", "method", ",", "args", ".", "first", ")", "elsif", "attr_name", "&&", "@_fields", ".", "include?", "(", "attr_name", ".", "to_sym", ")", "value", "=", "@attrs", "[", "attr_name", ".", "to_sym", "]", "case", "suffix", "when", "nil", "@_metaclass", ".", "send", "(", ":attr_accessor", ",", "attr_name", ")", "value", "when", "ATTR_PREDICATE", "then", "!", "!", "value", "end", "elsif", "suffix", ".", "nil?", "&&", "SPECIAL_METHODS", ".", "include?", "(", "attr_name", ")", "instance_variable_get", "\"@_#{attr_name}\"", "elsif", "attr_name", "&&", "!", "@_fields", ".", "include?", "(", "attr_name", ".", "to_sym", ")", "nil", "else", "super", "end", "end" ]
Provides access to a resource's attributes.
[ "Provides", "access", "to", "a", "resource", "s", "attributes", "." ]
a541a68be349a7982e24b80d94fe380a37b4805c
https://github.com/lostisland/sawyer/blob/a541a68be349a7982e24b80d94fe380a37b4805c/lib/sawyer/resource.rb#L76-L97
17,494
lostisland/sawyer
lib/sawyer/agent.rb
Sawyer.Agent.call
def call(method, url, data = nil, options = nil) if NO_BODY.include?(method) options ||= data data = nil end options ||= {} url = expand_url(url, options[:uri]) started = nil res = @conn.send method, url do |req| if data req.body = data.is_a?(String) ? data : encode_body(data) end if params = options[:query] req.params.update params end if headers = options[:headers] req.headers.update headers end started = Time.now end Response.new self, res, :sawyer_started => started, :sawyer_ended => Time.now end
ruby
def call(method, url, data = nil, options = nil) if NO_BODY.include?(method) options ||= data data = nil end options ||= {} url = expand_url(url, options[:uri]) started = nil res = @conn.send method, url do |req| if data req.body = data.is_a?(String) ? data : encode_body(data) end if params = options[:query] req.params.update params end if headers = options[:headers] req.headers.update headers end started = Time.now end Response.new self, res, :sawyer_started => started, :sawyer_ended => Time.now end
[ "def", "call", "(", "method", ",", "url", ",", "data", "=", "nil", ",", "options", "=", "nil", ")", "if", "NO_BODY", ".", "include?", "(", "method", ")", "options", "||=", "data", "data", "=", "nil", "end", "options", "||=", "{", "}", "url", "=", "expand_url", "(", "url", ",", "options", "[", ":uri", "]", ")", "started", "=", "nil", "res", "=", "@conn", ".", "send", "method", ",", "url", "do", "|", "req", "|", "if", "data", "req", ".", "body", "=", "data", ".", "is_a?", "(", "String", ")", "?", "data", ":", "encode_body", "(", "data", ")", "end", "if", "params", "=", "options", "[", ":query", "]", "req", ".", "params", ".", "update", "params", "end", "if", "headers", "=", "options", "[", ":headers", "]", "req", ".", "headers", ".", "update", "headers", "end", "started", "=", "Time", ".", "now", "end", "Response", ".", "new", "self", ",", "res", ",", ":sawyer_started", "=>", "started", ",", ":sawyer_ended", "=>", "Time", ".", "now", "end" ]
Makes a request through Faraday. method - The Symbol name of an HTTP method. url - The String URL to access. This can be relative to the Agent's endpoint. data - The Optional Hash or Resource body to be sent. :get or :head requests can have no body, so this can be the options Hash instead. options - Hash of option to configure the API request. :headers - Hash of API headers to set. :query - Hash of URL query params to set. Returns a Sawyer::Response.
[ "Makes", "a", "request", "through", "Faraday", "." ]
a541a68be349a7982e24b80d94fe380a37b4805c
https://github.com/lostisland/sawyer/blob/a541a68be349a7982e24b80d94fe380a37b4805c/lib/sawyer/agent.rb#L85-L108
17,495
lostisland/sawyer
lib/sawyer/response.rb
Sawyer.Response.process_data
def process_data(data) case data when Hash then Resource.new(agent, data) when Array then data.map { |hash| process_data(hash) } when nil then nil else data end end
ruby
def process_data(data) case data when Hash then Resource.new(agent, data) when Array then data.map { |hash| process_data(hash) } when nil then nil else data end end
[ "def", "process_data", "(", "data", ")", "case", "data", "when", "Hash", "then", "Resource", ".", "new", "(", "agent", ",", "data", ")", "when", "Array", "then", "data", ".", "map", "{", "|", "hash", "|", "process_data", "(", "hash", ")", "}", "when", "nil", "then", "nil", "else", "data", "end", "end" ]
Turns parsed contents from an API response into a Resource or collection of Resources. data - Either an Array or Hash parsed from JSON. Returns either a Resource or Array of Resources.
[ "Turns", "parsed", "contents", "from", "an", "API", "response", "into", "a", "Resource", "or", "collection", "of", "Resources", "." ]
a541a68be349a7982e24b80d94fe380a37b4805c
https://github.com/lostisland/sawyer/blob/a541a68be349a7982e24b80d94fe380a37b4805c/lib/sawyer/response.rb#L38-L45
17,496
lostisland/sawyer
lib/sawyer/response.rb
Sawyer.Response.process_rels
def process_rels links = ( @headers["Link"] || "" ).split(', ').map do |link| href, name = link.match(/<(.*?)>; rel="(\w+)"/).captures [name.to_sym, Relation.from_link(@agent, name, :href => href)] end Hash[*links.flatten] end
ruby
def process_rels links = ( @headers["Link"] || "" ).split(', ').map do |link| href, name = link.match(/<(.*?)>; rel="(\w+)"/).captures [name.to_sym, Relation.from_link(@agent, name, :href => href)] end Hash[*links.flatten] end
[ "def", "process_rels", "links", "=", "(", "@headers", "[", "\"Link\"", "]", "||", "\"\"", ")", ".", "split", "(", "', '", ")", ".", "map", "do", "|", "link", "|", "href", ",", "name", "=", "link", ".", "match", "(", "/", "\\w", "/", ")", ".", "captures", "[", "name", ".", "to_sym", ",", "Relation", ".", "from_link", "(", "@agent", ",", "name", ",", ":href", "=>", "href", ")", "]", "end", "Hash", "[", "links", ".", "flatten", "]", "end" ]
Finds link relations from 'Link' response header Returns an array of Relations
[ "Finds", "link", "relations", "from", "Link", "response", "header" ]
a541a68be349a7982e24b80d94fe380a37b4805c
https://github.com/lostisland/sawyer/blob/a541a68be349a7982e24b80d94fe380a37b4805c/lib/sawyer/response.rb#L50-L58
17,497
mdp/gibberish
lib/gibberish/aes.rb
Gibberish.AES::SJCL.check_cipher_options
def check_cipher_options(c_opts) if @opts[:max_iter] < c_opts[:iter] # Prevent DOS attacks from high PBKDF iterations # You an increase this by passing in opts[:max_iter] raise CipherOptionsError.new("Iteration count of #{c_opts[:iter]} exceeds the maximum of #{@opts[:max_iter]}") elsif !ALLOWED_MODES.include?(c_opts[:mode]) raise CipherOptionsError.new("Mode '#{c_opts[:mode]}' not supported") elsif !ALLOWED_KS.include?(c_opts[:ks]) raise CipherOptionsError.new("Keystrength of #{c_opts[:ks]} not supported") elsif !ALLOWED_TS.include?(c_opts[:ts]) raise CipherOptionsError.new("Tag length of #{c_opts[:ts]} not supported") elsif c_opts[:iv] && Base64.decode64(c_opts[:iv]).length > 12 raise CipherOptionsError.new("Initialization vector's greater than 12 bytes are not supported in Ruby.") end end
ruby
def check_cipher_options(c_opts) if @opts[:max_iter] < c_opts[:iter] # Prevent DOS attacks from high PBKDF iterations # You an increase this by passing in opts[:max_iter] raise CipherOptionsError.new("Iteration count of #{c_opts[:iter]} exceeds the maximum of #{@opts[:max_iter]}") elsif !ALLOWED_MODES.include?(c_opts[:mode]) raise CipherOptionsError.new("Mode '#{c_opts[:mode]}' not supported") elsif !ALLOWED_KS.include?(c_opts[:ks]) raise CipherOptionsError.new("Keystrength of #{c_opts[:ks]} not supported") elsif !ALLOWED_TS.include?(c_opts[:ts]) raise CipherOptionsError.new("Tag length of #{c_opts[:ts]} not supported") elsif c_opts[:iv] && Base64.decode64(c_opts[:iv]).length > 12 raise CipherOptionsError.new("Initialization vector's greater than 12 bytes are not supported in Ruby.") end end
[ "def", "check_cipher_options", "(", "c_opts", ")", "if", "@opts", "[", ":max_iter", "]", "<", "c_opts", "[", ":iter", "]", "# Prevent DOS attacks from high PBKDF iterations", "# You an increase this by passing in opts[:max_iter]", "raise", "CipherOptionsError", ".", "new", "(", "\"Iteration count of #{c_opts[:iter]} exceeds the maximum of #{@opts[:max_iter]}\"", ")", "elsif", "!", "ALLOWED_MODES", ".", "include?", "(", "c_opts", "[", ":mode", "]", ")", "raise", "CipherOptionsError", ".", "new", "(", "\"Mode '#{c_opts[:mode]}' not supported\"", ")", "elsif", "!", "ALLOWED_KS", ".", "include?", "(", "c_opts", "[", ":ks", "]", ")", "raise", "CipherOptionsError", ".", "new", "(", "\"Keystrength of #{c_opts[:ks]} not supported\"", ")", "elsif", "!", "ALLOWED_TS", ".", "include?", "(", "c_opts", "[", ":ts", "]", ")", "raise", "CipherOptionsError", ".", "new", "(", "\"Tag length of #{c_opts[:ts]} not supported\"", ")", "elsif", "c_opts", "[", ":iv", "]", "&&", "Base64", ".", "decode64", "(", "c_opts", "[", ":iv", "]", ")", ".", "length", ">", "12", "raise", "CipherOptionsError", ".", "new", "(", "\"Initialization vector's greater than 12 bytes are not supported in Ruby.\"", ")", "end", "end" ]
Assume the worst
[ "Assume", "the", "worst" ]
707bfc1f6c4ab17df8a980a9e2b80970768a41c6
https://github.com/mdp/gibberish/blob/707bfc1f6c4ab17df8a980a9e2b80970768a41c6/lib/gibberish/aes.rb#L190-L204
17,498
mdp/gibberish
lib/gibberish/aes.rb
Gibberish.AES::CBC.encrypt
def encrypt(data, opts={}) salt = generate_salt(opts[:salt]) setup_cipher(:encrypt, salt) e = cipher.update(data) + cipher.final e = "Salted__#{salt}#{e}" #OpenSSL compatible opts[:binary] ? e : Base64.encode64(e) end
ruby
def encrypt(data, opts={}) salt = generate_salt(opts[:salt]) setup_cipher(:encrypt, salt) e = cipher.update(data) + cipher.final e = "Salted__#{salt}#{e}" #OpenSSL compatible opts[:binary] ? e : Base64.encode64(e) end
[ "def", "encrypt", "(", "data", ",", "opts", "=", "{", "}", ")", "salt", "=", "generate_salt", "(", "opts", "[", ":salt", "]", ")", "setup_cipher", "(", ":encrypt", ",", "salt", ")", "e", "=", "cipher", ".", "update", "(", "data", ")", "+", "cipher", ".", "final", "e", "=", "\"Salted__#{salt}#{e}\"", "#OpenSSL compatible", "opts", "[", ":binary", "]", "?", "e", ":", "Base64", ".", "encode64", "(", "e", ")", "end" ]
Initialize with the password @param [String] password @param [Integer] size @param [String] mode
[ "Initialize", "with", "the", "password" ]
707bfc1f6c4ab17df8a980a9e2b80970768a41c6
https://github.com/mdp/gibberish/blob/707bfc1f6c4ab17df8a980a9e2b80970768a41c6/lib/gibberish/aes.rb#L225-L231
17,499
mdp/gibberish
lib/gibberish/rsa.rb
Gibberish.RSA.encrypt
def encrypt(data, opts={}) data = data.to_s enc = @key.public_encrypt(data) if opts[:binary] enc else Base64.encode64(enc) end end
ruby
def encrypt(data, opts={}) data = data.to_s enc = @key.public_encrypt(data) if opts[:binary] enc else Base64.encode64(enc) end end
[ "def", "encrypt", "(", "data", ",", "opts", "=", "{", "}", ")", "data", "=", "data", ".", "to_s", "enc", "=", "@key", ".", "public_encrypt", "(", "data", ")", "if", "opts", "[", ":binary", "]", "enc", "else", "Base64", ".", "encode64", "(", "enc", ")", "end", "end" ]
Expects a public key at the minumum @param [#to_s] key public or private @param [String] passphrase to key Encrypt data using the key @param [#to_s] data @param [Hash] opts @option opts [Boolean] :binary (false) encode the data in binary, not Base64
[ "Expects", "a", "public", "key", "at", "the", "minumum" ]
707bfc1f6c4ab17df8a980a9e2b80970768a41c6
https://github.com/mdp/gibberish/blob/707bfc1f6c4ab17df8a980a9e2b80970768a41c6/lib/gibberish/rsa.rb#L87-L95